<commit_before>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Mesh loading.
//!
//! A `Mesh` describes the geometry of an object. All or part of a `Mesh` can be drawn with a
//! single draw call. A `Mesh` consists of a series of vertices, each with a certain amount of
//! user-specified attributes. These attributes are fed into shader programs. The easiest way to
//! create a mesh is to use the `#[vertex_format]` attribute on a struct, upload them into a
//! `Buffer`, and then use `Mesh::from`.

use device;
use device::attrib;

/// Describes a single attribute of a vertex buffer, including its type, name, etc.
#[deriving(Clone, PartialEq, Show)]
pub struct Attribute {
    /// A name to match the shader input
    pub name: String,
    /// Vertex buffer to contain the data
    pub buffer: device::RawBufferHandle,
    /// Format of the attribute
    pub format: attrib::Format,
}

/// A trait implemented automatically for user vertex structure by
/// `#[vertex_format] attribute
pub trait VertexFormat {
    /// Create the attributes for this type, using the given buffer.
    fn generate(Option<Self>, buffer: device::RawBufferHandle) -> Vec<Attribute>;
}

/// Describes geometry to render.
#[deriving(Clone, PartialEq, Show)]
pub struct Mesh {
    /// Number of vertices in the mesh.
    pub num_vertices: device::VertexCount,
    /// Vertex attributes to use.
    pub attributes: Vec<Attribute>,
}

impl Mesh {
    /// Create a new mesh, which is a `TriangleList` with no attributes and `nv` vertices.
    pub fn new(nv: device::VertexCount) -> Mesh {
        Mesh {
            num_vertices: nv,
            attributes: Vec::new(),
        }
    }

    /// Create a new `Mesh` from a struct that implements `VertexFormat` and a buffer.
    pub fn from_format<V: VertexFormat>(buf: device::BufferHandle<V>, nv: device::VertexCount) -> Mesh {
        Mesh {
            num_vertices: nv,
            attributes: VertexFormat::generate(None::<V>, buf.raw()),
        }
    }

    /// Create a new intanced `Mesh` given a vertex buffer and an instance buffer.
    pub fn from_format_instanced<V: VertexFormat, U: VertexFormat>(
                                 buf: device::BufferHandle<V>, nv: device::VertexCount,
                                 inst: device::BufferHandle<U>) -> Mesh {
        let per_vertex   = VertexFormat::generate(None::<V>, buf.raw());
        let per_instance = VertexFormat::generate(None::<U>, inst.raw());

        let mut attributes = per_vertex;
        for mut at in per_instance.move_iter() {
            at.format.instance_rate = 1;
            attributes.push(at);
        }

        Mesh {
            num_vertices: nv,
            attributes: attributes,
        }
    }

    /// Return a vertex slice of the whole mesh
    pub fn get_slice(&self, pt: device::PrimitiveType) -> Slice {
        VertexSlice(pt, 0, self.num_vertices)
    }
}

/// Description of a subset of `Mesh` data to render.
/// We provide a primitive type in a slice because it is how we interpret mesh
/// contents. For example, we can have a `Point` typed vertex slice to do shape
/// blending, while still rendereing it as an indexed `TriangleList`.
#[deriving(Clone, Show)]
pub enum Slice  {
    /// Render vertex data directly from the `Mesh`'s buffer, using only the vertices between the two
    /// endpoints.
    VertexSlice(device::PrimitiveType, device::VertexCount, device::VertexCount),
    /// The `IndexSlice*` buffer contains a list of indices into the `Mesh` data, so every vertex
    /// attribute does not need to be duplicated, only its position in the `Mesh`.  For example,
    /// when drawing a square, two triangles are needed.  Using only `VertexSlice`, one would need
    /// 6 separate vertices, 3 for each triangle. However, two of the vertices will be identical,
    /// wasting space for the duplicated attributes.  Instead, the `Mesh` can store 4 vertices and
    /// an `IndexSlice8` can be used instead.
    IndexSlice8(device::PrimitiveType, device::BufferHandle<u8>, device::IndexCount, device::IndexCount),
    /// As `IndexSlice8` but with `u16` indices
    IndexSlice16(device::PrimitiveType, device::BufferHandle<u16>, device::IndexCount, device::IndexCount),
    /// As `IndexSlice8` but with `u32` indices
    IndexSlice32(device::PrimitiveType, device::BufferHandle<u32>, device::IndexCount, device::IndexCount),
}

/// Describes kinds of errors that may occur in the mesh linking
#[deriving(Clone, Show)]
pub enum LinkError {
    /// An attribute index is out of supported bounds
    ErrorMeshAttribute(uint),
    /// An input index is out of supported bounds
    ErrorShaderInput(uint),
}

static BITS_PER_ATTRIBUTE: uint = 4;
static MAX_SHADER_INPUTS: uint = 64 / BITS_PER_ATTRIBUTE;
static MESH_ATTRIBUTE_MASK: uint = (1u << BITS_PER_ATTRIBUTE) - 1;

/// An iterator over mesh attributes.
pub struct AttributeIndices {
    value: u64,
}

impl Iterator<uint> for AttributeIndices {
    fn next(&mut self) -> Option<uint> {
        let id = (self.value as uint) & MESH_ATTRIBUTE_MASK;
        self.value >>= BITS_PER_ATTRIBUTE;
        Some(id)
    }
}

/// Holds a remapping table from shader inputs to mesh attributes.
pub struct Link {
    table: u64,
}

impl Link {
    /// Construct a new link from an iterator over attribute indices.
    pub fn from_iter<I: Iterator<uint>>(iter: I) -> Result<Link, LinkError> {
        let mut table = 0u64;
        for (input, attrib) in iter.enumerate() {
            if input >= MAX_SHADER_INPUTS {
                return Err(ErrorShaderInput(input))
            }else if attrib > MESH_ATTRIBUTE_MASK {
                return Err(ErrorMeshAttribute(attrib))
            }else {
                table |= attrib as u64 << (input * BITS_PER_ATTRIBUTE);
            }
        }
        Ok(Link {
            table: table,
        })
    }

    /// Convert to an iterator returning attribute indices
    pub fn attribute_indices(&self) -> AttributeIndices {
        AttributeIndices {
            value: self.table,
        }
    }
}
<commit_msg>Formatting<commit_after>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Mesh loading.
//!
//! A `Mesh` describes the geometry of an object. All or part of a `Mesh` can be drawn with a
//! single draw call. A `Mesh` consists of a series of vertices, each with a certain amount of
//! user-specified attributes. These attributes are fed into shader programs. The easiest way to
//! create a mesh is to use the `#[vertex_format]` attribute on a struct, upload them into a
//! `Buffer`, and then use `Mesh::from`.

use device;
use device::attrib;

/// Describes a single attribute of a vertex buffer, including its type, name, etc.
#[deriving(Clone, PartialEq, Show)]
pub struct Attribute {
    /// A name to match the shader input
    pub name: String,
    /// Vertex buffer to contain the data
    pub buffer: device::RawBufferHandle,
    /// Format of the attribute
    pub format: attrib::Format,
}

/// A trait implemented automatically for user vertex structure by
/// `#[vertex_format] attribute
pub trait VertexFormat {
    /// Create the attributes for this type, using the given buffer.
    fn generate(Option<Self>, buffer: device::RawBufferHandle) -> Vec<Attribute>;
}

/// Describes geometry to render.
#[deriving(Clone, PartialEq, Show)]
pub struct Mesh {
    /// Number of vertices in the mesh.
    pub num_vertices: device::VertexCount,
    /// Vertex attributes to use.
    pub attributes: Vec<Attribute>,
}

impl Mesh {
    /// Create a new mesh, which is a `TriangleList` with no attributes and `nv` vertices.
    pub fn new(nv: device::VertexCount) -> Mesh {
        Mesh {
            num_vertices: nv,
            attributes: Vec::new(),
        }
    }

    /// Create a new `Mesh` from a struct that implements `VertexFormat` and a buffer.
    pub fn from_format<V: VertexFormat>(buf: device::BufferHandle<V>, nv: device::VertexCount) -> Mesh {
        Mesh {
            num_vertices: nv,
            attributes: VertexFormat::generate(None::<V>, buf.raw()),
        }
    }

    /// Create a new intanced `Mesh` given a vertex buffer and an instance buffer.
    pub fn from_format_instanced<V: VertexFormat, U: VertexFormat>(
                                 buf: device::BufferHandle<V>, nv: device::VertexCount,
                                 inst: device::BufferHandle<U>) -> Mesh {
        let per_vertex   = VertexFormat::generate(None::<V>, buf.raw());
        let per_instance = VertexFormat::generate(None::<U>, inst.raw());

        let mut attributes = per_vertex;
        for mut at in per_instance.move_iter() {
            at.format.instance_rate = 1;
            attributes.push(at);
        }

        Mesh {
            num_vertices: nv,
            attributes: attributes,
        }
    }

    /// Return a vertex slice of the whole mesh
    pub fn get_slice(&self, pt: device::PrimitiveType) -> Slice {
        VertexSlice(pt, 0, self.num_vertices)
    }
}

/// Description of a subset of `Mesh` data to render.
/// We provide a primitive type in a slice because it is how we interpret mesh
/// contents. For example, we can have a `Point` typed vertex slice to do shape
/// blending, while still rendereing it as an indexed `TriangleList`.
#[deriving(Clone, Show)]
pub enum Slice  {
    /// Render vertex data directly from the `Mesh`'s buffer, using only the vertices between the two
    /// endpoints.
    VertexSlice(device::PrimitiveType, device::VertexCount, device::VertexCount),
    /// The `IndexSlice*` buffer contains a list of indices into the `Mesh` data, so every vertex
    /// attribute does not need to be duplicated, only its position in the `Mesh`.  For example,
    /// when drawing a square, two triangles are needed.  Using only `VertexSlice`, one would need
    /// 6 separate vertices, 3 for each triangle. However, two of the vertices will be identical,
    /// wasting space for the duplicated attributes.  Instead, the `Mesh` can store 4 vertices and
    /// an `IndexSlice8` can be used instead.
    IndexSlice8(device::PrimitiveType, device::BufferHandle<u8>, device::IndexCount, device::IndexCount),
    /// As `IndexSlice8` but with `u16` indices
    IndexSlice16(device::PrimitiveType, device::BufferHandle<u16>, device::IndexCount, device::IndexCount),
    /// As `IndexSlice8` but with `u32` indices
    IndexSlice32(device::PrimitiveType, device::BufferHandle<u32>, device::IndexCount, device::IndexCount),
}

