<commit_before>#![deny(rust_2018_idioms)]

use rust_playground_top_crates::*;
use serde::Serialize;
use std::{
    collections::BTreeMap,
    fs::File,
    io::{Read, Write},
    path::{Path, PathBuf},
};

/// A Cargo.toml file.
#[derive(Serialize)]
struct TomlManifest {
    package: TomlPackage,
    profile: Profiles,
    #[serde(serialize_with = "toml::ser::tables_last")]
    dependencies: BTreeMap<String, DependencySpec>,
}

/// Header of Cargo.toml file.
#[derive(Serialize)]
struct TomlPackage {
    name: String,
    version: String,
    authors: Vec<String>,
    resolver: String,
}

/// A profile section in a Cargo.toml file
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
struct Profile {
    codegen_units: u32,
    incremental: bool,
}

/// Available profile types
#[derive(Serialize)]
struct Profiles {
    dev: Profile,
    release: Profile,
}

fn main() {
    let mut f =
        File::open("crate-modifications.toml").expect("unable to open crate modifications file");

    let mut d = Vec::new();
    f.read_to_end(&mut d)
        .expect("unable to read crate modifications file");

    let modifications: Modifications =
        toml::from_slice(&d).expect("unable to parse crate modifications file");

    let (dependencies, infos) = rust_playground_top_crates::generate_info(&modifications);

    // Construct playground's Cargo.toml.
    let manifest = TomlManifest {
        package: TomlPackage {
            name: "playground".to_owned(),
            version: "0.0.1".to_owned(),
            authors: vec!["The Rust Playground".to_owned()],
            resolver: "2".to_owned(),
        },
        profile: Profiles {
            dev: Profile {
                codegen_units: 1,
                incremental: false,
            },
            release: Profile {
                codegen_units: 1,
                incremental: false,
            },
        },
        dependencies,
    };

    // Write manifest file.
    let base_directory: PathBuf = std::env::args_os()
        .nth(1)
        .unwrap_or_else(|| "../compiler/base".into())
        .into();

    let cargo_toml = base_directory.join("Cargo.toml");
    write_manifest(manifest, &cargo_toml);
    println!("wrote {}", cargo_toml.display());

    let path = base_directory.join("crate-information.json");
    let mut f = File::create(&path)
        .unwrap_or_else(|e| panic!("Unable to create {}: {}", path.display(), e));
    serde_json::to_writer_pretty(&mut f, &infos)
        .unwrap_or_else(|e| panic!("Unable to write {}: {}", path.display(), e));
    println!("Wrote {}", path.display());
}

fn write_manifest(manifest: TomlManifest, path: impl AsRef<Path>) {
    let mut f = File::create(path).expect("Unable to create Cargo.toml");
    let content = toml::to_vec(&manifest).expect("Couldn't serialize TOML");
    f.write_all(&content).expect("Couldn't write Cargo.toml");
}
<commit_msg>Override build dependencies to build with 1 codegen unit instead of 256<commit_after>#![deny(rust_2018_idioms)]

use rust_playground_top_crates::*;
use serde::Serialize;
use std::{
    collections::BTreeMap,
    fs::File,
    io::{Read, Write},
    path::{Path, PathBuf},
};

/// A Cargo.toml file.
#[derive(Serialize)]
struct TomlManifest {
    package: TomlPackage,
    profile: Profiles,
    #[serde(serialize_with = "toml::ser::tables_last")]
    dependencies: BTreeMap<String, DependencySpec>,
}

/// Header of Cargo.toml file.
#[derive(Serialize)]
struct TomlPackage {
    name: String,
    version: String,
    authors: Vec<String>,
    resolver: String,
}

/// Profile used for build dependencies (build scripts, proc macros, and their
/// dependencies).
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
struct BuildOverride {
    codegen_units: u32,
}

/// A profile section in a Cargo.toml file
#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
struct Profile {
    codegen_units: u32,
    incremental: bool,
    build_override: BuildOverride,
}

/// Available profile types
#[derive(Serialize)]
struct Profiles {
    dev: Profile,
    release: Profile,
}

fn main() {
    let mut f =
        File::open("crate-modifications.toml").expect("unable to open crate modifications file");

    let mut d = Vec::new();
    f.read_to_end(&mut d)
        .expect("unable to read crate modifications file");

    let modifications: Modifications =
        toml::from_slice(&d).expect("unable to parse crate modifications file");

    let (dependencies, infos) = rust_playground_top_crates::generate_info(&modifications);

    // Construct playground's Cargo.toml.
    let manifest = TomlManifest {
        package: TomlPackage {
            name: "playground".to_owned(),
            version: "0.0.1".to_owned(),
            authors: vec!["The Rust Playground".to_owned()],
            resolver: "2".to_owned(),
        },
        profile: Profiles {
            dev: Profile {
                codegen_units: 1,
                incremental: false,
                build_override: BuildOverride { codegen_units: 1 },
            },
            release: Profile {
                codegen_units: 1,
                incremental: false,
                build_override: BuildOverride { codegen_units: 1 },
            },
        },
        dependencies,
    };

    // Write manifest file.
    let base_directory: PathBuf = std::env::args_os()
        .nth(1)
        .unwrap_or_else(|| "../compiler/base".into())
        .into();

    let cargo_toml = base_directory.join("Cargo.toml");
    write_manifest(manifest, &cargo_toml);
    println!("wrote {}", cargo_toml.display());

    let path = base_directory.join("crate-information.json");
    let mut f = File::create(&path)
        .unwrap_or_else(|e| panic!("Unable to create {}: {}", path.display(), e));
    serde_json::to_writer_pretty(&mut f, &infos)
        .unwrap_or_else(|e| panic!("Unable to write {}: {}", path.display(), e));
    println!("Wrote {}", path.display());
}

fn write_manifest(manifest: TomlManifest, path: impl AsRef<Path>) {
    let mut f = File::create(path).expect("Unable to create Cargo.toml");
    let content = toml::to_vec(&manifest).expect("Couldn't serialize TOML");
    f.write_all(&content).expect("Couldn't write Cargo.toml");
}
<|endoftext|>


<commit_before>#![no_main]
extern crate libfuzzer_sys;
extern crate pnet;

use pnet::packet::Packet;
use pnet::packet::tcp::TcpPacket;

#[export_name="rust_fuzzer_test_input"]
pub extern fn go(data: &[u8]) {
	if let Some(tcp) = TcpPacket::new(data) {
		let options = tcp.get_options_raw();
		for o in options.iter() {
			*o;
		}
		for b in tcp.payload().iter() {
			*b;
		}
	}
}
<commit_msg>Make TCP fail again<commit_after>#![no_main]
extern crate libfuzzer_sys;
extern crate pnet;

use pnet::packet::Packet;
use pnet::packet::tcp::TcpPacket;

#[export_name="rust_fuzzer_test_input"]
pub extern fn go(data: &[u8]) {
	if let Some(tcp) = TcpPacket::new(data) {
		let options = tcp.get_options_iter();
		for o in options {
			o.payload();
		}
		for b in tcp.payload().iter() {
			*b;
		}
	}
}
<|endoftext|>


<commit_before>fn can_spell(w: &str, blocks: &[&str]) -> bool {
    true
}

fn main() {
    let words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"];
    let blocks = ["BO", "XK", "DQ", "CP", "NA", "GT", "RE",
                  "TG", "QD", "FS", "JW", "HU", "VI", "AN",
                  "OB", "ER", "FS", "LY", "PC", "ZM"];

    for w in words.iter() {
        println!("Can I spell {}: {}", w, can_spell(w, &blocks));
    }
}
<commit_msg>Working on recursive solution<commit_after>fn can_spell(w: &str, blocks: &Vec<&str>) -> bool {
    fn solve(chars: Vec<&char>, avail_blocks: &Vec<&str>) -> bool {
        if chars.len() == 0 {
            true
        } else if avail_blocks.len() == 0 {
            false
        } else {
            match avail_blocks.iter().position(|&b| b.char_at(0) == *chars[0] || b.char_at(1) == *chars[0]) {
                Some(i) => solve(chars.tail(), avail_blocks),
                None => false
            }
        }
    }

    solve(w.chars().collect(), blocks)
}

fn main() {
    let words = ["A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE"];
    let blocks = vec!["BO", "XK", "DQ", "CP", "NA", "GT", "RE",
                      "TG", "QD", "FS", "JW", "HU", "VI", "AN",
                      "OB", "ER", "FS", "LY", "PC", "ZM"];

    for w in words.iter() {
        println!("Can I spell {}: {}", w, can_spell(w, &blocks));
    }
}
<|endoftext|>


<commit_before>use super::Rope;
use std::iter;

#[test]
fn rebalance_test_1() {
    let r = Rope::from("This is a large string \
                        that will need to be rebalanced.".to_string());
    let r = r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn rebalance_test_2() {
    let r = Rope::from("Lorem ipsum dolor sit amet, consectetur adipiscing eli\
                        t, sed do eiusmod tempor incididunt ut labore et dolor\
                        e magna aliqua. Ut enim ad minim veniam, quis nostrud \
                        exercitation ullamco laboris nisi ut aliquip ex ea com\
                        modo consequat. Duis aute irure dolor in reprehenderit\
                         in voluptate velit esse cillum dolore eu fugiat nulla\
                         pariatur. Excepteur sint occaecat cupidatat non proid\
                        ent, sunt in culpa qui officia deserunt mollit anim id\
                         est laborum.".to_string());
    let r = r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn big_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let r = Rope::from(s);
    let r = r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn repeated_concat_left_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    for _ in 1..1000 {
        r = r + iter::repeat('a').take(100).collect::<String>();
    }
    assert!(r.is_balanced());
}

#[test]
fn repeated_concat_right_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    for _ in 1..1000 {
        let s2 = iter::repeat('a').take(100).collect::<String>();
        r = Rope::from(s2) + r;
    }
    assert!(r.is_balanced());
}

#[test]
fn merge_rebalance_test() {
    let s = "Lorem ipsum dolor sit amet, consectetur adipiscing eli\
             t, sed do eiusmod tempor incididunt ut labore et dolor\
             e magna aliqua. Ut enim ad minim veniam, quis nostrud \
             exercitation ullamco laboris nisi ut aliquip ex ea com\
             modo consequat. Duis aute irure dolor in reprehenderit\
              in voluptate velit esse cillum dolore eu fugiat nulla\
              pariatur. Excepteur sint occaecat cupidatat non proid\
             ent, sunt in culpa qui officia deserunt mollit anim id\
              est laborum.";

     let t = Rope::from(s.to_owned());
     let u = t + s;
     let u = u.rebalance();
     assert!(u.is_balanced());
}

