<commit_before><commit_msg>add example drawing a dragon curve (#29)<commit_after>//! Draw a dragon curve, more specifically a highway dragon.
//! (https://en.wikipedia.org/wiki/Dragon_curve)
//!
//! As can be seen in the above wikipedia article, the highway dragon can be
//! constructed by repeatedly folding a strip of paper and looking at the
//! directions of the folds/turns.
//!
//! Starting with a strip going left to right (l2r):
//!
//! start|--->---l2r--->---|end
//!
//! you might fold it like this:
//!
//! end|---<---r2l---<---\
//! start|->---l2r--->---/
//!
//! Getting a l2r strip, followed by a left turn, followed by a r2l strip.
//!
//! Folding a right to left strip:
//!
//! end|---<---r2l---<---|start
//!
//! In the same way:
//!
//! start|-->---l2r--->---\
//! end|----<---r2l---<---/
//!
//! Would give you a l2r, followed by a right turn, followed by a r2l strip.
//!
//! As you can see, the only difference between the two is the direction of
//! the turn in the middle.
//!
//! This folding of paper is simulated by recursively calling the dragon(..)
//! function, passing the direction of the turn for this fold as an angle
//! (+90 for a right turn, -90 for a left turn).

extern crate turtle;

use turtle::Turtle;
use turtle::Color;

fn main() {
    let mut turtle = Turtle::new();

    turtle.set_background_color("#112244");

    turtle.pen_up();
    turtle.backward(160.0);
    turtle.right(90.);
    turtle.forward(110.);
    turtle.pen_down();
    turtle.set_speed(10);

    dragon(&mut turtle, -90., 11, 0., 255.);

    turtle.hide();
}

/// Draw the dragon curve by simulating folding a strip of paper
///
/// `fold_direction`: The direction of the fold, +90 for a right, -90 for a
/// left turn.
/// `num_folds`: The number of times to fold the 'strip of paper'.
/// `color_start`/`color_end`: The color at the start/end of this subsection
/// of the curve as a number 0-255.
fn dragon(
    turtle: &mut Turtle,
    fold_direction: f64,
    num_folds: usize,
    color_start: f64,
    color_end: f64,
) {
    let color_mid = (color_start + color_end) * 0.5;
    if num_folds == 0 {
        // mapping a color number 0-255 to an rgb gradient.
        turtle.set_pen_color(Color {
            red: (color_mid - 128.).abs() * 2.,
            green: color_mid,
            blue: 160.,
            alpha: 1.,
        });
        return turtle.forward(10.);
    }

    // draw a left to right strip (which has a left turn in the middle)
    dragon(turtle, -90., num_folds - 1, color_start, color_mid);
    turtle.right(fold_direction);
    // draw a right to left strip (which has a right turn in the middle)
    dragon(turtle, 90., num_folds - 1, color_mid, color_end);
}
<|endoftext|>


<commit_before><commit_msg>Add a roll back to the trajectory to make it more interesting<commit_after><|endoftext|>


<commit_before><commit_msg>Fix file_is_newer_than()<commit_after><|endoftext|>


<commit_before><commit_msg>[No-auto] bin/core/annotate: Fix Clippy warnings<commit_after><|endoftext|>


<commit_before><commit_msg>to force Travis build<commit_after><|endoftext|>


<commit_before><commit_msg>Remove POST_MATHEXPR when it is seen<commit_after><|endoftext|>


<commit_before><commit_msg>Update Arc and Channel code to be compatible with rust master.<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test for issue #17458<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.

static X: uint = 0 as *const uint as uint;

fn main() {
    assert_eq!(X, 0);
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2425<commit_after>// https://leetcode.com/problems/bitwise-xor-of-all-pairings/
pub fn xor_all_nums(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!("{}", xor_all_nums(vec![2, 1, 3], vec![10, 2, 5, 0])); // 13
    println!("{}", xor_all_nums(vec![1, 2], vec![3, 4])); // 0
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::collections::hash_map::Entry::{ Occupied, Vacant };
use std::f32::consts::{PI, SQRT2};
use std::f32::INFINITY;
use std::old_io::fs::File;
use std::num::Float;
use std::str::FromStr;

use self::OrthoRotation::*;

use array::*;
use cube;
use serialize::json;
use texture::AtlasBuilder;

#[derive(Copy)]
pub struct Vertex {
    pub xyz: [f32; 3],
    pub uv: [f32; 2]
}

#[derive(Copy, Clone)]
pub enum Tint {
    None,
    Grass,
    Foliage,
    Redstone
}

#[derive(Copy)]
pub enum OrthoRotation {
    Rotate0,
    Rotate90,
    Rotate180,
    Rotate270
}

impl OrthoRotation {
    pub fn from_json(json: &json::Json) -> Option<OrthoRotation> {
        json.as_i64().and_then(|r| Some(match r {
            0 => Rotate0,
            90 => Rotate90,
            180 => Rotate180,
            270 => Rotate270,
            _ => return None
        }))
    }
}

#[derive(Copy)]
pub struct Face {
    pub vertices: [Vertex; 4],
    pub tint: bool,
    pub cull_face: Option<cube::Face>,
    pub ao_face: Option<cube::Face>
}

impl Clone for Face {
    fn clone(&self) -> Face { *self }
}

#[derive(Clone)]
enum PartialTexture {
    Variable(String),
    Coords(f32, f32)
}

#[derive(Clone)]
pub struct PartialModel {
    textures: HashMap<String, PartialTexture>,
    faces: Vec<(Face, String)>,
    full_faces: Vec<usize>,
    no_ambient_occlusion: bool
}

#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Opacity {
    Transparent,
    TranslucentSolid,
    TransparentSolid,
    Opaque
}

impl Opacity {
    pub fn is_opaque(self) -> bool {
        self == Opacity::Opaque
    }

    pub fn is_solid(self) -> bool {
        self != Opacity::Transparent
    }
}

#[derive(Clone)]
pub struct Model {
    pub faces: Vec<Face>,
    pub opacity: Opacity,
    pub tint_source: Tint
}

fn array3_num<T, F>(json: &json::Json, mut f: F) -> [T; 3] where F: FnMut(f64) -> T {
    Array::from_iter(json.as_array().unwrap().iter().map(|x| f(x.as_f64().unwrap())))
}

fn clone_parent(m: &PartialModel, a: &mut AtlasBuilder) -> PartialModel {
    m.clone()
}

impl PartialModel {
    fn load<T, F>(name: &str, assets: &Path, atlas: &mut AtlasBuilder,
               cache: &mut HashMap<String, PartialModel>,
               mut f: F) -> T
        where F: FnMut(&PartialModel, &mut AtlasBuilder) -> T
    {
        match cache.get(name) {
            Some(model) => return f(model, atlas),
            None => {}
        }
        let path = assets.join(Path::new(format!("minecraft/models/{}.json", name).as_slice()));
        let obj = json::Json::from_reader(&mut File::open(&path).unwrap()).unwrap();

        let mut model = match obj.find("parent").and_then(|x| x.as_string()) {
            // FIXME(toqueteos): Cthulu himself came here and inspired me, if we use a closure here instead of
            // "clone_parent" this would trigger an error: "reached the recursion limit during monomorphization"
            Some(parent) => PartialModel::load(parent, assets, atlas, cache, clone_parent),
            None => PartialModel {
                textures: HashMap::new(),
                faces: vec![],
                full_faces: vec![],
                no_ambient_occlusion: false
            }
        };

        match obj.find("ambientocclusion").and_then(|x| x.as_boolean()) {
            Some(ambient_occlusion) => model.no_ambient_occlusion = !ambient_occlusion,
            None => {}
        }

        match obj.find("textures").and_then(|x| x.as_object()) {
            Some(textures) => for (name, tex) in textures.iter() {
                let tex = tex.as_string().unwrap();
                let tex = if tex.starts_with("#") {
                    PartialTexture::Variable(tex.slice_from(1).to_string())
                } else {
                    let (u, v) = atlas.load(tex);
                    PartialTexture::Coords(u as f32, v as f32)
                };
                model.textures.insert(name.clone(), tex);
            },
            None => {}
        }

        match obj.find("elements").and_then(|x: &json::Json| x.as_array().map(|x| x.clone())) {
            Some(elements) => for element in elements.iter().map(|x| x) {
                let from = array3_num(element.find("from").unwrap(), |x| x as f32 / 16.0);
                let to = array3_num(element.find("to").unwrap(), |x| x as f32 / 16.0);
                let scale = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];

                let is_full_cube = from == [0.0, 0.0, 0.0] && to == [1.0, 1.0, 1.0];
                let element_start = model.faces.len();

                for (k, v) in element.find("faces").unwrap().as_object().unwrap().iter() {
                    let face: cube::Face = FromStr::from_str(k.as_slice()).unwrap();
                    let [u0, v0, u1, v1] = match v.find("uv") {
                        Some(uv) => {
                            Array::from_iter(uv.as_array().unwrap().iter().map(|x| x.as_f64().unwrap() as f32))
                        }
                        None => match face {
                            cube::West  | cube::East  => [from[2], from[1], to[2], to[1]],
                            cube::Down  | cube::Up    => [from[0], from[2], to[0], to[2]],
                            cube::North | cube::South => [from[0], from[1], to[0], to[1]]
                        }.map(|x| x * 16.0)
                    };

                    let tex = v.find("texture").unwrap().as_string().unwrap();
                    assert!(tex.starts_with("#"));
                    let tex = tex.slice_from(1).to_string();

                    let cull_face = v.find("cullface").map(|s| {
                        FromStr::from_str(s.as_string().unwrap()).unwrap()
                    });

                    if cull_face.is_some() && cull_face != Some(face) {
                        println!("odd case: cull_face = {:?} for face = {:?}", cull_face.unwrap(), face);
                    }

                    let tint = v.find("tintindex").map(|x| {
                        let x = x.as_i64().unwrap();
                        if x != 0 {
                            println!("odd case: tint_index = {}", x);
                        }
                    }).is_some();

                    if cull_face == Some(face) && is_full_cube {
                        model.full_faces.push(model.faces.len());
                    }

                    let rotation = v.find("rotation").map_or(Rotate0, |r| {
                        match OrthoRotation::from_json(r) {
                            Some(r) => r,
                            None => panic!("invalid rotation for face {}", r)
                        }
                    });

                    let xyz = face.vertices(from, scale);
                    // Swap vertical texture coordinates.
                    let [v0, v1] = [v1, v0];
                    // Bring texture coordinates closer to avoid seams.
                    let u_center = (u0 + u1) / 2.0;
                    let [u0, u1] = [u0, u1].map(|u| u - (u - u_center).signum() / 128.0);
                    let v_center = (v0 + v1) / 2.0;
                    let [v0, v1] = [v0, v1].map(|v| v - (v - v_center).signum() / 128.0);
                    // Clockwise quad (from bottom-right to top-right).
                    let uvs = [
                        [u1, v0],
                        [u0, v0],
                        [u0, v1],
                        [u1, v1]
                    ].map(|[u, v]| match rotation {
                        Rotate0 => [u, v],
                        Rotate90 => [v, 16.0 - u],
                        Rotate180 => [16.0 - u, 16.0 - v],
                        Rotate270 => [16.0 - v, u]
                    });

                    model.faces.push((Face {
                        vertices: Array::from_fn(|i| Vertex { xyz: xyz[i], uv: uvs[i] }),
                        tint: tint,
                        cull_face: cull_face,
                        ao_face: Some(face)
                    }, tex));
                }

                match element.find("rotation") {
                    Some(r) => {
                        let angle = r.find("angle").unwrap().as_f64().unwrap();
                        let angle = angle as f32 / 180.0 * PI;
                        let rescale = r.find("rescale").map_or(false, |x| x.as_boolean().unwrap());
                        let origin = array3_num(r.find("origin").unwrap(), |x| x as f32 / 16.0);

                        let (s, c) = (angle.sin(), angle.cos());
                        let mut rot = |&mut: ix: usize, iy: usize| {
                            for &mut (ref mut face, _) in model.faces.slice_from_mut(element_start).iter_mut() {
                                face.ao_face = None;

                                let [ox, oy] = [origin[ix], origin[iy]];
                                for v in face.vertices.iter_mut() {
                                    let [x, y] = [v.xyz[ix] - ox, v.xyz[iy] - oy];
                                    v.xyz[ix] = x * c + y * s;
                                    v.xyz[iy] =-x * s + y * c;
                                }

                                if rescale {
                                    for v in face.vertices.iter_mut() {
                                        v.xyz[ix] *= SQRT2;
                                        v.xyz[iy] *= SQRT2;
                                    }
                                }

                                for v in face.vertices.iter_mut() {
                                    v.xyz[ix] += ox;
                                    v.xyz[iy] += oy;
                                }
                            }
                        };
                        match r.find("axis").unwrap().as_string().unwrap() {
                            "x" => rot(2, 1),
                            "y" => rot(0, 2),
                            "z" => rot(1, 0),
                            axis => panic!("invalid rotation axis {}", axis)
                        }
                    }
                    None => {}
                }
            },
            None => {}
        }

        match cache.entry(name.to_string()) {
            Occupied(entry) => f(entry.get(), atlas),
            Vacant(entry) => f(entry.insert(model), atlas)
        }
    }
}

impl Model {
    pub fn load(name: &str, assets: &Path, atlas: &mut AtlasBuilder,
                cache: &mut HashMap<String, PartialModel>) -> Model {
        PartialModel::load(format!("block/{}", name).as_slice(), assets, atlas, cache, |partial, atlas| {
            let mut faces: Vec<Face> = partial.faces.iter().map(|&(mut face, ref tex)| {
                fn texture_coords(textures: &HashMap<String, PartialTexture>,
                                  tex: &String) -> Option<(f32, f32)> {
                    match textures.get(tex) {
                        Some(&PartialTexture::Variable(ref tex)) => texture_coords(textures, tex),
                        Some(&PartialTexture::Coords(u, v)) => Some((u, v)),
                        None => None
                    }
                }
                let (u, v) = texture_coords(&partial.textures, tex).unwrap();
                for vertex in face.vertices.iter_mut() {
                    vertex.uv[0] += u;
                    vertex.uv[1] += v;
                }
                face
            }).collect();

            let mut full_faces = [Opacity::Transparent; 6];
            if partial.full_faces.len() >= 6 {
                for &i in partial.full_faces.iter() {
                    let face = faces[i].cull_face.unwrap() as usize;
                    if full_faces[face] == Opacity::Opaque {
                        continue;
                    }
                    let (mut min_u, mut min_v) = (INFINITY, INFINITY);
                    let (mut max_u, mut max_v) = (0.0, 0.0);
                    for vertex in faces[i].vertices.iter() {
                        let [u, v] = vertex.uv;
                        min_u = u.min(min_u);
                        min_v = v.min(min_v);
                        max_u = u.max(max_u);
                        max_v = v.max(max_v);
                    }
                    let (u0, v0) = (min_u.floor() as u32, min_v.floor() as u32);
                    let (u1, v1) = (max_u.ceil() as u32, max_v.ceil() as u32);
                    let rect = [u0, v0, u1 - u0, v1 - v0];
                    let opacity = match atlas.min_alpha(rect) {
                        0 => Opacity::TransparentSolid,
                        255 => Opacity::Opaque,
                        _ => Opacity::TranslucentSolid
                    };
                    if full_faces[face] < opacity {
                        full_faces[face] = opacity;
                    }
                }
            }

            if !partial.no_ambient_occlusion {
                if faces.iter().any(|f| f.ao_face.is_none()) {
                    println!("Warning: model {} uses AO but has faces which are unsuitable", name);
                }
            } else {
                for face in faces.iter_mut() {
                    face.ao_face = None;
                }
            }

            let tint_source = if faces.iter().any(|f| f.tint) {
                match name {
                    name if name.starts_with("grass_") ||
                            name.starts_with("double_grass_") ||
                            name.starts_with("double_fern_") => Tint::Grass,
                    "reeds" | "fern" | "tall_grass" => Tint::Grass,
                    name if name.ends_with("_leaves") || name.ends_with("_stem_fruit") ||
                            name.starts_with("vine_") || name.starts_with("stem_") => Tint::Foliage,
                    "waterlily" => Tint::Foliage,
                    name if name.starts_with("redstone_") => Tint::Redstone,
                    _ => {
                        println!("tint source not known for '{}'", name);
                        Tint::None
                    }
                }
            } else {
                Tint::None
            };

            Model {
                faces: faces,
                opacity: *full_faces.iter().min().unwrap(),
                tint_source: tint_source
            }
        })
    }

    pub fn empty() -> Model {
        Model {
            faces: Vec::new(),
            opacity: Opacity::Transparent,
            tint_source: Tint::None
        }
    }

    pub fn is_empty(&self) -> bool {
        self.faces.is_empty()
    }
}

<commit_msg>Closure syntax update.<commit_after>use std::collections::HashMap;
use std::collections::hash_map::Entry::{ Occupied, Vacant };
use std::f32::consts::{PI, SQRT2};
use std::f32::INFINITY;
use std::old_io::fs::File;
use std::num::Float;
use std::str::FromStr;

use self::OrthoRotation::*;

use array::*;
use cube;
use serialize::json;
use texture::AtlasBuilder;

#[derive(Copy)]
pub struct Vertex {
    pub xyz: [f32; 3],
    pub uv: [f32; 2]
}

#[derive(Copy, Clone)]
pub enum Tint {
    None,
    Grass,
    Foliage,
    Redstone
}

#[derive(Copy)]
pub enum OrthoRotation {
    Rotate0,
    Rotate90,
    Rotate180,
    Rotate270
}

impl OrthoRotation {
    pub fn from_json(json: &json::Json) -> Option<OrthoRotation> {
        json.as_i64().and_then(|r| Some(match r {
            0 => Rotate0,
            90 => Rotate90,
            180 => Rotate180,
            270 => Rotate270,
            _ => return None
        }))
    }
}

#[derive(Copy)]
pub struct Face {
    pub vertices: [Vertex; 4],
    pub tint: bool,
    pub cull_face: Option<cube::Face>,
    pub ao_face: Option<cube::Face>
}

impl Clone for Face {
    fn clone(&self) -> Face { *self }
}

#[derive(Clone)]
enum PartialTexture {
    Variable(String),
    Coords(f32, f32)
}

#[derive(Clone)]
pub struct PartialModel {
    textures: HashMap<String, PartialTexture>,
    faces: Vec<(Face, String)>,
    full_faces: Vec<usize>,
    no_ambient_occlusion: bool
}

#[derive(Copy, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum Opacity {
    Transparent,
    TranslucentSolid,
    TransparentSolid,
    Opaque
}

