<commit_before>use std::collections::BTreeMap;
use std::error;
use std::fmt;
use std::mem;

use {Value, Table};

#[cfg(feature = "rustc-serialize")] mod rustc_serialize;
#[cfg(feature = "serde")] mod serde;

/// A structure to transform Rust values into TOML values.
///
/// This encoder implements the serialization `Encoder` interface, allowing
/// `Encodable` rust types to be fed into the encoder. The output of this
/// encoder is a TOML `Table` structure. The resulting TOML can be stringified
/// if necessary.
///
/// # Example
///
/// ```
/// extern crate rustc_serialize;
/// extern crate toml;
///
/// # fn main() {
/// use toml::{Encoder, Value};
/// use rustc_serialize::Encodable;
///
/// #[derive(RustcEncodable)]
/// struct MyStruct { foo: isize, bar: String }
/// let my_struct = MyStruct { foo: 4, bar: "hello!".to_string() };
///
/// let mut e = Encoder::new();
/// my_struct.encode(&mut e).unwrap();
///
/// assert_eq!(e.toml.get(&"foo".to_string()), Some(&Value::Integer(4)))
/// # }
/// ```
pub struct Encoder {
    /// Output TOML that is emitted. The current version of this encoder forces
    /// the top-level representation of a structure to be a table.
    ///
    /// This field can be used to extract the return value after feeding a value
    /// into this `Encoder`.
    pub toml: Table,
    state: State,
}

/// Enumeration of errors which can occur while encoding a rust value into a
/// TOML value.
#[allow(missing_copy_implementations)]
#[derive(Debug)]
pub enum Error {
    /// Indication that a key was needed when a value was emitted, but no key
    /// was previously emitted.
    NeedsKey,
    /// Indication that a key was emitted, but not value was emitted.
    NoValue,
    /// Indicates that a map key was attempted to be emitted at an invalid
    /// location.
    InvalidMapKeyLocation,
    /// Indicates that a type other than a string was attempted to be used as a
    /// map key type.
    InvalidMapKeyType,
}

#[derive(PartialEq)]
enum State {
    Start,
    NextKey(String),
    NextArray(Vec<Value>),
    NextMapKey,
}

impl Encoder {
    /// Constructs a new encoder which will emit to the given output stream.
    pub fn new() -> Encoder {
        Encoder { state: State::Start, toml: BTreeMap::new() }
    }

    fn emit_value(&mut self, v: Value) -> Result<(), Error> {
        match mem::replace(&mut self.state, State::Start) {
            State::NextKey(key) => { self.toml.insert(key, v); Ok(()) }
            State::NextArray(mut vec) => {
                // TODO: validate types
                vec.push(v);
                self.state = State::NextArray(vec);
                Ok(())
            }
            State::NextMapKey => {
                match v {
                    Value::String(s) => { self.state = State::NextKey(s); Ok(()) }
                    _ => Err(Error::InvalidMapKeyType)
                }
            }
            _ => Err(Error::NeedsKey)
        }
    }

    fn emit_none(&mut self) -> Result<(), Error> {
        match mem::replace(&mut self.state, State::Start) {
            State::Start => unreachable!(),
            State::NextKey(_) => Ok(()),
            State::NextArray(..) => panic!("how to encode None in an array?"),
            State::NextMapKey => Err(Error::InvalidMapKeyLocation),
        }
    }

    fn seq<F>(&mut self, f: F) -> Result<(), Error>
        where F: FnOnce(&mut Encoder) -> Result<(), Error>
    {
        let old = mem::replace(&mut self.state, State::NextArray(Vec::new()));
        try!(f(self));
        match mem::replace(&mut self.state, old) {
            State::NextArray(v) => self.emit_value(Value::Array(v)),
            _ => unreachable!(),
        }
    }

    fn table<F>(&mut self, f: F) -> Result<(), Error>
        where F: FnOnce(&mut Encoder) -> Result<(), Error>
    {
        match mem::replace(&mut self.state, State::Start) {
            State::NextKey(key) => {
                let mut nested = Encoder::new();
                try!(f(&mut nested));
                self.toml.insert(key, Value::Table(nested.toml));
                Ok(())
            }
            State::NextArray(mut arr) => {
                let mut nested = Encoder::new();
                try!(f(&mut nested));
                arr.push(Value::Table(nested.toml));
                self.state = State::NextArray(arr);
                Ok(())
            }
            State::Start => f(self),
            State::NextMapKey => Err(Error::InvalidMapKeyLocation),
        }
    }

    fn table_key<F>(&mut self, f: F) -> Result<(), Error>
        where F: FnOnce(&mut Encoder) -> Result<(), Error>
    {
        match mem::replace(&mut self.state, State::NextMapKey) {
            State::Start => {}
            _ => return Err(Error::InvalidMapKeyLocation),
        }
        try!(f(self));
        match self.state {
            State::NextKey(_) => Ok(()),
            _ => Err(Error::InvalidMapKeyLocation),
        }
    }
}

/// Encodes an encodable value into a TOML value.
///
/// This function expects the type given to represent a TOML table in some form.
/// If encoding encounters an error, then this function will fail the task.
#[cfg(feature = "rustc-serialize")]
pub fn encode<T: ::rustc_serialize::Encodable>(t: &T) -> Value {
    let mut e = Encoder::new();
    t.encode(&mut e).unwrap();
    Value::Table(e.toml)
}

/// Encodes an encodable value into a TOML value.
///
/// This function expects the type given to represent a TOML table in some form.
/// If encoding encounters an error, then this function will fail the task.
#[cfg(all(not(feature = "rustc-serialize"), feature = "serde"))]
pub fn encode<T: ::serde::Serialize>(t: &T) -> Value {
    let mut e = Encoder::new();
    t.deserialize(&mut e).unwrap();
    Value::Table(e.toml)
}

/// Encodes an encodable value into a TOML string.
///
/// This function expects the type given to represent a TOML table in some form.
/// If encoding encounters an error, then this function will fail the task.
#[cfg(feature = "rustc-serialize")]
pub fn encode_str<T: ::rustc_serialize::Encodable>(t: &T) -> String {
    encode(t).to_string()
}

/// Encodes an encodable value into a TOML string.
///
/// This function expects the type given to represent a TOML table in some form.
/// If encoding encounters an error, then this function will fail the task.
#[cfg(all(not(feature = "rustc-serialize"), feature = "serde"))]
pub fn encode_str<T: ::serde::Serialize>(t: &T) -> String {
    encode(t).to_string()
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::NeedsKey => write!(f, "need a key to encode"),
            Error::NoValue => write!(f, "not value to emit for a previous key"),
            Error::InvalidMapKeyLocation => write!(f, "a map cannot be emitted \
                                                       at this location"),
            Error::InvalidMapKeyType => write!(f, "only strings can be used as \
                                                   key types"),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str { "TOML encoding error" }
}
<commit_msg>Fix serde-only compilation<commit_after>use std::collections::BTreeMap;
use std::error;
use std::fmt;
use std::mem;

use {Value, Table};

#[cfg(feature = "rustc-serialize")] mod rustc_serialize;
#[cfg(feature = "serde")] mod serde;

/// A structure to transform Rust values into TOML values.
///
/// This encoder implements the serialization `Encoder` interface, allowing
/// `Encodable` rust types to be fed into the encoder. The output of this
/// encoder is a TOML `Table` structure. The resulting TOML can be stringified
/// if necessary.
///
/// # Example
///
/// ```
/// extern crate rustc_serialize;
/// extern crate toml;
///
/// # fn main() {
/// use toml::{Encoder, Value};
/// use rustc_serialize::Encodable;
///
/// #[derive(RustcEncodable)]
/// struct MyStruct { foo: isize, bar: String }
/// let my_struct = MyStruct { foo: 4, bar: "hello!".to_string() };
///
/// let mut e = Encoder::new();
/// my_struct.encode(&mut e).unwrap();
///
/// assert_eq!(e.toml.get(&"foo".to_string()), Some(&Value::Integer(4)))
/// # }
/// ```
pub struct Encoder {
    /// Output TOML that is emitted. The current version of this encoder forces
    /// the top-level representation of a structure to be a table.
    ///
    /// This field can be used to extract the return value after feeding a value
    /// into this `Encoder`.
    pub toml: Table,
    state: State,
}

/// Enumeration of errors which can occur while encoding a rust value into a
/// TOML value.
#[allow(missing_copy_implementations)]
#[derive(Debug)]
pub enum Error {
    /// Indication that a key was needed when a value was emitted, but no key
    /// was previously emitted.
    NeedsKey,
    /// Indication that a key was emitted, but not value was emitted.
    NoValue,
    /// Indicates that a map key was attempted to be emitted at an invalid
    /// location.
    InvalidMapKeyLocation,
    /// Indicates that a type other than a string was attempted to be used as a
    /// map key type.
    InvalidMapKeyType,
}

#[derive(PartialEq)]
enum State {
    Start,
    NextKey(String),
    NextArray(Vec<Value>),
    NextMapKey,
}

impl Encoder {
    /// Constructs a new encoder which will emit to the given output stream.
    pub fn new() -> Encoder {
        Encoder { state: State::Start, toml: BTreeMap::new() }
    }

    fn emit_value(&mut self, v: Value) -> Result<(), Error> {
        match mem::replace(&mut self.state, State::Start) {
            State::NextKey(key) => { self.toml.insert(key, v); Ok(()) }
            State::NextArray(mut vec) => {
                // TODO: validate types
                vec.push(v);
                self.state = State::NextArray(vec);
                Ok(())
            }
            State::NextMapKey => {
                match v {
                    Value::String(s) => { self.state = State::NextKey(s); Ok(()) }
                    _ => Err(Error::InvalidMapKeyType)
                }
            }
            _ => Err(Error::NeedsKey)
        }
    }

    fn emit_none(&mut self) -> Result<(), Error> {
        match mem::replace(&mut self.state, State::Start) {
            State::Start => unreachable!(),
            State::NextKey(_) => Ok(()),
            State::NextArray(..) => panic!("how to encode None in an array?"),
            State::NextMapKey => Err(Error::InvalidMapKeyLocation),
        }
    }

    fn seq<F>(&mut self, f: F) -> Result<(), Error>
        where F: FnOnce(&mut Encoder) -> Result<(), Error>
    {
        let old = mem::replace(&mut self.state, State::NextArray(Vec::new()));
        try!(f(self));
        match mem::replace(&mut self.state, old) {
            State::NextArray(v) => self.emit_value(Value::Array(v)),
            _ => unreachable!(),
        }
    }