#[test]
fn insert_balance_test() {
    let s: String = iter::repeat('a').take(10).collect();
    let mut r_1 = Rope::from(s);
    for _ in 0..99 {
        let t: String = iter::repeat('a').take(10).collect();
        r_1 = r_1.insert(&Rope::from(t), 5);
    }
    //  this isn't necessary, insert() will automatically rebalance
    //      - eliza, 12/18/2016
    // r_1.rebalance();
    assert!(r_1.is_balanced());
}

#[test]
fn insert_test_1() {
    let s: String = iter::repeat('a').take(1_000).collect();
    let r_1 = Rope::from(s);
    let r_2 = Rope::new();
    for _ in 0..100 {
        let t: String = iter::repeat('a').take(10).collect();
        r_2.insert(&Rope::from(t), 0);
    }
    assert_eq!(r_1, r_2);
}

#[test]
fn insert_test_2() {
    let s: String = iter::repeat('a').take(10).collect();
    let r_1 = Rope::from(s);
    for _ in 0..99 {
        let t: String = iter::repeat('a').take(10).collect();
        r_1.insert(&Rope::from(t), 5);
    }

    let q: String = iter::repeat('a').take(1_000).collect();
    let r_2 = Rope::from(q);
    assert_eq!(r_1, r_2);
}

#[test]
fn insert_test_3() {
    let s_1 = Rope::from(String::from("aaaaa"));
    let s_2 = Rope::from(String::from("bbbbb"));
    let s_3 = Rope::from(String::from("ccccc"));
    s_2.insert(&s_3, 0);
    s_1.insert(&s_2, 0);
    assert_eq!(&s_1, "cccccbbbbbaaaaa");
}
<commit_msg>Added appropriate mutability to insert tests<commit_after>use super::Rope;
use std::iter;

#[test]
fn rebalance_test_1() {
    let r = Rope::from("This is a large string \
                        that will need to be rebalanced.".to_string());
    let r = r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn rebalance_test_2() {
    let r = Rope::from("Lorem ipsum dolor sit amet, consectetur adipiscing eli\
                        t, sed do eiusmod tempor incididunt ut labore et dolor\
                        e magna aliqua. Ut enim ad minim veniam, quis nostrud \
                        exercitation ullamco laboris nisi ut aliquip ex ea com\
                        modo consequat. Duis aute irure dolor in reprehenderit\
                         in voluptate velit esse cillum dolore eu fugiat nulla\
                         pariatur. Excepteur sint occaecat cupidatat non proid\
                        ent, sunt in culpa qui officia deserunt mollit anim id\
                         est laborum.".to_string());
    let r = r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn big_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let r = Rope::from(s);
    let r = r.rebalance();
    assert!(r.is_balanced());
}

#[test]
fn repeated_concat_left_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    for _ in 1..1000 {
        r = r + iter::repeat('a').take(100).collect::<String>();
    }
    assert!(r.is_balanced());
}

#[test]
fn repeated_concat_right_rebalance() {
    let s: String = iter::repeat('a').take(10_000).collect();
    let mut r = Rope::from(s);
    for _ in 1..1000 {
        let s2 = iter::repeat('a').take(100).collect::<String>();
        r = Rope::from(s2) + r;
    }
    assert!(r.is_balanced());
}

#[test]
fn merge_rebalance_test() {
    let s = "Lorem ipsum dolor sit amet, consectetur adipiscing eli\
             t, sed do eiusmod tempor incididunt ut labore et dolor\
             e magna aliqua. Ut enim ad minim veniam, quis nostrud \
             exercitation ullamco laboris nisi ut aliquip ex ea com\
             modo consequat. Duis aute irure dolor in reprehenderit\
              in voluptate velit esse cillum dolore eu fugiat nulla\
              pariatur. Excepteur sint occaecat cupidatat non proid\
             ent, sunt in culpa qui officia deserunt mollit anim id\
              est laborum.";

     let t = Rope::from(s.to_owned());
     let u = t + s;
     let u = u.rebalance();
     assert!(u.is_balanced());
}

#[test]
fn insert_balance_test() {
    let s: String = iter::repeat('a').take(10).collect();
    let mut r_1 = Rope::from(s);
    for _ in 0..99 {
        let t: String = iter::repeat('a').take(10).collect();
        r_1 = r_1.insert(&Rope::from(t), 5);
    }
    //  this isn't necessary, insert() will automatically rebalance
    //      - eliza, 12/18/2016
    // r_1.rebalance();
    assert!(r_1.is_balanced());
}

#[test]
fn insert_test_1() {
    let s: String = iter::repeat('a').take(1_000).collect();
    let r_1 = Rope::from(s);
    let mut r_2 = Rope::new();
    for _ in 0..100 {
        let t: String = iter::repeat('a').take(10).collect();
        r_2.insert(&Rope::from(t), 0);
    }
    assert_eq!(r_1, r_2);
}

#[test]
fn insert_test_2() {
    let s: String = iter::repeat('a').take(10).collect();
    let mut r_1 = Rope::from(s);
    for _ in 0..99 {
        let t: String = iter::repeat('a').take(10).collect();
        r_1.insert(&Rope::from(t), 5);
    }

    let q: String = iter::repeat('a').take(1_000).collect();
    let r_2 = Rope::from(q);
    assert_eq!(r_1, r_2);
}

#[test]
fn insert_test_3() {
    let mut s_1 = Rope::from(String::from("aaaaa"));
    let mut s_2 = Rope::from(String::from("bbbbb"));
    let s_3 = Rope::from(String::from("ccccc"));
    s_2.insert(&s_3, 0);
    s_1.insert(&s_2, 0);
    assert_eq!(&s_1, "cccccbbbbbaaaaa");
}
<|endoftext|>


<commit_before>use std::time::Duration;
use std::fmt;

use game::{Move, FromTo, Color, Score, NumPlies, NumMoves};
use search::NumNodes;
use types::{NumVariations, PerMill, NumCpu};

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum RegisterParam {
    Later,
    Name(String),
    Code(String),
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum GoParam {
    SearchMoves(Vec<FromTo>),
    Ponder,
    Time(Color, Duration),
    IncTime(Color, Duration),
    MovesToGo(NumMoves),
    Depth(NumPlies),
    Nodes(NumNodes),
    Mate(NumMoves),
    MoveTime(Duration),
    Infinite,
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum IdParam {
    Name(&'static str),
    Author(&'static str),
}
impl fmt::Display for IdParam {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            IdParam::Name(ref val)   => write!(f, "name {}", val),
            IdParam::Author(ref val) => write!(f, "author {}", val),
        }
    }
}

pub const ID_DATA: [IdParam; 2] = [IdParam::Name("chess_project"),
                                   IdParam::Author("Theemathas Chirananthavat")];

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum InfoParam {
    Depth(NumPlies),
    SelDepth(NumPlies),
    TimeSearched(Duration),
    NodesSearched(NumNodes),
    PrincipalVariation(Vec<Move>),
    MultiPv(NumVariations),
    Score(Option<ScoreType>, Score),
    CurrMove(Move),
    CurrMoveNumber(NumMoves),
    HashFull(PerMill),
    NodesPerSec(u64),
    TablebaseHits(u64),
    ShredderTablebaseHits(u64),
    CpuLoad(PerMill),
    ShowString(String),
    Refutation(Vec<Move>),
    CurrLine(Option<NumCpu>, Vec<Move>),
}
impl fmt::Display for InfoParam {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            InfoParam::Depth(val)          => write!(f, "depth {}", val.0),
            InfoParam::SelDepth(val)       => write!(f, "seldepth {}", val.0),
            InfoParam::TimeSearched(val)   => write!(f, "time {}", val.num_milliseconds()),
            InfoParam::NodesSearched(val)  => write!(f, "nodes {}", val.0),
            InfoParam::PrincipalVariation(ref moves) => {
                try!(write!(f, "pv"));
                for x in moves.iter() { try!(write!(f, " {}", x)) }
                Ok(())
            },
            InfoParam::MultiPv(val)        => write!(f, "multipv {}", val.0),
            InfoParam::Score(score_type, val) => {
                try!(write!(f, "score {}", val));
                if let Some(x) = score_type { try!(write!(f, " {}", x)) }
                Ok(())
            },
            InfoParam::CurrMove(ref val)   => write!(f, "currmove {}", val),
            InfoParam::CurrMoveNumber(val) => write!(f, "currmovenumber {}", val.0),
            InfoParam::HashFull(val)       => write!(f, "hashfull {}", val.0),
            InfoParam::NodesPerSec(val)    => write!(f, "nps {}", val),
            InfoParam::TablebaseHits(val)  => write!(f, "tbhits {}", val),
            InfoParam::ShredderTablebaseHits(val) => write!(f, "sbhits {}", val),
            InfoParam::CpuLoad(val)        => write!(f, "cpuload {}", val.0),
            InfoParam::ShowString(ref val) => write!(f, "string {}", val),
            InfoParam::Refutation(ref moves) => {
                try!(write!(f, "refutation"));
                for x in moves.iter() { try!(write!(f, " {}", x)) }
                Ok(())
            },
            InfoParam::CurrLine(num_cpu, ref moves) => {
                try!(write!(f, "currline"));
                if let Some(x) = num_cpu { try!(write!(f, " {}", x.0)) }
                for x in moves.iter() { try!(write!(f, " {}", x)) }
                Ok(())
            },
        }
    }
}

#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum ScoreType {
    LowerBound,
    UpperBound,
}
impl fmt::Display for ScoreType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", match *self {
            ScoreType::LowerBound => "lowerbound",
            ScoreType::UpperBound => "upperbound",
        })
    }
}
<commit_msg>Correction of engine name<commit_after>use std::time::Duration;
use std::fmt;