impl Opacity {
    pub fn is_opaque(self) -> bool {
        self == Opacity::Opaque
    }

    pub fn is_solid(self) -> bool {
        self != Opacity::Transparent
    }
}

#[derive(Clone)]
pub struct Model {
    pub faces: Vec<Face>,
    pub opacity: Opacity,
    pub tint_source: Tint
}

fn array3_num<T, F>(json: &json::Json, mut f: F) -> [T; 3] where F: FnMut(f64) -> T {
    Array::from_iter(json.as_array().unwrap().iter().map(|x| f(x.as_f64().unwrap())))
}

fn clone_parent(m: &PartialModel, a: &mut AtlasBuilder) -> PartialModel {
    m.clone()
}

impl PartialModel {
    fn load<T, F>(name: &str, assets: &Path, atlas: &mut AtlasBuilder,
               cache: &mut HashMap<String, PartialModel>,
               mut f: F) -> T
        where F: FnMut(&PartialModel, &mut AtlasBuilder) -> T
    {
        match cache.get(name) {
            Some(model) => return f(model, atlas),
            None => {}
        }
        let path = assets.join(Path::new(format!("minecraft/models/{}.json", name).as_slice()));
        let obj = json::Json::from_reader(&mut File::open(&path).unwrap()).unwrap();

        let mut model = match obj.find("parent").and_then(|x| x.as_string()) {
            // FIXME(toqueteos): Cthulu himself came here and inspired me, if we use a closure here instead of
            // "clone_parent" this would trigger an error: "reached the recursion limit during monomorphization"
            Some(parent) => PartialModel::load(parent, assets, atlas, cache, clone_parent),
            None => PartialModel {
                textures: HashMap::new(),
                faces: vec![],
                full_faces: vec![],
                no_ambient_occlusion: false
            }
        };

        match obj.find("ambientocclusion").and_then(|x| x.as_boolean()) {
            Some(ambient_occlusion) => model.no_ambient_occlusion = !ambient_occlusion,
            None => {}
        }

        match obj.find("textures").and_then(|x| x.as_object()) {
            Some(textures) => for (name, tex) in textures.iter() {
                let tex = tex.as_string().unwrap();
                let tex = if tex.starts_with("#") {
                    PartialTexture::Variable(tex.slice_from(1).to_string())
                } else {
                    let (u, v) = atlas.load(tex);
                    PartialTexture::Coords(u as f32, v as f32)
                };
                model.textures.insert(name.clone(), tex);
            },
            None => {}
        }

        match obj.find("elements").and_then(|x: &json::Json| x.as_array().map(|x| x.clone())) {
            Some(elements) => for element in elements.iter().map(|x| x) {
                let from = array3_num(element.find("from").unwrap(), |x| x as f32 / 16.0);
                let to = array3_num(element.find("to").unwrap(), |x| x as f32 / 16.0);
                let scale = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];

                let is_full_cube = from == [0.0, 0.0, 0.0] && to == [1.0, 1.0, 1.0];
                let element_start = model.faces.len();

                for (k, v) in element.find("faces").unwrap().as_object().unwrap().iter() {
                    let face: cube::Face = FromStr::from_str(k.as_slice()).unwrap();
                    let [u0, v0, u1, v1] = match v.find("uv") {
                        Some(uv) => {
                            Array::from_iter(uv.as_array().unwrap().iter().map(|x| x.as_f64().unwrap() as f32))
                        }
                        None => match face {
                            cube::West  | cube::East  => [from[2], from[1], to[2], to[1]],
                            cube::Down  | cube::Up    => [from[0], from[2], to[0], to[2]],
                            cube::North | cube::South => [from[0], from[1], to[0], to[1]]
                        }.map(|x| x * 16.0)
                    };

                    let tex = v.find("texture").unwrap().as_string().unwrap();
                    assert!(tex.starts_with("#"));
                    let tex = tex.slice_from(1).to_string();

                    let cull_face = v.find("cullface").map(|s| {
                        FromStr::from_str(s.as_string().unwrap()).unwrap()
                    });

                    if cull_face.is_some() && cull_face != Some(face) {
                        println!("odd case: cull_face = {:?} for face = {:?}", cull_face.unwrap(), face);
                    }

                    let tint = v.find("tintindex").map(|x| {
                        let x = x.as_i64().unwrap();
                        if x != 0 {
                            println!("odd case: tint_index = {}", x);
                        }
                    }).is_some();

                    if cull_face == Some(face) && is_full_cube {
                        model.full_faces.push(model.faces.len());
                    }

                    let rotation = v.find("rotation").map_or(Rotate0, |r| {
                        match OrthoRotation::from_json(r) {
                            Some(r) => r,
                            None => panic!("invalid rotation for face {}", r)
                        }
                    });

                    let xyz = face.vertices(from, scale);
                    // Swap vertical texture coordinates.
                    let [v0, v1] = [v1, v0];
                    // Bring texture coordinates closer to avoid seams.
                    let u_center = (u0 + u1) / 2.0;
                    let [u0, u1] = [u0, u1].map(|u| u - (u - u_center).signum() / 128.0);
                    let v_center = (v0 + v1) / 2.0;
                    let [v0, v1] = [v0, v1].map(|v| v - (v - v_center).signum() / 128.0);
                    // Clockwise quad (from bottom-right to top-right).
                    let uvs = [
                        [u1, v0],
                        [u0, v0],
                        [u0, v1],
                        [u1, v1]
                    ].map(|[u, v]| match rotation {
                        Rotate0 => [u, v],
                        Rotate90 => [v, 16.0 - u],
                        Rotate180 => [16.0 - u, 16.0 - v],
                        Rotate270 => [16.0 - v, u]
                    });

                    model.faces.push((Face {
                        vertices: Array::from_fn(|i| Vertex { xyz: xyz[i], uv: uvs[i] }),
                        tint: tint,
                        cull_face: cull_face,
                        ao_face: Some(face)
                    }, tex));
                }

                match element.find("rotation") {
                    Some(r) => {
                        let angle = r.find("angle").unwrap().as_f64().unwrap();
                        let angle = angle as f32 / 180.0 * PI;
                        let rescale = r.find("rescale").map_or(false, |x| x.as_boolean().unwrap());
                        let origin = array3_num(r.find("origin").unwrap(), |x| x as f32 / 16.0);

                        let (s, c) = (angle.sin(), angle.cos());
                        let mut rot = |ix: usize, iy: usize| {
                            for &mut (ref mut face, _) in model.faces.slice_from_mut(element_start).iter_mut() {
                                face.ao_face = None;

                                let [ox, oy] = [origin[ix], origin[iy]];
                                for v in face.vertices.iter_mut() {
                                    let [x, y] = [v.xyz[ix] - ox, v.xyz[iy] - oy];
                                    v.xyz[ix] = x * c + y * s;
                                    v.xyz[iy] =-x * s + y * c;
                                }

                                if rescale {
                                    for v in face.vertices.iter_mut() {
                                        v.xyz[ix] *= SQRT2;
                                        v.xyz[iy] *= SQRT2;
                                    }
                                }

                                for v in face.vertices.iter_mut() {
                                    v.xyz[ix] += ox;
                                    v.xyz[iy] += oy;
                                }
                            }
                        };
                        match r.find("axis").unwrap().as_string().unwrap() {
                            "x" => rot(2, 1),
                            "y" => rot(0, 2),
                            "z" => rot(1, 0),
                            axis => panic!("invalid rotation axis {}", axis)
                        }
                    }
                    None => {}
                }
            },
            None => {}
        }