    fn table<F>(&mut self, f: F) -> Result<(), Error>
        where F: FnOnce(&mut Encoder) -> Result<(), Error>
    {
        match mem::replace(&mut self.state, State::Start) {
            State::NextKey(key) => {
                let mut nested = Encoder::new();
                try!(f(&mut nested));
                self.toml.insert(key, Value::Table(nested.toml));
                Ok(())
            }
            State::NextArray(mut arr) => {
                let mut nested = Encoder::new();
                try!(f(&mut nested));
                arr.push(Value::Table(nested.toml));
                self.state = State::NextArray(arr);
                Ok(())
            }
            State::Start => f(self),
            State::NextMapKey => Err(Error::InvalidMapKeyLocation),
        }
    }

    fn table_key<F>(&mut self, f: F) -> Result<(), Error>
        where F: FnOnce(&mut Encoder) -> Result<(), Error>
    {
        match mem::replace(&mut self.state, State::NextMapKey) {
            State::Start => {}
            _ => return Err(Error::InvalidMapKeyLocation),
        }
        try!(f(self));
        match self.state {
            State::NextKey(_) => Ok(()),
            _ => Err(Error::InvalidMapKeyLocation),
        }
    }
}

/// Encodes an encodable value into a TOML value.
///
/// This function expects the type given to represent a TOML table in some form.
/// If encoding encounters an error, then this function will fail the task.
#[cfg(feature = "rustc-serialize")]
pub fn encode<T: ::rustc_serialize::Encodable>(t: &T) -> Value {
    let mut e = Encoder::new();
    t.encode(&mut e).unwrap();
    Value::Table(e.toml)
}

/// Encodes an encodable value into a TOML value.
///
/// This function expects the type given to represent a TOML table in some form.
/// If encoding encounters an error, then this function will fail the task.
#[cfg(all(not(feature = "rustc-serialize"), feature = "serde"))]
pub fn encode<T: ::serde::Serialize>(t: &T) -> Value {
    let mut e = Encoder::new();
    t.serialize(&mut e).unwrap();
    Value::Table(e.toml)
}

/// Encodes an encodable value into a TOML string.
///
/// This function expects the type given to represent a TOML table in some form.
/// If encoding encounters an error, then this function will fail the task.
#[cfg(feature = "rustc-serialize")]
pub fn encode_str<T: ::rustc_serialize::Encodable>(t: &T) -> String {
    encode(t).to_string()
}

/// Encodes an encodable value into a TOML string.
///
/// This function expects the type given to represent a TOML table in some form.
/// If encoding encounters an error, then this function will fail the task.
#[cfg(all(not(feature = "rustc-serialize"), feature = "serde"))]
pub fn encode_str<T: ::serde::Serialize>(t: &T) -> String {
    encode(t).to_string()
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::NeedsKey => write!(f, "need a key to encode"),
            Error::NoValue => write!(f, "not value to emit for a previous key"),
            Error::InvalidMapKeyLocation => write!(f, "a map cannot be emitted \
                                                       at this location"),
            Error::InvalidMapKeyType => write!(f, "only strings can be used as \
                                                   key types"),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str { "TOML encoding error" }
}
<|endoftext|>


<commit_before><commit_msg>Fix clean all<commit_after><|endoftext|>


<commit_before><commit_msg>unbreak <collections::vec::IntoIter as Iterator>::next<commit_after><|endoftext|>


<commit_before>import std::io;
import std::io::writer_util;
import rustc::syntax::ast;
import rustc::syntax::print::pprust;

type ctxt = {
    ps: pprust::ps,
    w: io::writer
};

fn write_markdown(
    doc: doc::cratedoc,
    crate: @ast::crate,
    writer: io::writer
) {
    let ctxt = {
        ps: pprust::rust_printer(writer),
        w: writer
    };

    write_header(ctxt, doc.topmod.name);
    write_top_module(ctxt, crate, doc.topmod);
}

fn write_top_module(
    ctxt: ctxt,
    crate: @ast::crate,
    moddoc: doc::moddoc
) {
    write_mod_contents(ctxt, crate, moddoc);
}

fn write_mod(
    ctxt: ctxt,
    crate: @ast::crate,
    moddoc: doc::moddoc
) {
    write_mod_contents(ctxt, crate, moddoc);
}

fn write_mod_contents(
    ctxt: ctxt,
    crate: @ast::crate,
    moddoc: doc::moddoc
) {
    for fndoc in *moddoc.fns {
        write_fn(ctxt, crate, fndoc);
    }

    for moddoc in *moddoc.mods {
        write_mod(ctxt, crate, moddoc);
    }
}

fn write_fn(
    ctxt: ctxt,
    crate: @ast::crate,
    fndoc: doc::fndoc
) {
    import rustc::middle::ast_map;

    let map = ast_map::map_crate(*crate);
    let decl = alt map.get(fndoc.id) {
      ast_map::node_item(@{
        node: ast::item_fn(decl, _, _), _
      }) { decl }
    };

    write_fndoc(ctxt, fndoc.name, fndoc, decl);
}

#[doc(
  brief = "Generate a crate document header.",
  args(rd = "Rustdoc context",
       name = "Crate name")
)]
fn write_header(ctxt: ctxt, name: str) {
    ctxt.w.write_line("# Crate " + name);
}

#[doc(
  brief = "Documents a single function.",
  args(rd = "Rustdoc context",
       ident = "Identifier for this function",
       doc = "Function docs extracted from attributes",
       _fn = "AST object representing this function")
)]
fn write_fndoc(ctxt: ctxt, ident: str, doc: doc::fndoc, decl: ast::fn_decl) {
    ctxt.w.write_line("## Function `" + ident + "`");
    ctxt.w.write_line(doc.brief);
    alt doc.desc {
        some(_d) {
            ctxt.w.write_line("");
            ctxt.w.write_line(_d);
            ctxt.w.write_line("");
        }
        none. { }
    }
    for arg: ast::arg in decl.inputs {
        ctxt.w.write_str("### Argument `" + arg.ident + "`: ");
        ctxt.w.write_line("`" + pprust::ty_to_str(arg.ty) + "`");
        alt doc.args.find(arg.ident) {
            some(_d) {
                ctxt.w.write_line(_d);
            }
            none. { }
        };
    }
    ctxt.w.write_line("### Returns `" + pprust::ty_to_str(decl.output) + "`");
    alt doc.return {
        some(_r) { ctxt.w.write_line(_r); }
        none. { }
    }
}

#[cfg(test)]
mod tests {
    fn write_markdown_str(
        doc: doc::cratedoc,
        crate: @ast::crate
    ) -> str {
        let buffer = io::mk_mem_buffer();
        let writer = io::mem_buffer_writer(buffer);
        write_markdown(doc, crate, writer);
        ret io::mem_buffer_str(buffer);
    }

    #[test]
    fn write_markdown_should_write_crate_header() {
        let source = "";
        let ast = parse::from_str(source);
        let doc = extract::extract(ast, "belch");
        let markdown = write_markdown_str(doc, ast);
        assert str::contains(markdown, "# Crate belch\n");
    }

    #[test]
    fn write_markdown_should_write_function_header() {
        let source = "fn func() { }";
        let ast = parse::from_str(source);
        let doc = extract::extract(ast, "");
        let markdown = write_markdown_str(doc, ast);
        assert str::contains(markdown, "## Function `func`");
    }
}<commit_msg>rustdoc: Make gen module exports explicit<commit_after>import std::io;
import std::io::writer_util;
import rustc::syntax::ast;
import rustc::syntax::print::pprust;

export write_markdown;

type ctxt = {
    ps: pprust::ps,
    w: io::writer
};

fn write_markdown(
    doc: doc::cratedoc,
    crate: @ast::crate,
    writer: io::writer
) {
    let ctxt = {
        ps: pprust::rust_printer(writer),
        w: writer
    };

    write_header(ctxt, doc.topmod.name);
    write_top_module(ctxt, crate, doc.topmod);
}

fn write_top_module(
    ctxt: ctxt,
    crate: @ast::crate,
    moddoc: doc::moddoc
) {
    write_mod_contents(ctxt, crate, moddoc);
}

fn write_mod(
    ctxt: ctxt,
    crate: @ast::crate,
    moddoc: doc::moddoc
) {
    write_mod_contents(ctxt, crate, moddoc);
}

fn write_mod_contents(
    ctxt: ctxt,
    crate: @ast::crate,
    moddoc: doc::moddoc
) {
    for fndoc in *moddoc.fns {
        write_fn(ctxt, crate, fndoc);
    }

    for moddoc in *moddoc.mods {
        write_mod(ctxt, crate, moddoc);
    }
}

fn write_fn(
    ctxt: ctxt,
    crate: @ast::crate,
    fndoc: doc::fndoc
) {
    import rustc::middle::ast_map;

    let map = ast_map::map_crate(*crate);
    let decl = alt map.get(fndoc.id) {
      ast_map::node_item(@{
        node: ast::item_fn(decl, _, _), _
      }) { decl }
    };

    write_fndoc(ctxt, fndoc.name, fndoc, decl);
}

#[doc(
  brief = "Generate a crate document header.",
  args(rd = "Rustdoc context",
       name = "Crate name")
)]
fn write_header(ctxt: ctxt, name: str) {
    ctxt.w.write_line("# Crate " + name);
}

#[doc(
  brief = "Documents a single function.",
  args(rd = "Rustdoc context",
       ident = "Identifier for this function",
       doc = "Function docs extracted from attributes",
       _fn = "AST object representing this function")
)]
fn write_fndoc(ctxt: ctxt, ident: str, doc: doc::fndoc, decl: ast::fn_decl) {
    ctxt.w.write_line("## Function `" + ident + "`");
    ctxt.w.write_line(doc.brief);
    alt doc.desc {
        some(_d) {
            ctxt.w.write_line("");
            ctxt.w.write_line(_d);
            ctxt.w.write_line("");
        }
        none. { }
    }
    for arg: ast::arg in decl.inputs {
        ctxt.w.write_str("### Argument `" + arg.ident + "`: ");
        ctxt.w.write_line("`" + pprust::ty_to_str(arg.ty) + "`");
        alt doc.args.find(arg.ident) {
            some(_d) {
                ctxt.w.write_line(_d);
            }
            none. { }
        };
    }
    ctxt.w.write_line("### Returns `" + pprust::ty_to_str(decl.output) + "`");
    alt doc.return {
        some(_r) { ctxt.w.write_line(_r); }
        none. { }
    }
}