use game::{Move, FromTo, Color, Score, NumPlies, NumMoves};
use search::NumNodes;
use types::{NumVariations, PerMill, NumCpu};

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum RegisterParam {
    Later,
    Name(String),
    Code(String),
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum GoParam {
    SearchMoves(Vec<FromTo>),
    Ponder,
    Time(Color, Duration),
    IncTime(Color, Duration),
    MovesToGo(NumMoves),
    Depth(NumPlies),
    Nodes(NumNodes),
    Mate(NumMoves),
    MoveTime(Duration),
    Infinite,
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum IdParam {
    Name(&'static str),
    Author(&'static str),
}
impl fmt::Display for IdParam {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            IdParam::Name(ref val)   => write!(f, "name {}", val),
            IdParam::Author(ref val) => write!(f, "author {}", val),
        }
    }
}

pub const ID_DATA: [IdParam; 2] = [IdParam::Name("Binary Turk"),
                                   IdParam::Author("Theemathas Chirananthavat")];

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum InfoParam {
    Depth(NumPlies),
    SelDepth(NumPlies),
    TimeSearched(Duration),
    NodesSearched(NumNodes),
    PrincipalVariation(Vec<Move>),
    MultiPv(NumVariations),
    Score(Option<ScoreType>, Score),
    CurrMove(Move),
    CurrMoveNumber(NumMoves),
    HashFull(PerMill),
    NodesPerSec(u64),
    TablebaseHits(u64),
    ShredderTablebaseHits(u64),
    CpuLoad(PerMill),
    ShowString(String),
    Refutation(Vec<Move>),
    CurrLine(Option<NumCpu>, Vec<Move>),
}
impl fmt::Display for InfoParam {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            InfoParam::Depth(val)          => write!(f, "depth {}", val.0),
            InfoParam::SelDepth(val)       => write!(f, "seldepth {}", val.0),
            InfoParam::TimeSearched(val)   => write!(f, "time {}", val.num_milliseconds()),
            InfoParam::NodesSearched(val)  => write!(f, "nodes {}", val.0),
            InfoParam::PrincipalVariation(ref moves) => {
                try!(write!(f, "pv"));
                for x in moves.iter() { try!(write!(f, " {}", x)) }
                Ok(())
            },
            InfoParam::MultiPv(val)        => write!(f, "multipv {}", val.0),
            InfoParam::Score(score_type, val) => {
                try!(write!(f, "score {}", val));
                if let Some(x) = score_type { try!(write!(f, " {}", x)) }
                Ok(())
            },
            InfoParam::CurrMove(ref val)   => write!(f, "currmove {}", val),
            InfoParam::CurrMoveNumber(val) => write!(f, "currmovenumber {}", val.0),
            InfoParam::HashFull(val)       => write!(f, "hashfull {}", val.0),
            InfoParam::NodesPerSec(val)    => write!(f, "nps {}", val),
            InfoParam::TablebaseHits(val)  => write!(f, "tbhits {}", val),
            InfoParam::ShredderTablebaseHits(val) => write!(f, "sbhits {}", val),
            InfoParam::CpuLoad(val)        => write!(f, "cpuload {}", val.0),
            InfoParam::ShowString(ref val) => write!(f, "string {}", val),
            InfoParam::Refutation(ref moves) => {
                try!(write!(f, "refutation"));
                for x in moves.iter() { try!(write!(f, " {}", x)) }
                Ok(())
            },
            InfoParam::CurrLine(num_cpu, ref moves) => {
                try!(write!(f, "currline"));
                if let Some(x) = num_cpu { try!(write!(f, " {}", x.0)) }
                for x in moves.iter() { try!(write!(f, " {}", x)) }
                Ok(())
            },
        }
    }
}

#[derive(PartialEq, Eq, Copy, Clone, Debug)]
pub enum ScoreType {
    LowerBound,
    UpperBound,
}
impl fmt::Display for ScoreType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", match *self {
            ScoreType::LowerBound => "lowerbound",
            ScoreType::UpperBound => "upperbound",
        })
    }
}
<|endoftext|>


<commit_before>extern crate futures;
extern crate rusoto_core;
extern crate rusoto_dynamodb;
extern crate tokio_core;

use futures::future::Future;
use rusoto_core::Region;
use rusoto_dynamodb::{
    AttributeDefinition, AttributeValue, CreateTableInput, CreateTableOutput, DynamoDb,
    DynamoDbClient, GetItemError, GetItemInput, GetItemOutput, KeySchemaElement,
    ProvisionedThroughput, UpdateItemInput, UpdateItemOutput,
};
use std::collections::HashMap;
use tokio_core::reactor::Core;

fn main() {
    let item = make_item();
    let client = get_dynamodb_local_client();

    let create_table_future = make_create_table_future(&client);
    let upsert_item_future = make_upsert_item_future(&client, &item);
    let item_from_dynamo_future = make_get_item_future(&client, &item);

    // tie them together
    let chained_futures = create_table_future
        .map_err(|_| ()) // throw away any error from creating the table (such as it already exists)
        .and_then(|_| upsert_item_future.map_err(|_| ())) // toss out any error on upsert
        .then(|_| item_from_dynamo_future.map_err(|e| e)); // return get_item error if it happens

    // This tokio core will run our futures to completion:
    let mut core = Core::new().unwrap();

    // run 'em
    let item_from_dynamo = match core.run(chained_futures) {
        Ok(item) => item,
        Err(_) => panic!("Error completing futures: {}"),
    };

    println!("item_from_dynamo is {:?}", item_from_dynamo);
    println!("Done");
}

fn make_create_table_future(client: &DynamoDbClient) -> impl Future<Item = CreateTableOutput> {
    let attribute_def = AttributeDefinition {
        attribute_name: "foo_name".to_string(),
        attribute_type: "S".to_string(),
    };
    let k_schema = KeySchemaElement {
        attribute_name: "foo_name".to_string(),
        key_type: "HASH".to_string(), // case sensitive
    };
    let p_throughput = ProvisionedThroughput {
        read_capacity_units: 1,
        write_capacity_units: 1,
    };
    let make_table_request = CreateTableInput {
        table_name: "a-testing-table".to_string(),
        attribute_definitions: vec![attribute_def],
        key_schema: vec![k_schema],
        provisioned_throughput: p_throughput,
        ..Default::default()
    };

    client.create_table(make_table_request)
}

fn make_upsert_item_future(
    client: &DynamoDbClient,
    item: &HashMap<String, AttributeValue>,
) -> impl Future<Item = UpdateItemOutput> {
    let add_item = UpdateItemInput {
        key: item.clone(),
        table_name: "a-testing-table".to_string(),
        ..Default::default()
    };

    client.update_item(add_item)
}

fn make_get_item_future(
    client: &DynamoDbClient,
    item: &HashMap<String, AttributeValue>,
) -> impl Future<Item = GetItemOutput, Error = GetItemError> {
    // future for getting the entry
    let get_item_request = GetItemInput {
        key: item.clone(),
        table_name: "a-testing-table".to_string(),
        ..Default::default()
    };
    client.get_item(get_item_request)
}

fn make_item() -> HashMap<String, AttributeValue> {
    let item_key = "foo_name";
    let mut item = HashMap::new();
    item.insert(
        item_key.to_string(),
        AttributeValue {
            s: Some("baz".to_string()),
            ..Default::default()
        },
    );

    item
}

fn get_dynamodb_local_client() -> DynamoDbClient {
    // Create custom Region
    let region = Region::Custom {
        name: "us-east-1".to_owned(),
        endpoint: "http://localhost:8000".to_owned(),
    };

    DynamoDbClient::new(region)
}<commit_msg>Toss 'then' everywhere.<commit_after>extern crate futures;
extern crate rusoto_core;
extern crate rusoto_dynamodb;
extern crate tokio_core;

use futures::future::Future;
use rusoto_core::Region;
use rusoto_dynamodb::{
    AttributeDefinition, AttributeValue, CreateTableInput, CreateTableOutput, DynamoDb,
    DynamoDbClient, GetItemError, GetItemInput, GetItemOutput, KeySchemaElement,
    ProvisionedThroughput, UpdateItemInput, UpdateItemOutput,
};
use std::collections::HashMap;
use tokio_core::reactor::Core;

fn main() {
    let item = make_item();
    let client = get_dynamodb_local_client();

    let create_table_future = make_create_table_future(&client);
    let upsert_item_future = make_upsert_item_future(&client, &item);
    let item_from_dynamo_future = make_get_item_future(&client, &item);

    // tie them together
    let chained_futures = create_table_future
        .then(|_| upsert_item_future)
        .then(|_| item_from_dynamo_future);

    // This tokio core will run our futures to completion:
    let mut core = Core::new().unwrap();

    // run 'em
    let item_from_dynamo = match core.run(chained_futures) {
        Ok(item) => item,
        Err(_) => panic!("Error completing futures: {}"),
    };

    println!("item_from_dynamo is {:?}", item_from_dynamo);
    println!("Done");
}

fn make_create_table_future(client: &DynamoDbClient) -> impl Future<Item = CreateTableOutput> {
    let attribute_def = AttributeDefinition {
        attribute_name: "foo_name".to_string(),
        attribute_type: "S".to_string(),
    };
    let k_schema = KeySchemaElement {
        attribute_name: "foo_name".to_string(),
        key_type: "HASH".to_string(), // case sensitive
    };
    let p_throughput = ProvisionedThroughput {
        read_capacity_units: 1,
        write_capacity_units: 1,
    };
    let make_table_request = CreateTableInput {
        table_name: "a-testing-table".to_string(),
        attribute_definitions: vec![attribute_def],
        key_schema: vec![k_schema],
        provisioned_throughput: p_throughput,
        ..Default::default()
    };

    client.create_table(make_table_request)
}

fn make_upsert_item_future(
    client: &DynamoDbClient,
    item: &HashMap<String, AttributeValue>,
) -> impl Future<Item = UpdateItemOutput> {
    let add_item = UpdateItemInput {
        key: item.clone(),
        table_name: "a-testing-table".to_string(),
        ..Default::default()
    };

    client.update_item(add_item)
}

fn make_get_item_future(
    client: &DynamoDbClient,
    item: &HashMap<String, AttributeValue>,
) -> impl Future<Item = GetItemOutput, Error = GetItemError> {
    // future for getting the entry
    let get_item_request = GetItemInput {
        key: item.clone(),
        table_name: "a-testing-table".to_string(),
        ..Default::default()
    };
    client.get_item(get_item_request)
}

fn make_item() -> HashMap<String, AttributeValue> {
    let item_key = "foo_name";
    let mut item = HashMap::new();
    item.insert(
        item_key.to_string(),
        AttributeValue {
            s: Some("baz".to_string()),
            ..Default::default()
        },
    );

    item
}