        match cache.entry(name.to_string()) {
            Occupied(entry) => f(entry.get(), atlas),
            Vacant(entry) => f(entry.insert(model), atlas)
        }
    }
}

impl Model {
    pub fn load(name: &str, assets: &Path, atlas: &mut AtlasBuilder,
                cache: &mut HashMap<String, PartialModel>) -> Model {
        PartialModel::load(format!("block/{}", name).as_slice(), assets, atlas, cache, |partial, atlas| {
            let mut faces: Vec<Face> = partial.faces.iter().map(|&(mut face, ref tex)| {
                fn texture_coords(textures: &HashMap<String, PartialTexture>,
                                  tex: &String) -> Option<(f32, f32)> {
                    match textures.get(tex) {
                        Some(&PartialTexture::Variable(ref tex)) => texture_coords(textures, tex),
                        Some(&PartialTexture::Coords(u, v)) => Some((u, v)),
                        None => None
                    }
                }
                let (u, v) = texture_coords(&partial.textures, tex).unwrap();
                for vertex in face.vertices.iter_mut() {
                    vertex.uv[0] += u;
                    vertex.uv[1] += v;
                }
                face
            }).collect();

            let mut full_faces = [Opacity::Transparent; 6];
            if partial.full_faces.len() >= 6 {
                for &i in partial.full_faces.iter() {
                    let face = faces[i].cull_face.unwrap() as usize;
                    if full_faces[face] == Opacity::Opaque {
                        continue;
                    }
                    let (mut min_u, mut min_v) = (INFINITY, INFINITY);
                    let (mut max_u, mut max_v) = (0.0, 0.0);
                    for vertex in faces[i].vertices.iter() {
                        let [u, v] = vertex.uv;
                        min_u = u.min(min_u);
                        min_v = v.min(min_v);
                        max_u = u.max(max_u);
                        max_v = v.max(max_v);
                    }
                    let (u0, v0) = (min_u.floor() as u32, min_v.floor() as u32);
                    let (u1, v1) = (max_u.ceil() as u32, max_v.ceil() as u32);
                    let rect = [u0, v0, u1 - u0, v1 - v0];
                    let opacity = match atlas.min_alpha(rect) {
                        0 => Opacity::TransparentSolid,
                        255 => Opacity::Opaque,
                        _ => Opacity::TranslucentSolid
                    };
                    if full_faces[face] < opacity {
                        full_faces[face] = opacity;
                    }
                }
            }

            if !partial.no_ambient_occlusion {
                if faces.iter().any(|f| f.ao_face.is_none()) {
                    println!("Warning: model {} uses AO but has faces which are unsuitable", name);
                }
            } else {
                for face in faces.iter_mut() {
                    face.ao_face = None;
                }
            }

            let tint_source = if faces.iter().any(|f| f.tint) {
                match name {
                    name if name.starts_with("grass_") ||
                            name.starts_with("double_grass_") ||
                            name.starts_with("double_fern_") => Tint::Grass,
                    "reeds" | "fern" | "tall_grass" => Tint::Grass,
                    name if name.ends_with("_leaves") || name.ends_with("_stem_fruit") ||
                            name.starts_with("vine_") || name.starts_with("stem_") => Tint::Foliage,
                    "waterlily" => Tint::Foliage,
                    name if name.starts_with("redstone_") => Tint::Redstone,
                    _ => {
                        println!("tint source not known for '{}'", name);
                        Tint::None
                    }
                }
            } else {
                Tint::None
            };

            Model {
                faces: faces,
                opacity: *full_faces.iter().min().unwrap(),
                tint_source: tint_source
            }
        })
    }

    pub fn empty() -> Model {
        Model {
            faces: Vec::new(),
            opacity: Opacity::Transparent,
            tint_source: Tint::None
        }
    }

    pub fn is_empty(&self) -> bool {
        self.faces.is_empty()
    }
}

<|endoftext|>


<commit_before><commit_msg>Add redirector to simplify imports.<commit_after>/* This file exists just to make it easier to import things inside of
 ./geom/ without specifying the file they came out of imports.

Note that you still must define each of the files as a module in
geom.rc. This is not ideal and may be changed in the future. */

pub use matrix::Matrix4;
pub use matrix2d::Matrix2D;
pub use point::Point2D;
pub use rect::Rect;
pub use size::Size2D;
<|endoftext|>


<commit_before><commit_msg>Auto merge of #34003 - frewsxcv:13727-regressions, r=brson<commit_after>// Copyright 2016 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.

fn test(val: u8) {
  match val {
    256 => print!("0b1110\n"),
    512 => print!("0b1111\n"),
    //~^ ERROR: unreachable pattern
    _   => print!("fail\n"),
  }
}

fn main() {
  test(1);
}
<|endoftext|>


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

// error-pattern: too big for the current architecture

#[cfg(target_pointer_width = "32")]
fn main() {
    let x = [0usize; 0xffff_ffff];
}

#[cfg(target_pointer_width = "64")]
fn main() {
    let x = [0usize; 0xffff_ffff_ffff_ffff];
}
<|endoftext|>


<commit_before><commit_msg>Regression test for #17740<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.

struct Foo<'a> {
    data: &'a[u8],
}

impl <'a> Foo<'a>{
    fn bar(self: &mut Foo) {
    //~^ mismatched types: expected `Foo<'a>`, found `Foo<'_>` (lifetime mismatch)
    //~| mismatched types: expected `Foo<'a>`, found `Foo<'_>` (lifetime mismatch)
    }
}

fn main() {}
<|endoftext|>


<commit_before>#![feature(env)]
#![feature(io)]
#![feature(std_misc)]
#![feature(path)]
#![feature(core)]

#![deny(warnings)]
#![feature(int_uint)]
#![feature(plugin)]

extern crate regex;

extern crate "rustc-serialize" as rustc_serialize;

use example::Example;
use std::thread::Thread;
use std::sync::mpsc;

mod example;
mod file;
mod markdown;
mod playpen;