/// Describes kinds of errors that may occur in the mesh linking
#[deriving(Clone, Show)]
pub enum LinkError {
    /// An attribute index is out of supported bounds
    ErrorMeshAttribute(uint),
    /// An input index is out of supported bounds
    ErrorShaderInput(uint),
}

static BITS_PER_ATTRIBUTE: uint = 4;
static MAX_SHADER_INPUTS: uint = 64 / BITS_PER_ATTRIBUTE;
static MESH_ATTRIBUTE_MASK: uint = (1u << BITS_PER_ATTRIBUTE) - 1;

/// An iterator over mesh attributes.
pub struct AttributeIndices {
    value: u64,
}

impl Iterator<uint> for AttributeIndices {
    fn next(&mut self) -> Option<uint> {
        let id = (self.value as uint) & MESH_ATTRIBUTE_MASK;
        self.value >>= BITS_PER_ATTRIBUTE;
        Some(id)
    }
}

/// Holds a remapping table from shader inputs to mesh attributes.
pub struct Link {
    table: u64,
}

impl Link {
    /// Construct a new link from an iterator over attribute indices.
    pub fn from_iter<I: Iterator<uint>>(iter: I) -> Result<Link, LinkError> {
        let mut table = 0u64;
        for (input, attrib) in iter.enumerate() {
            if input >= MAX_SHADER_INPUTS {
                return Err(ErrorShaderInput(input))
            } else if attrib > MESH_ATTRIBUTE_MASK {
                return Err(ErrorMeshAttribute(attrib))
            } else {
                table |= attrib as u64 << (input * BITS_PER_ATTRIBUTE);
            }
        }
        Ok(Link {
            table: table,
        })
    }

    /// Convert to an iterator returning attribute indices
    pub fn attribute_indices(&self) -> AttributeIndices {
        AttributeIndices {
            value: self.table,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix echo<commit_after><|endoftext|>


<commit_before><commit_msg>style(tmux/Window): Better styling for where<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Fix include path for release"<commit_after><|endoftext|>


<commit_before><commit_msg>Add unit test for VecRef.<commit_after>extern crate cell_gc;
#[macro_use]
extern crate cell_gc_derive;

use cell_gc::GcHeap;
use cell_gc::collections::VecRef;

#[test]
fn test_vec_ref() {
    #[derive(IntoHeap)]
    struct Car<'h> {
        wheels: VecRef<'h, String>
    }

    let mut heap = GcHeap::new();
    heap.enter(|hs| {
        let wheels = vec![
            "lf".to_string(),
            "rf".to_string(),
            "lr".to_string(),
            "rr".to_string(),
        ];
        let wheels_gc = hs.alloc(wheels);
        let car = hs.alloc(Car {
            wheels: wheels_gc
        });
        hs.force_gc();
        hs.force_gc();
        assert_eq!(car.wheels().len(), 4);
        assert_eq!(car.wheels().get(3), "rr");
    });
}
<|endoftext|>


<commit_before><commit_msg>INSERT<commit_after><|endoftext|>


<commit_before><commit_msg>is_eye<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed typo<commit_after><|endoftext|>


<commit_before>#![feature(box_syntax)]
#![feature(plugin)]
#![plugin(peg_syntax_ext)]

use std::collections::{BTreeMap, HashMap};
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;

use self::to_num::ToNum;
use self::directory_stack::DirectoryStack;
use self::input_editor::readln;
use self::peg::parse;
use self::expansion::expand_variables;

pub mod builtin;
pub mod directory_stack;
pub mod to_num;
pub mod input_editor;
pub mod peg;
pub mod expansion;

pub type Variables = BTreeMap<String, String>;

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell {
    pub variables: Variables,
    pub modes: Vec<Mode>,
    pub directory_stack: DirectoryStack,
}

impl Shell {
    /// Panics if DirectoryStack construction fails
    pub fn new() -> Self {
        Shell {
            variables: BTreeMap::new(),
            modes: vec![],
            directory_stack: DirectoryStack::new().expect(""),
        }
    }
}

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &[String]| {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&[String], &mut Shell)>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> HashMap<&'static str, Self> {
        let mut commands: HashMap<&str, Self> = HashMap::new();

        commands.insert("cd",
                        Command {
                            name: "cd",
                            help: "To change the current directory\n    cd <your_destination>",
                            main: box |args: &[String], _: &mut Shell| {
                                builtin::cd(args);
                            },
                        });

        commands.insert("exit",
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: box |_: &[String], _: &mut Shell| {},
                        });

        commands.insert("read",
                        Command {
                            name: "read",
                            help: "To read some variables\n    read <my_variable>",
                            main: box |args: &[String], shell: &mut Shell| {
                                builtin::read(args, &mut shell.variables);
                            },
                        });

        commands.insert("run",
                        Command {
                            name: "run",
                            help: "Run a script\n    run <script>",
                            main: box |args: &[String], shell: &mut Shell| {
                                builtin::run(args, &mut shell.variables);
                            },
                        });

        commands.insert("pushd",
                        Command {
                            name: "pushd",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.pushd(args);
                            },
                        });

        commands.insert("popd",
                        Command {
                            name: "popd",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.popd(args);
                            },
                        });

        commands.insert("dirs",
                        Command {
                            name: "dirs",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.dirs(args);
                            },
                        });

        // TODO: Someone should implement FromIterator for HashMap before
        //       changing the type back to HashMap
        let command_helper: HashMap<String, String> = commands.iter()
                                                              .map(|(k, v)| {
                                                                  (k.to_string(),
                                                                   v.help.to_string())
                                                              })
                                                              .collect();

        commands.insert("help",
                        Command {
                            name: "help",
                            help: "Display a little helper for a given command\n    help ls",
                            main: box move |args: &[String], _: &mut Shell| {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command) {
                                        match command_helper.get(command) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                            },
                        });

        commands
    }
}

pub struct Mode {
    value: bool,
}

fn on_command(command_string: &str, commands: &HashMap<&str, Command>, shell: &mut Shell) {
    // Show variables
    if command_string == "$" {
        for (key, value) in shell.variables.iter() {
            println!("{}={}", key, value);
        }
        return;
    }

    let mut jobs = parse(command_string);
    expand_variables(&mut jobs, &shell.variables);

    // Execute commands
    for job in jobs.iter() {
        if job.command == "if" {
            let mut value = false;

            if let Some(left) = job.args.get(0) {
                if let Some(cmp) = job.args.get(1) {
                    if let Some(right) = job.args.get(2) {
                        if cmp == "==" {
                            value = *left == *right;
                        } else if cmp == "!=" {
                            value = *left != *right;
                        } else if cmp == ">" {
                            value = left.to_num_signed() > right.to_num_signed();
                        } else if cmp == ">=" {
                            value = left.to_num_signed() >= right.to_num_signed();
                        } else if cmp == "<" {
                            value = left.to_num_signed() < right.to_num_signed();
                        } else if cmp == "<=" {
                            value = left.to_num_signed() <= right.to_num_signed();
                        } else {
                            println!("Unknown comparison: {}", cmp);
                        }
                    } else {
                        println!("No right hand side");
                    }
                } else {
                    println!("No comparison operator");
                }
            } else {
                println!("No left hand side");
            }

            shell.modes.insert(0, Mode { value: value });
            continue;
        }

        if job.command == "else" {
            if let Some(mode) = shell.modes.get_mut(0) {
                mode.value = !mode.value;
            } else {
                println!("Syntax error: else found with no previous if");
            }
            continue;
        }

        if job.command == "fi" {
            if !shell.modes.is_empty() {
                shell.modes.remove(0);
            } else {
                println!("Syntax error: fi found with no previous if");
            }
            continue;
        }

        let mut skipped: bool = false;
        for mode in shell.modes.iter() {
            if !mode.value {
                skipped = true;
                break;
            }
        }
        if skipped {
            continue;
        }

        // Set variables
        if let Some(i) = job.command.find('=') {
            let name = job.command[0..i].trim();
            let mut value = job.command[i + 1..job.command.len()].trim().to_string();

            for i in 0..job.args.len() {
                if let Some(arg) = job.args.get(i) {
                    value = value + " " + &arg;
                }
            }

            set_var(&mut shell.variables, name, &value);
            continue;
        }

        // Commands
        let mut args = job.args.clone();
        args.insert(0, job.command.clone());
        if let Some(command) = commands.get(&job.command.as_str()) {
            (*command.main)(&args, shell);
        } else {
            run_external_commmand(args, &mut shell.variables);
        }
    }
}

pub fn set_var(variables: &mut Variables, name: &str, value: &str) {
    if name.is_empty() {
        return;
    }

    if value.is_empty() {
        variables.remove(&name.to_string());
    } else {
        variables.insert(name.to_string(), value.to_string());
    }
}

fn print_prompt(modes: &[Mode]) {
    let mode = modes.iter().rev().fold(String::new(), |acc, mode| {
        acc + if mode.value { "+ " } else { "- " }
    });
    print!("{}", mode.trim_right());

    let cwd = env::current_dir().ok().map_or("?".to_string(), |ref p| p.to_str().unwrap_or("?").to_string());

    print!("ion:{}# ", cwd);
    if let Err(message) = stdout().flush() {
        println!("{}: failed to flush prompt to stdout", message);
    }
}

fn run_external_commmand(args: Vec<String>, variables: &mut Variables) {
    if let Some(path) = args.get(0) {
        let mut command = process::Command::new(path);
        for i in 1..args.len() {
            if let Some(arg) = args.get(i) {
                command.arg(arg);
            }
        }
        match command.spawn() {
            Ok(mut child) => {
                match child.wait() {
                    Ok(status) => {
                        if let Some(code) = status.code() {
                            set_var(variables, "?", &code.to_string());
                        } else {
                            println!("{}: No child exit code", path);
                        }
                    }
                    Err(err) => println!("{}: Failed to wait: {}", path, err),
                }
            }
            Err(err) => println!("{}: Failed to execute: {}", path, err),
        }
    }
}

fn main() {
    let commands = Command::map();
    let mut shell = Shell::new();

    for arg in env::args().skip(1) {
        let mut command_list = String::new();
        if let Ok(mut file) = File::open(&arg) {
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {}", message, arg);
            }
        }
        on_command(&command_list, &commands, &mut shell);

        return;
    }

    loop {

        print_prompt(&shell.modes);

        if let Some(command_original) = readln() {
            let command = command_original.trim();
            if command == "exit" {
                break;
            } else if !command.is_empty() {
                on_command(&command, &commands, &mut shell);
            }
        } else {
            break;
        }
    }
}
<commit_msg>Do requests for skylerberg<commit_after>#![feature(box_syntax)]
#![feature(plugin)]
#![plugin(peg_syntax_ext)]