fn get_dynamodb_local_client() -> DynamoDbClient {
    // Create custom Region
    let region = Region::Custom {
        name: "us-east-1".to_owned(),
        endpoint: "http://localhost:8000".to_owned(),
    };

    DynamoDbClient::new(region)
}<|endoftext|>


<commit_before>use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::io::Read;
use std::os::raw::c_char;
use std::path::PathBuf;

use goblin::Object;
use serde_json as json;
use serde_json::json;

use analyzer::Analyzer;

const VERSION: &[u8] = b"0.1.0\0";

thread_local!(
    static OPEN_HANDLES: RefCell<Option<HashMap<u32, Box<Analyzer>>>> = RefCell::new(None));
thread_local!(
    static NEXT_HANDLE: u32 = 1);
const INVALID_HANDLE: u32 = 0;

#[no_mangle]
pub extern "C" fn version() -> *const c_char {
    unsafe {
        return CStr::from_bytes_with_nul_unchecked(VERSION).as_ptr();
    }
}

#[no_mangle]
pub extern "C" fn init() -> bool {
    OPEN_HANDLES.with(|handles|
        *handles.borrow_mut() = Some(HashMap::new())
    );
    true
}

#[no_mangle]
pub extern "C" fn open_binary_file(path: *const c_char) -> u32 {
    // TODO: Move out parts of this function
    let path = match to_str(path).map(|p| PathBuf::from(p)) {
        Some(p) => p,
        None => return INVALID_HANDLE,
    };
    let mut file = match File::open(&path) {
        Ok(f) => f,
        Err(_) => return INVALID_HANDLE,
    };
    let mut buf = vec![];
    file.read_to_end(&mut buf).expect("Failed to read file");
    let mut analyzer = None;
    match Object::parse(&buf).expect("Failed to parse the file contents") {
        Object::Elf(elf) => {
            for section in elf.section_headers {
                if section.is_executable() {
                    let range = section.file_range();
                    let vm_range = section.vm_range();
                    let text = Vec::from(&buf[range]);
                    analyzer = Some(Analyzer::create(text, vm_range.start as u64)
                        .expect("Failed to create the analyze"));
                }
            }
        }
        Object::PE(pe) => return INVALID_HANDLE,
        _ => return INVALID_HANDLE,
    }
    return match analyzer {
        Some(analyzer) => {
            let handle = NEXT_HANDLE.with(|next_cell| {
                let handle = *next_cell;
                OPEN_HANDLES.with(|handles_cell|
                    handles_cell.borrow_mut().as_mut().unwrap().insert(handle, Box::new(analyzer))
                );
                handle
            });
            handle
        }
        None => INVALID_HANDLE
    }
}

#[no_mangle]
pub fn print_instructions(handle: u32, ptr: *mut c_char, size: usize) {
    OPEN_HANDLES.with(|handles_cell| {
        let handles = handles_cell.borrow();
        let analyzer = &handles.as_ref().unwrap()[&handle];
        let mut asm = vec![];
        for (_, insn) in analyzer.graph().instructions_iter() {
            asm.push(json!({
                "address": insn.address,
                "hex": insn.hex.clone(),
                "assembly": insn.assembly.clone(),
            }));
        }
        let s = json::Value::Array(asm).to_string();
        let count = std::cmp::min(s.len() + 1, size);
        unsafe {
            let data = CString::from_vec_unchecked(s.into_bytes());
            std::ptr::copy_nonoverlapping(data.as_ptr(), ptr, count - 1);
            std::slice::from_raw_parts_mut(ptr, count)[count - 1] = 0;
        }
    });
}

fn to_str<'a>(s: *const c_char) -> Option<&'a str> {
    let cstr = unsafe { CStr::from_ptr(s) };
    match cstr.to_str() {
        Ok(s) => Some(s),
        Err(_) => None,
    }
}
<commit_msg>Add support for PE files<commit_after>use std::cell::RefCell;
use std::collections::HashMap;
use std::ffi::{CStr, CString};
use std::fs::File;
use std::io::Read;
use std::os::raw::c_char;
use std::path::PathBuf;

use goblin::Object;
use serde_json as json;
use serde_json::json;

use analyzer::Analyzer;

const VERSION: &[u8] = b"0.1.0\0";

thread_local!(
    static OPEN_HANDLES: RefCell<Option<HashMap<u32, Box<Analyzer>>>> = RefCell::new(None));
thread_local!(
    static NEXT_HANDLE: u32 = 1);
const INVALID_HANDLE: u32 = 0;

#[no_mangle]
pub extern "C" fn version() -> *const c_char {
    unsafe {
        return CStr::from_bytes_with_nul_unchecked(VERSION).as_ptr();
    }
}

#[no_mangle]
pub extern "C" fn init() -> bool {
    OPEN_HANDLES.with(|handles|
        *handles.borrow_mut() = Some(HashMap::new())
    );
    true
}

#[no_mangle]
pub extern "C" fn open_binary_file(path: *const c_char) -> u32 {
    // TODO: Move out parts of this function
    let path = match to_str(path).map(|p| PathBuf::from(p)) {
        Some(p) => p,
        None => return INVALID_HANDLE,
    };
    let mut file = match File::open(&path) {
        Ok(f) => f,
        Err(_) => return INVALID_HANDLE,
    };
    let mut buf = vec![];
    file.read_to_end(&mut buf).expect("Failed to read file");
    let mut analyzer = None;
    match Object::parse(&buf).expect("Failed to parse the file contents") {
        Object::Elf(elf) => {
            for section in elf.section_headers {
                if section.is_executable() {
                    let range = section.file_range();
                    let vm_range = section.vm_range();
                    let text = Vec::from(&buf[range]);
                    analyzer = Some(Analyzer::create(text, vm_range.start as u64)
                        .expect("Failed to create the analyze"));
                }
            }
        }
        Object::PE(pe) => {
            for section in pe.sections {
                match section.name() {
                    Ok(name) if name == ".text" => {
                        let range = section.pointer_to_raw_data as usize ..
                            (section.pointer_to_raw_data as usize + section.size_of_raw_data as usize);
                        let text = Vec::from(&buf[range]);
                        analyzer = Some(Analyzer::create(text, pe.image_base as u64 + section.virtual_address as u64)
                            .expect("Failed to create the analyze"));
                    }
                    _ => {}
                }
            }
        }
        _ => return INVALID_HANDLE,
    }
    return match analyzer {
        Some(analyzer) => {
            let handle = NEXT_HANDLE.with(|next_cell| {
                let handle = *next_cell;
                OPEN_HANDLES.with(|handles_cell|
                    handles_cell.borrow_mut().as_mut().unwrap().insert(handle, Box::new(analyzer))
                );
                handle
            });
            handle
        }
        None => INVALID_HANDLE
    }
}

#[no_mangle]
pub fn print_instructions(handle: u32, ptr: *mut c_char, size: usize) {
    OPEN_HANDLES.with(|handles_cell| {
        let handles = handles_cell.borrow();
        let analyzer = &handles.as_ref().unwrap()[&handle];
        let mut asm = vec![];
        for (_, insn) in analyzer.graph().instructions_iter() {
            asm.push(json!({
                "address": insn.address,
                "hex": insn.hex.clone(),
                "assembly": insn.assembly.clone(),
            }));
        }
        let s = json::Value::Array(asm).to_string();
        let count = std::cmp::min(s.len() + 1, size);
        unsafe {
            let data = CString::from_vec_unchecked(s.into_bytes());
            std::ptr::copy_nonoverlapping(data.as_ptr(), ptr, count - 1);
            std::slice::from_raw_parts_mut(ptr, count)[count - 1] = 0;
        }
    });
}

fn to_str<'a>(s: *const c_char) -> Option<&'a str> {
    let cstr = unsafe { CStr::from_ptr(s) };
    match cstr.to_str() {
        Ok(s) => Some(s),
        Err(_) => None,
    }
}
<|endoftext|>


<commit_before>//! Draw rectangle

use current::{ Get, Modifier, Set };
use internal;
use triangulation;
use Context;
use BackEnd;
use ImageSize;
use Color;

pub use vecmath::margin_rectangle as margin;

/// Use x, y, half-width, half-height
pub fn centered(rect: internal::Rectangle) -> internal::Rectangle {
    let [cx, cy, rw, rh] = rect;
    [cx - rw, cy - rh, 2.0 * rw, 2.0 * rh]
}

/// Use centered square
pub fn centered_square(
    x: internal::Scalar,
    y: internal::Scalar,
    radius: internal::Scalar
) -> internal::Rectangle {
    [x - radius, y - radius, 2.0 * radius, 2.0 * radius]
}

/// Use square with x, y in upper left corner
pub fn square(
    x: internal::Scalar,
    y: internal::Scalar,
    size: internal::Scalar
) -> internal::Rectangle {
    [x, y, size, size]
}

/// The shape of the rectangle
pub enum Shape {
    /// Square corners
    Square,
    /// Round corners
    Round(internal::Radius),
    /// Bevel corners
    Bevel(internal::Radius),
}

/// Wrapper trait for `Get<Shape>`
pub trait GetShape: Get<Shape> {
    /// Get shape
    #[inline(always)]
    fn get_shape(&self) -> Shape {
        self.get()
    }
}

impl<T: Get<Shape>> GetShape for T {}

/// Wrapper trait for `Set<Shape>`
pub trait SetShape: Set<Shape> {
    /// Set shape
    #[inline(always)]
    fn set_shape(&mut self, val: Shape) {
        self.set_mut(val);
    }
}

impl<T: Set<Shape>> SetShape for T {}

/// The border of the rectangle
pub struct Border {
    /// The color of the border
    pub color: internal::Color,
    /// The radius of the border
    pub radius: internal::Radius,
}

/// Wrapper trait for `Get<Border>`
pub trait GetBorder: Get<Border> {
    /// Get border
    #[inline(always)]
    fn get_border(&self) -> Border {
        self.get()
    }
}

impl<T: Get<Border>> GetBorder for T {}

/// Wrapper trait for `Set<Border>`
pub trait SetBorder: Set<Border> {
    /// Set border
    #[inline(always)]
    fn set_border(&mut self, val: Border) {
        self.set_mut(val);
    }
}

impl<T: Set<Border>> SetBorder for T {}

/// Maybe border property
pub struct MaybeBorder(pub Option<Border>);

/// Wrapper trait for `Get<MaybeBorder>`
pub trait GetMaybeBorder: Get<MaybeBorder> {
    /// Get maybe border
    #[inline(always)]
    fn get_maybe_border(&self) -> MaybeBorder {
        self.get()
    }
}