fn main() {
    let examples = Example::get_list();
    let (tx, rx) = mpsc::channel();

    let mut nexamples = 0;
    for (i, example) in examples.into_iter().enumerate() {
        let tx = tx.clone();
        let count = example.count();

        let _ = Thread::scoped(move || {
            example.process(vec!(i + 1), tx, 0, String::new());
        });

        nexamples += count;
    }

    let mut entries = (0..nexamples).map(|_| {
        rx.recv().unwrap()
    }).collect::<Vec<(Vec<uint>, String)>>();

    entries.sort_by(|&(ref i, _), &(ref j, _)| i.cmp(j));

    let summary = entries.into_iter()
                         .map(|(_, s)| s)
                         .collect::<Vec<String>>()
                         .connect("\n");

    match file::write(&Path::new("stage/SUMMARY.md"), summary.as_slice()) {
        Err(why) => panic!("{}", why),
        Ok(_) => {},
    }
}
<commit_msg>Fix the build<commit_after>#![feature(env)]
#![feature(old_io)]
#![feature(old_path)]
#![feature(core)]

#![deny(warnings)]
#![feature(int_uint)]
#![feature(plugin)]

extern crate regex;

extern crate "rustc-serialize" as rustc_serialize;

use example::Example;
use std::thread;
use std::sync::mpsc;

mod example;
mod file;
mod markdown;
mod playpen;

fn main() {
    let examples = Example::get_list();
    let (tx, rx) = mpsc::channel();

    let mut nexamples = 0;
    for (i, example) in examples.into_iter().enumerate() {
        let tx = tx.clone();
        let count = example.count();

        let _ = thread::scoped(move || {
            example.process(vec!(i + 1), tx, 0, String::new());
        });

        nexamples += count;
    }

    let mut entries = (0..nexamples).map(|_| {
        rx.recv().unwrap()
    }).collect::<Vec<(Vec<uint>, String)>>();

    entries.sort_by(|&(ref i, _), &(ref j, _)| i.cmp(j));

    let summary = entries.into_iter()
                         .map(|(_, s)| s)
                         .collect::<Vec<String>>()
                         .connect("\n");

    match file::write(&Path::new("stage/SUMMARY.md"), summary.as_slice()) {
        Err(why) => panic!("{}", why),
        Ok(_) => {},
    }
}
<|endoftext|>


<commit_before><commit_msg>Removed unused struct.<commit_after><|endoftext|>


<commit_before><commit_msg>bit of refactoring<commit_after><|endoftext|>


<commit_before><commit_msg>Parse client messages as array of bulk strings<commit_after><|endoftext|>


<commit_before><commit_msg>Small test for SSH key<commit_after><|endoftext|>


<commit_before><commit_msg>Add composition of unwrapped packets for each type<commit_after><|endoftext|>


<commit_before><commit_msg>chat bar is working<commit_after><|endoftext|>


<commit_before><commit_msg>Add example code to get a merge request id (from its iid, the value shown in the URL)<commit_after>extern crate gitlab_api as gitlab;

use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
#[macro_use]
extern crate clap;

use gitlab::GitLab;
use gitlab::issues;
use gitlab::Lister;

use gitlab::errors::*;

fn main() {
    if let Err(ref e) = run() {
        println!("error: {}", e);

        for e in e.iter().skip(1) {
            println!("caused by: {}", e);
        }

        // The backtrace is not always generated. Try to run this example
        // with `RUST_BACKTRACE=1`.
        if let Some(backtrace) = e.backtrace() {
            println!("backtrace: {:?}", backtrace);
        }

        ::std::process::exit(1);
    }
}

fn run() -> Result<()> {
    env_logger::init().unwrap();
    info!("starting up");

    let hostname = match env::var("GITLAB_HOSTNAME") {
        Ok(val) => val,
        Err(_) => {
            let default = String::from("gitlab.com");
            println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.",
                     default);
            default
        }
    };

    let token = match env::var("GITLAB_TOKEN") {
        Ok(val) => val,
        Err(_) => {
            panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \
                    http://{}/profile/account",
                   hostname);
        }
    };

    let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?;
    // let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?.scheme("http").port(80);
    // let gl = gl.scheme("http").port(80);

    let matches = clap::App::new("get_id_merge_request")
        .version("1.0")
        .author("Nicolas Bigaouette <nbigaouette@gmail.com>")
        .about("Get the id of a GitLab project from namespace/project.")
        .arg(clap::Arg::with_name("namespace")
            .help("The project's namespace (or group)")
            .long("namespace")
            .short("n")
            .takes_value(true)
            .required(true))
        .arg(clap::Arg::with_name("project")
            .help("The project's name")
            .long("project")
            .short("p")
            .takes_value(true)
            .required(true))
        .arg(clap::Arg::with_name("id")
            .help("The merge request's id")
            .long("id")
            .short("i")
            .takes_value(true)
            .required(true))
        .get_matches();

    let project_namespace = matches.value_of("namespace").unwrap();
    let project_name = matches.value_of("project").unwrap();
    let merge_request_iid = value_t!(matches, "id", i64).unwrap_or_else(|e| e.exit());

    let merge_request = gl.get_merge_request(project_namespace, project_name, merge_request_iid).chain_err(|| "cannot get merge request")?;
    // println!("merge_request: {:?}", merge_request);

    println!("Id for {}/{}!{}: {}", project_namespace, project_name, merge_request_iid, merge_request.id);

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>add regression test<commit_after>// build-pass
// compile-flags: -Copt-level=0

// Regression test for #88043: LLVM crash when the RemoveZsts mir-opt pass is enabled.
// We should not see the error:
// `Basic Block in function '_ZN4main10take_until17h0067b8a660429bc9E' does not have terminator!`

fn bump() -> Option<usize> {
    unreachable!()
}

fn take_until(terminate: impl Fn() -> bool) {
    loop {
        if terminate() {
            return;
        } else {
            bump();
        }
    }
}

// CHECK-LABEL: @main
fn main() {
    take_until(|| true);
}
<|endoftext|>


<commit_before><commit_msg>Add Viewer Trait<commit_after>use libimagstore::store::Entry;

use result::Result;

pub trait Viewer {

    fn view_entry(&self, e: &Entry) -> Result<()>;

    fn view_entries<I: Iterator<Item = Entry>>(&self, entries: I) -> Result<()> {
        for entry in entries {
            if let Err(e) = self.view_entry(&entry) {
                return Err(e);
            }
        }
        Ok(())
    }
}
<|endoftext|>


<commit_before>extern crate orbital;

use orbital::Color;

use std::fs::File;
use std::io::{Read, Write};
use std::ops::Deref;
use std::sync::Arc;
use std::syscall::*;
use std::thread;

use window::ConsoleWindow;

mod window;

macro_rules! readln {
    () => ({
        let mut buffer = String::new();
        match std::io::stdin().read_line(&mut buffer) {
            Ok(_) => Some(buffer),
            Err(_) => None
        }
    });
}

pub fn pipe() -> [usize; 2] {
    let mut fds = [0; 2];
    SysError::demux(unsafe { sys_pipe2(fds.as_mut_ptr(), 0) }).unwrap();
    fds
}