#[cfg(test)]
mod tests {
    fn write_markdown_str(
        doc: doc::cratedoc,
        crate: @ast::crate
    ) -> str {
        let buffer = io::mk_mem_buffer();
        let writer = io::mem_buffer_writer(buffer);
        write_markdown(doc, crate, writer);
        ret io::mem_buffer_str(buffer);
    }

    #[test]
    fn write_markdown_should_write_crate_header() {
        let source = "";
        let ast = parse::from_str(source);
        let doc = extract::extract(ast, "belch");
        let markdown = write_markdown_str(doc, ast);
        assert str::contains(markdown, "# Crate belch\n");
    }

    #[test]
    fn write_markdown_should_write_function_header() {
        let source = "fn func() { }";
        let ast = parse::from_str(source);
        let doc = extract::extract(ast, "");
        let markdown = write_markdown_str(doc, ast);
        assert str::contains(markdown, "## Function `func`");
    }
}<|endoftext|>


<commit_before><commit_msg>Formatting<commit_after><|endoftext|>


<commit_before>//! Server Responses
//!
//! These are responses sent by a `hyper::Server` to clients, after
//! receiving a request.
use std::io::{BufferedWriter, IoResult};
use std::io::net::tcp::TcpStream;

use time::now_utc;

use header;
use header::common;
use status;
use version;
use rfc7230::{CR, LF, LINE_ENDING};

/// Phantom type indicating Headers and StatusCode have not been written.
pub struct Fresh;

/// Phantom type indicating Headers and StatusCode have been written.
pub struct Streaming;

/// The status of a Response, indicating if the headers and status have been written.
pub trait WriteStatus {}

impl WriteStatus for Streaming {}
impl WriteStatus for Fresh {}

/// The outgoing half for a Tcp connection, created by a `Server` and given to a `Handler`.
pub struct Response<W: WriteStatus> {
    /// The HTTP version of this response.
    pub version: version::HttpVersion,
    // Stream the Response is writing to, not accessible through UnwrittenResponse
    body: BufferedWriter<TcpStream>, // TODO: use a HttpWriter from rfc7230
    // The status code for the request.
    status: status::StatusCode,
    // The outgoing headers on this response.
    headers: header::Headers
}

impl<W: WriteStatus> Response<W> {
    /// The status of this response.
    #[inline]
    pub fn status(&self) -> status::StatusCode { self.status }

    /// The headers of this response.
    pub fn headers(&self) -> &header::Headers { &self.headers }
}

impl Response<Fresh> {
    /// Creates a new Response that can be used to write to a network stream.
    pub fn new(tcp: TcpStream) -> Response<Fresh> {
        Response {
            status: status::Ok,
            version: version::Http11,
            headers: header::Headers::new(),
            body: BufferedWriter::new(tcp)
        }
    }

    /// Consume this Response<Fresh>, writing the Headers and Status and creating a Response<Streaming>
    pub fn start(mut self) -> IoResult<Response<Streaming>> {
        debug!("writing head: {} {}", self.version, self.status);
        try!(write!(self.body, "{} {}{}{}", self.version, self.status, CR as char, LF as char));

        if !self.headers.has::<common::Date>() {
            self.headers.set(common::Date(now_utc()));
        }

        for (name, header) in self.headers.iter() {
            debug!("headers {}: {}", name, header);
            try!(write!(self.body, "{}: {}", name, header));
            try!(self.body.write(LINE_ENDING));
        }

        try!(self.body.write(LINE_ENDING));

        // "copy" to change the phantom type
        Ok(Response {
            version: self.version,
            body: self.body,
            status: self.status,
            headers: self.headers
        })
    }

    /// Get a mutable reference to the status.
    #[inline]
    pub fn status_mut(&mut self) -> &mut status::StatusCode { &mut self.status }

    /// Get a mutable reference to the Headers.
    pub fn headers_mut(&mut self) -> &mut header::Headers { &mut self.headers }
}

impl Response<Streaming> {
    /// Flushes all writing of a response to the client.
    pub fn end(mut self) -> IoResult<()> {
        debug!("ending");
        self.flush()
    }
}

impl Writer for Response<Streaming> {
    fn write(&mut self, msg: &[u8]) -> IoResult<()> {
        debug!("write {:u} bytes", msg.len());
        self.body.write(msg)
    }

    fn flush(&mut self) -> IoResult<()> {
        self.body.flush()
    }
}

<commit_msg>Provide Response::<Fresh>::deconstruct to deconstruct a Response.<commit_after>//! Server Responses
//!
//! These are responses sent by a `hyper::Server` to clients, after
//! receiving a request.
use std::io::{BufferedWriter, IoResult};
use std::io::net::tcp::TcpStream;

use time::now_utc;

use header;
use header::common;
use status;
use version;
use rfc7230::{CR, LF, LINE_ENDING};

/// Phantom type indicating Headers and StatusCode have not been written.
pub struct Fresh;

/// Phantom type indicating Headers and StatusCode have been written.
pub struct Streaming;

/// The status of a Response, indicating if the headers and status have been written.
pub trait WriteStatus {}

impl WriteStatus for Streaming {}
impl WriteStatus for Fresh {}

/// The outgoing half for a Tcp connection, created by a `Server` and given to a `Handler`.
pub struct Response<W: WriteStatus> {
    /// The HTTP version of this response.
    pub version: version::HttpVersion,
    // Stream the Response is writing to, not accessible through UnwrittenResponse
    body: BufferedWriter<TcpStream>, // TODO: use a HttpWriter from rfc7230
    // The status code for the request.
    status: status::StatusCode,
    // The outgoing headers on this response.
    headers: header::Headers
}

impl<W: WriteStatus> Response<W> {
    /// The status of this response.
    #[inline]
    pub fn status(&self) -> status::StatusCode { self.status }

    /// The headers of this response.
    pub fn headers(&self) -> &header::Headers { &self.headers }

    /// Construct a Response from its constituent parts.
    pub fn construct(version: version::HttpVersion,
                     body: BufferedWriter<TcpStream>,
                     status: status::StatusCode,
                     headers: header::Headers) -> Response<Fresh> {
        Response {
            status: status,
            version: version,
            body: body,
            headers: headers
        }
    }
}

impl Response<Fresh> {
    /// Creates a new Response that can be used to write to a network stream.
    pub fn new(tcp: TcpStream) -> Response<Fresh> {
        Response {
            status: status::Ok,
            version: version::Http11,
            headers: header::Headers::new(),
            body: BufferedWriter::new(tcp)
        }
    }

    /// Consume this Response<Fresh>, writing the Headers and Status and creating a Response<Streaming>
    pub fn start(mut self) -> IoResult<Response<Streaming>> {
        debug!("writing head: {} {}", self.version, self.status);
        try!(write!(self.body, "{} {}{}{}", self.version, self.status, CR as char, LF as char));

        if !self.headers.has::<common::Date>() {
            self.headers.set(common::Date(now_utc()));
        }

        for (name, header) in self.headers.iter() {
            debug!("headers {}: {}", name, header);
            try!(write!(self.body, "{}: {}", name, header));
            try!(self.body.write(LINE_ENDING));
        }

        try!(self.body.write(LINE_ENDING));

        // "copy" to change the phantom type
        Ok(Response {
            version: self.version,
            body: self.body,
            status: self.status,
            headers: self.headers
        })
    }

    /// Get a mutable reference to the status.
    #[inline]
    pub fn status_mut(&mut self) -> &mut status::StatusCode { &mut self.status }

    /// Get a mutable reference to the Headers.
    pub fn headers_mut(&mut self) -> &mut header::Headers { &mut self.headers }

    /// Deconstruct this Response into its constituent parts.
    pub fn deconstruct(self) -> (version::HttpVersion, BufferedWriter<TcpStream>, status::StatusCode, header::Headers) {
        (self.version, self.body, self.status, self.headers)
    }
}

impl Response<Streaming> {
    /// Flushes all writing of a response to the client.
    pub fn end(mut self) -> IoResult<()> {
        debug!("ending");
        self.flush()
    }
}

impl Writer for Response<Streaming> {
    fn write(&mut self, msg: &[u8]) -> IoResult<()> {
        debug!("write {:u} bytes", msg.len());
        self.body.write(msg)
    }

    fn flush(&mut self) -> IoResult<()> {
        self.body.flush()
    }
}

<|endoftext|>


<commit_before>use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fmt::Result as FMTResult;
use std::fs::File as FSFile;
use std::fs::{create_dir_all, remove_file};
use std::io::{Read, Write};
use std::vec::{Vec, IntoIter};

use glob::glob;
use glob::Paths;

use module::Module;
use runtime::Runtime;
use storage::file::File;
use storage::file_id::*;
use storage::parser::{FileHeaderParser, Parser};

pub type BackendOperationResult<T = ()> = Result<T, StorageBackendError>;

pub struct StorageBackend {
    basepath: String,
    storepath: String,
}

impl StorageBackend {

    pub fn new(rt: &Runtime) -> BackendOperationResult<StorageBackend> {
        let storepath = rt.get_rtp() + "/store/";
        debug!("Trying to create {}", storepath);
        create_dir_all(&storepath).and_then(|_| {
            debug!("Creating succeeded, constructing backend instance");
            Ok(StorageBackend {
                basepath: rt.get_rtp(),
                storepath: storepath.clone(),
            })
        }).or_else(|e| {
            debug!("Creating failed, constructing error instance");
            let mut serr = StorageBackendError::new(
                "create_dir_all()",
                "Could not create store directories",
                Some(storepath)
            );
            serr.caused_by = Some(Box::new(e));
            Err(serr)
        })
    }

    pub fn iter_ids(&self, m: &Module) -> Result<IntoIter<FileID>, StorageBackendError>
    {
        let globstr = self.prefix_of_files_for_module(m) + "*.imag";
        debug!("Globstring = {}", globstr);
        glob(&globstr[..])
            .and_then(|globlist| {
                debug!("Iterating over globlist");
                Ok(globlist_to_file_id_vec(globlist).into_iter())
            })
            .map_err(|e| {
                debug!("glob() returned error: {:?}", e);
                let serr = StorageBackendError::new(
                        "iter_ids()",
                        "Cannot iter on file ids",
                        None);
                // Why the hack is Error not implemented for glob::PatternError
                // serr.caused_by = Some(Box::new(e));
                serr
            })
    }