impl<T: Get<MaybeBorder>> GetMaybeBorder for T {}

/// Wrapper trait for `Set<MaybeBorder>`
pub trait SetMaybeBorder: Set<MaybeBorder> {
    /// Set maybe border
    #[inline(always)]
    fn set_maybe_border(&mut self, val: MaybeBorder) {
        self.set_mut(val);
    }
}

impl<T: Set<MaybeBorder>> SetMaybeBorder for T {}

/// A filled rectangle
#[deriving(Copy)]
pub struct Rectangle {
    /// The rectangle color
    pub color: internal::Color,
    /// The roundness of the rectangle
    pub shape: Shape,
    /// The border
    pub border: Option<Border>,
}

impl Rectangle {
    /// Creates a new rectangle.
    pub fn new(color: internal::Color) -> Rectangle {
        Rectangle {
            color: color,
            shape: Shape::Square,
            border: None,
        }
    }

    /// Creates a new rectangle border.
    pub fn border(
        color: internal::Color,
        radius: internal::Radius
    ) -> Rectangle {
        Rectangle {
            color: [0.0, ..4],
            shape: Shape::Square,
            border: Some(Border {
                    color: color,
                    radius: radius
                })
        }
    }

    /// Draws the rectangle
    pub fn draw<B: BackEnd<I>, I: ImageSize>(
        &self,
        rectangle: internal::Rectangle,
        c: &Context,
        back_end: &mut B
    ) {
        if self.color[3] != 0.0 {
            back_end.color(self.color);
            match self.shape {
                Shape::Square => {
                    back_end.tri_list(
                        &triangulation::rect_tri_list_xy(c.transform, rectangle),
                    );
                }
                Shape::Round(round_radius) => {
                    triangulation::with_round_rectangle_tri_list(
                        32,
                        c.transform,
                        rectangle,
                        round_radius,
                        |vertices| back_end.tri_list(vertices)
                    );
                }
                Shape::Bevel(bevel_radius) => {
                    triangulation::with_round_rectangle_tri_list(
                        2,
                        c.transform,
                        rectangle,
                        bevel_radius,
                        |vertices| back_end.tri_list(vertices)
                    );
                }
            }
        }

        if let Some(Border { color, radius: border_radius }) = self.border {
            if color[3] == 0.0 { return; }
            back_end.color(color);
            match self.shape {
                Shape::Square => {
                    back_end.tri_list(
                        &triangulation::rect_border_tri_list_xy(
                            c.transform, rectangle, border_radius),
                    );
                }
                Shape::Round(round_radius) => {
                    triangulation::with_round_rectangle_border_tri_list(
                        128,
                        c.transform,
                        rectangle,
                        round_radius,
                        border_radius,
                        |vertices| back_end.tri_list(vertices)
                    );
                }
                Shape::Bevel(bevel_radius) => {
                    triangulation::with_round_rectangle_border_tri_list(
                        2,
                        c.transform,
                        rectangle,
                        bevel_radius,
                        border_radius,
                        |vertices| back_end.tri_list(vertices)
                    );
                }
            }
        }
    }
}

impl Modifier<Rectangle> for Color {
    #[inline(always)]
    fn modify(self, r: &mut Rectangle) {
        let Color(val) = self;
        r.color = val;
    }
}

impl Get<Color> for Rectangle {
    #[inline(always)]
    fn get(&self) -> Color {
        Color(self.color)
    }
}

impl Modifier<Rectangle> for Shape {
    #[inline(always)]
    fn modify(self, r: &mut Rectangle) {
        r.shape = self;
    }
}

impl Get<Shape> for Rectangle {
    #[inline(always)]
    fn get(&self) -> Shape {
        self.shape
    }
}

impl Modifier<Rectangle> for Border {
    #[inline(always)]
    fn modify(self, r: &mut Rectangle) {
        r.border = Some(self);
    }
}

impl Modifier<Rectangle> for MaybeBorder {
    #[inline(always)]
    fn modify(self, r: &mut Rectangle) {
        let MaybeBorder(val) = self;
        r.border = val;
    }
}

impl Get<MaybeBorder> for Rectangle {
    #[inline(always)]
    fn get(&self) -> MaybeBorder {
        MaybeBorder(self.border)
    }
}

#[cfg(test)]
mod test {
    use super::Rectangle;
    use super::Shape;
    use super::Border;
    use Color;
    use current::Set;

    #[test]
    fn test_rectangle() {
        let _rectangle = Rectangle::new([1.0, ..4])
            .set(Color([0.0, ..4]))
            .set(Shape::Round(10.0))
            .set(Border { color: [0.0, ..4], radius: 4.0 });
    }
}

<commit_msg>Added round and round_border constructors to Rectangle<commit_after>//! Draw rectangle

use current::{ Get, Modifier, Set };
use internal;
use triangulation;
use Context;
use BackEnd;
use ImageSize;
use Color;

pub use vecmath::margin_rectangle as margin;

/// Use x, y, half-width, half-height
pub fn centered(rect: internal::Rectangle) -> internal::Rectangle {
    let [cx, cy, rw, rh] = rect;
    [cx - rw, cy - rh, 2.0 * rw, 2.0 * rh]
}

/// Use centered square
pub fn centered_square(
    x: internal::Scalar,
    y: internal::Scalar,
    radius: internal::Scalar
) -> internal::Rectangle {
    [x - radius, y - radius, 2.0 * radius, 2.0 * radius]
}

/// Use square with x, y in upper left corner
pub fn square(
    x: internal::Scalar,
    y: internal::Scalar,
    size: internal::Scalar
) -> internal::Rectangle {
    [x, y, size, size]
}

/// The shape of the rectangle
pub enum Shape {
    /// Square corners
    Square,
    /// Round corners
    Round(internal::Radius),
    /// Bevel corners
    Bevel(internal::Radius),
}

/// Wrapper trait for `Get<Shape>`
pub trait GetShape: Get<Shape> {
    /// Get shape
    #[inline(always)]
    fn get_shape(&self) -> Shape {
        self.get()
    }
}

impl<T: Get<Shape>> GetShape for T {}

/// Wrapper trait for `Set<Shape>`
pub trait SetShape: Set<Shape> {
    /// Set shape
    #[inline(always)]
    fn set_shape(&mut self, val: Shape) {
        self.set_mut(val);
    }
}

impl<T: Set<Shape>> SetShape for T {}

/// The border of the rectangle
pub struct Border {
    /// The color of the border
    pub color: internal::Color,
    /// The radius of the border
    pub radius: internal::Radius,
}

/// Wrapper trait for `Get<Border>`
pub trait GetBorder: Get<Border> {
    /// Get border
    #[inline(always)]
    fn get_border(&self) -> Border {
        self.get()
    }
}

impl<T: Get<Border>> GetBorder for T {}

/// Wrapper trait for `Set<Border>`
pub trait SetBorder: Set<Border> {
    /// Set border
    #[inline(always)]
    fn set_border(&mut self, val: Border) {
        self.set_mut(val);
    }
}

impl<T: Set<Border>> SetBorder for T {}

/// Maybe border property
pub struct MaybeBorder(pub Option<Border>);

/// Wrapper trait for `Get<MaybeBorder>`
pub trait GetMaybeBorder: Get<MaybeBorder> {
    /// Get maybe border
    #[inline(always)]
    fn get_maybe_border(&self) -> MaybeBorder {
        self.get()
    }
}

impl<T: Get<MaybeBorder>> GetMaybeBorder for T {}

/// Wrapper trait for `Set<MaybeBorder>`
pub trait SetMaybeBorder: Set<MaybeBorder> {
    /// Set maybe border
    #[inline(always)]
    fn set_maybe_border(&mut self, val: MaybeBorder) {
        self.set_mut(val);
    }
}

impl<T: Set<MaybeBorder>> SetMaybeBorder for T {}

/// A filled rectangle
#[deriving(Copy)]
pub struct Rectangle {
    /// The rectangle color
    pub color: internal::Color,
    /// The roundness of the rectangle
    pub shape: Shape,
    /// The border
    pub border: Option<Border>,
}

impl Rectangle {
    /// Creates a new rectangle.
    pub fn new(color: internal::Color) -> Rectangle {
        Rectangle {
            color: color,
            shape: Shape::Square,
            border: None,
        }
    }

    /// Creates a new round rectangle.
    pub fn round(
        color: internal::Color,
        round_radius: internal::Radius
    ) -> Rectangle {
        Rectangle {
            color: color,
            shape: Shape::Round(round_radius),
            border: None
        }
    }

    /// Creates a new rectangle border.
    pub fn border(
        color: internal::Color,
        radius: internal::Radius
    ) -> Rectangle {
        Rectangle {
            color: [0.0, ..4],
            shape: Shape::Square,
            border: Some(Border {
                    color: color,
                    radius: radius
                })
        }
    }

    /// Creates a new round rectangle border.
    pub fn round_border(
        color: internal::Color,
        round_radius: internal::Radius,
        border_radius: internal::Radius
    ) -> Rectangle {
        Rectangle {
            color: [0.0, ..4],
            shape: Shape::Round(round_radius),
            border: Some(Border {
                    color: color,
                    radius: border_radius
                })
        }
    }

    /// Draws the rectangle
    pub fn draw<B: BackEnd<I>, I: ImageSize>(
        &self,
        rectangle: internal::Rectangle,
        c: &Context,
        back_end: &mut B
    ) {
        if self.color[3] != 0.0 {
            back_end.color(self.color);
            match self.shape {
                Shape::Square => {
                    back_end.tri_list(
                        &triangulation::rect_tri_list_xy(c.transform, rectangle),
                    );
                }
                Shape::Round(round_radius) => {
                    triangulation::with_round_rectangle_tri_list(
                        32,
                        c.transform,
                        rectangle,
                        round_radius,
                        |vertices| back_end.tri_list(vertices)
                    );
                }
                Shape::Bevel(bevel_radius) => {
                    triangulation::with_round_rectangle_tri_list(
                        2,
                        c.transform,
                        rectangle,
                        bevel_radius,
                        |vertices| back_end.tri_list(vertices)
                    );
                }
            }
        }

        if let Some(Border { color, radius: border_radius }) = self.border {
            if color[3] == 0.0 { return; }
            back_end.color(color);
            match self.shape {
                Shape::Square => {
                    back_end.tri_list(
                        &triangulation::rect_border_tri_list_xy(
                            c.transform, rectangle, border_radius),
                    );
                }
                Shape::Round(round_radius) => {
                    triangulation::with_round_rectangle_border_tri_list(
                        128,
                        c.transform,
                        rectangle,
                        round_radius,
                        border_radius,
                        |vertices| back_end.tri_list(vertices)
                    );
                }
                Shape::Bevel(bevel_radius) => {
                    triangulation::with_round_rectangle_border_tri_list(
                        2,
                        c.transform,
                        rectangle,
                        bevel_radius,
                        border_radius,
                        |vertices| back_end.tri_list(vertices)
                    );
                }
            }
        }
    }
}