#[no_mangle]
pub fn main() {
    let to_shell_fds = pipe();
    let from_shell_fds = pipe();

    unsafe {
        if SysError::demux(sys_clone(0)).unwrap() == 0 {
            // Close STDIO
            sys_close(2);
            sys_close(1);
            sys_close(0);

            // Create piped STDIO
            sys_dup(to_shell_fds[0]);
            sys_dup(from_shell_fds[1]);
            sys_dup(from_shell_fds[1]);

            // Close extra pipes
            sys_close(to_shell_fds[0]);
            sys_close(to_shell_fds[1]);
            sys_close(from_shell_fds[0]);
            sys_close(from_shell_fds[1]);

            // Execute the shell
            let shell = "file:/apps/shell/main.bin\0";
            sys_execve(shell.as_ptr(), 0 as *const *const u8);
            panic!("Shell not found");
        } else {
            // Close extra pipes
            sys_close(to_shell_fds[0]);
            sys_close(from_shell_fds[1]);
        }
    };

    let window = Arc::new(ConsoleWindow::new(-1, -1, 576, 400, "Terminal"));

    let window_weak = Arc::downgrade(&window);
    thread::spawn(move || {
        let mut from_shell = unsafe { File::from_fd(from_shell_fds[0]).unwrap() };
        loop {
            let mut output = String::new();
            if let Ok(_) = from_shell.read_to_string(&mut output) {
                if let Some(window) = window_weak.upgrade() {
                    let window_ptr = (window.deref() as *const Box<ConsoleWindow>) as *mut Box<ConsoleWindow>;
                    unsafe { &mut *window_ptr }.print(&output, Color::rgb(255, 255, 255));
                    unsafe { &mut *window_ptr }.sync();
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    });

    {
        let mut to_shell = unsafe { File::from_fd(to_shell_fds[1]).unwrap() };
        let window_ptr = (window.deref() as *const Box<ConsoleWindow>) as *mut Box<ConsoleWindow>;
        while let Some(string) = unsafe { &mut *window_ptr }.read() {
            if ! string.is_empty() {
                println!("{}", string);
                if let Ok(_) = to_shell.write(&string.into_bytes()) {

                } else {
                    break;
                }
            }
        }
    }
}
<commit_msg>Remove print<commit_after>extern crate orbital;

use orbital::Color;

use std::fs::File;
use std::io::{Read, Write};
use std::ops::Deref;
use std::sync::Arc;
use std::syscall::*;
use std::thread;

use window::ConsoleWindow;

mod window;

macro_rules! readln {
    () => ({
        let mut buffer = String::new();
        match std::io::stdin().read_line(&mut buffer) {
            Ok(_) => Some(buffer),
            Err(_) => None
        }
    });
}

pub fn pipe() -> [usize; 2] {
    let mut fds = [0; 2];
    SysError::demux(unsafe { sys_pipe2(fds.as_mut_ptr(), 0) }).unwrap();
    fds
}

#[no_mangle]
pub fn main() {
    let to_shell_fds = pipe();
    let from_shell_fds = pipe();

    unsafe {
        if SysError::demux(sys_clone(0)).unwrap() == 0 {
            // Close STDIO
            sys_close(2);
            sys_close(1);
            sys_close(0);

            // Create piped STDIO
            sys_dup(to_shell_fds[0]);
            sys_dup(from_shell_fds[1]);
            sys_dup(from_shell_fds[1]);

            // Close extra pipes
            sys_close(to_shell_fds[0]);
            sys_close(to_shell_fds[1]);
            sys_close(from_shell_fds[0]);
            sys_close(from_shell_fds[1]);

            // Execute the shell
            let shell = "file:/apps/shell/main.bin\0";
            sys_execve(shell.as_ptr(), 0 as *const *const u8);
            panic!("Shell not found");
        } else {
            // Close extra pipes
            sys_close(to_shell_fds[0]);
            sys_close(from_shell_fds[1]);
        }
    };

    let window = Arc::new(ConsoleWindow::new(-1, -1, 576, 400, "Terminal"));

    let window_weak = Arc::downgrade(&window);
    thread::spawn(move || {
        let mut from_shell = unsafe { File::from_fd(from_shell_fds[0]).unwrap() };
        loop {
            let mut output = String::new();
            if let Ok(_) = from_shell.read_to_string(&mut output) {
                if let Some(window) = window_weak.upgrade() {
                    let window_ptr = (window.deref() as *const Box<ConsoleWindow>) as *mut Box<ConsoleWindow>;
                    unsafe { &mut *window_ptr }.print(&output, Color::rgb(255, 255, 255));
                    unsafe { &mut *window_ptr }.sync();
                } else {
                    break;
                }
            } else {
                break;
            }
        }
    });

    {
        let mut to_shell = unsafe { File::from_fd(to_shell_fds[1]).unwrap() };
        let window_ptr = (window.deref() as *const Box<ConsoleWindow>) as *mut Box<ConsoleWindow>;
        while let Some(string) = unsafe { &mut *window_ptr }.read() {
            if ! string.is_empty() {
                if let Ok(_) = to_shell.write(&string.into_bytes()) {

                } else {
                    break;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test to check that we do not get a cycle due to resolving `Self::Bar` in the where clauses<commit_after>// check-pass

// Test that we do not get a cycle due to
// resolving `Self::Bar` in the where clauses
// on a trait definition (in particular, in
// a where clause that is defining a superpredicate).

trait Foo {
    type Bar;
}
trait Qux
where
    Self: Foo,
    Self: AsRef<Self::Bar>,
{
}
trait Foo2 {}

trait Qux2
where
    Self: Foo2,
    Self: AsRef<Self::Bar>,
{
    type Bar;
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Allow unused variable here<commit_after><|endoftext|>


<commit_before><commit_msg>Don't add margin/border/padding twice to position<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: `--debug` on CLI should enable logging and override it<commit_after><|endoftext|>


<commit_before><commit_msg>Reexported shared routines.<commit_after><|endoftext|>


<commit_before>#![feature(
    btree_range,
    collections,
    collections_bound,
    question_mark,
    rustc_private,
    pub_restricted,
)]

// From rustc.
#[macro_use] extern crate rustc;
extern crate rustc_borrowck;
extern crate rustc_data_structures;
extern crate rustc_mir;
extern crate rustc_const_math;
extern crate syntax;
#[macro_use] extern crate log;
extern crate log_settings;

// From crates.io.
extern crate byteorder;

mod error;
mod interpreter;
mod memory;
mod primval;

pub use error::{
    EvalError,
    EvalResult,
};

pub use interpreter::{
    CachedMir,
    EvalContext,
    Frame,
    eval_main,
    run_mir_passes,
    StackPopCleanup,
};

pub use memory::{
    Memory,
    Pointer,
    AllocId,
};
<commit_msg>Update for changes in rustc.<commit_after>#![feature(
    btree_range,
    collections,
    collections_bound,
    rustc_private,
    pub_restricted,
)]

// From rustc.
#[macro_use] extern crate rustc;
extern crate rustc_borrowck;
extern crate rustc_data_structures;
extern crate rustc_mir;
extern crate rustc_const_math;
extern crate syntax;
#[macro_use] extern crate log;
extern crate log_settings;

// From crates.io.
extern crate byteorder;

mod error;
mod interpreter;
mod memory;
mod primval;

pub use error::{
    EvalError,
    EvalResult,
};

pub use interpreter::{
    CachedMir,
    EvalContext,
    Frame,
    eval_main,
    run_mir_passes,
    StackPopCleanup,
};

pub use memory::{
    Memory,
    Pointer,
    AllocId,
};
<|endoftext|>


<commit_before>extern crate rustc_version;
extern crate rusoto_codegen;

use std::env;
use std::path::Path;
use std::io::Write;
use std::fs::File;

use rusoto_codegen::{Service, generate};

/// Parses and generates variables used to construct a User-Agent.
///
/// This is used to create a User-Agent header string resembling
/// `rusoto/x.y.z rust/x.y.z <os>`.
fn generate_user_agent_vars(output_path: &Path) {
    let rust_version = rustc_version::version();
    let mut f = File::create(&output_path.join("user_agent_vars.rs"))
            .expect("Could not create user agent file");
    f.write_all(format!("static RUST_VERSION: &'static str = \"{}\";", rust_version).as_bytes())
            .expect("Unable to write user agent");
}

/*
gamelift/2015-10-01/service-2.json:    "protocol":"json"
support/2013-04-15/service-2.json:    "protocol":"json"
*/

// expand to use cfg!() so codegen only gets run for services
// in the features list
macro_rules! services {
    ( $( [$name:expr, $date:expr] ),* ) => {
        {
            let mut services = Vec::new();
            $(
                if cfg!(feature = $name) {
                    services.push(Service::new($name, $date));
                }
            )*
            services
        }
    }
}

fn main() {
    let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR not specified");
    let out_path = Path::new(&out_dir);

    let services = services! {
        ["acm", "2015-12-08"],
        ["cloudformation", "2010-05-15"],
        ["cloudhsm", "2014-05-30"],
        ["cloudtrail", "2013-11-01"],
        ["cloudwatch", "2010-08-01"],
        ["codecommit", "2015-04-13"],
        ["codedeploy", "2014-10-06"],
        ["codepipeline", "2015-07-09"],
        ["cognito-identity", "2014-06-30"],
        ["config", "2014-11-12"],
        ["datapipeline", "2012-10-29"],
        ["devicefarm", "2015-06-23"],
        ["directconnect", "2012-10-25"],
        ["ds", "2015-04-16"],
        ["dynamodb", "2012-08-10"],
        ["dynamodbstreams", "2012-08-10"],
        ["ec2", "2015-10-01"],
        ["ecr", "2015-09-21"],
        ["ecs", "2014-11-13"],
        ["elastictranscoder", "2012-09-25"],
        ["emr", "2009-03-31"],
        ["events", "2014-02-03"],
        ["firehose", "2015-08-04"],
        ["iam", "2010-05-08"],
        ["inspector", "2016-02-16"],
        ["iot", "2015-05-28"],
        ["kinesis", "2013-12-02"],
        ["kms", "2014-11-01"],
        ["logs", "2014-03-28"],
        ["machinelearning", "2014-12-12"],
        ["marketplacecommerceanalytics", "2015-07-01"],
        ["opsworks", "2013-02-18"],
        ["route53domains", "2014-05-15"],
        ["s3", "2006-03-01"],
        ["sqs", "2012-11-05"],
        ["ssm", "2014-11-06"],
        ["storagegateway", "2013-06-30"],
        ["swf", "2012-01-25"],
        ["waf", "2015-08-24"],
        ["workspaces", "2015-04-08"]
    };

    for service in services {
        generate(service, out_path);
    }

    generate_user_agent_vars(out_path);

    let codegen_dir = Path::new("codegen");

    // avoid unnecessary recompiles when used as a crates.io dependency
    if codegen_dir.exists() {
        println!("cargo:rerun-if-changed=codegen");
    }
}
<commit_msg>Try using threads for codegen.<commit_after>extern crate rustc_version;
extern crate rusoto_codegen;

use std::env;
use std::path::Path;
use std::io::Write;
use std::fs::File;
use std::thread;

use rusoto_codegen::{Service, generate};

/// Parses and generates variables used to construct a User-Agent.
///
/// This is used to create a User-Agent header string resembling
/// `rusoto/x.y.z rust/x.y.z <os>`.
fn generate_user_agent_vars(output_path: &Path) {
    let rust_version = rustc_version::version();
    let mut f = File::create(&output_path.join("user_agent_vars.rs"))
            .expect("Could not create user agent file");
    f.write_all(format!("static RUST_VERSION: &'static str = \"{}\";", rust_version).as_bytes())
            .expect("Unable to write user agent");
}

/*
gamelift/2015-10-01/service-2.json:    "protocol":"json"
support/2013-04-15/service-2.json:    "protocol":"json"
*/

// expand to use cfg!() so codegen only gets run for services
// in the features list
macro_rules! services {
    ( $( [$name:expr, $date:expr] ),* ) => {
        {
            let mut services = Vec::new();
            $(
                if cfg!(feature = $name) {
                    services.push(Service::new($name, $date));
                }
            )*
            services
        }
    }
}

fn main() {
    let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR not specified");
    let out_path = Path::new(&out_dir).to_owned();

    let services = services! {
        ["acm", "2015-12-08"],
        ["cloudformation", "2010-05-15"],
        ["cloudhsm", "2014-05-30"],
        ["cloudtrail", "2013-11-01"],
        ["cloudwatch", "2010-08-01"],
        ["codecommit", "2015-04-13"],
        ["codedeploy", "2014-10-06"],
        ["codepipeline", "2015-07-09"],
        ["cognito-identity", "2014-06-30"],
        ["config", "2014-11-12"],
        ["datapipeline", "2012-10-29"],
        ["devicefarm", "2015-06-23"],
        ["directconnect", "2012-10-25"],
        ["ds", "2015-04-16"],
        ["dynamodb", "2012-08-10"],
        ["dynamodbstreams", "2012-08-10"],
        ["ec2", "2015-10-01"],
        ["ecr", "2015-09-21"],
        ["ecs", "2014-11-13"],
        ["elastictranscoder", "2012-09-25"],
        ["emr", "2009-03-31"],
        ["events", "2014-02-03"],
        ["firehose", "2015-08-04"],
        ["iam", "2010-05-08"],
        ["inspector", "2016-02-16"],
        ["iot", "2015-05-28"],
        ["kinesis", "2013-12-02"],
        ["kms", "2014-11-01"],
        ["logs", "2014-03-28"],
        ["machinelearning", "2014-12-12"],
        ["marketplacecommerceanalytics", "2015-07-01"],
        ["opsworks", "2013-02-18"],
        ["route53domains", "2014-05-15"],
        ["s3", "2006-03-01"],
        ["sqs", "2012-11-05"],
        ["ssm", "2014-11-06"],
        ["storagegateway", "2013-06-30"],
        ["swf", "2012-01-25"],
        ["waf", "2015-08-24"],
        ["workspaces", "2015-04-08"]
    };

    let mut generate_threads = vec![];
    for service in services {
        let thread_outpath = out_path.clone();
        generate_threads.push(thread::spawn(move || {
            generate(service, &thread_outpath);
        }));
    }

    for child_thread in generate_threads {
        let _ = child_thread.join();
    }

    generate_user_agent_vars(&out_path);

    let codegen_dir = Path::new("codegen");

    // avoid unnecessary recompiles when used as a crates.io dependency
    if codegen_dir.exists() {
        println!("cargo:rerun-if-changed=codegen");
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix the Vulkan library path calculation on Linux<commit_after><|endoftext|>


<commit_before><commit_msg>add build.rs for code generation to support both stable & nightly Rust<commit_after>#[cfg(not(feature = "serde_macros"))]
mod inner {
    extern crate serde_codegen;

    use std::env;
    use std::path::Path;

    pub fn main() {
        let out_dir = env::var_os("OUT_DIR").unwrap();

        let src = Path::new("src/main.rs.in");
        let dst = Path::new(&out_dir).join("main.rs");

        serde_codegen::expand(&src, &dst).unwrap();
    }
}

#[cfg(feature = "serde_macros")]
mod inner {
    pub fn main() {}
}

fn main() {
    inner::main();
}
<|endoftext|>


<commit_before><commit_msg>Remove Store::reset_backend()<commit_after><|endoftext|>


<commit_before><commit_msg>Use a streamed 'Responder' body for 'File', as before.<commit_after><|endoftext|>


<commit_before><commit_msg>Use ? instead of try!().<commit_after><|endoftext|>


<commit_before><commit_msg>First pass at neural net<commit_after>use linalg::matrix::Matrix;
use rand::{Rng, thread_rng};

pub struct NeuralNet<'a> {
	layer_sizes: &'a [usize]
}

impl<'a> NeuralNet<'a> {
	pub fn new(layer_sizes: &[usize]) -> NeuralNet {
		NeuralNet{layer_sizes: layer_sizes}
	}

	fn create_layers(&self) {
		let total_layers = self.layer_sizes.len();

		let mut layers = Vec::with_capacity(total_layers-1);

		for l in 0..total_layers-1 {
			layers.push(
				initialize_weights(self.layer_sizes[l],self.layer_sizes[l+1]));
		}
	}
}

fn initialize_weights(rows: usize, cols: usize) -> Matrix<f64> {
	let mut weights = Vec::with_capacity(rows * cols);
	let eps_init = (6f64).sqrt() / ((rows + cols) as f64).sqrt();

	let mut rng = thread_rng();

	for _i in 0..rows*cols {
		let w = (rng.gen_range(0f64,1f64) * 2f64 * eps_init) - eps_init;
		weights.push(w);
	}

	Matrix::new(rows, cols, weights)
}<|endoftext|>


<commit_before><commit_msg>Fix editor command<commit_after><|endoftext|>


<commit_before><commit_msg>Tests - Add test for #63, reproduces on Mint 18.3<commit_after>// compile-flags: -O

// ::"core"::iter::Map<::"core"::iter::Chain<::"core"::iter::sources::Once<::"syntax"::ast::NodeId/*S*/,>/*S*/,::"core"::iter::Map<::"core"::slice::Iter<::"syntax"::codemap::Spanned<::"syntax"::ast::PathListItem_/*S*/,>/*S*/,>/*S*/,::"rustc"::closure_I_82<::"rustc"::hir::lowering::LoweringContext/*S*/,>/*S*/,>/*S*/,>/*S*/,::"rustc"::closure_I_83<::"rustc"::hir::lowering::LoweringContext/*S*/,>/*S*/,>

#[derive(Copy,Debug)]
struct NodeId(u32);
struct Ident(u32);
struct PathListItem_
{
    i: Ident,
    i2: Option<Ident>,
    n: NodeId,
}
struct Span(u32, u32, u32);
struct Spanned<T>
{
    v: T,
    sp: Span,
}
#[derive(Copy,Debug)]
struct ItemId {
    id: NodeId,
}

fn main()
{
    // return iter::once(i.id).chain(imports.iter().map(|import| import.node.id)).map(|id| hir::ItemId { id: id }).collect();
    //let list = [ Spanned { v: PathListItem_ { i: Ident(0), i2: None, n: NodeId(0) }, sp: Span(1,1,1) } ];
    let list: [Spanned<PathListItem_>; 0] = [ ];

    println!("{:?}", foo(0, &[]));
    println!("{:?}", foo(0, &[ Spanned { v: PathListItem_ { i: Ident(0), i2: None, n: NodeId(0) }, sp: Span(1,1,1) } ]));
    println!("{:?}", foo(0, &vec![]));
}

fn foo(n: u32, list: &[Spanned<PathListItem_>]) -> Vec<ItemId> {
    Iterator::chain(
            ::std::iter::once(NodeId(0)),
            list.iter().map(|v| v.v.n)
        ).map(|id| ItemId { id: id })
        .collect()
}

<|endoftext|>


<commit_before><commit_msg>Fix: Use backend abstraction for checking whether a path exists<commit_after><|endoftext|>


<commit_before>use alloc::boxed::Box;

use collections::vec::Vec;

use core::mem;

use drivers::pciconfig::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Gtd {
    flags: u32,
    buffer: u32,
    next: u32,
    end: u32,
}

pub struct Ohci {
    pub base: usize,
    pub irq: u8,
}

impl KScheme for Ohci {
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // d("OHCI IRQ\n");
        }
    }

    fn on_poll(&mut self) {
    }
}

impl Ohci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        pci.flag(4, 4, true); // Bus mastering

        let mut module = box Ohci {
            base: pci.read(0x10) as usize & 0xFFFFFFF0,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        return module;
    }

    pub unsafe fn init(&mut self) {
        debugln!("OHCI on: {:X}, IRQ: {:X}", self.base, self.irq);
    }
}

impl UsbHci for Ohci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Gtd) as u32,
                None => 0
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Gtd {
                    flags: 0b00 << 19,
                    buffer: (setup as *const Setup) as u32,
                    next: link_ptr,
                    end: (setup as *const Setup) as u32 + mem::size_of::<Setup>() as u32
                }),
                UsbMsg::In(ref data) => tds.push(Gtd {
                    flags: 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::InIso(ref data) => tds.push(Gtd {
                    flags: 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::Out(ref data) => tds.push(Gtd {
                    flags: 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::OutIso(ref data) => tds.push(Gtd {
                    flags: 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                })
            }
        }

        0
    }
}
<commit_msg>WIP: OHCI<commit_after>use alloc::boxed::Box;

use collections::vec::Vec;

use core::intrinsics::volatile_load;
use core::{mem, slice};

use drivers::mmio::Mmio;
use drivers::pciconfig::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Gtd {
    flags: u32,
    buffer: u32,
    next: u32,
    end: u32,
}

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Ed {
    flags: u32,
    tail: u32,
    head: u32,
    next: u32,
}

const CTRL_CBSR: u32 = 0b11;
const CTRL_PLE: u32 = 1 << 2;
const CTRL_IE: u32 = 1 << 3;
const CTRL_CLE: u32 = 1 << 4;
const CTRL_BLE: u32 = 1 << 5;
const CTRL_HCFS: u32 = 0b11 << 6;
const CTRL_IR: u32 = 1 << 8;
const CTRL_RWC: u32 = 1 << 9;
const CTRL_RWE: u32 = 1 << 10;

const CMD_STS_HCR: u32 = 1;
const CMD_STS_CLF: u32 = 1 << 1;
const CMD_STS_BLF: u32 = 1 << 2;
const CMD_STS_OCR: u32 = 1 << 3;

const PORT_STS_CCS: u32 = 1;
const PORT_STS_PES: u32 = 1 << 1;
const PORT_STS_PSS: u32 = 1 << 2;
const PORT_STS_POCI: u32 = 1 << 3;
const PORT_STS_PPS: u32 = 1 << 8;
const PORT_STS_LSDA: u32 = 1 << 9;
const PORT_STS_CSC: u32 = 1 << 16;
const PORT_STS_PESC: u32 = 1 << 17;
const PORT_STS_PSSC: u32 = 1 << 18;
const PORT_STS_OCIC: u32 = 1 << 19;
const PORT_STS_PRSC: u32 = 1 << 20;

#[repr(packed)]
pub struct OhciRegs {
    pub revision: Mmio<u32>,
    pub control: Mmio<u32>,
    pub cmd_sts: Mmio<u32>,
    pub int_sts: Mmio<u32>,
    pub int_en: Mmio<u32>,
    pub int_dis: Mmio<u32>,
    pub hcca: Mmio<u32>,
    pub period_current: Mmio<u32>,
    pub control_head: Mmio<u32>,
    pub control_current: Mmio<u32>,
    pub bulk_head: Mmio<u32>,
    pub bulk_current: Mmio<u32>,
    pub done_head: Mmio<u32>,
    pub fm_interval: Mmio<u32>,
    pub fm_remain: Mmio<u32>,
    pub fm_num: Mmio<u32>,
    pub periodic_start: Mmio<u32>,
    pub ls_thresh: Mmio<u32>,
    pub rh_desc_a: Mmio<u32>,
    pub rh_desc_b: Mmio<u32>,
    pub rh_sts: Mmio<u32>,
    pub port_sts: [Mmio<u32>; 15],
}

pub struct Ohci {
    pub regs: &'static mut OhciRegs,
    pub irq: u8,
}

impl KScheme for Ohci {
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // d("OHCI IRQ\n");
        }
    }

    fn on_poll(&mut self) {
    }
}

impl Ohci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        pci.flag(4, 4, true); // Bus mastering

        let base = pci.read(0x10) as usize & 0xFFFFFFF0;
        let regs = &mut *(base as *mut OhciRegs);

        let mut module = box Ohci {
            regs: regs,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        return module;
    }

    pub unsafe fn init(&mut self) {
        debugln!("OHCI on: {:X}, IRQ: {:X}", (self.regs as *mut OhciRegs) as usize, self.irq);

        let ctrl = self.regs.control.read();
        self.regs.control.write(ctrl & (0xFFFFFFFF - CTRL_HCFS) | 0b10 << 6);

        let ndp = self.regs.rh_desc_a.read() & 0xF;
        for i in 0..ndp as usize {
            debugln!("Port {}: {:X}", i, self.regs.port_sts[i].read());

            if self.regs.port_sts[i].readf(PORT_STS_CCS) {
                debugln!("Device");

                debugln!("Enable");
                while ! self.regs.port_sts[i].readf(PORT_STS_PES) {
                    self.regs.port_sts[i].writef(PORT_STS_PES, true);
                }

                self.device(i as u8);
            }
        }
    }
}