    pub fn iter_files<'a, HP>(&self, m: &'a Module, p: &Parser<HP>)
        -> Result<IntoIter<File<'a>>, StorageBackendError>
        where HP: FileHeaderParser
    {
        self.iter_ids(m)
            .and_then(|ids| {
                debug!("Iterating ids and building files from them");
                debug!("  number of ids = {}", ids.len());
                Ok(self.filter_map_ids_to_files(m, p, ids).into_iter())
            })
            .map_err(|e| {
                debug!("StorageBackend::iter_ids() returned error = {:?}", e);
                let mut serr = StorageBackendError::new("iter_files()",
                                           "Cannot iter on files",
                                           None);
                serr.caused_by = Some(Box::new(e));
                serr
            })
    }

    /*
     * Write a file to disk.
     *
     * The file is moved to this function as the file won't be edited afterwards
     */
    pub fn put_file<HP>(&self, f: File, p: &Parser<HP>) -> BackendOperationResult
        where HP: FileHeaderParser
    {
        let written = write_with_parser(&f, p);
        if written.is_err() { return Err(written.err().unwrap()); }
        let string = written.unwrap();

        let path = self.build_filepath(&f);
        debug!("Writing file: {}", path);
        debug!("      string: {}", string);

        FSFile::create(&path).map(|mut file| {
            debug!("Created file at '{}'", path);
            file.write_all(&string.clone().into_bytes())
                .map_err(|ioerr| {
                    debug!("Could not write file");
                    let mut err = StorageBackendError::new(
                            "File::write_all()",
                            "Could not write out File contents",
                            None
                        );
                    err.caused_by = Some(Box::new(ioerr));
                    err
                })
        }).map_err(|writeerr| {
            debug!("Could not create file at '{}'", path);
            let mut err = StorageBackendError::new(
                "File::create()",
                "Creating file on disk failed",
                None
            );
            err.caused_by = Some(Box::new(writeerr));
            err
        }).and(Ok(()))
    }

    /*
     * Update a file. We have the UUID and can find the file on FS with it and
     * then replace its contents with the contents of the passed file object
     */
    pub fn update_file<HP>(&self, f: File, p: &Parser<HP>) -> BackendOperationResult
        where HP: FileHeaderParser
    {
        let contents = write_with_parser(&f, p);
        if contents.is_err() { return Err(contents.err().unwrap()); }
        let string = contents.unwrap();

        let path = self.build_filepath(&f);
        debug!("Writing file: {}", path);
        debug!("      string: {}", string);

        FSFile::open(&path).map(|mut file| {
            debug!("Open file at '{}'", path);
            file.write_all(&string.clone().into_bytes())
                .map_err(|ioerr| {
                    debug!("Could not write file");
                    let mut err = StorageBackendError::new(
                            "File::write()",
                            "Tried to write contents of this file, though operation did not succeed",
                            Some(string)
                        );
                    err.caused_by = Some(Box::new(ioerr));
                    err
                })
        }).map_err(|writeerr| {
            debug!("Could not write file at '{}'", path);
            let mut err = StorageBackendError::new(
                "File::open()",
                "Tried to update contents of this file, though file doesn't exist",
                None
            );
            err.caused_by = Some(Box::new(writeerr));
            err
        }).and(Ok(()))
    }

    /*
     * Find a file by its ID and return it if found. Return nothing if not
     * found, of course.
     *
     * TODO: Needs refactoring, as there might be an error when reading from
     * disk OR the id just does not exist.
     */
    pub fn get_file_by_id<'a, HP>(&self, m: &'a Module, id: &FileID, p: &Parser<HP>) -> Option<File<'a>>
        where HP: FileHeaderParser
    {
        debug!("Searching for file with id '{}'", id);

        if id.get_type() == FileIDType::NONE {
            // We don't know the hash type, so we glob() around a bit.
            debug!("Having FileIDType::NONE, so we glob() for the raw ID");

            let id_str = id.get_id().unwrap_or(String::from("INVALID"));
            let globstr = self.prefix_of_files_for_module(m) + "*" + &id_str[..] + ".imag";
            debug!("Globbing with globstr = '{}'", globstr);
            glob(&globstr[..]).map(|globlist| {
                let idvec = globlist_to_file_id_vec(globlist).into_iter();
                let mut vec = self.filter_map_ids_to_files(m, p, idvec);
                vec.reverse();
                vec.pop()
            }).unwrap_or({
                debug!("No glob matches, actually. We can't do anything at this point");
                None
            })
        } else {
            // The (hash)type is already in the FileID object, so we can just
            // build a path from the information we already have
            debug!("We know FileIDType, so we build the path directly now");
            let filepath = self.build_filepath_with_id(m, id.clone());
            if let Ok(mut fs) = FSFile::open(filepath) {
                let mut s = String::new();
                fs.read_to_string(&mut s);

                debug!("Success opening file with id '{}'", id);
                debug!("Parsing to internal structure now");
                p.read(s).and_then(|(h, d)| {
                    Ok(File::from_parser_result(m, id.clone(), h, d))
                }).ok()
            } else {
                debug!("No file with id '{}'", id);
                None
            }
        }
    }

    pub fn remove_file(&self, m: &Module, file: File, checked: bool) -> BackendOperationResult {
        if checked {
            error!("Checked remove not implemented yet. I will crash now");
            unimplemented!()
        }

        debug!("Doing unchecked remove");
        info!("Going to remove file: {}", file);

        let fp = self.build_filepath(&file);
        remove_file(fp).map_err(|e| {
            let mut serr = StorageBackendError::new(
                "remove_file()",
                "File removal failed",
                Some(format!("{}", file))
            );
            serr.caused_by = Some(Box::new(e));
            serr
        })
    }

    fn build_filepath(&self, f: &File) -> String {
        self.build_filepath_with_id(f.owner(), f.id())
    }

    fn build_filepath_with_id(&self, owner: &Module, id: FileID) -> String {
        let idstr   : String        = id.clone().into();
        let idtype  : FileIDType    = id.into();
        let typestr : String        = idtype.into();

        debug!("Building filepath with id");
        debug!("  basepath: '{}'", self.basepath);
        debug!(" storepath: '{}'", self.storepath);
        debug!("        id: '{}'", idstr);
        debug!("      type: '{}'", typestr);

        self.prefix_of_files_for_module(owner) +
            "-" + &typestr[..] +
            "-" + &idstr[..] +
            ".imag"
    }

    fn prefix_of_files_for_module(&self, m: &Module) -> String {
        self.storepath.clone() + m.name()
    }

    fn filter_map_ids_to_files<'a, HP>(&self,
                                        m: &'a Module,
                                        p: &Parser<HP>,
                                        ids: IntoIter<FileID>)
        -> Vec<File<'a>>
        where HP: FileHeaderParser
    {
        ids.filter_map(|id| self.get_file_by_id(m, &id, p))
           .collect::<Vec<File>>()
    }

}

#[derive(Debug)]
pub struct StorageBackendError {
    pub action: String,             // The file system action in words
    pub desc: String,               // A short description
    pub data_dump: Option<String>,  // Data dump, if any
    pub caused_by: Option<Box<Error>>,  // caused from this error
}

impl StorageBackendError {

    fn new<S>(action: S, desc: S, data: Option<String>) -> StorageBackendError
        where S: Into<String>
    {
        StorageBackendError {
            action:         action.into(),
            desc:           desc.into(),
            data_dump:      data,
            caused_by:      None,
        }
    }

}

impl Error for StorageBackendError {

    fn description(&self) -> &str {
        &self.desc[..]
    }

    fn cause(&self) -> Option<&Error> {
        self.caused_by.as_ref().map(|e| &**e)
    }

}

impl<'a> Display for StorageBackendError {
    fn fmt(&self, f: &mut Formatter) -> FMTResult {
        write!(f, "StorageBackendError[{}]: {}",
               self.action, self.desc)
    }
}

fn write_with_parser<'a, HP>(f: &File, p: &Parser<HP>) -> Result<String, StorageBackendError>
    where HP: FileHeaderParser
{
    p.write(f.contents())
        .or_else(|err| {
            let mut serr = StorageBackendError::new(
                "Parser::write()",
                "Cannot translate internal representation of file contents into on-disk representation",
                None
            );
            serr.caused_by = Some(Box::new(err));
            Err(serr)
        })
}

fn globlist_to_file_id_vec(globlist: Paths) -> Vec<FileID> {
    globlist.filter_map(Result::ok)
            .map(|pbuf| FileID::from(&pbuf))
            .collect::<Vec<FileID>>()
}

<commit_msg>Outsource StorageBackendError building into helper function<commit_after>use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fmt::Result as FMTResult;
use std::fs::File as FSFile;
use std::fs::{create_dir_all, remove_file};
use std::io::{Read, Write};
use std::vec::{Vec, IntoIter};

use glob::glob;
use glob::Paths;

use module::Module;
use runtime::Runtime;
use storage::file::File;
use storage::file_id::*;
use storage::parser::{FileHeaderParser, Parser};

pub type BackendOperationResult<T = ()> = Result<T, StorageBackendError>;

pub struct StorageBackend {
    basepath: String,
    storepath: String,
}

impl StorageBackend {

    pub fn new(rt: &Runtime) -> BackendOperationResult<StorageBackend> {
        let storepath = rt.get_rtp() + "/store/";
        debug!("Trying to create {}", storepath);
        create_dir_all(&storepath).and_then(|_| {
            debug!("Creating succeeded, constructing backend instance");
            Ok(StorageBackend {
                basepath: rt.get_rtp(),
                storepath: storepath.clone(),
            })
        }).or_else(|e| {
            debug!("Creating failed, constructing error instance");
            Err(serr_build("create_dir_all()", "Could not create store directories",
                           Some(storepath), Some(Box::new(e))))
        })
    }

    pub fn iter_ids(&self, m: &Module) -> Result<IntoIter<FileID>, StorageBackendError>
    {
        let globstr = self.prefix_of_files_for_module(m) + "*.imag";
        debug!("Globstring = {}", globstr);
        glob(&globstr[..])
            .and_then(|globlist| {
                debug!("Iterating over globlist");
                Ok(globlist_to_file_id_vec(globlist).into_iter())
            })
            .map_err(|e| {
                debug!("glob() returned error: {:?}", e);
                serr_build("iter_ids()", "Cannot iter on file ids",
                        None, None)
            })
    }