use std::collections::{BTreeMap, HashMap};
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;

use self::to_num::ToNum;
use self::directory_stack::DirectoryStack;
use self::input_editor::readln;
use self::peg::parse;
use self::expansion::expand_variables;

pub mod builtin;
pub mod directory_stack;
pub mod to_num;
pub mod input_editor;
pub mod peg;
pub mod expansion;

pub type Variables = BTreeMap<String, String>;

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell {
    pub variables: Variables,
    pub modes: Vec<Mode>,
    pub directory_stack: DirectoryStack,
}

impl Shell {
    /// Panics if DirectoryStack construction fails
    pub fn new() -> Self {
        Shell {
            variables: BTreeMap::new(),
            modes: vec![],
            directory_stack: DirectoryStack::new().expect(""),
        }
    }
}

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &[String]| {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&[String], &mut Shell)>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> HashMap<&'static str, Self> {
        let mut commands: HashMap<&str, Self> = HashMap::new();

        commands.insert("cd",
                        Command {
                            name: "cd",
                            help: "To change the current directory\n    cd <your_destination>",
                            main: box |args: &[String], _: &mut Shell| {
                                builtin::cd(args);
                            },
                        });

        commands.insert("exit",
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: box |_: &[String], _: &mut Shell| {},
                        });

        commands.insert("read",
                        Command {
                            name: "read",
                            help: "To read some variables\n    read <my_variable>",
                            main: box |args: &[String], shell: &mut Shell| {
                                builtin::read(args, &mut shell.variables);
                            },
                        });

        commands.insert("run",
                        Command {
                            name: "run",
                            help: "Run a script\n    run <script>",
                            main: box |args: &[String], shell: &mut Shell| {
                                builtin::run(args, &mut shell.variables);
                            },
                        });

        commands.insert("pushd",
                        Command {
                            name: "pushd",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.pushd(args);
                            },
                        });

        commands.insert("popd",
                        Command {
                            name: "popd",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.popd(args);
                            },
                        });

        commands.insert("dirs",
                        Command {
                            name: "dirs",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: box |args: &[String], shell: &mut Shell| {
                                shell.directory_stack.dirs(args);
                            },
                        });

        // TODO: Someone should implement FromIterator for HashMap before
        //       changing the type back to HashMap
        let command_helper: HashMap<String, String> = commands.iter()
                                                              .map(|(k, v)| {
                                                                  (k.to_string(),
                                                                   v.help.to_string())
                                                              })
                                                              .collect();

        commands.insert("help",
                        Command {
                            name: "help",
                            help: "Display a little helper for a given command\n    help ls",
                            main: box move |args: &[String], _: &mut Shell| {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command) {
                                        match command_helper.get(command) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                            },
                        });

        commands
    }
}

pub struct Mode {
    value: bool,
}

fn on_command(command_string: &str, commands: &HashMap<&str, Command>, shell: &mut Shell) {
    // Show variables
    if command_string == "$" {
        for (key, value) in shell.variables.iter() {
            println!("{}={}", key, value);
        }
        return;
    }

    let mut jobs = parse(command_string);
    expand_variables(&mut jobs, &shell.variables);

    // Execute commands
    for job in jobs.iter() {
        if job.command == "if" {
            let mut value = false;

            if let Some(left) = job.args.get(0) {
                if let Some(cmp) = job.args.get(1) {
                    if let Some(right) = job.args.get(2) {
                        if cmp == "==" {
                            value = *left == *right;
                        } else if cmp == "!=" {
                            value = *left != *right;
                        } else if cmp == ">" {
                            value = left.to_num_signed() > right.to_num_signed();
                        } else if cmp == ">=" {
                            value = left.to_num_signed() >= right.to_num_signed();
                        } else if cmp == "<" {
                            value = left.to_num_signed() < right.to_num_signed();
                        } else if cmp == "<=" {
                            value = left.to_num_signed() <= right.to_num_signed();
                        } else {
                            println!("Unknown comparison: {}", cmp);
                        }
                    } else {
                        println!("No right hand side");
                    }
                } else {
                    println!("No comparison operator");
                }
            } else {
                println!("No left hand side");
            }

            shell.modes.insert(0, Mode { value: value });
            continue;
        }

        if job.command == "else" {
            if let Some(mode) = shell.modes.get_mut(0) {
                mode.value = !mode.value;
            } else {
                println!("Syntax error: else found with no previous if");
            }
            continue;
        }

        if job.command == "fi" {
            if !shell.modes.is_empty() {
                shell.modes.remove(0);
            } else {
                println!("Syntax error: fi found with no previous if");
            }
            continue;
        }

        let mut skipped: bool = false;
        for mode in shell.modes.iter() {
            if !mode.value {
                skipped = true;
                break;
            }
        }
        if skipped {
            continue;
        }

        // Set variables
        if let Some(i) = job.command.find('=') {
            let name = job.command[0..i].trim();
            let mut value = job.command[i + 1..job.command.len()].trim().to_string();

            for i in 0..job.args.len() {
                if let Some(arg) = job.args.get(i) {
                    value = value + " " + &arg;
                }
            }

            set_var(&mut shell.variables, name, &value);
            continue;
        }

        // Commands
        let mut args = job.args.clone();
        args.insert(0, job.command.clone());
        if let Some(command) = commands.get(&job.command.as_str()) {
            (*command.main)(&args, shell);
        } else {
            run_external_commmand(args, &mut shell.variables);
        }
    }
}

pub fn set_var(variables: &mut Variables, name: &str, value: &str) {
    if name.is_empty() {
        return;
    }

    if value.is_empty() {
        variables.remove(&name.to_string());
    } else {
        variables.insert(name.to_string(), value.to_string());
    }
}

fn print_prompt(modes: &[Mode]) {
    let prompt_prefix = modes.iter().rev().fold(String::new(), |acc, mode| {
        acc + if mode.value { "+ " } else { "- " }
    });
    print!("{}", prompt_prefix);

    let cwd = env::current_dir().ok().map_or("?".to_string(), |ref p| p.to_str().unwrap_or("?").to_string());

    print!("ion:{}# ", cwd);
    if let Err(message) = stdout().flush() {
        println!("{}: failed to flush prompt to stdout", message);
    }
}

fn run_external_commmand(args: Vec<String>, variables: &mut Variables) {
    if let Some(path) = args.get(0) {
        let mut command = process::Command::new(path);
        for i in 1..args.len() {
            if let Some(arg) = args.get(i) {
                command.arg(arg);
            }
        }
        match command.spawn() {
            Ok(mut child) => {
                match child.wait() {
                    Ok(status) => {
                        if let Some(code) = status.code() {
                            set_var(variables, "?", &code.to_string());
                        } else {
                            println!("{}: No child exit code", path);
                        }
                    }
                    Err(err) => println!("{}: Failed to wait: {}", path, err),
                }
            }
            Err(err) => println!("{}: Failed to execute: {}", path, err),
        }
    }
}