impl UsbHci for Ohci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Gtd) as u32,
                None => 0
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b00 << 19,
                    buffer: (setup as *const Setup) as u32,
                    next: link_ptr,
                    end: (setup as *const Setup) as u32 + mem::size_of::<Setup>() as u32
                }),
                UsbMsg::In(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::InIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::Out(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::OutIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                })
            }
        }

        let mut count = 0;

        if ! tds.is_empty() {
            let ed = box Ed {
                flags: 1024 << 16 | (endpoint as u32) << 7 | address as u32,
                tail: 0,
                head: (tds.last().unwrap() as *const Gtd) as u32,
                next: 0
            };

            //TODO: Calculate actual bytes
            for td in tds.iter().rev() {
                count += (td.end - td.buffer) as usize;
            }

            /*
            self.regs.control_head.write((&*ed as *const Ed) as u32);
            while ! self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, true);
            }
            while ! self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, true);
            }

            for td in tds.iter().rev() {
                while unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28 == 0b1111 << 28 {
                    //unsafe { context_switch(false) };
                }
            }

            while self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, false);
            }
            while self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, false);
            }
            self.regs.control_head.write(0);
            */
        }

        count
    }
}
<|endoftext|>


<commit_before><commit_msg>implement a more generic message channel over unix sockets<commit_after>use mio::Ready;
use mio_uds::UnixStream;
use std::str::from_utf8;
use std::marker::PhantomData;
use std::io::{self,Read,Write,ErrorKind};
use std::cmp::min;
use log;
use serde_json;
use serde::ser::Serialize;
use serde::de::Deserialize;