    pub fn iter_files<'a, HP>(&self, m: &'a Module, p: &Parser<HP>)
        -> Result<IntoIter<File<'a>>, StorageBackendError>
        where HP: FileHeaderParser
    {
        self.iter_ids(m)
            .and_then(|ids| {
                debug!("Iterating ids and building files from them");
                debug!("  number of ids = {}", ids.len());
                Ok(self.filter_map_ids_to_files(m, p, ids).into_iter())
            })
            .map_err(|e| {
                debug!("StorageBackend::iter_ids() returned error = {:?}", e);
                serr_build("iter_files()", "Cannot iter on files",
                            None, Some(Box::new(e)))
            })
    }

    /*
     * Write a file to disk.
     *
     * The file is moved to this function as the file won't be edited afterwards
     */
    pub fn put_file<HP>(&self, f: File, p: &Parser<HP>) -> BackendOperationResult
        where HP: FileHeaderParser
    {
        let written = write_with_parser(&f, p);
        if written.is_err() { return Err(written.err().unwrap()); }
        let string = written.unwrap();

        let path = self.build_filepath(&f);
        debug!("Writing file: {}", path);
        debug!("      string: {}", string);

        FSFile::create(&path).map(|mut file| {
            debug!("Created file at '{}'", path);
            file.write_all(&string.clone().into_bytes())
                .map_err(|ioerr| {
                    debug!("Could not write file");
                    serr_build("File::write_all()",
                               "Could not write out File contents",
                               None, Some(Box::new(ioerr)))
                })
        }).map_err(|writeerr| {
            debug!("Could not create file at '{}'", path);
            serr_build("File::create()", "Creating file on disk failed",
                       None, Some(Box::new(writeerr)))
        }).and(Ok(()))
    }

    /*
     * Update a file. We have the UUID and can find the file on FS with it and
     * then replace its contents with the contents of the passed file object
     */
    pub fn update_file<HP>(&self, f: File, p: &Parser<HP>) -> BackendOperationResult
        where HP: FileHeaderParser
    {
        let contents = write_with_parser(&f, p);
        if contents.is_err() { return Err(contents.err().unwrap()); }
        let string = contents.unwrap();

        let path = self.build_filepath(&f);
        debug!("Writing file: {}", path);
        debug!("      string: {}", string);

        FSFile::open(&path).map(|mut file| {
            debug!("Open file at '{}'", path);
            file.write_all(&string.clone().into_bytes())
                .map_err(|ioerr| {
                    debug!("Could not write file");
                    serr_build("File::write()",
                               "Tried to write contents of this file, though operation did not succeed",
                                Some(string), Some(Box::new(ioerr)))
                })
        }).map_err(|writeerr| {
            debug!("Could not write file at '{}'", path);
            serr_build("File::open()",
                       "Tried to update contents of this file, though file doesn't exist",
                       None, Some(Box::new(writeerr)))
        }).and(Ok(()))
    }

    /*
     * Find a file by its ID and return it if found. Return nothing if not
     * found, of course.
     *
     * TODO: Needs refactoring, as there might be an error when reading from
     * disk OR the id just does not exist.
     */
    pub fn get_file_by_id<'a, HP>(&self, m: &'a Module, id: &FileID, p: &Parser<HP>) -> Option<File<'a>>
        where HP: FileHeaderParser
    {
        debug!("Searching for file with id '{}'", id);

        if id.get_type() == FileIDType::NONE {
            // We don't know the hash type, so we glob() around a bit.
            debug!("Having FileIDType::NONE, so we glob() for the raw ID");

            let id_str = id.get_id().unwrap_or(String::from("INVALID"));
            let globstr = self.prefix_of_files_for_module(m) + "*" + &id_str[..] + ".imag";
            debug!("Globbing with globstr = '{}'", globstr);
            glob(&globstr[..]).map(|globlist| {
                let idvec = globlist_to_file_id_vec(globlist).into_iter();
                let mut vec = self.filter_map_ids_to_files(m, p, idvec);
                vec.reverse();
                vec.pop()
            }).unwrap_or({
                debug!("No glob matches, actually. We can't do anything at this point");
                None
            })
        } else {
            // The (hash)type is already in the FileID object, so we can just
            // build a path from the information we already have
            debug!("We know FileIDType, so we build the path directly now");
            let filepath = self.build_filepath_with_id(m, id.clone());
            if let Ok(mut fs) = FSFile::open(filepath) {
                let mut s = String::new();
                fs.read_to_string(&mut s);

                debug!("Success opening file with id '{}'", id);
                debug!("Parsing to internal structure now");
                p.read(s).and_then(|(h, d)| {
                    Ok(File::from_parser_result(m, id.clone(), h, d))
                }).ok()
            } else {
                debug!("No file with id '{}'", id);
                None
            }
        }
    }

    pub fn remove_file(&self, m: &Module, file: File, checked: bool) -> BackendOperationResult {
        if checked {
            error!("Checked remove not implemented yet. I will crash now");
            unimplemented!()
        }

        debug!("Doing unchecked remove");
        info!("Going to remove file: {}", file);

        let fp = self.build_filepath(&file);
        remove_file(fp).map_err(|e| {
            serr_build("remove_file()", "File removal failed",
                       Some(format!("{}", file)), Some(Box::new(e)))
        })
    }

    fn build_filepath(&self, f: &File) -> String {
        self.build_filepath_with_id(f.owner(), f.id())
    }

    fn build_filepath_with_id(&self, owner: &Module, id: FileID) -> String {
        let idstr   : String        = id.clone().into();
        let idtype  : FileIDType    = id.into();
        let typestr : String        = idtype.into();

        debug!("Building filepath with id");
        debug!("  basepath: '{}'", self.basepath);
        debug!(" storepath: '{}'", self.storepath);
        debug!("        id: '{}'", idstr);
        debug!("      type: '{}'", typestr);

        self.prefix_of_files_for_module(owner) +
            "-" + &typestr[..] +
            "-" + &idstr[..] +
            ".imag"
    }

    fn prefix_of_files_for_module(&self, m: &Module) -> String {
        self.storepath.clone() + m.name()
    }

    fn filter_map_ids_to_files<'a, HP>(&self,
                                        m: &'a Module,
                                        p: &Parser<HP>,
                                        ids: IntoIter<FileID>)
        -> Vec<File<'a>>
        where HP: FileHeaderParser
    {
        ids.filter_map(|id| self.get_file_by_id(m, &id, p))
           .collect::<Vec<File>>()
    }

}

#[derive(Debug)]
pub struct StorageBackendError {
    pub action: String,             // The file system action in words
    pub desc: String,               // A short description
    pub data_dump: Option<String>,  // Data dump, if any
    pub caused_by: Option<Box<Error>>,  // caused from this error
}

impl StorageBackendError {

    fn new<S>(action: S, desc: S, data: Option<String>) -> StorageBackendError
        where S: Into<String>
    {
        StorageBackendError {
            action:         action.into(),
            desc:           desc.into(),
            data_dump:      data,
            caused_by:      None,
        }
    }

}

impl Error for StorageBackendError {

    fn description(&self) -> &str {
        &self.desc[..]
    }

    fn cause(&self) -> Option<&Error> {
        self.caused_by.as_ref().map(|e| &**e)
    }

}

impl<'a> Display for StorageBackendError {
    fn fmt(&self, f: &mut Formatter) -> FMTResult {
        write!(f, "StorageBackendError[{}]: {}",
               self.action, self.desc)
    }
}

fn write_with_parser<'a, HP>(f: &File, p: &Parser<HP>) -> Result<String, StorageBackendError>
    where HP: FileHeaderParser
{
    p.write(f.contents())
        .or_else(|err| {
            Err(serr_build("Parser::write()",
                           "Cannot translate internal representation of file contents into on-disk representation",
                           None, Some(Box::new(err))))
        })
}

fn globlist_to_file_id_vec(globlist: Paths) -> Vec<FileID> {
    globlist.filter_map(Result::ok)
            .map(|pbuf| FileID::from(&pbuf))
            .collect::<Vec<FileID>>()
}

/*
 * Helper to build a StorageBackendError object with cause, because one line is
 * less than three lines
 */
fn serr_build(action: &'static str, desc: &'static str,
              data: Option<String>, caused_by: Option<Box<Error>>)
    -> StorageBackendError
{
    let mut err = StorageBackendError::new(action, desc, data);
    err.caused_by = caused_by;
    err
}

<|endoftext|>


<commit_before><commit_msg>style: convert NS_STYLE_OBJECT_FIT_* to an enum class in nsStyleConsts.h<commit_after><|endoftext|>


<commit_before><commit_msg>Add control switcher<commit_after>use player::Player;
use ghost::Ghost;
use super::camera::*;
use super::event_manager::*;
use glium::glutin::{ElementState, Event, VirtualKeyCode};

/// Switch between `ghost` and `player` cameras with `G` key
pub struct ControlSwitcher {
    player: Player,
    ghost: Ghost,
    is_ghost: bool,
}

impl ControlSwitcher {
    pub fn new(player: Player, ghost: Ghost) -> Self {
        ControlSwitcher {
            player: player,
            ghost: ghost,
            is_ghost: true,
        }
    }
    /// Return current `Camera`
    pub fn get_camera(&self) -> Camera {
        if self.is_ghost { self.ghost.get_camera() } else { self.player.get_camera() }
    }

    /// Run camera `update` function
    pub fn update(&mut self, delta: f32) {
        if self.is_ghost {
            self.ghost.update(delta);
        } else {
            self.player.update(delta);
        }
    }

    /// Switch current camera between `ghost` and `player`
    /// Return to original location of `player`
    pub fn switch_cam(&mut self) {
        if self.is_ghost {
            self.player.set_camera(self.ghost.get_camera());
            self.is_ghost = false;
        } else {
            self.is_ghost = true;
        }

    }
}