impl Modifier<Rectangle> for Color {
    #[inline(always)]
    fn modify(self, r: &mut Rectangle) {
        let Color(val) = self;
        r.color = val;
    }
}

impl Get<Color> for Rectangle {
    #[inline(always)]
    fn get(&self) -> Color {
        Color(self.color)
    }
}

impl Modifier<Rectangle> for Shape {
    #[inline(always)]
    fn modify(self, r: &mut Rectangle) {
        r.shape = self;
    }
}

impl Get<Shape> for Rectangle {
    #[inline(always)]
    fn get(&self) -> Shape {
        self.shape
    }
}

impl Modifier<Rectangle> for Border {
    #[inline(always)]
    fn modify(self, r: &mut Rectangle) {
        r.border = Some(self);
    }
}

impl Modifier<Rectangle> for MaybeBorder {
    #[inline(always)]
    fn modify(self, r: &mut Rectangle) {
        let MaybeBorder(val) = self;
        r.border = val;
    }
}

impl Get<MaybeBorder> for Rectangle {
    #[inline(always)]
    fn get(&self) -> MaybeBorder {
        MaybeBorder(self.border)
    }
}

#[cfg(test)]
mod test {
    use super::Rectangle;
    use super::Shape;
    use super::Border;
    use Color;
    use current::Set;

    #[test]
    fn test_rectangle() {
        let _rectangle = Rectangle::new([1.0, ..4])
            .set(Color([0.0, ..4]))
            .set(Shape::Round(10.0))
            .set(Border { color: [0.0, ..4], radius: 4.0 });
    }
}

<|endoftext|>


<commit_before>use serde::{ser};
use std::mem::transmute;
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
use std::fmt::{Display,Debug};
use std::fmt;
use serialize::{
    serialize_u64
};

// Option to display references as nested
pub static mut NESTED_REFERENCE: bool = false;

#[derive(Serialize, Debug)]
pub struct MftEnumReference{
    #[serde(serialize_with = "serialize_u64")]
    reference: u64,
    entry: u64,
    sequence: u16
}

// Represents a MFT Reference struct
// https://msdn.microsoft.com/en-us/library/bb470211(v=vs.85).aspx
// https://jmharkness.wordpress.com/2011/01/27/mft-file-reference-number/
pub struct MftReference(pub u64);
impl MftReference{
    fn get_from_entry_and_seq(entry: u64, sequence: u16) -> MftReference{
        let entry_buffer: [u8; 8] = unsafe {
            transmute(entry.to_le())
        };
        let seq_buffer: [u8; 2] = unsafe {
            transmute(sequence.to_le())
        };
        let mut ref_buffer = vec![];
        ref_buffer.extend_from_slice(&entry_buffer[0..6]);
        ref_buffer.extend_from_slice(&seq_buffer);

        MftReference(LittleEndian::read_u64(&ref_buffer[0..8]))
    }
    fn get_enum_ref(&self)->MftEnumReference{
        let mut raw_buffer = vec![];
        raw_buffer.write_u64::<LittleEndian>(self.0).unwrap();
        MftEnumReference{
            reference: LittleEndian::read_u64(&raw_buffer[0..8]),
            entry: LittleEndian::read_u64(
                &[&raw_buffer[0..6], &[0,0]].concat()
            ),
            sequence: LittleEndian::read_u16(&raw_buffer[6..8])
        }
    }
}
impl Display for MftReference {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,"{}",self.0)
    }
}
impl Debug for MftReference {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,"{}",self.0)
    }
}
impl ser::Serialize for MftReference {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: ser::Serializer
    {
        // If NESTED_REFERENCE we need to serialize the enumerated structure
        if unsafe{NESTED_REFERENCE} {
            serializer.serialize_newtype_struct("mft_reference",&self.get_enum_ref())
        } else {
            // Just serialize the u64 version
            serialize_u64(&self.0,serializer)
        }
    }
}

#[test]
fn test_reference() {
    let raw_reference: &[u8] = &[0x73,0x00,0x00,0x00,0x00,0x00,0x68,0x91];

    let mft_reference = MftReference(
        LittleEndian::read_u64(&raw_reference[0..8])
    );
    assert_eq!(mft_reference.0,10477624533077459059);
    assert_eq!(format!("{}", mft_reference),"10477624533077459059");
    // assert_eq!(mft_reference.sequence,37224);

    let mft_reference_01 = MftReference::get_from_entry_and_seq(
        115,
        37224
    );
    assert_eq!(mft_reference_01.0,10477624533077459059);
}
<commit_msg>method to enumerate reference self from entry and sequence.<commit_after>use serde::{ser};
use std::mem::transmute;
use byteorder::{ByteOrder, LittleEndian, WriteBytesExt};
use std::fmt::{Display,Debug};
use std::fmt;
use serialize::{
    serialize_u64
};

// Option to display references as nested
pub static mut NESTED_REFERENCE: bool = false;

#[derive(Serialize, Debug)]
pub struct MftEnumReference{
    #[serde(serialize_with = "serialize_u64")]
    reference: u64,
    entry: u64,
    sequence: u16
}

// Represents a MFT Reference struct
// https://msdn.microsoft.com/en-us/library/bb470211(v=vs.85).aspx
// https://jmharkness.wordpress.com/2011/01/27/mft-file-reference-number/
pub struct MftReference(pub u64);
impl MftReference{
    fn from_entry_and_seq(&mut self, entry: u64, sequence: u16){
        let entry_buffer: [u8; 8] = unsafe {
            transmute(entry.to_le())
        };
        let seq_buffer: [u8; 2] = unsafe {
            transmute(sequence.to_le())
        };
        let mut ref_buffer = vec![];
        ref_buffer.extend_from_slice(&entry_buffer[0..6]);
        ref_buffer.extend_from_slice(&seq_buffer);

        self.0 = LittleEndian::read_u64(&ref_buffer[0..8]);
    }
    fn get_from_entry_and_seq(entry: u64, sequence: u16) -> MftReference{
        let entry_buffer: [u8; 8] = unsafe {
            transmute(entry.to_le())
        };
        let seq_buffer: [u8; 2] = unsafe {
            transmute(sequence.to_le())
        };
        let mut ref_buffer = vec![];
        ref_buffer.extend_from_slice(&entry_buffer[0..6]);
        ref_buffer.extend_from_slice(&seq_buffer);

        MftReference(LittleEndian::read_u64(&ref_buffer[0..8]))
    }
    fn get_enum_ref(&self)->MftEnumReference{
        let mut raw_buffer = vec![];
        raw_buffer.write_u64::<LittleEndian>(self.0).unwrap();
        MftEnumReference{
            reference: LittleEndian::read_u64(&raw_buffer[0..8]),
            entry: LittleEndian::read_u64(
                &[&raw_buffer[0..6], &[0,0]].concat()
            ),
            sequence: LittleEndian::read_u16(&raw_buffer[6..8])
        }
    }
}
impl Display for MftReference {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,"{}",self.0)
    }
}
impl Debug for MftReference {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f,"{}",self.0)
    }
}
impl ser::Serialize for MftReference {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: ser::Serializer
    {
        // If NESTED_REFERENCE we need to serialize the enumerated structure
        if unsafe{NESTED_REFERENCE} {
            serializer.serialize_newtype_struct("mft_reference",&self.get_enum_ref())
        } else {
            // Just serialize the u64 version
            serialize_u64(&self.0,serializer)
        }
    }
}