use network::buffer::Buffer;

#[derive(Debug,PartialEq)]
pub enum ConnError {
  Continue,
  ParseError,
  SocketError,
}

pub struct CommandClient<Tx,Rx> {
  pub sock:        UnixStream,
  front_buf:       Buffer,
  back_buf:        Buffer,
  max_buffer_size: usize,
  pub readiness:   Ready,
  pub interest:    Ready,
  phantom_tx:      PhantomData<Tx>,
  phantom_rx:      PhantomData<Rx>,
}

impl<Tx: Serialize, Rx: Deserialize> CommandClient<Tx,Rx> {
  pub fn new(sock: UnixStream, buffer_size: usize, max_buffer_size: usize) -> CommandClient<Tx,Rx> {
    CommandClient {
      sock:            sock,
      front_buf:       Buffer::with_capacity(buffer_size),
      back_buf:        Buffer::with_capacity(buffer_size),
      max_buffer_size: max_buffer_size,
      readiness:       Ready::none(),
      interest:        Ready::readable(),
      phantom_tx:      PhantomData,
      phantom_rx:      PhantomData,
    }
  }

  fn handle_events(&mut self, events: Ready) {
    self.readiness = self.readiness | events;
  }

  fn run(&mut self) {
    let interest = self.interest & self.readiness;

    if interest.is_readable() {
      self.readable();
    }

    if interest.is_writable() {
      self.writable();
    }
  }

  fn readable(&mut self) -> Result<usize,ConnError> {
    if !(self.interest & self.readiness).is_readable() {
      return Err(ConnError::Continue);
    }

    let mut count = 0usize;
    loop {
      let size = self.front_buf.available_space();
      if size == 0 {
        self.interest.remove(Ready::readable());
        break;
      }

      match self.sock.read(self.front_buf.space()) {
        Ok(0) => {
          break;
        },
        Err(e) => {
          match e.kind() {
            ErrorKind::WouldBlock => {
              self.readiness.remove(Ready::readable());
              break;
            },
            code => {
              //log!(log::LogLevel::Error, "UNIX CLIENT[{}] read error (kind: {:?}): {:?}", tok.0, code, e);
              self.interest  = Ready::none();
              self.readiness = Ready::none();
              return Err(ConnError::SocketError);
            }
          }
        },
        Ok(r) => {
          count += r;
          self.front_buf.fill(r);
          //debug!("UNIX CLIENT[{}] sent {} bytes: {:?}", tok.0, r, from_utf8(self.buf.data()));
        },
      };
    }

    Ok(count)
  }

  fn writable(&mut self) -> Result<usize,ConnError> {
    if !(self.interest & self.readiness).is_writable() {
      return Err(ConnError::Continue);
    }

    let mut count = 0usize;
    loop {
      let size = self.back_buf.available_data();
      if size == 0 {
        self.interest.remove(Ready::writable());
        break;
      }

      match self.sock.write(self.back_buf.data()) {
        Ok(0) => {
          break;
        },
        Ok(r) => {
          count += r;
          self.back_buf.consume(r);
        },
        Err(e) => {
          match e.kind() {
            ErrorKind::WouldBlock => {
              self.interest.remove(Ready::writable());
              break;
            },
            code => {
              self.interest  = Ready::none();
              self.readiness = Ready::none();
              return Err(ConnError::SocketError);
            }
          }
        }
      }
    }

    Ok(count)
  }

  fn read_message(&mut self) -> Option<Rx> {
    let mut offset = 0usize;
    let mut grow   = false;

    if let Some(pos) = self.front_buf.data().iter().position(|&x| x == 0) {
      let mut res = None;

      if let Ok(s) = from_utf8(&self.front_buf.data()[..pos]) {
        if let Ok(message) = serde_json::from_str(s) {
          res = Some(message);
        } else {
          error!("could not parse message, ignoring:\n{}", s);
        }
      } else {
        error!("invalid utf-8 encoding in command message, ignoring");
      }

      self.front_buf.consume(pos+1);
      res
    } else {
      if self.front_buf.available_space() == 0 {
        if self.front_buf.capacity() == self.max_buffer_size {
          error!("command buffer full, cannot grow more, ignoring");
        } else {
          let new_size = min(self.front_buf.capacity()+5000, self.max_buffer_size);
          self.front_buf.grow(new_size);
        }
      }

      self.interest.insert(Ready::readable());
      None
    }
  }

  pub fn write_message(&mut self, message: Tx) -> bool {
    let message = &serde_json::to_string(&message).map(|s| s.into_bytes()).unwrap_or(vec!());

    let msg_len = message.len() + 1;
    if msg_len > self.back_buf.available_space() {
      self.back_buf.shift();
    }

    if msg_len > self.back_buf.available_space() {
      if msg_len - self.back_buf.available_space() + self.back_buf.capacity() > self.max_buffer_size {
        error!("message is too large to write to back buffer");
        return false;
      }

      let new_len = msg_len - self.back_buf.available_space() + self.back_buf.capacity();
      self.back_buf.grow( new_len );
    }

    self.back_buf.write(message);
    self.back_buf.write(&b"\0"[..]);
    true
  }
}

<|endoftext|>


<commit_before><commit_msg>Add more enums to wrap constants.<commit_after><|endoftext|>


<commit_before><commit_msg>Create a Movement enum<commit_after>//! Movement for a Turing machine is restricted to Left and Right. This tells
//! which way the Turing machines read/write head should move after a state
//! transition.

pub enum Movement {
    Left,
    Right,
}
<|endoftext|>


<commit_before><commit_msg>Fix Word Parser Test<commit_after><|endoftext|>


<commit_before><commit_msg>Update index_iter tests<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #28993 - frewsxcv:regression-test-17336, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>Added test for map and reduce<commit_after>use std::thread;

fn main () {
     let data = "86967897737416471853297327050364959
     11861322575564723963297542624962850
     70856234701860851907960690014725639
     38397966707106094172783238747669219
     52380795257888236525459303330302837
     58495327135744041048897885734297812
     69920216438980873548808413720956532
     16278424637452589860345374828574668";

     let mut children = vec![];
     let chunked_data = data.split_whitespace();

     //Map
     for (i, data_segment) in chunked_data.enumerate() {
        println!("data segment  {} is \"{}\"", i, data_segment);
        children.push(thread::spawn(
            move || -> u32 {
                let result = data.chars().map(|c| c.to_digit(10).expect("should be a digit")).sum();
                println!("processed segement {}, result={}",i, result);
                result
            }));
     }

    //Reduce
    let mut intermediate_sums = vec![];
    for child in children {
        let intermediate_sum = child.join().unwrap();
        intermediate_sums.push(intermediate_sum);
    }

    let final_result = intermediate_sums.iter().sum::<u32>();
    println!("Final sum result: {}", final_result);

}

<|endoftext|>


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

#![deny(warnings)]

extern crate build_helper;
extern crate cc;

use std::env;
use std::path::PathBuf;
use std::process::Command;
use build_helper::{run, native_lib_boilerplate};

fn main() {
    // FIXME: This is a hack to support building targets that don't
    // support jemalloc alongside hosts that do. The jemalloc build is
    // controlled by a feature of the std crate, and if that feature
    // changes between targets, it invalidates the fingerprint of
    // std's build script (this is a cargo bug); so we must ensure
    // that the feature set used by std is the same across all
    // targets, which means we have to build the alloc_jemalloc crate
    // for targets like emscripten, even if we don't use it.
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    if target.contains("rumprun") || target.contains("bitrig") || target.contains("openbsd") ||
       target.contains("msvc") || target.contains("emscripten") || target.contains("fuchsia") ||
       target.contains("redox") || target.contains("wasm32") {
        println!("cargo:rustc-cfg=dummy_jemalloc");
        return;
    }

    if target.contains("android") {
        println!("cargo:rustc-link-lib=gcc");
    } else if !target.contains("windows") && !target.contains("musl") {
        println!("cargo:rustc-link-lib=pthread");
    }

    if let Some(jemalloc) = env::var_os("JEMALLOC_OVERRIDE") {
        let jemalloc = PathBuf::from(jemalloc);
        println!("cargo:rustc-link-search=native={}",
                 jemalloc.parent().unwrap().display());
        let stem = jemalloc.file_stem().unwrap().to_str().unwrap();
        let name = jemalloc.file_name().unwrap().to_str().unwrap();
        let kind = if name.ends_with(".a") {
            "static"
        } else {
            "dylib"
        };
        println!("cargo:rustc-link-lib={}={}", kind, &stem[3..]);
        return;
    }

    let link_name = if target.contains("windows") { "jemalloc" } else { "jemalloc_pic" };
    let native = match native_lib_boilerplate("jemalloc", "jemalloc", link_name, "lib") {
        Ok(native) => native,
        _ => return,
    };

    let mut cmd = Command::new("sh");
    cmd.arg(native.src_dir.join("configure")
                          .to_str()
                          .unwrap()
                          .replace("C:\\", "/c/")
                          .replace("\\", "/"))
       .current_dir(&native.out_dir)
       // jemalloc generates Makefile deps using GCC's "-MM" flag. This means
       // that GCC will run the preprocessor, and only the preprocessor, over
       // jemalloc's source files. If we don't specify CPPFLAGS, then at least
       // on ARM that step fails with a "Missing implementation for 32-bit
       // atomic operations" error. This is because no "-march" flag will be
       // passed to GCC, and then GCC won't define the
       // "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4" macro that jemalloc needs to
       // select an atomic operation implementation.
       .env("CPPFLAGS", env::var_os("CFLAGS").unwrap_or_default());

    if target.contains("ios") {
        cmd.arg("--disable-tls");
    } else if target.contains("android") {
        // We force android to have prefixed symbols because apparently
        // replacement of the libc allocator doesn't quite work. When this was
        // tested (unprefixed symbols), it was found that the `realpath`
        // function in libc would allocate with libc malloc (not jemalloc
        // malloc), and then the standard library would free with jemalloc free,
        // causing a segfault.
        //
        // If the test suite passes, however, without symbol prefixes then we
        // should be good to go!
        cmd.arg("--with-jemalloc-prefix=je_");
        cmd.arg("--disable-tls");
    } else if target.contains("dragonfly") || target.contains("musl") {
        cmd.arg("--with-jemalloc-prefix=je_");
    }

    // FIXME: building with jemalloc assertions is currently broken.
    // See <https://github.com/rust-lang/rust/issues/44152>.
    //if cfg!(feature = "debug") {
    //    cmd.arg("--enable-debug");
    //}

    cmd.arg(format!("--host={}", build_helper::gnu_target(&target)));
    cmd.arg(format!("--build={}", build_helper::gnu_target(&host)));

    // for some reason, jemalloc configure doesn't detect this value
    // automatically for this target
    if target == "sparc64-unknown-linux-gnu" {
        cmd.arg("--with-lg-quantum=4");
    }

    run(&mut cmd);

    let mut make = Command::new(build_helper::make(&host));
    make.current_dir(&native.out_dir)
        .arg("build_lib_static");

    // These are intended for mingw32-make which we don't use
    if cfg!(windows) {
        make.env_remove("MAKEFLAGS").env_remove("MFLAGS");
    }

    // mingw make seems... buggy? unclear...
    if !host.contains("windows") {
        make.arg("-j")
            .arg(env::var("NUM_JOBS").expect("NUM_JOBS was not set"));
    }

    run(&mut make);

    // The pthread_atfork symbols is used by jemalloc on android but the really
    // old android we're building on doesn't have them defined, so just make
    // sure the symbols are available.
    if target.contains("androideabi") {
        println!("cargo:rerun-if-changed=pthread_atfork_dummy.c");
        cc::Build::new()
            .flag("-fvisibility=hidden")
            .file("pthread_atfork_dummy.c")
            .compile("pthread_atfork_dummy");
    }
}
<commit_msg>Add CloudABI to the list of systems on which we stub out alloc_jemalloc.<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![deny(warnings)]