/// Listen for `G`
impl EventHandler for ControlSwitcher {
    fn handle_event(&mut self, e: &Event) -> EventResponse {
        match *e {

            Event::KeyboardInput(ElementState::Pressed, _, Some(VirtualKeyCode::G)) => {
                self.switch_cam();
                EventResponse::Continue
            }

            _ => {
                if self.is_ghost {
                    self.ghost.handle_event(e)
                } else {
                    self.player.handle_event(e)
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Added arrays and slices example.<commit_after>use std::mem;

// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
    println!("first element of the slice: {}", slice[0]);
    println!("the slice has {} elements", slice.len());
}

fn main() {
    // Fixed-size array (type signature is superfluous)
    let xs: [i32; 5] = [1, 2, 3, 4, 5];

    // All elements can be initialized to the same value
    let ys: [i32; 500] = [0; 500];

    // Indexing starts at 0
    println!("first element of the array: {}", xs[0]);
    println!("second element of the array: {}", xs[1]);

    // `len` returns the size of the array
    println!("array size: {}", xs.len());

    // Arrays are stack allocated
    println!("array occupies {} bytes", mem::size_of_val(&xs));

    // Arrays can be automatically borrowed as slices
    println!("borrow the whole array as a slice");
    analyze_slice(&xs);

    // Slices can point to a section of an array
    println!("borrow a section of the array as a slice");
    analyze_slice(&ys[1 .. 4]);

    // Out of bound indexing yields a panic
    println!("{}", xs[5]);
}
<|endoftext|>


<commit_before><commit_msg>currency resolver from tokio tutorial<commit_after>pub fn resolve(host: &str) -> ResolveFuture;

enum State {
    Resolving(ResolveFuture), // currently resolving the host name
    Connecting(ConnectFuture), // establishing a TCP connection to the remote host
}

pub struct ResolveAndConnect {
    state: State,
}

pub fn resolve_and_connect(host: &str) -> ResolveAndConnect {
    let state = State::Resolving(resolve(host));
    ResolveAndConnect { state }
}

impl Future for ResolveAndConnect {
    type Item = TcpStream;
    type Error = io::Error;

    fn poll(&mut self) -> Result<Async<TcpStream>, io::Error> {
        use self::State::*;

        loop {
            let addr = match self.state {
                Resolving(ref mut fut) => {
                    try_ready!(fut.poll())
                }
                Connecting(ref mut fut) => {
                    return fut.poll()
                }
            }

            // if we reach here, the state was `Resolving`
            // and the call to the inner Future return ed `Ready`
            // it happens because `try_ready!` does not leave the method.
            let connecting = TcpStream::connect(&addr);
            self.state = Connecting(connecting)
        }
    }
}

// This is not very smart in fact, that looks
// just like reimplementation of and_then combinator.

resolve(my_host).and_then(|addr| TcpStream::connect(&addr))
<|endoftext|>


<commit_before><commit_msg>Time log writes.<commit_after><|endoftext|>


<commit_before><commit_msg>De-batchify by inlining.<commit_after><|endoftext|>


<commit_before><commit_msg>Add getters for DeserVcard helper type<commit_after><|endoftext|>


<commit_before>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// xfail-fast
// aux-build:cci_class_cast.rs
extern mod cci_class_cast;
use to_str::ToStr;
use cci_class_cast::kitty::*;

fn print_out<T: ToStr>(thing: T, expected: ~str) {
  let actual = thing.to_str();
  debug!("%s", actual);
  assert(actual == expected);
}

fn main() {
  let nyan : ToStr  = cat(0u, 2, ~"nyan") as ToStr;
  print_out(nyan, ~"nyan");
}

<commit_msg>test: Fix test/run-pass/class-cast-to-trait-cross-crate-2. rs=fire<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// xfail-fast
// aux-build:cci_class_cast.rs
extern mod cci_class_cast;
use core::to_str::ToStr;
use cci_class_cast::kitty::*;

fn print_out<T: ToStr>(thing: T, expected: ~str) {
  let actual = thing.to_str();
  debug!("%s", actual);
  assert(actual == expected);
}

fn main() {
  let nyan : ToStr  = cat(0u, 2, ~"nyan") as ToStr;
  print_out(nyan, ~"nyan");
}

<|endoftext|>


<commit_before>use std::collections::HashMap;
use rustc_serialize::json;

#[derive(RustcDecodable, RustcEncodable)]
pub struct AvrDataMemory {
    pub registers: Vec<u8>,
    pub io: Vec<u8>,
    pub ram: Vec<u8>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct Emulator {
    pub data_memory: AvrDataMemory
}

pub fn serialize(emulator: &Emulator) -> String {
    // Serialize using `json::encode`
    json::encode(emulator).unwrap()
}

pub struct Instruction {
    label: String,
    operation: String,
    operands: Vec<String>
}

pub fn parse_instruction(instruction: String) -> Instruction {
    let mut instruction_iterator = instruction.split(" ");
    let instruction_vector = instruction_iterator.collect::<Vec<&str>>();

    let mut operands_iterator = instruction_vector[1].split(",");
    let operands_vector = operands_iterator.map(|x| x.to_string()).collect::<Vec<String>>();

    Instruction {
        label: "".to_string(),
        operation: instruction_vector[0].to_string(),
        operands: operands_vector
    }
}
fn get_register_index(operand: &String) -> usize {
    let index = operand.replace("r", "").parse::<usize>();
    index.unwrap()
}
pub fn add(emulator: &Emulator, rd: &String, rr: &String) -> Emulator {
    let rd_index = get_register_index(rd);
    let rr_index = get_register_index(rr);

    let registers = &emulator.data_memory.registers;
    let result = registers[rd_index] + registers[rr_index];

    let mut new_registers = registers.to_vec();
    new_registers[rd_index] = result;

    let data_memory = &emulator.data_memory;
    Emulator {
        data_memory: AvrDataMemory {
            registers: new_registers,
            io: data_memory.io.to_vec(),
            ram: data_memory.ram.to_vec()
        }
    }
}

// This is a reducer just like redux!
// (emulator, instruction) => (emulator)
// (state, action) => (state)
pub fn perform_instruction(emulator: &Emulator, instruction_line: String) -> Emulator {
    println!("instruction line: {}", instruction_line);
    let instruction = parse_instruction(instruction_line);
    add(&emulator, &instruction.operands[0], &instruction.operands[1])
}

#[test]
fn can_add() {
    let emulator = Emulator {
        data_memory: AvrDataMemory {
            registers: vec![0,2,3],
            io: vec![],
            ram: vec![]
        }
    };
    let instruction_line = "add r0,r2".to_string();
    let next_emulator = perform_instruction(&emulator, instruction_line);
    assert_eq!(3, next_emulator.data_memory.registers[0]);
    assert_eq!(3, next_emulator.data_memory.registers[2]);
}

#[test]
fn it_works() {
    let emulator = Emulator {
        data_memory: AvrDataMemory {
            registers: vec![0,2,3],
            io: vec![],
            ram: vec![]
        }
    };
    assert_eq!("{\"data_memory\":{\"registers\":[0,2,3],\"io\":[],\"ram\":[]}}", serialize(&emulator));
}
<commit_msg>Adds basic inc and ldi opcodes<commit_after>use std::collections::HashMap;
use rustc_serialize::json;
use rustc_serialize::hex::FromHex;

#[derive(RustcDecodable, RustcEncodable)]
pub struct AvrDataMemory {
    pub registers: Vec<u8>,
    pub io: Vec<u8>,
    pub ram: Vec<u8>
}

#[derive(RustcDecodable, RustcEncodable)]
pub struct Emulator {
    pub data_memory: AvrDataMemory
}

pub fn serialize(emulator: &Emulator) -> String {
    // Serialize using `json::encode`
    json::encode(emulator).unwrap()
}

pub struct Instruction {
    label: String,
    operation: String,
    operands: Vec<String>
}

pub fn parse_instruction(instruction: String) -> Instruction {
    let mut instruction_iterator = instruction.split(" ");
    let instruction_vector = instruction_iterator.collect::<Vec<&str>>();

    let mut operands_iterator = instruction_vector[1].split(",");
    let operands_vector = operands_iterator.map(|x| x.to_string()).collect::<Vec<String>>();

    Instruction {
        label: "".to_string(),
        operation: instruction_vector[0].to_string(),
        operands: operands_vector
    }
}
fn get_register_index(operand: &String) -> usize {
    let index = operand.replace("r", "").parse::<usize>();
    index.unwrap()
}

fn hex_to_int(operand: &String) -> u8 {
    let hex = operand.replace("$", "");
    hex.from_hex().unwrap()[0]
}

pub fn add(emulator: &Emulator, rd: &String, rr: &String) -> Emulator {
    let rd_index = get_register_index(rd);
    let rr_index = get_register_index(rr);

    let registers = &emulator.data_memory.registers;
    let result = registers[rd_index] + registers[rr_index];

    let mut new_registers = registers.to_vec();
    new_registers[rd_index] = result;

    let data_memory = &emulator.data_memory;
    Emulator {
        data_memory: AvrDataMemory {
            registers: new_registers,
            io: data_memory.io.to_vec(),
            ram: data_memory.ram.to_vec()
        }
    }
}

pub fn inc(emulator: &Emulator, rd: &String) -> Emulator {
    let rd_index = get_register_index(rd);

    let registers = &emulator.data_memory.registers;
    let result = registers[rd_index] + 1;

    let mut new_registers = registers.to_vec();
    new_registers[rd_index] = result;

    let data_memory = &emulator.data_memory;
    Emulator {
        data_memory: AvrDataMemory {
            registers: new_registers,
            io: data_memory.io.to_vec(),
            ram: data_memory.ram.to_vec()
        }
    }
}

pub fn ldi(emulator: &Emulator, rd: &String, k: &String) -> Emulator {
    let rd_index = get_register_index(rd);
    let k_value = hex_to_int(k);

    let registers = &emulator.data_memory.registers;
    let mut new_registers = registers.to_vec();
    new_registers[rd_index] = k_value;

    let data_memory = &emulator.data_memory;
    Emulator {
        data_memory: AvrDataMemory {
            registers: new_registers,
            io: data_memory.io.to_vec(),
            ram: data_memory.ram.to_vec()
        }
    }
}

// This is a reducer just like redux!
// (emulator, instruction) => (emulator)
// (state, action) => (state)
pub fn perform_instruction(emulator: &Emulator, instruction_line: String) -> Emulator {
    println!("instruction line: {}", instruction_line);
    let instruction = parse_instruction(instruction_line);
    match &instruction.operation.to_owned()[..] { // http://stackoverflow.com/a/23977218
      "add" => add(&emulator, &instruction.operands[0], &instruction.operands[1]),
      "inc" => inc(&emulator, &instruction.operands[0]),
      "ldi" => ldi(&emulator, &instruction.operands[0], &instruction.operands[1]),
      _ => inc(&emulator, &instruction.operands[0]),
    }
}

#[test]
fn can_ldi() {
    let emulator = Emulator {
        data_memory: AvrDataMemory {
            registers: vec![1,0,0],
            io: vec![],
            ram: vec![]
        }
    };
    let instruction_line = "ldi r0,$0F".to_string();
    let next_emulator = perform_instruction(&emulator, instruction_line);
    assert_eq!(15, next_emulator.data_memory.registers[0]);
}

#[test]
fn can_inc() {
    let emulator = Emulator {
        data_memory: AvrDataMemory {
            registers: vec![0,2,3],
            io: vec![],
            ram: vec![]
        }
    };
    let instruction_line = "inc r0".to_string();
    let next_emulator = perform_instruction(&emulator, instruction_line);
    assert_eq!(1, next_emulator.data_memory.registers[0]);
}

#[test]
fn can_add() {
    let emulator = Emulator {
        data_memory: AvrDataMemory {
            registers: vec![0,2,3],
            io: vec![],
            ram: vec![]
        }
    };
    let instruction_line = "add r0,r2".to_string();
    let next_emulator = perform_instruction(&emulator, instruction_line);
    assert_eq!(3, next_emulator.data_memory.registers[0]);
    assert_eq!(3, next_emulator.data_memory.registers[2]);
}

#[test]
fn it_works() {
    let emulator = Emulator {
        data_memory: AvrDataMemory {
            registers: vec![0,2,3],
            io: vec![],
            ram: vec![]
        }
    };
    assert_eq!("{\"data_memory\":{\"registers\":[0,2,3],\"io\":[],\"ram\":[]}}", serialize(&emulator));
}
<|endoftext|>


<commit_before><commit_msg>udpate<commit_after><|endoftext|>


<commit_before><commit_msg>Map long double to c_double<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for cross crate newtype struct in match pattern.<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// xfail-fast
// aux-build:newtype_struct_xc.rs

extern mod newtype_struct_xc;

fn main() {
    let x = newtype_struct_xc::Au(21);
    match x {
        newtype_struct_xc::Au(n) => assert_eq!(n, 21)
    }
}
<|endoftext|>


<commit_before>//! OpenGL back-end for Rust-Graphics.

use gl = opengles::gl2;
use shader_utils::{with_shader_source, compile_shader};
use BackEnd = graphics::BackEnd;

static VERTEX_SHADER_TRI_LIST_XY_RGBA: &'static str = "
attribute vec4 a_v4Position;
attribute vec4 a_v4FillColor;

varying vec4 v_v4FillColor;

void main()
{
    v_v4FillColor = a_v4FillColor;
    gl_Position = a_v4Position;
}
";

static FRAGMENT_SHADER_TRI_LIST_XY_RGBA: &'static str = "
varying vec4 v_v4FillColor;

void main()
{
        gl_FragColor = v_v4FillColor;
}
";

/// OpenGL back-end for Rust-Graphics.
pub struct Gl {
    vertex_shader: gl::GLuint,
    fragment_shader: gl::GLuint,
    program: gl::GLuint,
    a_v4Position: gl::GLuint,
    a_v4FillColor: gl::GLuint,
    position_id: gl::GLuint,
    fill_color_id: gl::GLuint,
}

impl Gl {
    /// Creates a new Gl.
    pub fn new() -> Gl {
        let vertex_shader = with_shader_source(
            VERTEX_SHADER_TRI_LIST_XY_RGBA, |src| {
                compile_shader(gl::VERTEX_SHADER, src)
            }).unwrap();
        let fragment_shader = with_shader_source(
            FRAGMENT_SHADER_TRI_LIST_XY_RGBA, |src| {
                compile_shader(gl::FRAGMENT_SHADER, src)
            }).unwrap();
        let program = gl::create_program();
        gl::attach_shader(program, vertex_shader);
        gl::attach_shader(program, fragment_shader);
        gl::link_program(program);
        gl::use_program(program);
        let a_v4Position =
            gl::get_attrib_location(program, "a_v4Position") as gl::GLuint;
        gl::enable_vertex_attrib_array(a_v4Position);
        let a_v4FillColor =
            gl::get_attrib_location(program, "a_v4FillColor") as gl::GLuint;
        gl::enable_vertex_attrib_array(a_v4FillColor);

        // Load the vertices and color buffers.
        let buffers = gl::gen_buffers(2);
        let position_id = *buffers.get(0);
        let fill_color_id = *buffers.get(1);

        Gl {
            vertex_shader: vertex_shader,
            fragment_shader: fragment_shader,
            program: program,
            a_v4Position: a_v4Position,
            a_v4FillColor: a_v4FillColor,
            position_id: position_id,
            fill_color_id: fill_color_id,
        }
    }
}

impl BackEnd for Gl {
    fn supports_clear_rgba(&self) -> bool { true }

    fn clear_rgba(&mut self, r: f32, g: f32, b: f32, a: f32) {
        gl::clear_color(r, g, b, a);
        gl::clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
    }

    fn supports_tri_list_xy_rgba_f32(&self) -> bool { true }

    fn tri_list_xy_rgba_f32(&mut self, vertices: &[f32], colors: &[f32]) {
        let size_vertices: i32 = 2;
        gl::bind_buffer(gl::ARRAY_BUFFER, self.position_id);
        gl::buffer_data(gl::ARRAY_BUFFER, vertices.as_slice(), gl::DYNAMIC_DRAW);
        gl::vertex_attrib_pointer_f32(self.a_v4Position, size_vertices, true, 0, 0);

        gl::bind_buffer(gl::ARRAY_BUFFER, self.fill_color_id);
        gl::buffer_data(gl::ARRAY_BUFFER, colors.as_slice(), gl::DYNAMIC_DRAW);
        gl::vertex_attrib_pointer_f32(self.a_v4FillColor, 4, false, 0, 0);

        // gl::enable(gl::DEPTH_TEST);
        gl::cull_face(gl::FRONT_AND_BACK);

        let items: i32 = vertices.len() as i32 / size_vertices;
        gl::draw_arrays(gl::TRIANGLES, 0, items);
    }
}

<commit_msg>Added alpha blending<commit_after>//! OpenGL back-end for Rust-Graphics.

use gl = opengles::gl2;
use shader_utils::{with_shader_source, compile_shader};
use BackEnd = graphics::BackEnd;

static VERTEX_SHADER_TRI_LIST_XY_RGBA: &'static str = "
attribute vec4 a_v4Position;
attribute vec4 a_v4FillColor;

varying vec4 v_v4FillColor;

void main()
{
    v_v4FillColor = a_v4FillColor;
    gl_Position = a_v4Position;
}
";

static FRAGMENT_SHADER_TRI_LIST_XY_RGBA: &'static str = "
varying vec4 v_v4FillColor;

void main()
{
        gl_FragColor = v_v4FillColor;
}
";

/// OpenGL back-end for Rust-Graphics.
pub struct Gl {
    vertex_shader: gl::GLuint,
    fragment_shader: gl::GLuint,
    program: gl::GLuint,
    a_v4Position: gl::GLuint,
    a_v4FillColor: gl::GLuint,
    position_id: gl::GLuint,
    fill_color_id: gl::GLuint,
}

impl Gl {
    /// Creates a new Gl.
    pub fn new() -> Gl {
        let vertex_shader = with_shader_source(
            VERTEX_SHADER_TRI_LIST_XY_RGBA, |src| {
                compile_shader(gl::VERTEX_SHADER, src)
            }).unwrap();
        let fragment_shader = with_shader_source(
            FRAGMENT_SHADER_TRI_LIST_XY_RGBA, |src| {
                compile_shader(gl::FRAGMENT_SHADER, src)
            }).unwrap();
        let program = gl::create_program();
        gl::attach_shader(program, vertex_shader);
        gl::attach_shader(program, fragment_shader);
        gl::link_program(program);
        gl::use_program(program);
        let a_v4Position =
            gl::get_attrib_location(program, "a_v4Position") as gl::GLuint;
        gl::enable_vertex_attrib_array(a_v4Position);
        let a_v4FillColor =
            gl::get_attrib_location(program, "a_v4FillColor") as gl::GLuint;
        gl::enable_vertex_attrib_array(a_v4FillColor);

        // Load the vertices and color buffers.
        let buffers = gl::gen_buffers(2);
        let position_id = *buffers.get(0);
        let fill_color_id = *buffers.get(1);

        Gl {
            vertex_shader: vertex_shader,
            fragment_shader: fragment_shader,
            program: program,
            a_v4Position: a_v4Position,
            a_v4FillColor: a_v4FillColor,
            position_id: position_id,
            fill_color_id: fill_color_id,
        }
    }
}

impl BackEnd for Gl {
    fn supports_clear_rgba(&self) -> bool { true }

    fn clear_rgba(&mut self, r: f32, g: f32, b: f32, a: f32) {
        gl::clear_color(r, g, b, a);
        gl::clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
    }

    fn alpha_blend(&mut self, on: bool) {
        if on {
            gl::enable(gl::BLEND);
            gl::blend_func(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA);
        } else {
            gl::disable(gl::BLEND);
        }
    }

    fn supports_tri_list_xy_rgba_f32(&self) -> bool { true }

    fn tri_list_xy_rgba_f32(&mut self, vertices: &[f32], colors: &[f32]) {
        let size_vertices: i32 = 2;
        gl::bind_buffer(gl::ARRAY_BUFFER, self.position_id);
        gl::buffer_data(gl::ARRAY_BUFFER, vertices.as_slice(), gl::DYNAMIC_DRAW);
        gl::vertex_attrib_pointer_f32(self.a_v4Position, size_vertices, true, 0, 0);

        gl::bind_buffer(gl::ARRAY_BUFFER, self.fill_color_id);
        gl::buffer_data(gl::ARRAY_BUFFER, colors.as_slice(), gl::DYNAMIC_DRAW);
        gl::vertex_attrib_pointer_f32(self.a_v4FillColor, 4, false, 0, 0);

        // gl::enable(gl::DEPTH_TEST);
        gl::cull_face(gl::FRONT_AND_BACK);

        let items: i32 = vertices.len() as i32 / size_vertices;
        gl::draw_arrays(gl::TRIANGLES, 0, items);
    }
}

<|endoftext|>


<commit_before><commit_msg>blank message<commit_after><|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg>Chore(commands): remove some cruft<commit_after><|endoftext|>


<commit_before><commit_msg>commands: Fix from_bytes_test<commit_after><|endoftext|>


<commit_before><commit_msg>Change names of doubled generics parameters<commit_after><|endoftext|>


<commit_before><commit_msg>Added rust-peid.rs<commit_after>use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
use std::string::String;

fn main() {

  let args: Vec<String> = env::args().collect();
  let mut file = File::open(&Path::new(&args[1])).unwrap();
  let mut buffer: Vec<u8> = Vec::new();
  let result = file.read_to_end(&mut buffer).unwrap();
  println!("File: {}, {} byte(s)", &args[1], result);

  if buffer[0] == 0x4d && buffer[1] == 0x5a {
    println!("MZ");
    let mut b1 = buffer[(0x3c + 1) as usize] as u16;
    b1 = b1 << 8;
    let b2 = buffer[0x3c] as u16;
    let addr = b1 | b2;
    let pe_offset = addr as usize;
    if buffer[pe_offset] == 0x50 && buffer[pe_offset + 1] == 0x45 {
      println!("PE");
      if buffer[pe_offset + 5] == 0x01 && buffer[pe_offset + 4] == 0x4c {
        println!("x86");
      } else if buffer[pe_offset + 5] == 0x86 && buffer[pe_offset + 4] == 0x64 {
        println!("x64");
      } else {
        println!("Other");
      }

    }
  }

}<|endoftext|>


<commit_before><commit_msg>Attemp to fix Windows issues (see #83)<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unneeded &mut reference.<commit_after><|endoftext|>


<commit_before><commit_msg>Add Sized bound to IsComposite<commit_after><|endoftext|>


<commit_before><commit_msg>added world neighbours test<commit_after><|endoftext|>


<commit_before>// should-fail

// this test ensures that when we forget to use
// any `//~ ERROR` comments whatsoever, that the test doesn't succeed

fn main() {}<commit_msg>Newlines.... newlines everywhere<commit_after>// should-fail

// this test ensures that when we forget to use
// any `//~ ERROR` comments whatsoever, that the test doesn't succeed

fn main() {}
<|endoftext|>


<commit_before><commit_msg>add more tests<commit_after><|endoftext|>


<commit_before><commit_msg>Insufficient number of RPL unittests<commit_after><|endoftext|>


<commit_before><commit_msg>Added tcsetpgrp<commit_after><|endoftext|>


<commit_before><commit_msg>Better error message when failing to deserialize state data.<commit_after><|endoftext|>


<commit_before><commit_msg>adds splitter from tutorial<commit_after>use std::rand::random;
use std::os;
use std::io::File;

fn main() {
    let args: ~[~str] = os::args();
    if args.len() != 2 {
        println!("Usage: {:s} <inputfile>", args[0]);
    } else {
        let fname = args[1];
        let path = Path::new(fname.clone());
        let msg_file = File::open(&path);

        match (msg_file) {
            Some(mut msg) => {
                let msg_bytes: ~[u8] = msg.read_to_end();
                let share1_file
                       = File::create(&Path::new(fname + ".share1"));
                let share2_file
                       = File::create(&Path::new(fname + ".share2"));

                match (share1_file, share2_file) {
                    (Some(share1), Some(share2)) => {
                        split(msg_bytes, share1, share2);
                        } ,
                    (_, _) => fail!("Error opening output files!"),
                }
            } ,
            None => fail!("Error opening message file: {:s}", fname)
        }
    }
}

fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
    let mut ret = ~[];
    for i in range(0, a.len()) {
	ret.push(a[i] ^ b[i]);
    }
    ret
}

fn split(msg_bytes: &[u8], mut share1: File, mut share2: File) {
    let mut random_bytes: ~[u8] = ~[];
    // This is not cryptographically strong randomness!
    // (For entertainment purposes only.)
    for _ in range(0, msg_bytes.len()) {
	let random_byte = random();
	random_bytes.push(random_byte);
    }

    let encrypted_bytes = xor(msg_bytes, random_bytes);
    share1.write(random_bytes);
    share2.write(encrypted_bytes);
}
<|endoftext|>


<commit_before><commit_msg>update<commit_after>fn main() {
    let program = "+ + * - /";

    let res = program.chars().fold(0, | x, x1 |
        match x1 {
            '+' => x + 1,
            '-' => x - 1,
            '*' => x * 2,
            '/' => x / 2,
            _ => x
        }
    );

    println!("The program \"{}\" calculates the value {}",
              program, res);
}
<|endoftext|>


<commit_before><commit_msg>Add missing file<commit_after>/// AST nodes that are part of a `Block`
///

pub use super::{
    Visibility,
    Ident,
    Path,
    Import,
    Type,
    Dims,
};

#[derive(Clone, Debug)]
pub struct Block {
    pub stmts: Vec<BlockStatement>,
}

#[derive(Clone, Debug)]
pub enum BlockStatement {
    LocalVariableDecl {
        final_: bool,
        ty: Type,
        vars: Vec<(Ident, Dims)>,
    },
    // ClassDecl,
    // Statement,
}
<|endoftext|>


<commit_before><commit_msg>Test with ravro::schema::Schema rather than deserialized JSON<commit_after><|endoftext|>


<commit_before>pub enum XdrOp {
    Encode,
    Decode,
    Free,
}

pub struct Xdr {
    op: XdrOp,
    /// Pointer to users' data
    public: usize,
    /// Pointer to private data
    private: usize,
    /// Pointer to private used for position info
    base: usize,
    /// extra private word
    handy: isize,
}

pub trait XdrOps {
    /// Get a long from underlying stream
    fn get_long(&mut self, l: &mut usize) -> bool;

    /// Put a long to underlying stream
    fn put_long(&mut self, l: &usize) -> bool;

    /// Get a i32 from underlying stream
    fn get_i32(&mut self, i: &mut i32) -> bool;

    /// Put a i32 to underlying stream
    fn put_i32(&mut self, i: &i32) -> bool;

    /// Get some bytes from the underlying stream
    fn get_bytes(&mut self, bytes: &mut [u8]) -> bool;

    /// Put some bytes into the underlying stream
    fn put_bytes(&mut self, bytes: &[u8]) -> bool;

    /// Returns bytes off from beginning
    fn get_pos(&self) -> usize;

    /// Lets you reposition the stream
    fn set_pos(&mut self, offset: usize) -> bool;

    // TODO: Not sure if we'll need this?
    // Buf quick ptr to buffered data
    //fn inline(&mut self, len: usize) -> *mut i32;

    /// Free privates of this xdr_stream
    fn destroy(&mut self);

    // TODO: Not sure if we'll need this?
    // Change, retrieve client info
    //fn control(&mut self, req: isize, op: void *);
}
<commit_msg>Removed xdr_rpc.rs<commit_after><|endoftext|>


<commit_before><commit_msg>toml option<commit_after><|endoftext|>


<commit_before><commit_msg>Create ex1.rs<commit_after>// Make me compile!

fn main() {
    println!();
}
<|endoftext|>


<commit_before><commit_msg>test: Add a test for fixed issue #10763<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

extern "Rust" fn foo() {}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #28417 - apasel422:issue-23036, r=arielb1<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::collections::HashMap;
use std::path::Path;

fn main() {
    let mut map = HashMap::new();
    map.insert(Path::new("a"), 0);
    map.get(Path::new("a"));
}
<|endoftext|>


<commit_before><commit_msg>Added regression function match value test, closes #44333<commit_after>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

type Func = fn(usize, usize) -> usize;

fn foo(a: usize, b: usize) -> usize { a + b }
fn bar(a: usize, b: usize) -> usize { a * b }
fn test(x: usize) -> Func {
    if x % 2 == 0 { foo }
    else { bar }
}

const FOO: Func = foo;
const BAR: Func = bar;

fn main() {
    match test(std::env::consts::ARCH.len()) {
        FOO => println!("foo"),
        BAR => println!("bar"),
        _ => unreachable!(),
    }
}
<|endoftext|>


<commit_before><commit_msg>Test drop order for (destructuring) assignments<commit_after>// run-pass

//! Test that let bindings and destructuring assignments have consistent drop orders

#![feature(destructuring_assignment)]
#![allow(unused_variables, unused_assignments)]

use std::cell::RefCell;

thread_local! {
    static DROP_ORDER: RefCell<Vec<usize>> = RefCell::new(Vec::new());
}

struct DropRecorder(usize);
impl Drop for DropRecorder {
    fn drop(&mut self) {
        DROP_ORDER.with(|d| d.borrow_mut().push(self.0));
    }
}

fn main() {
    let expected_drop_order = vec![1, 4, 5, 3, 2];
    // Check the drop order for let bindings:
    {
        let _ = DropRecorder(1);
        let _val = DropRecorder(2);
        let (x, _) = (DropRecorder(3), DropRecorder(4));
        drop(DropRecorder(5));
    }
    DROP_ORDER.with(|d| {
        assert_eq!(&*d.borrow(), &expected_drop_order);
        d.borrow_mut().clear();
    });
    // Check that the drop order for destructuring assignment is the same:
    {
        let _val;
        let x;
        _ = DropRecorder(1);
        _val = DropRecorder(2);
        (x, _) = (DropRecorder(3), DropRecorder(4));
        drop(DropRecorder(5));
    }
    DROP_ORDER.with(|d| assert_eq!(&*d.borrow(), &expected_drop_order));
}
<|endoftext|>


<commit_before><commit_msg>add timesheet.rs<commit_after>extern crate time;

use std::time::{SystemTime, UNIX_EPOCH};

#[derive(Debug)]
pub struct Session {
    pub id: u64,
    pub user: &'static str,
}

impl Session {
    pub fn new() -> Session {
        let now = SystemTime::now();
        let seconds = now.duration_since(UNIX_EPOCH).unwrap().as_secs();
        Session {
            id: seconds,
            user: "Rafael",
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>GTK Clicker!<commit_after><|endoftext|>


<commit_before><commit_msg>Add lints<commit_after><|endoftext|>


<commit_before><commit_msg>libimagtimetrack: Replace read with typed read<commit_after><|endoftext|>


<commit_before><commit_msg>Fix expected link in test<commit_after><|endoftext|>


<commit_before><commit_msg>Remove Encodable impls for protocol structs/enums<commit_after><|endoftext|>