fn main() {
    let commands = Command::map();
    let mut shell = Shell::new();

    for arg in env::args().skip(1) {
        let mut command_list = String::new();
        if let Ok(mut file) = File::open(&arg) {
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {}", message, arg);
            }
        }
        on_command(&command_list, &commands, &mut shell);

        return;
    }

    loop {

        print_prompt(&shell.modes);

        if let Some(command_original) = readln() {
            let command = command_original.trim();
            if command == "exit" {
                break;
            } else if !command.is_empty() {
                on_command(&command, &commands, &mut shell);
            }
        } else {
            break;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove index on title<commit_after><|endoftext|>


<commit_before><commit_msg>Add breakpoints and a way to continue<commit_after><|endoftext|>


<commit_before><commit_msg>Added getMusicFolders.<commit_after><|endoftext|>


<commit_before><commit_msg>disable reconnect<commit_after><|endoftext|>


<commit_before><commit_msg>day 7 solved (long overdue).<commit_after>use std::collections::HashMap;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;
use std::cell::RefCell;

// necessary in order to enforce copy rather than move semantics!
#[derive(Clone)]
enum Gate {
    ConstVal(u16),
    Const(String),
    Not(String),
    And(String, String),
    Or(String, String),
    LShift(String, u16),
    RShift(String, u16)
}

struct Node {
    orig: Gate,
    val : u16,
    ideg: u16,
    adj : Vec<String>
}

struct Graph {
    names: HashMap<String, usize>,
    nodes: Vec<RefCell<Node>>
}

impl Node {
    fn new() -> Node {
        Node {
            orig: Gate::ConstVal(0), //dummy gate
            val : 0,
            ideg: 0,
            adj : Vec::new()
        }
    }
}

impl Graph {
    fn new() -> Graph {
        Graph {
            names: HashMap::new(),
            nodes: Vec::new()
        }
    }

    fn spawn_if_missing(&mut self, name: String) {
        if !self.names.contains_key(&name) {
            let index = self.nodes.len();
            self.nodes.push(RefCell::new(Node::new()));
            self.names.insert(name, index);
        }
    }

    fn spawn_or_parse_if_missing(&mut self, name: String) {
        if !self.names.contains_key(&name) {
            match name.parse() {
                Ok(num) => {
                    self.spawn_if_missing(name.clone());
                    let mut node = self.nodes[self.names[&name]].borrow_mut();
                    node.orig = Gate::ConstVal(num);
                }
                Err(_)  => {
                    let index = self.nodes.len();
                    self.nodes.push(RefCell::new(Node::new()));
                    self.names.insert(name, index);
                }
            }
        }
    }

    fn add_edge(&mut self, from: String, to: String) {
        let mut node_a = self.nodes[self.names[&from]].borrow_mut();
        node_a.adj.push(to.clone());

    }

    fn remove_edge(&mut self, from: String, to: String) {
        let mut node_a = self.nodes[self.names[&from]].borrow_mut();
        let index = node_a.adj.iter().position(|x| *x == to).unwrap();
        node_a.adj.remove(index);
    }

    fn add_connection(&mut self, gate: Gate, output: String) {
        self.spawn_if_missing(output.clone());
        {
            let mut node = self.nodes[self.names[&output]].borrow_mut();
            node.orig = gate.clone();
        }
        match gate {
            Gate::ConstVal(_)    => { },
            Gate::Const(x)       => {
                self.spawn_or_parse_if_missing(x.clone());
                self.add_edge(x.clone(), output.clone());
            },
            Gate::Not(x)         => {
                self.spawn_or_parse_if_missing(x.clone());
                self.add_edge(x.clone(), output.clone());
            },
            Gate::And(x, y)      => {
                self.spawn_or_parse_if_missing(x.clone());
                self.spawn_or_parse_if_missing(y.clone());
                self.add_edge(x.clone(), output.clone());
                self.add_edge(y.clone(), output.clone());
            },
            Gate::Or(x, y)       => {
                self.spawn_or_parse_if_missing(x.clone());
                self.spawn_or_parse_if_missing(y.clone());
                self.add_edge(x.clone(), output.clone());
                self.add_edge(y.clone(), output.clone());
            },
            Gate::LShift(x, _)   => {
                self.spawn_or_parse_if_missing(x.clone());
                self.add_edge(x.clone(), output.clone());
            },
            Gate::RShift(x, _)   => {
                self.spawn_or_parse_if_missing(x.clone());
                self.add_edge(x.clone(), output.clone());
            }
        }
    }

    fn cut(&mut self, name: String) {
        let old_gate;
        {
            let mut node = self.nodes[self.names[&name]].borrow_mut();
            old_gate = node.orig.clone();
            node.orig = Gate::ConstVal(0); // dummy gate
        }
        match old_gate {
            Gate::ConstVal(_)    => { },
            Gate::Const(x)       => {
                self.remove_edge(x.clone(), name.clone());
            },
            Gate::Not(x)         => {
                self.remove_edge(x.clone(), name.clone());
            },
            Gate::And(x, y)      => {
                self.remove_edge(x.clone(), name.clone());
                self.remove_edge(y.clone(), name.clone());
            },
            Gate::Or(x, y)       => {
                self.remove_edge(x.clone(), name.clone());
                self.remove_edge(y.clone(), name.clone());
            },
            Gate::LShift(x, _)   => {
                self.remove_edge(x.clone(), name.clone());
            },
            Gate::RShift(x, _)   => {
                self.remove_edge(x.clone(), name.clone());
            }
        }
    }

    fn recompute_indegrees(&mut self) {
        for ref_node in self.nodes.iter() {
            ref_node.borrow_mut().ideg = 0;
        }

        for ref_node in self.nodes.iter() {
            let node = ref_node.borrow();
            let neighbours = node.adj.clone();
            for n_name in neighbours.iter() {
                let mut neighbour = self.nodes[self.names[n_name]].borrow_mut();
                neighbour.ideg += 1;
            }
        }
    }

    fn expand(&mut self, name: String, queue: &mut Vec<String>) -> u16 {
        let mut node = self.nodes[self.names[&name]].borrow_mut();
        node.val = match node.orig.clone() {
            Gate::ConstVal(val)  => val,
            Gate::Const(x)       => self.nodes[self.names[&x]].borrow().val,
            Gate::Not(x)         => !self.nodes[self.names[&x]].borrow().val,
            Gate::And(x, y)      => {
                self.nodes[self.names[&x]].borrow().val
                & self.nodes[self.names[&y]].borrow().val
            },
            Gate::Or(x, y)       => {
                self.nodes[self.names[&x]].borrow().val
                | self.nodes[self.names[&y]].borrow().val
            },
            Gate::LShift(x, val) => self.nodes[self.names[&x]].borrow().val << val,
            Gate::RShift(x, val) => self.nodes[self.names[&x]].borrow().val >> val
        };
        let neighbours = node.adj.to_owned();
        for n_name in neighbours.iter() {
            let mut neighbour = self.nodes[self.names[n_name]].borrow_mut();
            neighbour.ideg -= 1;
            if neighbour.ideg == 0 {
                queue.push(n_name.clone());
            }
        }
        node.val
    }

    fn toposort(&mut self) -> Vec<(String, u16)> {
        let mut ret   = Vec::new();
        let mut queue = Vec::new();

        self.recompute_indegrees();

        for (name, index) in self.names.iter() {
            if self.nodes[*index].borrow().ideg == 0 {
                queue.push(name.clone());
            }
        }

        while !queue.is_empty() {
            let name = queue[0].clone();
            let val = self.expand(name.clone(), &mut queue);
            ret.push((name, val));
            queue.swap_remove(0);
        }

        ret
    }
}

fn main() {
    let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
    	.ok()
    	.expect("Failed to open the input file!");

	let mut input = String::new();
	f.read_to_string(&mut input)
		.ok()
		.expect("Failed to read from the input file!");

    let mut graph = Graph::new();

    for line in input.lines() {
        let parts: Vec<_> = line.split_whitespace().collect();

        let gate: Gate;
        let output;

        if parts[0] == "NOT" {
            gate = Gate::Not(parts[1].to_string());
            output = parts[3];
        } else if parts[1] == "AND" {
            gate = Gate::And(parts[0].to_string(), parts[2].to_string());
            output = parts[4];
        } else if parts[1] == "OR" {
            gate = Gate::Or(parts[0].to_string(), parts[2].to_string());
            output = parts[4];
        } else if parts[1] == "LSHIFT" {
            gate = Gate::LShift(parts[0].to_string(), parts[2].parse().ok().expect("Could not parse into an integer!"));
            output = parts[4];
        } else if parts[1] == "RSHIFT" {
            gate = Gate::RShift(parts[0].to_string(), parts[2].parse().ok().expect("Could not parse into an integer!"));
            output = parts[4];
        } else { // const or assign
            gate = Gate::Const(parts[0].to_string());
            output = parts[2];
        }

        graph.add_connection(gate, output.to_string());
    }

    let mut sig_a = 0;

    for (id, val) in graph.toposort() {
        if id == "a" {
            sig_a = val;
        }
    }

    println!("The signal on wire a is {}.", sig_a);

    graph.cut("b".to_string());
    graph.add_connection(Gate::ConstVal(sig_a), "b".to_string());

    for (id, val) in graph.toposort() {
        if id == "a" {
            sig_a = val;
        }
    }

    println!("The new signal on wire a is {}.", sig_a);

}<|endoftext|>


<commit_before><commit_msg>traits are actually mixing really well with structs<commit_after><|endoftext|>


<commit_before><commit_msg>Add new function SessionStateResponse::single_packet.<commit_after><|endoftext|>


<commit_before><commit_msg>Upgrade to rustc 81eeec094 2014-11-21.<commit_after><|endoftext|>


<commit_before><commit_msg>refactor(HashSalt): add explanations and simplify code<commit_after><|endoftext|>


<commit_before><commit_msg>Add source code<commit_after>#[desc = "A hello world Rust package."];
#[license = "MIT"];

pub fn world() {
    println("Hello, World!");
}
<|endoftext|>


<commit_before><commit_msg>Test for the array-Value roundtrip failure (#404)<commit_after>use ron::{
    error::{Error, Position, SpannedError},
    value::{Number, Value},
};

#[test]
fn test_array() {
    let array: [i32; 3] = [1, 2, 3];

    let ser = ron::to_string(&array).unwrap();
    assert_eq!(ser, "(1,2,3)");

    let de: [i32; 3] = ron::from_str(&ser).unwrap();
    assert_eq!(de, array);

    let value: Value = ron::from_str(&ser).unwrap();
    assert_eq!(
        value,
        Value::Seq(vec![
            Value::Number(Number::from(1)),
            Value::Number(Number::from(2)),
            Value::Number(Number::from(3)),
        ])
    );

    let ser = ron::to_string(&value).unwrap();
    assert_eq!(ser, "[1,2,3]");

    let de: [i32; 3] = value.into_rust().unwrap();
    assert_eq!(de, array);

    // FIXME: fails and hence arrays do not roundtrip
    let de: SpannedError = ron::from_str::<[i32; 3]>(&ser).unwrap_err();
    assert_eq!(
        de,
        SpannedError {
            code: Error::ExpectedStructLike,
            position: Position { line: 1, col: 1 },
        }
    );

    let value: Value = ron::from_str(&ser).unwrap();
    assert_eq!(
        value,
        Value::Seq(vec![
            Value::Number(Number::from(1)),
            Value::Number(Number::from(2)),
            Value::Number(Number::from(3)),
        ])
    );
}
<|endoftext|>


<commit_before><commit_msg>LeetCode:  953. Verifying an Alien Dictionary<commit_after>// use std::collections::HashMap;

#[derive(Debug)]
struct Solution {}

impl Solution {
    pub fn is_alien_sorted(words: Vec<String>, order: String) -> bool {
        // let dict = order.chars().zip("abcdefghijklmnopqrstuvwxyz".chars()).collect::<HashMap<char, char>>();
        let mut dict2: Vec<char> = vec![' '; 26];
        order.chars().enumerate().for_each(|(i, v)| {
            dict2[(v as u8 - 'a' as u8) as usize] = ('a' as u8 + i as u8) as char;
        });
        let sorted = words.iter().map(|a| {
            a.chars().map(|c| {
                // dict.get(&c).unwrap()
                dict2.get((c as u8 - 'a' as u8) as usize).unwrap()
            }).collect::<String>()
        }).collect::<Vec<String>>();

        sorted.windows(2).all(|w| w[0] <= w[1])
    }
}

fn main() {
    println!("{:?}", Solution::is_alien_sorted(vec![String::from("abc"), String::from("abcdef")], String::from("bacdefghijklmnopqrstuvwxzy")));
}
<|endoftext|>


<commit_before><commit_msg>Consistent naming and List::Compound proto_len missing<commit_after><|endoftext|>


<commit_before><commit_msg>Usage of unsage random generator. Swapped for OsRng generator.<commit_after><|endoftext|>


<commit_before>// 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.

#[test]
fn test_clone() {
    let a = (1i, "2");
    let b = a.clone();
    assert_eq!(a, b);
}

#[test]
fn test_getters() {
    macro_rules! test_getter(
        ($x:expr, $valN:ident, $refN:ident, $mutN:ident,
         $init:expr, $incr:expr, $result:expr) => ({
            assert_eq!($x.$valN(), $init);
            assert_eq!(*$x.$refN(), $init);
            *$x.$mutN() += $incr;
            assert_eq!(*$x.$refN(), $result);
        })
    )
    let mut x = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64);
    test_getter!(x, val0,  ref0,  mut0,  0,    1,   1);
    test_getter!(x, val1,  ref1,  mut1,  1,    1,   2);
    test_getter!(x, val2,  ref2,  mut2,  2,    1,   3);
    test_getter!(x, val3,  ref3,  mut3,  3,    1,   4);
    test_getter!(x, val4,  ref4,  mut4,  4,    1,   5);
    test_getter!(x, val5,  ref5,  mut5,  5,    1,   6);
    test_getter!(x, val6,  ref6,  mut6,  6,    1,   7);
    test_getter!(x, val7,  ref7,  mut7,  7,    1,   8);
    test_getter!(x, val8,  ref8,  mut8,  8,    1,   9);
    test_getter!(x, val9,  ref9,  mut9,  9,    1,   10);
    test_getter!(x, val10, ref10, mut10, 10.0, 1.0, 11.0);
    test_getter!(x, val11, ref11, mut11, 11.0, 1.0, 12.0);
}

#[test]
fn test_tuple_cmp() {
    let (small, big) = ((1u, 2u, 3u), (3u, 2u, 1u));

    let nan = 0.0f64/0.0;

    // PartialEq
    assert_eq!(small, small);
    assert_eq!(big, big);
    assert!(small != big);
    assert!(big != small);

    // PartialOrd
    assert!(small < big);
    assert!(!(small < small));
    assert!(!(big < small));
    assert!(!(big < big));

    assert!(small <= small);
    assert!(big <= big);

    assert!(big > small);
    assert!(small >= small);
    assert!(big >= small);
    assert!(big >= big);

    assert!(!((1.0f64, 2.0f64) < (nan, 3.0)));
    assert!(!((1.0f64, 2.0f64) <= (nan, 3.0)));
    assert!(!((1.0f64, 2.0f64) > (nan, 3.0)));
    assert!(!((1.0f64, 2.0f64) >= (nan, 3.0)));
    assert!(((1.0f64, 2.0f64) < (2.0, nan)));
    assert!(!((2.0f64, 2.0f64) < (2.0, nan)));

    // Ord
    assert!(small.cmp(&small) == Equal);
    assert!(big.cmp(&big) == Equal);
    assert!(small.cmp(&big) == Less);
    assert!(big.cmp(&small) == Greater);
}

#[test]
fn test_show() {
    let s = format!("{}", (1i,));
    assert_eq!(s, "(1,)");
    let s = format!("{}", (1i, true));
    assert_eq!(s, "(1, true)");
    let s = format!("{}", (1i, "hi", true));
    assert_eq!(s, "(1, hi, true)");
}
<commit_msg>rollup merge of #19911: mdinger/tuple_tests2<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.

#[test]
fn test_clone() {
    let a = (1i, "2");
    let b = a.clone();
    assert_eq!(a, b);
}

#[test]
fn test_tuple_cmp() {
    let (small, big) = ((1u, 2u, 3u), (3u, 2u, 1u));

    let nan = 0.0f64/0.0;

    // PartialEq
    assert_eq!(small, small);
    assert_eq!(big, big);
    assert!(small != big);
    assert!(big != small);

    // PartialOrd
    assert!(small < big);
    assert!(!(small < small));
    assert!(!(big < small));
    assert!(!(big < big));

    assert!(small <= small);
    assert!(big <= big);

    assert!(big > small);
    assert!(small >= small);
    assert!(big >= small);
    assert!(big >= big);

    assert!(!((1.0f64, 2.0f64) < (nan, 3.0)));
    assert!(!((1.0f64, 2.0f64) <= (nan, 3.0)));
    assert!(!((1.0f64, 2.0f64) > (nan, 3.0)));
    assert!(!((1.0f64, 2.0f64) >= (nan, 3.0)));
    assert!(((1.0f64, 2.0f64) < (2.0, nan)));
    assert!(!((2.0f64, 2.0f64) < (2.0, nan)));

    // Ord
    assert!(small.cmp(&small) == Equal);
    assert!(big.cmp(&big) == Equal);
    assert!(small.cmp(&big) == Less);
    assert!(big.cmp(&small) == Greater);
}

#[test]
fn test_show() {
    let s = format!("{}", (1i,));
    assert_eq!(s, "(1,)");
    let s = format!("{}", (1i, true));
    assert_eq!(s, "(1, true)");
    let s = format!("{}", (1i, "hi", true));
    assert_eq!(s, "(1, hi, true)");
}
<|endoftext|>


<commit_before><commit_msg>Split rendering from fetching for front page.<commit_after><|endoftext|>


<commit_before>// Data structures for storing garbage to be freed later (once the
// epochs have sufficiently advanced).
//
// In general, we try to manage the garbage thread locally whenever
// possible. Each thread keep track of three bags of garbage. But if a
// thread is exiting, these bags must be moved into the global garbage
// bags.

use std::ptr;
use std::mem;
use std::sync::atomic::AtomicPtr;
use std::sync::atomic::Ordering::{Relaxed, Release};

use mem::ZerosValid;

/// One item of garbage.
///
/// Stores enough information to do a deallocation.
struct Item {
    ptr: *mut u8,
    free: unsafe fn(*mut u8),
}

/// A single, thread-local bag of garbage.
pub struct Bag(Vec<Item>);

impl Bag {
    fn new() -> Bag {
        Bag(vec![])
    }

    fn insert<T>(&mut self, elem: *mut T) {
        let size = mem::size_of::<T>();
        if size > 0 {
            self.0.push(Item {
                ptr: elem as *mut u8,
                free: free::<T>,
            })
        }
        unsafe fn free<T>(t: *mut u8) {
            drop(Vec::from_raw_parts(t as *mut T, 0, 1));
        }
    }

    fn len(&self) -> usize {
        self.0.len()
    }

    /// Deallocate all garbage in the bag
    pub unsafe fn collect(&mut self) {
        let mut data = mem::replace(&mut self.0, Vec::new());
        for item in data.iter() {
            (item.free)(item.ptr);
        }
        data.truncate(0);
        self.0 = data;
    }
}

// needed because the bags store raw pointers.
unsafe impl Send for Bag {}
unsafe impl Sync for Bag {}

/// A thread-local set of garbage bags.
// FIXME: switch this to use modular arithmetic and accessors instead
pub struct Local {
    /// Garbage added at least one epoch behind the current local epoch
    pub old: Bag,
    /// Garbage added in the current local epoch or earlier
    pub cur: Bag,
    /// Garbage added in the current *global* epoch
    pub new: Bag,
}

impl Local {
    pub fn new() -> Local {
        Local {
            old: Bag::new(),
            cur: Bag::new(),
            new: Bag::new(),
        }
    }

    pub fn reclaim<T>(&mut self, elem: *mut T) {
        self.new.insert(elem)
    }

    /// Collect one epoch of garbage, rotating the local garbage bags.
    pub unsafe fn collect(&mut self) {
        let ret = self.old.collect();
        mem::swap(&mut self.old, &mut self.cur);
        mem::swap(&mut self.cur, &mut self.new);
        ret
    }

    pub fn size(&self) -> usize {
        self.old.len() + self.cur.len()
    }
}

/// A concurrent garbage bag, currently based on Treiber's stack.
///
/// The elements are themselves owned `Bag`s.
pub struct ConcBag {
    head: AtomicPtr<Node>,
}

unsafe impl ZerosValid for ConcBag {}

struct Node {
    data: Bag,
    next: AtomicPtr<Node>,
}

impl ConcBag {
    pub fn insert(&self, t: Bag){
        let n = Box::into_raw(Box::new(
            Node { data: t, next: AtomicPtr::new(ptr::null_mut()) }));
        loop {
            let head = self.head.load(Relaxed);
            unsafe { (*n).next.store(head, Relaxed) };
            if self.head.compare_and_swap(head, n, Release) == head { break }
        }
    }

    pub unsafe fn collect(&self) {
        let mut head = self.head.load(Relaxed);
        self.head.store(ptr::null_mut(), Relaxed);

        while head != ptr::null_mut() {
            let mut n = Box::from_raw(head);
            n.data.collect();
            head = n.next.load(Relaxed);
        }
    }
}
<commit_msg>Fixing race condition in garbage collection<commit_after>// Data structures for storing garbage to be freed later (once the
// epochs have sufficiently advanced).
//
// In general, we try to manage the garbage thread locally whenever
// possible. Each thread keep track of three bags of garbage. But if a
// thread is exiting, these bags must be moved into the global garbage
// bags.

use std::ptr;
use std::mem;
use std::sync::atomic::AtomicPtr;
use std::sync::atomic::Ordering::{Relaxed, Release, Acquire};

use mem::ZerosValid;

/// One item of garbage.
///
/// Stores enough information to do a deallocation.
struct Item {
    ptr: *mut u8,
    free: unsafe fn(*mut u8),
}

/// A single, thread-local bag of garbage.
pub struct Bag(Vec<Item>);

impl Bag {
    fn new() -> Bag {
        Bag(vec![])
    }

    fn insert<T>(&mut self, elem: *mut T) {
        let size = mem::size_of::<T>();
        if size > 0 {
            self.0.push(Item {
                ptr: elem as *mut u8,
                free: free::<T>,
            })
        }
        unsafe fn free<T>(t: *mut u8) {
            drop(Vec::from_raw_parts(t as *mut T, 0, 1));
        }
    }

    fn len(&self) -> usize {
        self.0.len()
    }

    /// Deallocate all garbage in the bag
    pub unsafe fn collect(&mut self) {
        let mut data = mem::replace(&mut self.0, Vec::new());
        for item in data.iter() {
            (item.free)(item.ptr);
        }
        data.truncate(0);
        self.0 = data;
    }
}

// needed because the bags store raw pointers.
unsafe impl Send for Bag {}
unsafe impl Sync for Bag {}

/// A thread-local set of garbage bags.
// FIXME: switch this to use modular arithmetic and accessors instead
pub struct Local {
    /// Garbage added at least one epoch behind the current local epoch
    pub old: Bag,
    /// Garbage added in the current local epoch or earlier
    pub cur: Bag,
    /// Garbage added in the current *global* epoch
    pub new: Bag,
}

impl Local {
    pub fn new() -> Local {
        Local {
            old: Bag::new(),
            cur: Bag::new(),
            new: Bag::new(),
        }
    }

    pub fn reclaim<T>(&mut self, elem: *mut T) {
        self.new.insert(elem)
    }

    /// Collect one epoch of garbage, rotating the local garbage bags.
    pub unsafe fn collect(&mut self) {
        let ret = self.old.collect();
        mem::swap(&mut self.old, &mut self.cur);
        mem::swap(&mut self.cur, &mut self.new);
        ret
    }

    pub fn size(&self) -> usize {
        self.old.len() + self.cur.len()
    }
}

/// A concurrent garbage bag, currently based on Treiber's stack.
///
/// The elements are themselves owned `Bag`s.
pub struct ConcBag {
    head: AtomicPtr<Node>,
}

unsafe impl ZerosValid for ConcBag {}

struct Node {
    data: Bag,
    next: AtomicPtr<Node>,
}

impl ConcBag {
    pub fn insert(&self, t: Bag){
        let n = Box::into_raw(Box::new(
            Node { data: t, next: AtomicPtr::new(ptr::null_mut()) }));
        loop {
            let head = self.head.load(Relaxed);
            unsafe { (*n).next.store(head, Relaxed) };
            if self.head.compare_and_swap(head, n, Release) == head { break }
        }
    }

    pub unsafe fn collect(&self) {
        // check to avoid xchg instruction
        // when no garbage exists
        let mut head = self.head.load(Relaxed);
        if head != ptr::null_mut() {
            head = self.head.swap(ptr::null_mut(), Acquire);

            while head != ptr::null_mut() {
                let mut n = Box::from_raw(head);
                n.data.collect();
                head = n.next.load(Relaxed);
            }
        }
    }
}
<|endoftext|>


<commit_before>use quote::{ToTokens, Tokens};
use syn::punctuated::Pair;
use syn::synom::Synom;
use syn::{Expr, Field, Ident, Meta};

mod metadata;
mod request;
mod response;

// use parse::Entry;
use self::metadata::Metadata;
use self::request::Request;
use self::response::Response;

// pub fn strip_serde_attrs(field: &Field) -> Field {
//     let mut field = field.clone();

//     field.attrs = field.attrs.into_iter().filter(|attr| {
//         let (attr_ident, _) = match attr.value {
//             Meta::List(ref attr_ident, _) => {
//                 (attr_ident, ())
//             }
//             _ => return true,
//         };

//         if attr_ident != "serde" {
//             return true;
//         }

//         false
//     }).collect();

//     field
// }

pub struct Api {
    metadata: Metadata,
    request: Request,
    response: Response,
}

impl From<Vec<Expr>> for Api {
    fn from(exprs: Vec<Expr>) -> Self {
        if exprs.len() != 3 {
            panic!("ruma_api! expects 3 blocks: metadata, request, and response");
        }

        let mut metadata = None;
        let mut request = None;
        let mut response = None;

        for expr in exprs {
            let expr = match expr {
                Expr::Struct(expr) => expr,
                _ => panic!("ruma_api! blocks should use struct syntax"),
            };

            let segments = expr.path.segments;

            if segments.len() != 1 {
                panic!("ruma_api! blocks must be one of: metadata, request, or response");
            }

            let Pair::End(last_segment) = segments.last().unwrap();

            match last_segment.ident.as_ref() {
                "metadata" => metadata = Some(expr.into()),
                "request" => request = Some(expr.into()),
                "response" => response = Some(expr.into()),
                _ => panic!("ruma_api! blocks must be one of: metadata, request, or response"),
            }
        }

        if metadata.is_none() {
            panic!("ruma_api! is missing metadata");
        }

        if request.is_none() {
            panic!("ruma_api! is missing request");
        }

        if response.is_none() {
            panic!("ruma_api! is missing response");
        }

        Api {
            metadata: metadata.unwrap(),
            request: request.unwrap(),
            response: response.unwrap(),
        }

    }
}

pub struct Exprs {
    pub inner: Vec<Expr>,
}

impl Synom for Exprs {
    named!(parse -> Self, do_parse!(
        exprs: many0!(syn!(Expr)) >>
        (Exprs {
            inner: exprs,
        })
    ));
}
// impl ToTokens for Api {
//     fn to_tokens(&self, tokens: &mut Tokens) {
//         let description = &self.metadata.description;
//         let method = &self.metadata.method;
//         let name = &self.metadata.name;
//         let path = &self.metadata.path;
//         let rate_limited = &self.metadata.rate_limited;
//         let requires_authentication = &self.metadata.requires_authentication;

//         let request_types = {
//             let mut tokens = Tokens::new();
//             self.request.to_tokens(&mut tokens);
//             tokens
//         };
//         let response_types = {
//             let mut tokens = Tokens::new();
//             self.response.to_tokens(&mut tokens);
//             tokens
//         };

//         let set_request_path = if self.request.has_path_fields() {
//             let path_str_quoted = path.as_str();
//             assert!(
//                 path_str_quoted.starts_with('"') && path_str_quoted.ends_with('"'),
//                 "path needs to be a string literal"
//             );

//             let path_str = &path_str_quoted[1 .. path_str_quoted.len() - 1];

//             assert!(path_str.starts_with('/'), "path needs to start with '/'");
//             assert!(
//                 path_str.chars().filter(|c| *c == ':').count() == self.request.path_field_count(),
//                 "number of declared path parameters needs to match amount of placeholders in path"
//             );

//             let request_path_init_fields = self.request.request_path_init_fields();

//             let mut tokens = quote! {
//                 let request_path = RequestPath {
//                     #request_path_init_fields
//                 };

//                 // This `unwrap()` can only fail when the url is a
//                 // cannot-be-base url like `mailto:` or `data:`, which is not
//                 // the case for our placeholder url.
//                 let mut path_segments = url.path_segments_mut().unwrap();
//             };

//             for segment in path_str[1..].split('/') {
//                 tokens.append(quote! {
//                     path_segments.push
//                 });

//                 tokens.append("(");

//                 if segment.starts_with(':') {
//                     tokens.append("&request_path.");
//                     tokens.append(&segment[1..]);
//                     tokens.append(".to_string()");
//                 } else {
//                     tokens.append("\"");
//                     tokens.append(segment);
//                     tokens.append("\"");
//                 }

//                 tokens.append(");");
//             }

//             tokens
//         } else {
//             quote! {
//                 url.set_path(metadata.path);
//             }
//         };

//         let set_request_query = if self.request.has_query_fields() {
//             let request_query_init_fields = self.request.request_query_init_fields();

//             quote! {
//                 let request_query = RequestQuery {
//                     #request_query_init_fields
//                 };

//                 url.set_query(Some(&::serde_urlencoded::to_string(request_query)?));
//             }
//         } else {
//             Tokens::new()
//         };

//         let add_body_to_request = if let Some(field) = self.request.newtype_body_field() {
//             let field_name = field.ident.as_ref().expect("expected body field to have a name");

//             quote! {
//                 let request_body = RequestBody(request.#field_name);

//                 hyper_request.set_body(::serde_json::to_vec(&request_body)?);
//             }
//         } else if self.request.has_body_fields() {
//             let request_body_init_fields = self.request.request_body_init_fields();

//             quote! {
//                 let request_body = RequestBody {
//                     #request_body_init_fields
//                 };

//                 hyper_request.set_body(::serde_json::to_vec(&request_body)?);
//             }
//         } else {
//             Tokens::new()
//         };

//         let deserialize_response_body = if let Some(field) = self.response.newtype_body_field() {
//             let field_type = &field.ty;
//             let mut tokens = Tokens::new();

//             tokens.append(quote! {
//                 let future_response = hyper_response.body()
//                     .fold::<_, _, Result<_, ::std::io::Error>>(Vec::new(), |mut bytes, chunk| {
//                         bytes.write_all(&chunk)?;

//                         Ok(bytes)
//                     })
//                     .map_err(::ruma_api::Error::from)
//                     .and_then(|bytes| {
//                         ::serde_json::from_slice::<#field_type>(bytes.as_slice())
//                             .map_err(::ruma_api::Error::from)
//                     })
//             });

//             tokens.append(".and_then(move |response_body| {");

//             tokens
//         } else if self.response.has_body_fields() {
//             let mut tokens = Tokens::new();

//             tokens.append(quote! {
//                 let future_response = hyper_response.body()
//                     .fold::<_, _, Result<_, ::std::io::Error>>(Vec::new(), |mut bytes, chunk| {
//                         bytes.write_all(&chunk)?;

//                         Ok(bytes)
//                     })
//                     .map_err(::ruma_api::Error::from)
//                     .and_then(|bytes| {
//                         ::serde_json::from_slice::<ResponseBody>(bytes.as_slice())
//                             .map_err(::ruma_api::Error::from)
//                     })
//             });

//             tokens.append(".and_then(move |response_body| {");

//             tokens
//         } else {
//             let mut tokens = Tokens::new();

//             tokens.append(quote! {
//                 let future_response = ::futures::future::ok(())
//             });

//             tokens.append(".and_then(move |_| {");

//             tokens
//         };

//         let mut closure_end = Tokens::new();
//         closure_end.append("});");

//         let extract_headers = if self.response.has_header_fields() {
//             quote! {
//                 let mut headers = hyper_response.headers().clone();
//             }
//         } else {
//             Tokens::new()
//         };

//         let response_init_fields = if self.response.has_fields() {
//             self.response.init_fields()
//         } else {
//             Tokens::new()
//         };

//         tokens.append(quote! {
//             #[allow(unused_imports)]
//             use std::io::Write as _Write;

//             #[allow(unused_imports)]
//             use ::futures::{Future as _Future, Stream as _Stream};
//             use ::ruma_api::Endpoint as _RumaApiEndpoint;

//             /// The API endpoint.
//             #[derive(Debug)]
//             pub struct Endpoint;

//             #request_types

//             impl ::std::convert::TryFrom<Request> for ::hyper::Request {
//                 type Error = ::ruma_api::Error;

//                 #[allow(unused_mut, unused_variables)]
//                 fn try_from(request: Request) -> Result<Self, Self::Error> {
//                     let metadata = Endpoint::METADATA;

//                     // Use dummy homeserver url which has to be overwritten in
//                     // the calling code. Previously (with hyper::Uri) this was
//                     // not required, but Url::parse only accepts absolute urls.
//                     let mut url = ::url::Url::parse("http://invalid-host-please-change/").unwrap();

//                     { #set_request_path }
//                     { #set_request_query }

//                     let mut hyper_request = ::hyper::Request::new(
//                         metadata.method,
//                         // Every valid URL is a valid URI
//                         url.into_string().parse().unwrap(),
//                     );

//                     { #add_body_to_request }

//                     Ok(hyper_request)
//                 }
//             }

//             #response_types

//             impl ::futures::future::FutureFrom<::hyper::Response> for Response {
//                 type Future = Box<_Future<Item = Self, Error = Self::Error>>;
//                 type Error = ::ruma_api::Error;

//                 #[allow(unused_variables)]
//                 fn future_from(hyper_response: ::hyper::Response)
//                 -> Box<_Future<Item = Self, Error = Self::Error>> {
//                     #extract_headers

//                     #deserialize_response_body

//                     let response = Response {
//                         #response_init_fields
//                     };

//                     Ok(response)
//                     #closure_end

//                     Box::new(future_response)
//                 }
//             }

//             impl ::ruma_api::Endpoint for Endpoint {
//                 type Request = Request;
//                 type Response = Response;

//                 const METADATA: ::ruma_api::Metadata = ::ruma_api::Metadata {
//                     description: #description,
//                     method: ::hyper::#method,
//                     name: #name,
//                     path: #path,
//                     rate_limited: #rate_limited,
//                     requires_authentication: #requires_authentication,
//                 };
//             }
//         });
//     }
// }

<commit_msg>Update strip_serde_attrs, uncomment code.<commit_after>use quote::{ToTokens, Tokens};
use syn::punctuated::Pair;
use syn::synom::Synom;
use syn::{Expr, FieldValue, Ident, Meta};

mod metadata;
mod request;
mod response;

// use parse::Entry;
use self::metadata::Metadata;
use self::request::Request;
use self::response::Response;

pub fn strip_serde_attrs(field_value: &FieldValue) -> FieldValue {
    let mut field_value = field_value.clone();

    field_value.attrs = field_value.attrs.into_iter().filter(|attr| {
        let meta = attr.interpret_meta()
            .expect("ruma_api! could not parse field attributes");

        let Meta::List(meta_list) = meta;

        if meta_list.ident.as_ref() != "serde" {
            return true;
        }

        false
    }).collect();

    field_value
}

pub struct Api {
    metadata: Metadata,
    request: Request,
    response: Response,
}

impl From<Vec<Expr>> for Api {
    fn from(exprs: Vec<Expr>) -> Self {
        if exprs.len() != 3 {
            panic!("ruma_api! expects 3 blocks: metadata, request, and response");
        }

        let mut metadata = None;
        let mut request = None;
        let mut response = None;

        for expr in exprs {
            let expr = match expr {
                Expr::Struct(expr) => expr,
                _ => panic!("ruma_api! blocks should use struct syntax"),
            };

            let segments = expr.path.segments;

            if segments.len() != 1 {
                panic!("ruma_api! blocks must be one of: metadata, request, or response");
            }

            let Pair::End(last_segment) = segments.last().unwrap();

            match last_segment.ident.as_ref() {
                "metadata" => metadata = Some(expr.into()),
                "request" => request = Some(expr.into()),
                "response" => response = Some(expr.into()),
                _ => panic!("ruma_api! blocks must be one of: metadata, request, or response"),
            }
        }

        if metadata.is_none() {
            panic!("ruma_api! is missing metadata");
        }

        if request.is_none() {
            panic!("ruma_api! is missing request");
        }

        if response.is_none() {
            panic!("ruma_api! is missing response");
        }

        Api {
            metadata: metadata.unwrap(),
            request: request.unwrap(),
            response: response.unwrap(),
        }

    }
}

pub struct Exprs {
    pub inner: Vec<Expr>,
}

impl Synom for Exprs {
    named!(parse -> Self, do_parse!(
        exprs: many0!(syn!(Expr)) >>
        (Exprs {
            inner: exprs,
        })
    ));
}

impl ToTokens for Api {
    fn to_tokens(&self, tokens: &mut Tokens) {
        let description = &self.metadata.description;
        let method = &self.metadata.method;
        let name = &self.metadata.name;
        let path = &self.metadata.path;
        let rate_limited = &self.metadata.rate_limited;
        let requires_authentication = &self.metadata.requires_authentication;

        let request_types = {
            let mut tokens = Tokens::new();
            self.request.to_tokens(&mut tokens);
            tokens
        };
        let response_types = {
            let mut tokens = Tokens::new();
            self.response.to_tokens(&mut tokens);
            tokens
        };

        let set_request_path = if self.request.has_path_fields() {
            let path_str_quoted = path.as_str();
            assert!(
                path_str_quoted.starts_with('"') && path_str_quoted.ends_with('"'),
                "path needs to be a string literal"
            );

            let path_str = &path_str_quoted[1 .. path_str_quoted.len() - 1];

            assert!(path_str.starts_with('/'), "path needs to start with '/'");
            assert!(
                path_str.chars().filter(|c| *c == ':').count() == self.request.path_field_count(),
                "number of declared path parameters needs to match amount of placeholders in path"
            );

            let request_path_init_fields = self.request.request_path_init_fields();

            let mut tokens = quote! {
                let request_path = RequestPath {
                    #request_path_init_fields
                };

                // This `unwrap()` can only fail when the url is a
                // cannot-be-base url like `mailto:` or `data:`, which is not
                // the case for our placeholder url.
                let mut path_segments = url.path_segments_mut().unwrap();
            };

            for segment in path_str[1..].split('/') {
                tokens.append(quote! {
                    path_segments.push
                });

                tokens.append("(");

                if segment.starts_with(':') {
                    tokens.append("&request_path.");
                    tokens.append(&segment[1..]);
                    tokens.append(".to_string()");
                } else {
                    tokens.append("\"");
                    tokens.append(segment);
                    tokens.append("\"");
                }

                tokens.append(");");
            }

            tokens
        } else {
            quote! {
                url.set_path(metadata.path);
            }
        };

        let set_request_query = if self.request.has_query_fields() {
            let request_query_init_fields = self.request.request_query_init_fields();

            quote! {
                let request_query = RequestQuery {
                    #request_query_init_fields
                };

                url.set_query(Some(&::serde_urlencoded::to_string(request_query)?));
            }
        } else {
            Tokens::new()
        };

        let add_body_to_request = if let Some(field) = self.request.newtype_body_field() {
            let field_name = field.ident.as_ref().expect("expected body field to have a name");

            quote! {
                let request_body = RequestBody(request.#field_name);

                hyper_request.set_body(::serde_json::to_vec(&request_body)?);
            }
        } else if self.request.has_body_fields() {
            let request_body_init_fields = self.request.request_body_init_fields();

            quote! {
                let request_body = RequestBody {
                    #request_body_init_fields
                };

                hyper_request.set_body(::serde_json::to_vec(&request_body)?);
            }
        } else {
            Tokens::new()
        };

        let deserialize_response_body = if let Some(field) = self.response.newtype_body_field() {
            let field_type = &field.ty;
            let mut tokens = Tokens::new();

            tokens.append(quote! {
                let future_response = hyper_response.body()
                    .fold::<_, _, Result<_, ::std::io::Error>>(Vec::new(), |mut bytes, chunk| {
                        bytes.write_all(&chunk)?;

                        Ok(bytes)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|bytes| {
                        ::serde_json::from_slice::<#field_type>(bytes.as_slice())
                            .map_err(::ruma_api::Error::from)
                    })
            });

            tokens.append(".and_then(move |response_body| {");

            tokens
        } else if self.response.has_body_fields() {
            let mut tokens = Tokens::new();

            tokens.append(quote! {
                let future_response = hyper_response.body()
                    .fold::<_, _, Result<_, ::std::io::Error>>(Vec::new(), |mut bytes, chunk| {
                        bytes.write_all(&chunk)?;

                        Ok(bytes)
                    })
                    .map_err(::ruma_api::Error::from)
                    .and_then(|bytes| {
                        ::serde_json::from_slice::<ResponseBody>(bytes.as_slice())
                            .map_err(::ruma_api::Error::from)
                    })
            });

            tokens.append(".and_then(move |response_body| {");

            tokens
        } else {
            let mut tokens = Tokens::new();

            tokens.append(quote! {
                let future_response = ::futures::future::ok(())
            });

            tokens.append(".and_then(move |_| {");

            tokens
        };

        let mut closure_end = Tokens::new();
        closure_end.append("});");

        let extract_headers = if self.response.has_header_fields() {
            quote! {
                let mut headers = hyper_response.headers().clone();
            }
        } else {
            Tokens::new()
        };

        let response_init_fields = if self.response.has_fields() {
            self.response.init_fields()
        } else {
            Tokens::new()
        };

        tokens.append(quote! {
            #[allow(unused_imports)]
            use std::io::Write as _Write;

            #[allow(unused_imports)]
            use ::futures::{Future as _Future, Stream as _Stream};
            use ::ruma_api::Endpoint as _RumaApiEndpoint;

            /// The API endpoint.
            #[derive(Debug)]
            pub struct Endpoint;

            #request_types

            impl ::std::convert::TryFrom<Request> for ::hyper::Request {
                type Error = ::ruma_api::Error;

                #[allow(unused_mut, unused_variables)]
                fn try_from(request: Request) -> Result<Self, Self::Error> {
                    let metadata = Endpoint::METADATA;

                    // Use dummy homeserver url which has to be overwritten in
                    // the calling code. Previously (with hyper::Uri) this was
                    // not required, but Url::parse only accepts absolute urls.
                    let mut url = ::url::Url::parse("http://invalid-host-please-change/").unwrap();

                    { #set_request_path }
                    { #set_request_query }

                    let mut hyper_request = ::hyper::Request::new(
                        metadata.method,
                        // Every valid URL is a valid URI
                        url.into_string().parse().unwrap(),
                    );

                    { #add_body_to_request }

                    Ok(hyper_request)
                }
            }

            #response_types

            impl ::futures::future::FutureFrom<::hyper::Response> for Response {
                type Future = Box<_Future<Item = Self, Error = Self::Error>>;
                type Error = ::ruma_api::Error;

                #[allow(unused_variables)]
                fn future_from(hyper_response: ::hyper::Response)
                -> Box<_Future<Item = Self, Error = Self::Error>> {
                    #extract_headers

                    #deserialize_response_body

                    let response = Response {
                        #response_init_fields
                    };

                    Ok(response)
                    #closure_end

                    Box::new(future_response)
                }
            }

            impl ::ruma_api::Endpoint for Endpoint {
                type Request = Request;
                type Response = Response;

                const METADATA: ::ruma_api::Metadata = ::ruma_api::Metadata {
                    description: #description,
                    method: ::hyper::#method,
                    name: #name,
                    path: #path,
                    rate_limited: #rate_limited,
                    requires_authentication: #requires_authentication,
                };
            }
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>Use metric and cleanup a bit<commit_after><|endoftext|>


<commit_before><commit_msg>Add define_dummy_network_bytes macro<commit_after><|endoftext|>


<commit_before><commit_msg>Implement sbcount, sbcmp, sbout, sbhit<commit_after><|endoftext|>


<commit_before><commit_msg>Move frequency+noise clocks to vsu<commit_after><|endoftext|>


<commit_before><commit_msg>Simple example of anonymous objects from nothing.  Closes #812.<commit_after>use std;

fn main() {

    // Anonymous object that doesn't extend an existing one.
    let my_obj = obj() {
        fn foo() -> int { ret 2; }
        fn bar() -> int { ret 3; }
        fn baz() -> str { "hello!" }
    };

    assert my_obj.foo() == 2;
    assert my_obj.bar() == 3;
    assert my_obj.baz() == "hello!";

    // Make sure the result is extendable.
    let my_ext_obj = obj() {
        fn foo() -> int { ret 3; }
        fn quux() -> str { ret self.baz(); }
        with my_obj
    };

    assert my_ext_obj.foo() == 3;
    assert my_ext_obj.bar() == 3;
    assert my_ext_obj.baz() == "hello!";
    assert my_ext_obj.quux() == "hello!";

    // And again.
    let my_ext_ext_obj = obj() {
        fn baz() -> str { "world!" }
        with my_ext_obj
    };

    assert my_ext_ext_obj.foo() == 3;
    assert my_ext_ext_obj.bar() == 3;
    assert my_ext_ext_obj.baz() == "world!";
    assert my_ext_ext_obj.quux() == "world!";
}
<|endoftext|>


<commit_before>use {Future, Poll};
/// Combines two different futures yielding the same item and error
/// types into a single type.
pub enum Either<A, B> {
    /// First branch of the type
    A(A),
    /// Second branch of the type
    B(B),
}

impl<A, B, Item, Error> Future for Either<A, B>
    where A: Future<Item = Item, Error = Error>,
          B: Future<Item = Item, Error = Error>
{
    type Item = Item;
    type Error = Error;
    fn poll(&mut self) -> Poll<Item, Error> {
        match *self {
            Either::A(ref mut a) => a.poll(),
            Either::B(ref mut b) => b.poll(),
        }
    }
}
<commit_msg>Use fewer generics in the Either impl<commit_after>use {Future, Poll};

/// Combines two different futures yielding the same item and error
/// types into a single type.
pub enum Either<A, B> {
    /// First branch of the type
    A(A),
    /// Second branch of the type
    B(B),
}

impl<A, B> Future for Either<A, B>
    where A: Future,
          B: Future<Item = A::Item, Error = A::Error>
{
    type Item = A::Item;
    type Error = A::Error;

    fn poll(&mut self) -> Poll<A::Item, A::Error> {
        match *self {
            Either::A(ref mut a) => a.poll(),
            Either::B(ref mut b) => b.poll(),
        }
    }
}
<|endoftext|>


<commit_before>#[crate_id = "github.com/musitdev/rust-portmidi#portmidi:0.1"];
#[comment = "PortMidi binding for Rust"];
#[license = "MIT"];
#[crate_type = "lib"];
#[crate_type = "dylib"];

///  build : rustpkg build portmidi
///  test : rustpkg test portmidi

//extern mod extra;
extern mod extra;  //= "extra#0.10-pre"
extern mod serialize;

pub mod midi;
pub mod time;
pub mod util;

<commit_msg>update for rust master change extern crate instead of mod.<commit_after>#[crate_id = "github.com/musitdev/rust-portmidi#portmidi:0.1"];
#[comment = "PortMidi binding for Rust"];
#[license = "MIT"];
#[crate_type = "lib"];
#[crate_type = "dylib"];

///  build : rustpkg build portmidi
///  test : rustpkg test portmidi

//extern mod extra;
extern crate extra;  //= "extra#0.10-pre"
extern crate serialize;

pub mod midi;
pub mod time;
pub mod util;

<|endoftext|>


<commit_before><commit_msg>Update serde attrs for room::message::LimitType<commit_after><|endoftext|>


<commit_before><commit_msg>cortex_m0: Add missing mod.rs<commit_after>// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <bgamari@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub mod lock;
<|endoftext|>


<commit_before><commit_msg>Missing file<commit_after>use rustc_serialize;

pub trait IntoJsonString<T: rustc_serialize::Encodable> {
    fn into(self) -> String;
}
<|endoftext|>


<commit_before><commit_msg>Added a basic implentation of a world, but without physics<commit_after><|endoftext|>


<commit_before><commit_msg>Tests for prompt handling of requests and responses.<commit_after>extern crate tiny_http;

use tiny_http::{Server, Response};
use std::net::{TcpStream, Shutdown};
use std::io::{copy, Write, Read};
use std::thread::{spawn, sleep};
use std::time::Duration;
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::ops::Deref;

/// Stream that produces bytes very slowly
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
struct SlowByteSrc { val: u8, len: usize }
impl<'b> Read for SlowByteSrc {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        sleep(Duration::from_millis(100));
        let l = self.len.min(buf.len()).min(1000);
        buf[..l].fill(self.val);
        self.len -= l;
        Ok(l)
    }
}

/// crude impl of http `Transfer-Encoding: chunked`
fn encode_chunked(data: &mut dyn Read, output: &mut dyn Write) {
    let mut buf = [0u8; 4096];
    loop {
        let l = data.read(&mut buf).unwrap();
        write!(output, "{:X}\r\n", l).unwrap();
        output.write_all(&buf[..l]).unwrap();
        write!(output, "\r\n").unwrap();
        if l == 0 { break; }
    }
}

mod prompt_pipelining {
    use super::*;

    /// Check that pipelined requests on the same connection are received promptly.
    fn assert_requests_parsed_promptly(
        req_cnt: usize,
        req_body: &'static [u8],
        timeout: Duration,
        req_writer: impl FnOnce(&mut dyn Write) + Send + 'static
    ) {
        let resp_body = SlowByteSrc { val: 42, len: 1000_000 }; // very slow response body

        let server = Server::http("0.0.0.0:0").unwrap();
        let mut client = TcpStream::connect(server.server_addr()).unwrap();
        let (svr_send, svr_rcv) = channel();

        spawn(move || {
            for _ in 0..req_cnt {
                let mut req = server.recv().unwrap();
                // read the whole body of the request
                let mut body = Vec::new();
                req.as_reader().read_to_end(&mut body).unwrap();
                assert_eq!(req_body, body.as_slice());
                // The next pipelined request should now be available for parsing,
                // while we send the (possibly slow) response in another thread
                spawn(move || req.respond(
                    Response::empty(200).with_data(resp_body, Some(resp_body.len))
                ));
            }
            svr_send.send(()).unwrap();
        });

        spawn(move || req_writer(&mut client));

        // requests must be sent and received quickly (before timeout expires)
        svr_rcv.recv_timeout(timeout)
            .expect("Server did not finish reading pipelined requests quickly enough");
    }

    // short (but not trivial) request body
    const REQ_BODY: &'static [u8] = &[65; 5000];

    #[test]
    fn content_length() {
        assert_requests_parsed_promptly(5, REQ_BODY, Duration::from_millis(200), move |wr| {
            for _ in 0..5 {
                write!(wr, "GET / HTTP/1.1\r\n").unwrap();
                write!(wr, "Connection: keep-alive\r\n").unwrap();
                write!(wr, "Content-Length: {}\r\n\r\n", REQ_BODY.len()).unwrap();
                wr.write_all(REQ_BODY).unwrap();
            }
        });
    }

    #[test]
    fn expect_continue() {
        assert_requests_parsed_promptly(5, REQ_BODY, Duration::from_millis(200), move |wr| {
            for _ in 0..5 {
                write!(wr, "GET / HTTP/1.1\r\n").unwrap();
                write!(wr, "Connection: keep-alive\r\n").unwrap();
                write!(wr, "Expect: 100 continue\r\n").unwrap();
                write!(wr, "Content-Length: {}\r\n\r\n", REQ_BODY.len()).unwrap();
                wr.write_all(REQ_BODY).unwrap();
            }
        });
    }

    #[test]
    fn chunked() {
        assert_requests_parsed_promptly(5, REQ_BODY, Duration::from_millis(200), move |wr| {
            for _ in 0..5 {
                write!(wr, "GET / HTTP/1.1\r\n").unwrap();
                write!(wr, "Connection: keep-alive\r\n").unwrap();
                write!(wr, "Transfer-Encoding: chunked\r\n\r\n").unwrap();
                let mut body = REQ_BODY;
                encode_chunked(&mut body, wr);
            }
        });
    }
}

mod prompt_responses {
    use super::*;

    /// Check that response is sent promptly without waiting for full request body.
    fn assert_responds_promptly(
        timeout: Duration,
        req_writer: impl FnOnce(&mut dyn Write) + Send + 'static
    ) {
        let server = Server::http("0.0.0.0:0").unwrap();
        let client = TcpStream::connect(server.server_addr()).unwrap();

        spawn(move || loop {
            // server attempts to respond immediately
            let req = server.recv().unwrap();
            req.respond(Response::empty(400)).unwrap();
        });

        let client = Arc::new(client);
        let client_write = Arc::clone(&client);
        // request written (possibly very slowly) in another thread
        spawn(move || req_writer(&mut client_write.deref()));

        // response should arrive quickly (before timeout expires)
        client.set_read_timeout(Some(timeout)).unwrap();
        let resp = client.deref().read(&mut [0u8; 4096]);
        client.shutdown(Shutdown::Both).unwrap();
        assert!(resp.is_ok(), "Server response was not sent promptly");
    }

    static SLOW_BODY: SlowByteSrc = SlowByteSrc { val: 65, len: 1000_000 };

    #[test]
    fn content_length_http11() {
        assert_responds_promptly(Duration::from_millis(200), move |wr| {
            write!(wr, "GET / HTTP/1.1\r\n").unwrap();
            write!(wr, "Content-Length: {}\r\n\r\n", SLOW_BODY.len).unwrap();
            copy(&mut SLOW_BODY.clone(), wr).unwrap();
        });
    }

    #[test]
    fn content_length_http10() {
        assert_responds_promptly(Duration::from_millis(200), move |wr| {
            write!(wr, "GET / HTTP/1.0\r\n").unwrap();
            write!(wr, "Content-Length: {}\r\n\r\n", SLOW_BODY.len).unwrap();
            copy(&mut SLOW_BODY.clone(), wr).unwrap();
        });
    }

    #[test]
    fn expect_continue() {
        assert_responds_promptly(Duration::from_millis(200), move |wr| {
            write!(wr, "GET / HTTP/1.1\r\n").unwrap();
            write!(wr, "Expect: 100 continue\r\n").unwrap();
            write!(wr, "Content-Length: {}\r\n\r\n", SLOW_BODY.len).unwrap();
            copy(&mut SLOW_BODY.clone(), wr).unwrap();
        });
    }

    #[test]
    fn chunked() {
        assert_responds_promptly(Duration::from_millis(200), move |wr| {
            write!(wr, "GET / HTTP/1.1\r\n").unwrap();
            write!(wr, "Transfer-Encoding: chunked\r\n\r\n").unwrap();
            encode_chunked(&mut SLOW_BODY.clone(), wr);
        });
    }
}<|endoftext|>


<commit_before><commit_msg>Add osc_server tests<commit_after>extern crate rosc;<|endoftext|>