extern crate build_helper;
extern crate cc;

use std::env;
use std::path::PathBuf;
use std::process::Command;
use build_helper::{run, native_lib_boilerplate};

fn main() {
    // FIXME: This is a hack to support building targets that don't
    // support jemalloc alongside hosts that do. The jemalloc build is
    // controlled by a feature of the std crate, and if that feature
    // changes between targets, it invalidates the fingerprint of
    // std's build script (this is a cargo bug); so we must ensure
    // that the feature set used by std is the same across all
    // targets, which means we have to build the alloc_jemalloc crate
    // for targets like emscripten, even if we don't use it.
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    if target.contains("bitrig") || target.contains("cloudabi") || target.contains("emscripten") ||
       target.contains("fuchsia") || target.contains("msvc") || target.contains("openbsd") ||
       target.contains("redox") || target.contains("rumprun") || target.contains("wasm32") {
        println!("cargo:rustc-cfg=dummy_jemalloc");
        return;
    }

    if target.contains("android") {
        println!("cargo:rustc-link-lib=gcc");
    } else if !target.contains("windows") && !target.contains("musl") {
        println!("cargo:rustc-link-lib=pthread");
    }

    if let Some(jemalloc) = env::var_os("JEMALLOC_OVERRIDE") {
        let jemalloc = PathBuf::from(jemalloc);
        println!("cargo:rustc-link-search=native={}",
                 jemalloc.parent().unwrap().display());
        let stem = jemalloc.file_stem().unwrap().to_str().unwrap();
        let name = jemalloc.file_name().unwrap().to_str().unwrap();
        let kind = if name.ends_with(".a") {
            "static"
        } else {
            "dylib"
        };
        println!("cargo:rustc-link-lib={}={}", kind, &stem[3..]);
        return;
    }

    let link_name = if target.contains("windows") { "jemalloc" } else { "jemalloc_pic" };
    let native = match native_lib_boilerplate("jemalloc", "jemalloc", link_name, "lib") {
        Ok(native) => native,
        _ => return,
    };

    let mut cmd = Command::new("sh");
    cmd.arg(native.src_dir.join("configure")
                          .to_str()
                          .unwrap()
                          .replace("C:\\", "/c/")
                          .replace("\\", "/"))
       .current_dir(&native.out_dir)
       // jemalloc generates Makefile deps using GCC's "-MM" flag. This means
       // that GCC will run the preprocessor, and only the preprocessor, over
       // jemalloc's source files. If we don't specify CPPFLAGS, then at least
       // on ARM that step fails with a "Missing implementation for 32-bit
       // atomic operations" error. This is because no "-march" flag will be
       // passed to GCC, and then GCC won't define the
       // "__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4" macro that jemalloc needs to
       // select an atomic operation implementation.
       .env("CPPFLAGS", env::var_os("CFLAGS").unwrap_or_default());

    if target.contains("ios") {
        cmd.arg("--disable-tls");
    } else if target.contains("android") {
        // We force android to have prefixed symbols because apparently
        // replacement of the libc allocator doesn't quite work. When this was
        // tested (unprefixed symbols), it was found that the `realpath`
        // function in libc would allocate with libc malloc (not jemalloc
        // malloc), and then the standard library would free with jemalloc free,
        // causing a segfault.
        //
        // If the test suite passes, however, without symbol prefixes then we
        // should be good to go!
        cmd.arg("--with-jemalloc-prefix=je_");
        cmd.arg("--disable-tls");
    } else if target.contains("dragonfly") || target.contains("musl") {
        cmd.arg("--with-jemalloc-prefix=je_");
    }

    // FIXME: building with jemalloc assertions is currently broken.
    // See <https://github.com/rust-lang/rust/issues/44152>.
    //if cfg!(feature = "debug") {
    //    cmd.arg("--enable-debug");
    //}

    cmd.arg(format!("--host={}", build_helper::gnu_target(&target)));
    cmd.arg(format!("--build={}", build_helper::gnu_target(&host)));

    // for some reason, jemalloc configure doesn't detect this value
    // automatically for this target
    if target == "sparc64-unknown-linux-gnu" {
        cmd.arg("--with-lg-quantum=4");
    }

    run(&mut cmd);

    let mut make = Command::new(build_helper::make(&host));
    make.current_dir(&native.out_dir)
        .arg("build_lib_static");

    // These are intended for mingw32-make which we don't use
    if cfg!(windows) {
        make.env_remove("MAKEFLAGS").env_remove("MFLAGS");
    }

    // mingw make seems... buggy? unclear...
    if !host.contains("windows") {
        make.arg("-j")
            .arg(env::var("NUM_JOBS").expect("NUM_JOBS was not set"));
    }

    run(&mut make);

    // The pthread_atfork symbols is used by jemalloc on android but the really
    // old android we're building on doesn't have them defined, so just make
    // sure the symbols are available.
    if target.contains("androideabi") {
        println!("cargo:rerun-if-changed=pthread_atfork_dummy.c");
        cc::Build::new()
            .flag("-fvisibility=hidden")
            .file("pthread_atfork_dummy.c")
            .compile("pthread_atfork_dummy");
    }
}
<|endoftext|>


<commit_before><commit_msg>Simplify assignment<commit_after><|endoftext|>


<commit_before>/*
Module: option

Represents the presence or absence of a value.

Every option<T> value can either be some(T) or none. Where in other languages
you might use a nullable type, in Rust you would use an option type.
*/

/*
Tag: t

The option type
*/
enum t<T> {
    /* Variant: none */
    none,
    /* Variant: some */
    some(T),
}

/* Section: Operations */

/*
Function: get

Gets the value out of an option

Failure:

Fails if the value equals `none`.
*/
pure fn get<T: copy>(opt: t<T>) -> T {
    alt opt { some(x) { ret x; } none { fail "option none"; } }
}

/*
*/
fn map<T, U: copy>(opt: t<T>, f: fn(T) -> U) -> t<U> {
    alt opt { some(x) { some(f(x)) } none { none } }
}

/*
Function: is_none

Returns true if the option equals none
*/
pure fn is_none<T>(opt: t<T>) -> bool {
    alt opt { none { true } some(_) { false } }
}

/*
Function: is_some

Returns true if the option contains some value
*/
pure fn is_some<T>(opt: t<T>) -> bool { !is_none(opt) }

/*
Function: from_maybe

Returns the contained value or a default
*/
pure fn from_maybe<T: copy>(def: T, opt: t<T>) -> T {
    alt opt { some(x) { x } none { def } }
}

/*
Function: maybe

Applies a function to the contained value or returns a default
*/
fn maybe<T, U: copy>(def: U, opt: t<T>, f: fn(T) -> U) -> U {
    alt opt { none { def } some(t) { f(t) } }
}

// FIXME: Can be defined in terms of the above when/if we have const bind.
/*
Function: may

Performs an operation on the contained value or does nothing
*/
fn may<T>(opt: t<T>, f: fn(T)) {
    alt opt { none {/* nothing */ } some(t) { f(t); } }
}

#[test]
fn test() { let _x = some::<int>(10); }

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>core: Remove a useless test from option mod<commit_after>/*
Module: option

Represents the presence or absence of a value.

Every option<T> value can either be some(T) or none. Where in other languages
you might use a nullable type, in Rust you would use an option type.
*/

/*
Tag: t

The option type
*/
enum t<T> {
    /* Variant: none */
    none,
    /* Variant: some */
    some(T),
}

/* Section: Operations */

/*
Function: get

Gets the value out of an option

Failure:

Fails if the value equals `none`.
*/
pure fn get<T: copy>(opt: t<T>) -> T {
    alt opt { some(x) { ret x; } none { fail "option none"; } }
}

/*
*/
fn map<T, U: copy>(opt: t<T>, f: fn(T) -> U) -> t<U> {
    alt opt { some(x) { some(f(x)) } none { none } }
}

/*
Function: is_none

Returns true if the option equals none
*/
pure fn is_none<T>(opt: t<T>) -> bool {
    alt opt { none { true } some(_) { false } }
}

/*
Function: is_some

Returns true if the option contains some value
*/
pure fn is_some<T>(opt: t<T>) -> bool { !is_none(opt) }

/*
Function: from_maybe

Returns the contained value or a default
*/
pure fn from_maybe<T: copy>(def: T, opt: t<T>) -> T {
    alt opt { some(x) { x } none { def } }
}

/*
Function: maybe

Applies a function to the contained value or returns a default
*/
fn maybe<T, U: copy>(def: U, opt: t<T>, f: fn(T) -> U) -> U {
    alt opt { none { def } some(t) { f(t) } }
}

// FIXME: Can be defined in terms of the above when/if we have const bind.
/*
Function: may

Performs an operation on the contained value or does nothing
*/
fn may<T>(opt: t<T>, f: fn(T)) {
    alt opt { none {/* nothing */ } some(t) { f(t); } }
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>