#[test]
fn test_reference() {
    use std::mem;
    let raw_reference: &[u8] = &[0x73,0x00,0x00,0x00,0x00,0x00,0x68,0x91];

    let mft_reference = MftReference(
        LittleEndian::read_u64(&raw_reference[0..8])
    );
    assert_eq!(mft_reference.0,10477624533077459059);
    assert_eq!(format!("{}", mft_reference),"10477624533077459059");
    // assert_eq!(mft_reference.sequence,37224);

    let mft_reference_01 = MftReference::get_from_entry_and_seq(
        115,
        37224
    );
    assert_eq!(mft_reference_01.0,10477624533077459059);

    let mut mft_reference_02: MftReference = unsafe {
        mem::zeroed()
    };
    assert_eq!(mft_reference_02.0,0);
    mft_reference_02.from_entry_and_seq(
        115,
        37224
    );
    assert_eq!(mft_reference_02.0,10477624533077459059);
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate lazy_static;
extern crate rustc_perf;
extern crate serde_json;
extern crate iron_test;
extern crate serde;
extern crate iron;

use std::fs::File;
use std::io::{Write, Read};
use std::path::Path;

use iron::prelude::*;
use iron::status::Status;
use iron::{Headers, headers};
use iron::response::ResponseBody;
use serde_json::Value;
use serde::Serialize;

use rustc_perf::server::{self, GroupBy};
use rustc_perf::load::{Kind, InputData};
use rustc_perf::date::{OptionalDate, Date};
use rustc_perf::api::{data, tabular, days, stats};

lazy_static! {
    static ref CHAIN: Chain = server::chain(InputData::from_fs("tests/data").unwrap());
}

fn request(path: &str) -> Response {
    iron_test::request::get(&format!("http://perf.rust-lang.org/{}", path),
                            Headers::new(),
                            &*CHAIN).unwrap()
}

fn post_request<T: Serialize>(path: &str,
                                          body: T)
                                          -> Response {
    iron_test::request::post(&format!("http://perf.rust-lang.org/{}", path),
                             Headers::new(),
                             &serde_json::to_string(&body).unwrap(),
                             &*CHAIN).unwrap()
}

fn response_body(response: Response) -> Value {
    if let Some(mut body) = response.body {
        let mut buf = Vec::new();
        body.write_body(&mut ResponseBody::new(&mut buf)).unwrap();
        let s = String::from_utf8(buf).unwrap();
        serde_json::from_str(&s).unwrap()
    } else {
        Value::Null
    }
}

fn round_trip_value(v: &Value) -> Value {
    let s = pretty_json(v);
    serde_json::from_str(&s).unwrap()
}

fn from_file<P: AsRef<Path>>(path: P) -> Value {
    let mut file = File::open(path).unwrap();
    let mut s = String::new();
    file.read_to_string(&mut s).unwrap();
    serde_json::from_str(&s).unwrap()
}

#[allow(dead_code)]
fn to_file<P: AsRef<Path>>(path: P, value: &Value) {
    let mut file = File::create(path).unwrap();
    file.write_all(pretty_json(&value).as_bytes()).unwrap();
}

fn pretty_json(value: &Value) -> String {
    serde_json::to_string_pretty(&value).unwrap()
}

fn check_response(response: Response, expected_file: &str) {
    assert_eq!(response.status, Some(Status::Ok));
    assert_eq!(response.headers.get(),
               Some(&headers::AccessControlAllowOrigin::Any));
    assert_eq!(response.headers.get(),
               Some(&headers::ContentType("application/json".parse().unwrap())));

    // The deserialized value from wire.
    // If new values are to be recorded to the files, this is the value that
    // should be recorded.
    // This has undergone: server serialize -> tests deserialize
    let raw_received_value = response_body(response);

    // Uncomment this line to refresh the expected results.
    // to_file(expected_file, &raw_received_value);

    // The deserialized value from the file.
    // This has undergone:
    //     server serialize -> tests deserialize ->
    //     to_file serialize (pretty) -> tests deserialize
    let expected_value = from_file(expected_file);

    // This value has now undergone the same amount of round trips through
    // Serde as the one in the file.
    let received_value = round_trip_value(&raw_received_value);

    if received_value != expected_value {
        // Note: This value's float fields should not be used for direct
        // comparison with the expected results, due to the loss of precision in Serde
        println!("{}", serde_json::to_string(&raw_received_value).unwrap());
        panic!("Compared {} body with server result, results not equal.", expected_file);
    }
}

#[test]
fn summary() {
    let response = request("/summary");
    check_response(response, "tests/expected_results/summary.json");
}

#[test]
fn info() {
    let response = request("/info");
    check_response(response, "tests/expected_results/info.json");
}

#[test]
fn data_crate_benchmarks() {
    let response = post_request("/data",
                                data::Request {
                                    start_date: OptionalDate::CouldNotParse("".into()),
                                    end_date: OptionalDate::CouldNotParse("".into()),
                                    group_by: GroupBy::Crate,
                                    kind: Kind::Benchmarks,
                                    phases: vec!["total".into()],
                                    crates: vec!["helloworld".into(), "regex.0.1.30".into()],
                                });
    check_response(response, "tests/expected_results/data_crate_benchmarks.json");
}

#[test]
fn data_crate_rustc_total() {
    let response = post_request("/data",
                                data::Request {
                                    start_date: OptionalDate::CouldNotParse("".into()),
                                    end_date: OptionalDate::CouldNotParse("".into()),
                                    group_by: GroupBy::Crate,
                                    kind: Kind::Rustc,
                                    phases: vec!["total".into()],
                                    crates: vec!["total".into()],
                                });
    check_response(response, "tests/expected_results/data_crate_rustc_total.json");
}

#[test]
fn tabular_rustc() {
    let response = post_request("/get_tabular",
                                tabular::Request {
                                    kind: Kind::Rustc,
                                    date: OptionalDate::CouldNotParse("".into()),
                                });
    check_response(response, "tests/expected_results/tabular_rustc.json");
}

#[test]
fn tabular_benchmarks() {
    let response = post_request("/get_tabular",
                                tabular::Request {
                                    kind: Kind::Benchmarks,
                                    date: OptionalDate::CouldNotParse("".into()),
                                });
    check_response(response, "tests/expected_results/tabular_benchmarks.json");
}

fn ymd_date(year: i32, month: u32, day: u32) -> OptionalDate {
    OptionalDate::Date(Date::ymd_hms(year, month, day, 0, 0, 0))
}

#[test]
fn days_benchmarks() {
    let response = post_request("/get",
                                days::Request {
                                    kind: Kind::Benchmarks,
                                    date_a: ymd_date(2016, 02, 21),
                                    date_b: ymd_date(2016, 03, 22),
                                    crates: vec!["helloworld".into(), "regex.0.1.30".into()],
                                    phases: vec!["total".into()],
                                    group_by: GroupBy::Crate,
                                });
    check_response(response, "tests/expected_results/days_benchmarks.json");
}

#[test]
fn days_rustc() {
    let response = post_request("/get",
                                days::Request {
                                    kind: Kind::Rustc,
                                    date_a: ymd_date(2016, 02, 21),
                                    date_b: ymd_date(2016, 03, 22),
                                    crates: vec!["total".into()],
                                    phases: vec!["total".into()],
                                    group_by: GroupBy::Crate,
                                });
    check_response(response, "tests/expected_results/days_rustc.json");
}

#[test]
fn stats_benchmarks() {
    let response = post_request("/stats",
                                stats::Request {
                                    kind: Kind::Benchmarks,
                                    start_date: OptionalDate::CouldNotParse("".into()),
                                    end_date: OptionalDate::CouldNotParse("".into()),
                                    crates: vec!["helloworld".into(), "regex.0.1.30".into()],
                                    phases: vec!["total".into()],
                                });
    check_response(response, "tests/expected_results/stats_benchmarks.json");
}

#[test]
fn stats_rustc() {
    let response = post_request("/stats",
                                stats::Request {
                                    kind: Kind::Rustc,
                                    start_date: OptionalDate::CouldNotParse("".into()),
                                    end_date: OptionalDate::CouldNotParse("".into()),
                                    crates: vec!["total".into()],
                                    phases: vec!["total".into()],
                                });
    check_response(response, "tests/expected_results/stats_rustc.json");
}
<commit_msg>Apply rustfmt.<commit_after>#[macro_use]
extern crate lazy_static;
extern crate rustc_perf;
extern crate serde_json;
extern crate iron_test;
extern crate serde;
extern crate iron;

use std::fs::File;
use std::io::{Write, Read};
use std::path::Path;

use iron::prelude::*;
use iron::status::Status;
use iron::{Headers, headers};
use iron::response::ResponseBody;
use serde_json::Value;
use serde::Serialize;

use rustc_perf::server::{self, GroupBy};
use rustc_perf::load::{Kind, InputData};
use rustc_perf::date::{OptionalDate, Date};
use rustc_perf::api::{data, tabular, days, stats};

lazy_static! {
    static ref CHAIN: Chain = server::chain(InputData::from_fs("tests/data").unwrap());
}

fn request(path: &str) -> Response {
    iron_test::request::get(&format!("http://perf.rust-lang.org/{}", path),
                            Headers::new(),
                            &*CHAIN)
        .unwrap()
}

fn post_request<T: Serialize>(path: &str, body: T) -> Response {
    iron_test::request::post(&format!("http://perf.rust-lang.org/{}", path),
                             Headers::new(),
                             &serde_json::to_string(&body).unwrap(),
                             &*CHAIN)
        .unwrap()
}

fn response_body(response: Response) -> Value {
    if let Some(mut body) = response.body {
        let mut buf = Vec::new();
        body.write_body(&mut ResponseBody::new(&mut buf)).unwrap();
        let s = String::from_utf8(buf).unwrap();
        serde_json::from_str(&s).unwrap()
    } else {
        Value::Null
    }
}

fn round_trip_value(v: &Value) -> Value {
    let s = pretty_json(v);
    serde_json::from_str(&s).unwrap()
}

fn from_file<P: AsRef<Path>>(path: P) -> Value {
    let mut file = File::open(path).unwrap();
    let mut s = String::new();
    file.read_to_string(&mut s).unwrap();
    serde_json::from_str(&s).unwrap()
}

#[allow(dead_code)]
fn to_file<P: AsRef<Path>>(path: P, value: &Value) {
    let mut file = File::create(path).unwrap();
    file.write_all(pretty_json(&value).as_bytes()).unwrap();
}

fn pretty_json(value: &Value) -> String {
    serde_json::to_string_pretty(&value).unwrap()
}

fn check_response(response: Response, expected_file: &str) {
    assert_eq!(response.status, Some(Status::Ok));
    assert_eq!(response.headers.get(),
               Some(&headers::AccessControlAllowOrigin::Any));
    assert_eq!(response.headers.get(),
               Some(&headers::ContentType("application/json".parse().unwrap())));

    // The deserialized value from wire.
    // If new values are to be recorded to the files, this is the value that
    // should be recorded.
    // This has undergone: server serialize -> tests deserialize
    let raw_received_value = response_body(response);

    // Uncomment this line to refresh the expected results.
    // to_file(expected_file, &raw_received_value);

    // The deserialized value from the file.
    // This has undergone:
    //     server serialize -> tests deserialize ->
    //     to_file serialize (pretty) -> tests deserialize
    let expected_value = from_file(expected_file);

    // This value has now undergone the same amount of round trips through
    // Serde as the one in the file.
    let received_value = round_trip_value(&raw_received_value);

    if received_value != expected_value {
        // Note: This value's float fields should not be used for direct
        // comparison with the expected results, due to the loss of precision in Serde
        println!("{}", serde_json::to_string(&raw_received_value).unwrap());
        panic!("Compared {} body with server result, results not equal.",
               expected_file);
    }
}

#[test]
fn summary() {
    let response = request("/summary");
    check_response(response, "tests/expected_results/summary.json");
}

#[test]
fn info() {
    let response = request("/info");
    check_response(response, "tests/expected_results/info.json");
}

#[test]
fn data_crate_benchmarks() {
    let response = post_request("/data",
                                data::Request {
                                    start_date: OptionalDate::CouldNotParse("".into()),
                                    end_date: OptionalDate::CouldNotParse("".into()),
                                    group_by: GroupBy::Crate,
                                    kind: Kind::Benchmarks,
                                    phases: vec!["total".into()],
                                    crates: vec!["helloworld".into(), "regex.0.1.30".into()],
                                });
    check_response(response,
                   "tests/expected_results/data_crate_benchmarks.json");
}

#[test]
fn data_crate_rustc_total() {
    let response = post_request("/data",
                                data::Request {
                                    start_date: OptionalDate::CouldNotParse("".into()),
                                    end_date: OptionalDate::CouldNotParse("".into()),
                                    group_by: GroupBy::Crate,
                                    kind: Kind::Rustc,
                                    phases: vec!["total".into()],
                                    crates: vec!["total".into()],
                                });
    check_response(response,
                   "tests/expected_results/data_crate_rustc_total.json");
}

#[test]
fn tabular_rustc() {
    let response = post_request("/get_tabular",
                                tabular::Request {
                                    kind: Kind::Rustc,
                                    date: OptionalDate::CouldNotParse("".into()),
                                });
    check_response(response, "tests/expected_results/tabular_rustc.json");
}

#[test]
fn tabular_benchmarks() {
    let response = post_request("/get_tabular",
                                tabular::Request {
                                    kind: Kind::Benchmarks,
                                    date: OptionalDate::CouldNotParse("".into()),
                                });
    check_response(response, "tests/expected_results/tabular_benchmarks.json");
}

fn ymd_date(year: i32, month: u32, day: u32) -> OptionalDate {
    OptionalDate::Date(Date::ymd_hms(year, month, day, 0, 0, 0))
}

#[test]
fn days_benchmarks() {
    let response = post_request("/get",
                                days::Request {
                                    kind: Kind::Benchmarks,
                                    date_a: ymd_date(2016, 02, 21),
                                    date_b: ymd_date(2016, 03, 22),
                                    crates: vec!["helloworld".into(), "regex.0.1.30".into()],
                                    phases: vec!["total".into()],
                                    group_by: GroupBy::Crate,
                                });
    check_response(response, "tests/expected_results/days_benchmarks.json");
}

#[test]
fn days_rustc() {
    let response = post_request("/get",
                                days::Request {
                                    kind: Kind::Rustc,
                                    date_a: ymd_date(2016, 02, 21),
                                    date_b: ymd_date(2016, 03, 22),
                                    crates: vec!["total".into()],
                                    phases: vec!["total".into()],
                                    group_by: GroupBy::Crate,
                                });
    check_response(response, "tests/expected_results/days_rustc.json");
}

#[test]
fn stats_benchmarks() {
    let response = post_request("/stats",
                                stats::Request {
                                    kind: Kind::Benchmarks,
                                    start_date: OptionalDate::CouldNotParse("".into()),
                                    end_date: OptionalDate::CouldNotParse("".into()),
                                    crates: vec!["helloworld".into(), "regex.0.1.30".into()],
                                    phases: vec!["total".into()],
                                });
    check_response(response, "tests/expected_results/stats_benchmarks.json");
}

#[test]
fn stats_rustc() {
    let response = post_request("/stats",
                                stats::Request {
                                    kind: Kind::Rustc,
                                    start_date: OptionalDate::CouldNotParse("".into()),
                                    end_date: OptionalDate::CouldNotParse("".into()),
                                    crates: vec!["total".into()],
                                    phases: vec!["total".into()],
                                });
    check_response(response, "tests/expected_results/stats_rustc.json");
}
<|endoftext|>


<commit_before>#![feature(iter_arith)]
use std::env::args;
use std::vec::Vec;

fn str_to_int(s: String) -> i32 {
    i32::from_str_radix(&s, 10).ok().unwrap()
}

struct Present {
    length: i32,
    width: i32,
    height: i32,
}

impl Present {
    fn from_string_dimensions(dimensions: String) -> Present {
        let mut dims = Vec::with_capacity(3);
        let mut s = "".to_string();
        for c in dimensions.chars() {
            if c == 'x' {
                dims.push(s.clone());
                s.clear();
            } else {
                s.push(c);
            }
        }
        dims.push(s);
        let height = str_to_int(dims[2].clone());
        let width = str_to_int(dims[1].clone());
        let length = str_to_int(dims[0].clone());
        Present {
            length: length,
            width: width,
            height: height,
        }
    }

    fn required_wrapping_paper(&self) -> i32 {
        // I really like that I get to call a builtin "unwrap" method inside a
        // Present here.
        self.surface_area() + self.side_surface_areas().iter().min().unwrap()
    }

    fn surface_area(&self) -> i32 {
        self.side_surface_areas().iter().map(|s| s * 2).sum()
    }

    fn side_surface_areas(&self) -> Vec<i32> {
        vec![self.length * self.width,
             self.length * self.height,
             self.width * self.height]
    }
}

fn main() {
    let presents: Vec<Present> = args().skip(1).map(Present::from_string_dimensions).collect();
    let amount: i32 = presents.iter().map(|p| p.required_wrapping_paper()).sum();
    println!("{}", amount);
}
<commit_msg>add part 2<commit_after>#![feature(iter_arith)]
use std::env::args;
use std::vec::Vec;

fn str_to_int(s: String) -> i32 {
    i32::from_str_radix(&s, 10).ok().unwrap()
}

struct Present {
    length: i32,
    width: i32,
    height: i32,
}

impl Present {
    fn from_string_dimensions(dimensions: String) -> Present {
        let mut dims = Vec::with_capacity(3);
        let mut s = "".to_string();
        for c in dimensions.chars() {
            if c == 'x' {
                dims.push(s.clone());
                s.clear();
            } else {
                s.push(c);
            }
        }
        dims.push(s);
        let height = str_to_int(dims[2].clone());
        let width = str_to_int(dims[1].clone());
        let length = str_to_int(dims[0].clone());
        Present {
            length: length,
            width: width,
            height: height,
        }
    }

    fn required_wrapping_paper(&self) -> i32 {
        // I really like that I get to call a builtin "unwrap" method inside a
        // Present here.
        self.surface_area() + self.side_surface_areas().iter().min().unwrap()
    }

    fn required_ribbon_length(&self) -> i32 {
        self.perimeters().iter().min().unwrap() + self.volume()
    }

    fn surface_area(&self) -> i32 {
        self.side_surface_areas().iter().map(|s| s * 2).sum()
    }

    fn perimeters(&self) -> Vec<i32> {
        vec![2 * (self.length + self.width),
             2 * (self.length + self.height),
             2 * (self.width + self.height)]
    }

    fn volume(&self) -> i32 {
        self.length * self.width * self.height
    }

    fn side_surface_areas(&self) -> Vec<i32> {
        vec![self.length * self.width,
             self.length * self.height,
             self.width * self.height]
    }
}

fn main() {
    let presents: Vec<Present> = args().skip(1).map(Present::from_string_dimensions).collect();
    let wrapping_paper: i32 = presents.iter().map(|p| p.required_wrapping_paper()).sum();
    let ribbon: i32 = presents.iter().map(|p| p.required_ribbon_length()).sum();
    println!("{} {}", wrapping_paper, ribbon);
}
<|endoftext|>


<commit_before><commit_msg>Reduce duplication of direct string checks<commit_after><|endoftext|>


<commit_before>fn main() {
    println!("Hello, world!");
}
<commit_msg>Add basic boilerplate for screen and a few uniforms<commit_after>#[macro_use]
extern crate gfx;
extern crate gfx_window_glutin;
extern crate glutin;

use gfx::traits::FactoryExt;
use gfx::Device;

use std::time::Instant;

type ColorFormat = gfx::format::Rgba8;
type DepthFormat = gfx::format::DepthStencil;

gfx_defines! {
    vertex Vertex {
        pos: [f32; 2] = "position",
    }

    pipeline pipe {
        // Vertex buffer
        vbuf: gfx::VertexBuffer<Vertex> = (),

        // Uniforms
        i_global_time: gfx::Global<f32> = "iGlobalTime",
        i_resolution: gfx::Global<[f32; 3]> = "iResolution",
        i_mouse: gfx::Global<[f32; 4]> = "iMouse",

        // Output color
        frag_color: gfx::RenderTarget<ColorFormat> = "fragColor",
    }
}

const SCREEN: [Vertex; 4] = [
    Vertex{pos: [ 1.0,  1.0]}, // Top right
    Vertex{pos: [-1.0,  1.0]}, // Top left
    Vertex{pos: [-1.0, -1.0]}, // Bottom left
    Vertex{pos: [ 1.0, -1.0]}, // Bottom right
];

const SCREEN_INDICES: [u16; 6] = [
    0, 1, 2,
    0, 2, 3,
];

const CLEAR_COLOR: [f32; 4] = [1.0; 4];

fn main() {
    let (w, h) = (600, 400);
    let (wf, hf) = (w as f32, h as f32);

    let builder = glutin::WindowBuilder::new()
                    .with_title("Hello, gfx-rs!")
                    .with_dimensions(w, h)
                    .with_vsync();

    let (window, mut device, mut factory, main_color, _) =
        gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);

    let mut encoder: gfx::Encoder<_,_> = factory.create_command_buffer().into();

    let pso = factory.create_pipeline_simple(
        include_bytes!("shaders/default.vert"),
        include_bytes!("shaders/default.frag"),
        pipe::new()
    ).expect("Error creating pipeline");

    let (vertex_buffer, slice) = factory.create_vertex_buffer_with_slice(&SCREEN, &SCREEN_INDICES[..]);

    let mut data = pipe::Data {
        vbuf: vertex_buffer,

        i_global_time: 0.0,
        i_resolution: [wf, hf, wf/hf],
        i_mouse: [0.0; 4],

        frag_color: main_color,
    };

    let mut running = true;

    let start_time = Instant::now();

    while running {
        for event in window.poll_events() {
            match event {
                glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => {
                    running = false;
                },

                glutin::Event::MouseMoved(x,y) => {
                    // TODO: Get zw-components too
                    data.i_mouse[0] = x as f32;
                    data.i_mouse[1] = hf - y as f32; // Flip y-axis
                },

                _ => ()
            }
        }

        let elapsed = start_time.elapsed();
        let elapsed_ms = (elapsed.as_secs() * 1000) + (elapsed.subsec_nanos()/1000000) as u64;
        let elapsed_sec = (elapsed_ms as f32) / 1000.0;
        data.i_global_time = elapsed_sec;

        encoder.clear(&data.frag_color, CLEAR_COLOR);
        encoder.draw(&slice, &pso, &data);
        encoder.flush(&mut device);

        window.swap_buffers().unwrap();

        device.cleanup();
    }
}
<|endoftext|>


<commit_before><commit_msg>Added a timestamp<commit_after><|endoftext|>


<commit_before><commit_msg>Change title<commit_after><|endoftext|>


<commit_before><commit_msg>Define more flags<commit_after><|endoftext|>