<commit_before>#![feature(test)]

extern crate gosol;
extern crate test;
extern crate rand;

use test::Bencher;
use gosol::game::simpleboard::*;
use gosol::game::board::*;
use rand::Rng;

#[bench]
fn bench_play_200_moves(b: &mut Bencher) {
    b.iter(|| {
        let mut game_board = SimpleBoard::new(19, 19);

        for i in 0..200 {
            let x = rand::thread_rng().gen_range(0, 19);
            let y = rand::thread_rng().gen_range(0, 19);

            if i % 2 == 0 {
                game_board.play_move(GoMove::Move{x: x, y: y, player: State::Black});
            }
            else {
                game_board.play_move(GoMove::Move{x: x, y: y, player: State::White});
            }
        }
    })
}

#[bench]
fn bench_play_10_moves_small(b: &mut Bencher) {
    b.iter(|| {
        let mut game_board = SimpleBoard::new(10, 10);

        for i in 0..10 {
            let x = rand::thread_rng().gen_range(0, 10);
            let y = rand::thread_rng().gen_range(0, 10);

            if i % 2 == 0 {
                game_board.play_move(GoMove::Move{x: x, y: y, player: State::Black});
            }
            else {
                game_board.play_move(GoMove::Move{x: x, y: y, player: State::White});
            }
        }
    })
}
<commit_msg>Benches now work<commit_after>#![feature(test)]

extern crate gosol;
extern crate test;
extern crate rand;

use test::Bencher;
use gosol::game::simpleboard::*;
use gosol::game::board::*;
use rand::Rng;

#[bench]
fn bench_play_200_moves(b: &mut Bencher) {
    b.iter(|| {
        let mut game_board = SimpleBoard::new(19, 19);

        for i in 0..200 {
            let x = rand::thread_rng().gen_range(0, 19);
            let y = rand::thread_rng().gen_range(0, 19);

            if i % 2 == 0 {
                game_board.play_move(&GoMove::Move{x: x, y: y, player: State::Black});
            }
            else {
                game_board.play_move(&GoMove::Move{x: x, y: y, player: State::White});
            }
        }
    })
}

#[bench]
fn bench_play_10_moves_small(b: &mut Bencher) {
    b.iter(|| {
        let mut game_board = SimpleBoard::new(10, 10);

        for i in 0..10 {
            let x = rand::thread_rng().gen_range(0, 10);
            let y = rand::thread_rng().gen_range(0, 10);

            if i % 2 == 0 {
                game_board.play_move(&GoMove::Move{x: x, y: y, player: State::Black});
            }
            else {
                game_board.play_move(&GoMove::Move{x: x, y: y, player: State::White});
            }
        }
    })
}
<|endoftext|>


<commit_before>#![feature(test)]

extern crate test;
extern crate xmltree;

use test::Bencher;

use std::fs::File;
use std::io::Cursor;
use std::io::Read;
use xmltree::Element;
use xmltree::ParseError;

fn _parse_file(filename: &str) -> std::result::Result<xmltree::Element, xmltree::ParseError> {
    let mut file = File::open(filename).unwrap();
    let mut data = String::new();
    file.read_to_string(&mut data).unwrap();

    Element::parse(data.as_bytes())
}

#[bench]
fn bench_01(b: &mut Bencher) {
    b.iter(|| {
        let filename = "tests/data/01.xml";
        let e: Element = _parse_file(filename).unwrap();

        assert_eq!(e.name, "project");
        let e2: &Element = e
            .get_child("libraries")
            .expect("Missing libraries child element");
        assert_eq!(e2.name, "libraries");

        assert!(e.get_child("doesnotexist").is_none());

        let mut buf = Vec::new();
        e.write(&mut buf).unwrap();

        let e2 = Element::parse(Cursor::new(buf)).unwrap();
        assert_eq!(e, e2);
    })
}

#[bench]
fn bench_02(b: &mut Bencher) {
    let filename = "tests/data/02.xml";
    b.iter(|| {
        let _ = _parse_file(filename).unwrap();
    });
}

#[bench]
fn bench_03(b: &mut Bencher) {
    let filename = "tests/data/03.xml";
    b.iter(|| {
        let _ = _parse_file(filename).unwrap();
    });
}

#[bench]
fn bench_04(b: &mut Bencher) {
    let filename = "tests/data/04.xml";
    b.iter(|| {
        let _ = _parse_file(filename).unwrap();
    });
}

#[bench]
fn bench_rw(b: &mut Bencher) {
    let filename = "tests/data/rw.xml";
    b.iter(|| {
        let e = _parse_file(filename).unwrap();

        let mut buf = Vec::new();
        e.write(&mut buf).unwrap();

        let e2 = Element::parse(Cursor::new(buf)).unwrap();
        assert_eq!(e, e2);
    })
}

#[bench]
fn bench_mal_01(b: &mut Bencher) {
    let data = r##"
        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <names>
            <name first="bob" last="jones />
            <name first="elizabeth" last="smith" />
        </names>
    "##;

    b.iter(|| {
        let names_element = Element::parse(data.as_bytes());
        if let Err(ParseError::MalformedXml(..)) = names_element {
            // OK
        } else {
            panic!("unexpected parse result");
        }
    });
}

#[bench]
fn bench_mal_02(b: &mut Bencher) {
    let data = r##"
            this is not even close
            to XML
    "##;

    b.iter(|| {
        let names_element = Element::parse(data.as_bytes());
        if let Err(ParseError::MalformedXml(..)) = names_element {
            // OK
        } else {
            panic!("unexpected parse result");
        }
    });
}

#[bench]
fn bench_mal_03(b: &mut Bencher) {
    let data = r##"
        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <names>
            <name first="bob" last="jones"></badtag>
            <name first="elizabeth" last="smith" />
        </names>
    "##;

    b.iter(|| {
        let names_element = Element::parse(data.as_bytes());
        if let Err(ParseError::MalformedXml(..)) = names_element {
            // OK
        } else {
            panic!("unexpected parse result");
        }
    });
}

#[bench]
fn bench_new(b: &mut Bencher) {
    b.iter(|| {
        let e = Element::new("foo");
        assert_eq!(e.name.as_str(), "foo");
        assert_eq!(e.attributes.len(), 0);
        assert_eq!(e.children.len(), 0);
        assert_eq!(e.text, None);
    });
}

#[bench]
fn bench_take(b: &mut Bencher) {
    let data_xml_1 = r##"
        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <names>
            <name first="bob" last="jones"></name>
            <name first="elizabeth" last="smith" />
            <remove_me key="value">
                <child />
            </remove_me>
        </names>
    "##;

    let data_xml_2 = r##"
        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <names>
            <name first="bob" last="jones"></name>
            <name first="elizabeth" last="smith" />
        </names>
    "##;

    b.iter(|| {
        let mut data_1 = Element::parse(data_xml_1.as_bytes()).unwrap();
        let data_2 = Element::parse(data_xml_2.as_bytes()).unwrap();

        if let Some(removed) = data_1.take_child("remove_me") {
            assert_eq!(removed.children.len(), 1);
        } else {
            panic!("take_child failed");
        }

        assert_eq!(data_1, data_2);
    });
}

#[bench]
fn bench_ns1_rw(b: &mut Bencher) {
    let filename = "tests/data/ns2.xml";
    b.iter(|| {
        let e = _parse_file(filename).unwrap();
        let mut buf = Vec::new();
        e.write(&mut buf).unwrap();
    });
}

#[bench]
fn bench_ns2_rw(b: &mut Bencher) {
    let filename = "tests/data/ns2.xml";
    b.iter(|| {
        let e = _parse_file(filename).unwrap();
        let mut buf = Vec::new();
        e.write(&mut buf).unwrap();
    });
}
<commit_msg>Fix benchmark build<commit_after>#![feature(test)]

extern crate test;
extern crate xmltree;

use test::Bencher;

use std::fs::File;
use std::io::Cursor;
use std::io::Read;
use xmltree::Element;
use xmltree::ParseError;

fn _parse_file(filename: &str) -> std::result::Result<xmltree::Element, xmltree::ParseError> {
    let mut file = File::open(filename).unwrap();
    let mut data = String::new();
    file.read_to_string(&mut data).unwrap();

    Element::parse(data.as_bytes())
}

#[bench]
fn bench_01(b: &mut Bencher) {
    b.iter(|| {
        let filename = "tests/data/01.xml";
        let e: Element = _parse_file(filename).unwrap();

        assert_eq!(e.name, "project");
        let e2: &Element = e
            .get_child("libraries")
            .expect("Missing libraries child element");
        assert_eq!(e2.name, "libraries");

        assert!(e.get_child("doesnotexist").is_none());

        let mut buf = Vec::new();
        e.write(&mut buf).unwrap();

        let e2 = Element::parse(Cursor::new(buf)).unwrap();
        assert_eq!(e, e2);
    })
}

#[bench]
fn bench_02(b: &mut Bencher) {
    let filename = "tests/data/02.xml";
    b.iter(|| {
        let _ = _parse_file(filename).unwrap();
    });
}

#[bench]
fn bench_03(b: &mut Bencher) {
    let filename = "tests/data/03.xml";
    b.iter(|| {
        let _ = _parse_file(filename).unwrap();
    });
}

#[bench]
fn bench_04(b: &mut Bencher) {
    let filename = "tests/data/04.xml";
    b.iter(|| {
        let _ = _parse_file(filename).unwrap();
    });
}

#[bench]
fn bench_rw(b: &mut Bencher) {
    let filename = "tests/data/rw.xml";
    b.iter(|| {
        let e = _parse_file(filename).unwrap();

        let mut buf = Vec::new();
        e.write(&mut buf).unwrap();

        let e2 = Element::parse(Cursor::new(buf)).unwrap();
        assert_eq!(e, e2);
    })
}

#[bench]
fn bench_mal_01(b: &mut Bencher) {
    let data = r##"
        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <names>
            <name first="bob" last="jones />
            <name first="elizabeth" last="smith" />
        </names>
    "##;

    b.iter(|| {
        let names_element = Element::parse(data.as_bytes());
        if let Err(ParseError::MalformedXml(..)) = names_element {
            // OK
        } else {
            panic!("unexpected parse result");
        }
    });
}

#[bench]
fn bench_mal_02(b: &mut Bencher) {
    let data = r##"
            this is not even close
            to XML
    "##;

    b.iter(|| {
        let names_element = Element::parse(data.as_bytes());
        if let Err(ParseError::MalformedXml(..)) = names_element {
            // OK
        } else {
            panic!("unexpected parse result");
        }
    });
}

#[bench]
fn bench_mal_03(b: &mut Bencher) {
    let data = r##"
        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <names>
            <name first="bob" last="jones"></badtag>
            <name first="elizabeth" last="smith" />
        </names>
    "##;

    b.iter(|| {
        let names_element = Element::parse(data.as_bytes());
        if let Err(ParseError::MalformedXml(..)) = names_element {
            // OK
        } else {
            panic!("unexpected parse result");
        }
    });
}

#[bench]
fn bench_new(b: &mut Bencher) {
    b.iter(|| {
        let e = Element::new("foo");
        assert_eq!(e.name.as_str(), "foo");
        assert_eq!(e.attributes.len(), 0);
        assert_eq!(e.children.len(), 0);
        assert_eq!(e.get_text(), None);
    });
}

#[bench]
fn bench_take(b: &mut Bencher) {
    let data_xml_1 = r##"
        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <names>
            <name first="bob" last="jones"></name>
            <name first="elizabeth" last="smith" />
            <remove_me key="value">
                <child />
            </remove_me>
        </names>
    "##;

    let data_xml_2 = r##"
        <?xml version="1.0" encoding="utf-8" standalone="yes"?>
        <names>
            <name first="bob" last="jones"></name>
            <name first="elizabeth" last="smith" />
        </names>
    "##;

    b.iter(|| {
        let mut data_1 = Element::parse(data_xml_1.as_bytes()).unwrap();
        let data_2 = Element::parse(data_xml_2.as_bytes()).unwrap();

        if let Some(removed) = data_1.take_child("remove_me") {
            assert_eq!(removed.children.len(), 1);
        } else {
            panic!("take_child failed");
        }

        assert_eq!(data_1, data_2);
    });
}

#[bench]
fn bench_ns1_rw(b: &mut Bencher) {
    let filename = "tests/data/ns2.xml";
    b.iter(|| {
        let e = _parse_file(filename).unwrap();
        let mut buf = Vec::new();
        e.write(&mut buf).unwrap();
    });
}

#[bench]
fn bench_ns2_rw(b: &mut Bencher) {
    let filename = "tests/data/ns2.xml";
    b.iter(|| {
        let e = _parse_file(filename).unwrap();
        let mut buf = Vec::new();
        e.write(&mut buf).unwrap();
    });
}
<|endoftext|>


<commit_before>// Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 G. Fraux — BSD license
use toml::{Table, Value};

use lumol::chfl::{Trajectory, ToChemfiles};
use lumol::units;
use lumol::system::*;

use error::{Error, Result};
use extract;
use {Input, InteractionsInput};
use simulations::get_input_path;

impl Input {
    /// Get the the simulated system. This is an internal function, public
    /// because of the code organization.
    // TODO: use restricted privacy here
    pub fn read_system(&self) -> Result<System> {
        let config = try!(self.system_table());

        let file = try!(extract::str("file", config, "system input"));
        let file = get_input_path(&self.path, file);
        let mut trajectory = try!(Trajectory::open(file));

        if let Some(cell) = try!(self.read_cell()) {
            let cell = try!(cell.to_chemfiles());
            try!(trajectory.as_chemfiles().set_cell(cell));
        }

        if config.get("topology").is_some() {
            let topology = try!(extract::str("topology", config, "system input"));
            try!(trajectory.as_chemfiles().set_topology_file(topology));
        }

        let guess_bonds = if let Some(guess_bonds) = config.get("guess_bonds") {
            try!(guess_bonds.as_bool().ok_or(
                Error::from("'guess_bonds' should be a boolean value in system")
            ))
        } else { false };

        let mut system = if guess_bonds {
            try!(trajectory.read_guess_bonds())
        } else {
            try!(trajectory.read())
        };

        try!(self.read_potentials(&mut system));
        try!(self.init_velocities(&mut system));

        Ok(system)
    }

    fn system_table(&self) -> Result<&Table> {
        let systems = try!(extract::slice("systems", &self.config, "input file"));
        if systems.len() != 1 {
            return Err(Error::from(
                "Only one system is supported in the input"
            ));
        }

        let system = try!(systems[0].as_table().ok_or(
            Error::from("Systems should be tables")
        ));

        return Ok(system);
    }

    fn read_cell(&self) -> Result<Option<UnitCell>> {
        let config = try!(self.system_table());
        if let Some(cell) = config.get("cell") {
            match *cell {
                Value::Array(ref cell) => {
                    if cell.len() == 0 {
                        Ok(Some(UnitCell::new()))
                    } else if cell.len() == 3 {
                        let a = try!(get_cell_number(&cell[0]));
                        let b = try!(get_cell_number(&cell[1]));
                        let c = try!(get_cell_number(&cell[2]));

                        Ok(Some(UnitCell::ortho(a, b, c)))
                    } else if cell.len() == 6 {
                        let a = try!(get_cell_number(&cell[0]));
                        let b = try!(get_cell_number(&cell[1]));
                        let c = try!(get_cell_number(&cell[2]));
                        let alpha = try!(get_cell_number(&cell[3]));
                        let beta  = try!(get_cell_number(&cell[4]));
                        let gamma = try!(get_cell_number(&cell[5]));

                        Ok(Some(UnitCell::triclinic(a, b, c, alpha, beta, gamma)))
                    } else {
                        Err(Error::from("'cell' array must have a size of 3 or 6"))
                    }
                },
                Value::Integer(lenght) => {
                    let lenght = lenght as f64;
                    Ok(Some(UnitCell::cubic(lenght)))
                },
                Value::Float(lenght) => {
                    Ok(Some(UnitCell::cubic(lenght)))
                },
                _ => Err(Error::from("'cell' must be a number or an array"))
            }
        } else {
            Ok(None)
        }
    }

    fn init_velocities(&self, system: &mut System) -> Result<()> {
        let config = try!(self.system_table());

        if let Some(velocities) = config.get("velocities") {
            let velocities = try!(velocities.as_table().ok_or(
                Error::from("'velocities' must be a table in system input")
            ));

            if velocities.get("init").is_some() {
                let temperature = try!(extract::str("init", velocities, "velocities initializer"));
                let temperature = try!(units::from_str(temperature));
                let mut velocities = BoltzmannVelocities::new(temperature);
                velocities.init(system);
            } else {
                warn!("'velocities' key does nothing in this input file");
            }
        }

        Ok(())
    }

    fn read_potentials(&self, system: &mut System) -> Result<()> {
        let config = try!(self.system_table());
        if let Some(potentials) = config.get("potentials") {
            if let Some(potentials) = potentials.as_str() {
                let path = get_input_path(&self.path, potentials);
                let input = try!(InteractionsInput::new(path));
                try!(input.read(system));
            } else if let Some(potentials) = potentials.as_table() {
                let input = try!(InteractionsInput::from_toml(potentials.clone()));
                try!(input.read(system));
            } else {
                return Err(Error::from("'potentials' must be a string or a table"))
            }
        } else {
            warn!("No potentials found in input file");
        }
        Ok(())
    }
}

fn get_cell_number(value: &Value) -> Result<f64> {
    if let Some(value) = value.as_integer() {
        Ok(value as f64)
    } else if let Some(value) = value.as_float() {
        Ok(value)
    } else {
        Err(Error::from("values must be numbers in 'cell' array"))
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;
    use Input;
    use testing::bad_inputs;
    use lumol::system::{Particle, UnitCell};

    #[test]
    fn system() {
        let path = Path::new(file!()).parent().unwrap()
                                     .join("data")
                                     .join("system.toml");
        let input = Input::new(path).unwrap();
        let config = input.read().unwrap();
        assert_eq!(*config.system.cell(), UnitCell::cubic(20.0));
        assert!(f64::abs(config.system.temperature() - 300.0) < 1e-12);

        let mut system = config.system;
        let last = system.size();
        system.add_particle(Particle::new("A"));
        system.add_particle(Particle::new("B"));
        assert_eq!(system.pair_potentials(last, last + 1).len(), 11);
    }

    #[test]
    fn inline_potentials() {
        let path = Path::new(file!()).parent().unwrap()
                                     .join("data")
                                     .join("potentials.toml");
        let input = Input::new(path).unwrap();
        let config = input.read().unwrap();
        assert_eq!(*config.system.cell(), UnitCell::cubic(20.0));
        assert!(f64::abs(config.system.temperature() - 300.0) < 1e-12);
        assert_eq!(config.system.pair_potentials(0, 1).len(), 2);
    }

    #[test]
    fn bad_systems() {
        for path in bad_inputs("simulations", "system") {
            assert!(Input::new(path).and_then(|input| input.read()).is_err());
        }
    }
}
<commit_msg>Emit a warning if no unit cell is defined in the input file<commit_after>// Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 G. Fraux — BSD license
use toml::{Table, Value};

use lumol::chfl::{Trajectory, ToChemfiles};
use lumol::units;
use lumol::system::*;

use error::{Error, Result};
use extract;
use {Input, InteractionsInput};
use simulations::get_input_path;

impl Input {
    /// Get the the simulated system. This is an internal function, public
    /// because of the code organization.
    // TODO: use restricted privacy here
    pub fn read_system(&self) -> Result<System> {
        let config = try!(self.system_table());

        let file = try!(extract::str("file", config, "system input"));
        let file = get_input_path(&self.path, file);
        let mut trajectory = try!(Trajectory::open(file));

        let mut with_cell = false;
        if let Some(cell) = try!(self.read_cell()) {
            let cell = try!(cell.to_chemfiles());
            try!(trajectory.as_chemfiles().set_cell(cell));
            with_cell = true;
        }

        if config.get("topology").is_some() {
            let topology = try!(extract::str("topology", config, "system input"));
            try!(trajectory.as_chemfiles().set_topology_file(topology));
        }

        let guess_bonds = if let Some(guess_bonds) = config.get("guess_bonds") {
            try!(guess_bonds.as_bool().ok_or(
                Error::from("'guess_bonds' should be a boolean value in system")
            ))
        } else { false };

        let mut system = if guess_bonds {
            try!(trajectory.read_guess_bonds())
        } else {
            try!(trajectory.read())
        };

        try!(self.read_potentials(&mut system));
        try!(self.init_velocities(&mut system));

        if !with_cell && system.cell().shape() == CellShape::Infinite {
            warn!("No unit cell in the system, using an infinite unit cell.\n\
            You can silent this warning by using `cell = []` in the input file \
            if this is what you want.");
        }

        Ok(system)
    }

    fn system_table(&self) -> Result<&Table> {
        let systems = try!(extract::slice("systems", &self.config, "input file"));
        if systems.len() != 1 {
            return Err(Error::from(
                "Only one system is supported in the input"
            ));
        }

        let system = try!(systems[0].as_table().ok_or(
            Error::from("Systems should be tables")
        ));

        return Ok(system);
    }

    fn read_cell(&self) -> Result<Option<UnitCell>> {
        let config = try!(self.system_table());
        if let Some(cell) = config.get("cell") {
            match *cell {
                Value::Array(ref cell) => {
                    if cell.len() == 0 {
                        Ok(Some(UnitCell::new()))
                    } else if cell.len() == 3 {
                        let a = try!(get_cell_number(&cell[0]));
                        let b = try!(get_cell_number(&cell[1]));
                        let c = try!(get_cell_number(&cell[2]));

                        Ok(Some(UnitCell::ortho(a, b, c)))
                    } else if cell.len() == 6 {
                        let a = try!(get_cell_number(&cell[0]));
                        let b = try!(get_cell_number(&cell[1]));
                        let c = try!(get_cell_number(&cell[2]));
                        let alpha = try!(get_cell_number(&cell[3]));
                        let beta  = try!(get_cell_number(&cell[4]));
                        let gamma = try!(get_cell_number(&cell[5]));

                        Ok(Some(UnitCell::triclinic(a, b, c, alpha, beta, gamma)))
                    } else {
                        Err(Error::from("'cell' array must have a size of 3 or 6"))
                    }
                },
                Value::Integer(lenght) => {
                    let lenght = lenght as f64;
                    Ok(Some(UnitCell::cubic(lenght)))
                },
                Value::Float(lenght) => {
                    Ok(Some(UnitCell::cubic(lenght)))
                },
                _ => Err(Error::from("'cell' must be a number or an array"))
            }
        } else {
            Ok(None)
        }
    }

    fn init_velocities(&self, system: &mut System) -> Result<()> {
        let config = try!(self.system_table());

        if let Some(velocities) = config.get("velocities") {
            let velocities = try!(velocities.as_table().ok_or(
                Error::from("'velocities' must be a table in system input")
            ));

            if velocities.get("init").is_some() {
                let temperature = try!(extract::str("init", velocities, "velocities initializer"));
                let temperature = try!(units::from_str(temperature));
                let mut velocities = BoltzmannVelocities::new(temperature);
                velocities.init(system);
            } else {
                warn!("'velocities' key does nothing in this input file");
            }
        }

        Ok(())
    }

    fn read_potentials(&self, system: &mut System) -> Result<()> {
        let config = try!(self.system_table());
        if let Some(potentials) = config.get("potentials") {
            if let Some(potentials) = potentials.as_str() {
                let path = get_input_path(&self.path, potentials);
                let input = try!(InteractionsInput::new(path));
                try!(input.read(system));
            } else if let Some(potentials) = potentials.as_table() {
                let input = try!(InteractionsInput::from_toml(potentials.clone()));
                try!(input.read(system));
            } else {
                return Err(Error::from("'potentials' must be a string or a table"))
            }
        } else {
            warn!("No potentials found in input file");
        }
        Ok(())
    }
}

fn get_cell_number(value: &Value) -> Result<f64> {
    if let Some(value) = value.as_integer() {
        Ok(value as f64)
    } else if let Some(value) = value.as_float() {
        Ok(value)
    } else {
        Err(Error::from("values must be numbers in 'cell' array"))
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;
    use Input;
    use testing::bad_inputs;
    use lumol::system::{Particle, UnitCell};

    #[test]
    fn system() {
        let path = Path::new(file!()).parent().unwrap()
                                     .join("data")
                                     .join("system.toml");
        let input = Input::new(path).unwrap();
        let config = input.read().unwrap();
        assert_eq!(*config.system.cell(), UnitCell::cubic(20.0));
        assert!(f64::abs(config.system.temperature() - 300.0) < 1e-12);

        let mut system = config.system;
        let last = system.size();
        system.add_particle(Particle::new("A"));
        system.add_particle(Particle::new("B"));
        assert_eq!(system.pair_potentials(last, last + 1).len(), 11);
    }

    #[test]
    fn inline_potentials() {
        let path = Path::new(file!()).parent().unwrap()
                                     .join("data")
                                     .join("potentials.toml");
        let input = Input::new(path).unwrap();
        let config = input.read().unwrap();
        assert_eq!(*config.system.cell(), UnitCell::cubic(20.0));
        assert!(f64::abs(config.system.temperature() - 300.0) < 1e-12);
        assert_eq!(config.system.pair_potentials(0, 1).len(), 2);
    }

    #[test]
    fn bad_systems() {
        for path in bad_inputs("simulations", "system") {
            assert!(Input::new(path).and_then(|input| input.read()).is_err());
        }
    }
}
<|endoftext|>


<commit_before>//! The [COLR](https://docs.microsoft.com/en-us/typography/opentype/spec/colr) table

use font_types::Tag;

/// 'COLR'
pub const TAG: Tag = Tag::new(b"COLR");

include!("../../generated/generated_colr.rs");<commit_msg>rustfmt!<commit_after>//! The [COLR](https://docs.microsoft.com/en-us/typography/opentype/spec/colr) table

use font_types::Tag;

/// 'COLR'
pub const TAG: Tag = Tag::new(b"COLR");

include!("../../generated/generated_colr.rs");
<|endoftext|>


<commit_before>use piston_window;
use gfx_device_gl::{Resources, Output, CommandBuffer};
use gfx_graphics::GfxGraphics;
use piston_window::Transformed;

pub struct Object {
    x: f64,
    y: f64,
}

impl Object {
    pub fn new() -> Object {
        Object { x: 0., y: 0. }
    }

    pub fn mov(&mut self, x: f64, y: f64) {
        self.x += x;
        self.y += y;
    }

    pub fn mov_to(&mut self, x: f64, y: f64) {
        self.x = x;
        self.y = y;
    }

    pub fn render(&self, graphic: &mut GfxGraphics<Resources, CommandBuffer<Resources>, Output>, view: &piston_window::math::Matrix2d) {
        let red = [1.0, 0.0, 0.0, 1.0];
        let square = piston_window::rectangle::square(0.0, 0.0, 100.0);
        piston_window::rectangle(red, square, view.trans(self.x, self.y).trans(-50.0, -50.0), graphic);
    }
}
<commit_msg>sprite fild has been added to Object<commit_after>use piston_window;
use gfx_device_gl::{Resources, Output, CommandBuffer};
use gfx_graphics::GfxGraphics;
use piston_window::Transformed;

pub struct Object {
    x: f64,
    y: f64,
    sprite: Option<piston_window::Texture<Resources>>,
}

impl Object {
    pub fn new() -> Object {
        Object { x: 0., y: 0., sprite: None }
    }

    pub fn mov(&mut self, x: f64, y: f64) {
        self.x += x;
        self.y += y;
    }

    pub fn mov_to(&mut self, x: f64, y: f64) {
        self.x = x;
        self.y = y;
    }

    pub fn render(&self, graphic: &mut GfxGraphics<Resources, CommandBuffer<Resources>, Output>, view: &piston_window::math::Matrix2d) {
        let red = [1.0, 0.0, 0.0, 1.0];
        let square = piston_window::rectangle::square(0.0, 0.0, 100.0);
        piston_window::rectangle(red, square, view.trans(self.x, self.y).trans(-50.0, -50.0), graphic);
    }
}
<|endoftext|>


<commit_before>// Verify debuginfo for generators:
//  - Each variant points to the file and line of its yield point
//  - The generator types and variants are marked artificial
//  - Captured vars from the source are not marked artificial
//
// ignore-tidy-linelength
// compile-flags: -C debuginfo=2 --edition=2018

#![feature(generators, generator_trait)]
use std::ops::Generator;

fn generator_test() -> impl Generator<Yield = i32, Return = ()> {
    || {
        yield 0;
        let s = String::from("foo");
        yield 1;
    }
}

async fn foo() {}
async fn async_fn_test() {
    foo().await;
    let s = String::from("foo");
    foo().await;
}

// FIXME: We need "checksum" to prevent matching with the wrong (duplicate) file
//        metadata, even when -C codegen-units=1.
// CHECK:      [[FILE:!.*]] = !DIFile(filename: "{{.*}}/generator-debug.rs", {{.*}}, checksum:

// CHECK:      [[GEN:!.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "generator-0", scope: [[FN:![0-9]*]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      [[FN]] = !DINamespace(name: "generator_test"
// CHECK:      [[VARIANT:!.*]] = !DICompositeType(tag: DW_TAG_variant_part, scope: [[FN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK-SAME: discriminator: [[DISC:![0-9]*]]
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "0", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 13,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DICompositeType(tag: DW_TAG_structure_type, name: "Unresumed", scope: [[GEN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "1", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 17,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "2", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 17,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "3", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 14,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "4", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 16,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      [[S1:!.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Suspend1", scope: [[GEN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "s", scope: [[S1]]
// CHECK-NOT:  flags: DIFlagArtificial
// CHECK-SAME: )
// CHECK:      [[DISC]] = !DIDerivedType(tag: DW_TAG_member, name: "__state", scope: [[FN]],
// CHECK-SAME: flags: DIFlagArtificial

// CHECK:      [[GEN:!.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "generator-0", scope: [[FN:![0-9]*]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      [[FN]] = !DINamespace(name: "async_fn_test"
// CHECK:      [[VARIANT:!.*]] = !DICompositeType(tag: DW_TAG_variant_part, scope: [[FN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK-SAME: discriminator: [[DISC:![0-9]*]]
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "0", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 21,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "1", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 25,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "2", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 25,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "3", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 22,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "4", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 24,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      [[S1:!.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Suspend1", scope: [[GEN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "s", scope: [[S1]]
// CHECK-NOT:  flags: DIFlagArtificial
// CHECK-SAME: )
// CHECK:      [[DISC]] = !DIDerivedType(tag: DW_TAG_member, name: "__state", scope: [[FN]],
// CHECK-SAME: flags: DIFlagArtificial

fn main() {
    let _dummy = generator_test();
    let _dummy = async_fn_test();
}
<commit_msg>Generalize generator-debug test a bit<commit_after>// Verify debuginfo for generators:
//  - Each variant points to the file and line of its yield point
//  - The generator types and variants are marked artificial
//  - Captured vars from the source are not marked artificial
//
// ignore-tidy-linelength
// compile-flags: -C debuginfo=2 --edition=2018
// ignore-msvc

#![feature(generators, generator_trait)]
use std::ops::Generator;

fn generator_test() -> impl Generator<Yield = i32, Return = ()> {
    || {
        yield 0;
        let s = String::from("foo");
        yield 1;
    }
}

async fn foo() {}
async fn async_fn_test() {
    foo().await;
    let s = String::from("foo");
    foo().await;
}

// FIXME: We need "checksum" to prevent matching with the wrong (duplicate) file
//        metadata, even when -C codegen-units=1.
// CHECK-DAG:  [[FILE:!.*]] = !DIFile(filename: "{{.*}}generator-debug.rs", {{.*}}, checksum:

// CHECK-DAG:  [[GEN_FN:!.*]] = !DINamespace(name: "generator_test"
// CHECK-DAG:  [[GEN:!.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "generator-0", scope: [[GEN_FN]], {{.*}}flags: DIFlagArtificial
// CHECK:      [[VARIANT:!.*]] = !DICompositeType(tag: DW_TAG_variant_part, scope: [[GEN_FN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK-SAME: discriminator: [[DISC:![0-9]*]]
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "0", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 14,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DICompositeType(tag: DW_TAG_structure_type, name: "Unresumed", scope: [[GEN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "1", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 18,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "2", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 18,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "3", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 15,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "4", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 17,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      [[S1:!.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Suspend1", scope: [[GEN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "s", scope: [[S1]]
// CHECK-NOT:  flags: DIFlagArtificial
// CHECK-SAME: )
// CHECK:      [[DISC]] = !DIDerivedType(tag: DW_TAG_member, name: "__state", scope: [[GEN_FN]],
// CHECK-SAME: flags: DIFlagArtificial

// CHECK-DAG:  [[GEN:!.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "generator-0", scope: [[ASYNC_FN:![0-9]*]], {{.*}}flags: DIFlagArtificial
// CHECK:      [[VARIANT:!.*]] = !DICompositeType(tag: DW_TAG_variant_part, scope: [[ASYNC_FN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK-SAME: discriminator: [[DISC:![0-9]*]]
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "0", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 22,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "1", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 26,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "2", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 26,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "3", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 23,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "4", scope: [[VARIANT]],
// CHECK-SAME: file: [[FILE]], line: 25,
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      [[S1:!.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Suspend1", scope: [[GEN]],
// CHECK-SAME: flags: DIFlagArtificial
// CHECK:      {{!.*}} = !DIDerivedType(tag: DW_TAG_member, name: "s", scope: [[S1]]
// CHECK-NOT:  flags: DIFlagArtificial
// CHECK-SAME: )
// CHECK:      [[DISC]] = !DIDerivedType(tag: DW_TAG_member, name: "__state", scope: [[ASYNC_FN]],
// CHECK-SAME: flags: DIFlagArtificial

fn main() {
    let _dummy = generator_test();
    let _dummy = async_fn_test();
}
<|endoftext|>


<commit_before>#![feature(test)]
extern crate adapton;
extern crate test;
use self::test::Bencher;
use adapton::trie::*;
use adapton::engine::*;

// The code that we want to compare/measure under naive versus DCG engines:
fn doit(v: Vec<usize>, t: Trie<usize>) -> Trie<usize> {
    v.into_iter().fold(t, |acc, i| TrieIntro::extend(name_of_usize(i), acc, i))
}

fn bench_naive_add_dups() {
    init_naive();
    let mut naive_input: Trie<usize> = SetIntro::empty();
    let mut v = Vec::new();

    for i in vec![1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3].iter() {
        v.push(*i);
        naive_input = doit(v.clone(), naive_input.clone())
    }
}

fn bench_dcg_add_dups() {
    init_dcg();
    let mut dcg_input: Trie<usize> = SetIntro::empty();
    let mut v = Vec::new();

    for i in vec![1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3].iter() {
        v.push(*i);
        dcg_input = doit(v.clone(), dcg_input.clone())
    }
}

#[bench]
fn benchmark_naive_trie(b: &mut Bencher) {
    b.iter(|| bench_naive_add_dups())
}

#[bench]
fn benchmark_dcg_trie(b: &mut Bencher) {
    b.iter(|| bench_dcg_add_dups())
}
<commit_msg>Run benchmarks on larger vector.<commit_after>#![feature(test)]
extern crate adapton;
extern crate test;
use self::test::Bencher;
use adapton::trie::*;
use adapton::engine::*;

// The code that we want to compare/measure under naive versus DCG engines:
fn doit(v: Vec<usize>, t: Trie<usize>) -> Trie<usize> {
    v.into_iter().fold(t, |acc, i| TrieIntro::extend(name_of_usize(i), acc, i))
}

fn bench_naive_add_dups() {
    init_naive();
    let mut naive_input: Trie<usize> = SetIntro::empty();
    let mut v = Vec::new();

    let mut ones = vec![1;100];
    let mut twos = vec![2;100];
    let mut threes = vec![3;100];
    twos.append(&mut threes);
    ones.append(&mut twos);
    for i in ones.iter() {
        v.push(*i);
        naive_input = doit(v.clone(), naive_input.clone())
    }
}

fn bench_dcg_add_dups() {
    init_dcg();
    let mut dcg_input: Trie<usize> = SetIntro::empty();
    let mut v = Vec::new();

    let mut ones = vec![1;100];
    let mut twos = vec![2;100];
    let mut threes = vec![3;100];
    twos.append(&mut threes);
    ones.append(&mut twos);
    for i in ones.iter() {
        v.push(*i);
        dcg_input = doit(v.clone(), dcg_input.clone())
    }
}

#[bench]
fn benchmark_naive_trie(b: &mut Bencher) {
    b.iter(|| bench_naive_add_dups())
}

#[bench]
fn benchmark_dcg_trie(b: &mut Bencher) {
    b.iter(|| bench_dcg_add_dups())
}
<|endoftext|>


<commit_before>// run-pass
// compile-flags: -Z borrowck=mir

use std::cell::Cell;

const FIVE: Cell<i32> = Cell::new(5);

#[inline(never)]
fn tuple_field() -> &'static u32 {
    // This test is MIR-borrowck-only because the old borrowck
    // doesn't agree that borrows of "frozen" (i.e., without any
    // interior mutability) fields of non-frozen temporaries,
    // should be promoted, while MIR promotion does promote them.
    &(FIVE, 42).1
}

fn main() {
    assert_eq!(tuple_field().to_string(), "42");
}
<commit_msg>remove a test that does not work any more<commit_after><|endoftext|>


<commit_before>#![feature(test)]

extern crate env_logger;
extern crate lzma_rs;
extern crate test;

use std::io::Read;
use test::Bencher;

fn compress_bench(x: &[u8], b: &mut Bencher) {
    b.iter(|| {
        let mut compressed: Vec<u8> = Vec::new();
        lzma_rs::lzma_compress(&mut std::io::BufReader::new(x), &mut compressed).unwrap();
    });
}

fn decompress_bench(x: &[u8], b: &mut Bencher) {
    let mut compressed: Vec<u8> = Vec::new();
    lzma_rs::lzma_compress(&mut std::io::BufReader::new(x), &mut compressed).unwrap();

    b.iter(|| {
        let mut bf = std::io::BufReader::new(compressed.as_slice());
        let mut decomp: Vec<u8> = Vec::new();
        lzma_rs::lzma_decompress(&mut bf, &mut decomp).unwrap();
    });
}

fn decompress_bench_file(compfile: &str, b: &mut Bencher) {
    let mut f = std::fs::File::open(compfile).unwrap();
    let mut buf = Vec::new();
    f.read_to_end(&mut buf).unwrap();
    decompress_bench(&buf, b);
}

#[bench]
fn compress_empty(b: &mut Bencher) {
    let _ = env_logger::try_init();
    compress_bench(b"", b);
}

#[bench]
fn decompress_empty(b: &mut Bencher) {
    let _ = env_logger::try_init();
    decompress_bench(b"", b);
}

#[bench]
fn compress_hello(b: &mut Bencher) {
    let _ = env_logger::try_init();
    compress_bench(b"Hello world", b);
}

#[bench]
fn decompress_hello(b: &mut Bencher) {
    let _ = env_logger::try_init();
    decompress_bench(b"Hello world", b);
}

#[bench]
fn compress_65536(b: &mut Bencher) {
    let _ = env_logger::try_init();
    compress_bench(&[0; 0x10000], b);
}

#[bench]
fn decompress_65536(b: &mut Bencher) {
    let _ = env_logger::try_init();
    decompress_bench(&[0; 0x10000], b);
}

#[bench]
fn decompress_big_file(b: &mut Bencher) {
    let _ = env_logger::try_init();
    decompress_bench_file("tests/files/foo.txt.lzma", b);
}
<commit_msg>More benchmarks.<commit_after>#![feature(test)]

extern crate env_logger;
extern crate lzma_rs;
extern crate test;

use std::io::Read;
use test::Bencher;

fn compress_bench(x: &[u8], b: &mut Bencher) {
    b.iter(|| {
        let mut compressed: Vec<u8> = Vec::new();
        lzma_rs::lzma_compress(&mut std::io::BufReader::new(x), &mut compressed).unwrap();
    });
}

fn decompress_after_compress_bench(x: &[u8], b: &mut Bencher) {
    let mut compressed: Vec<u8> = Vec::new();
    lzma_rs::lzma_compress(&mut std::io::BufReader::new(x), &mut compressed).unwrap();

    b.iter(|| {
        let mut bf = std::io::BufReader::new(compressed.as_slice());
        let mut decomp: Vec<u8> = Vec::new();
        lzma_rs::lzma_decompress(&mut bf, &mut decomp).unwrap();
    });
}

fn decompress_bench(compressed: &[u8], b: &mut Bencher) {
    b.iter(|| {
        let mut bf = std::io::BufReader::new(compressed);
        let mut decomp: Vec<u8> = Vec::new();
        lzma_rs::lzma_decompress(&mut bf, &mut decomp).unwrap();
    });
}

fn decompress_bench_file(compfile: &str, b: &mut Bencher) {
    let mut f = std::fs::File::open(compfile).unwrap();
    let mut compressed = Vec::new();
    f.read_to_end(&mut compressed).unwrap();
    decompress_bench(&compressed, b);
}

#[bench]
fn compress_empty(b: &mut Bencher) {
    let _ = env_logger::try_init();
    compress_bench(b"", b);
}

#[bench]
fn decompress_after_compress_empty(b: &mut Bencher) {
    let _ = env_logger::try_init();
    decompress_after_compress_bench(b"", b);
}

#[bench]
fn compress_hello(b: &mut Bencher) {
    let _ = env_logger::try_init();
    compress_bench(b"Hello world", b);
}

#[bench]
fn decompress_after_compress_hello(b: &mut Bencher) {
    let _ = env_logger::try_init();
    decompress_after_compress_bench(b"Hello world", b);
}

#[bench]
fn compress_65536(b: &mut Bencher) {
    let _ = env_logger::try_init();
    compress_bench(&[0; 0x10000], b);
}

#[bench]
fn decompress_after_compress_65536(b: &mut Bencher) {
    let _ = env_logger::try_init();
    decompress_after_compress_bench(&[0; 0x10000], b);
}

#[bench]
fn decompress_big_file(b: &mut Bencher) {
    let _ = env_logger::try_init();
    decompress_bench_file("tests/files/foo.txt.lzma", b);
}

#[bench]
fn decompress_huge_dict(b: &mut Bencher) {
    let _ = env_logger::try_init();
    let compressed: &[u8] = b"\x5d\x7f\x7f\x7f\x7f\xff\xff\xff\
                              \xff\xff\xff\xff\xff\x00\x24\x19\
                              \x49\x98\x6f\x10\x19\xc6\xd7\x31\
                              \xeb\x36\x50\xb2\x98\x48\xff\xfe\
                              \xa5\xb0\x00";
    decompress_bench(&compressed, b);
}
<|endoftext|>


<commit_before>use attrs::AttributeSpanWrapper;
use field::Field;
use model::Model;
use proc_macro2::TokenStream;
use quote::quote_spanned;
use syn::{DeriveInput, Expr, Path, Type};
use util::{inner_of_option_ty, is_option_ty, wrap_in_dummy_mod};

pub fn derive(item: DeriveInput) -> TokenStream {
    let model = Model::from_item(&item, false);

    let treat_none_as_default_value = model.treat_none_as_default_value();
    let table_name = &model.table_name();
    let struct_name = &item.ident;

    let (impl_generics, ty_generics, where_clause) = item.generics.split_for_impl();

    let mut generate_borrowed_insert = true;

    let mut direct_field_ty = Vec::with_capacity(model.fields().len());
    let mut direct_field_assign = Vec::with_capacity(model.fields().len());
    let mut ref_field_ty = Vec::with_capacity(model.fields().len());
    let mut ref_field_assign = Vec::with_capacity(model.fields().len());

    for field in model.fields() {
        match (field.serialize_as.as_ref(), field.embed()) {
            (None, true) => {
                direct_field_ty.push(field_ty_embed(field, None));
                direct_field_assign.push(field_expr_embed(field, None));
                ref_field_ty.push(field_ty_embed(field, Some(quote!(&'insert))));
                ref_field_assign.push(field_expr_embed(field, Some(quote!(&))));
            }
            (None, false) => {
                direct_field_ty.push(field_ty(
                    field,
                    table_name,
                    None,
                    treat_none_as_default_value,
                ));
                direct_field_assign.push(field_expr(
                    field,
                    table_name,
                    None,
                    treat_none_as_default_value,
                ));
                ref_field_ty.push(field_ty(
                    field,
                    table_name,
                    Some(quote!(&'insert)),
                    treat_none_as_default_value,
                ));
                ref_field_assign.push(field_expr(
                    field,
                    table_name,
                    Some(quote!(&)),
                    treat_none_as_default_value,
                ));
            }
            (Some(AttributeSpanWrapper { item: ty, .. }), false) => {
                direct_field_ty.push(field_ty_serialize_as(
                    field,
                    table_name,
                    ty,
                    treat_none_as_default_value,
                ));
                direct_field_assign.push(field_expr_serialize_as(
                    field,
                    table_name,
                    ty,
                    treat_none_as_default_value,
                ));

                generate_borrowed_insert = false; // as soon as we hit one field with #[diesel(serialize_as)] there is no point in generating the impl of Insertable for borrowed structs
            }
            (Some(AttributeSpanWrapper { attribute_span, .. }), true) => {
                abort!(
                    attribute_span,
                    "`#[diesel(embed)]` cannot be combined with `#[diesel(serialize_as)]`"
                )
            }
        }
    }

    let insert_owned = quote! {
        impl #impl_generics Insertable<#table_name::table> for #struct_name #ty_generics
            #where_clause
        {
            type Values = <(#(#direct_field_ty,)*) as Insertable<#table_name::table>>::Values;

            fn values(self) -> <(#(#direct_field_ty,)*) as Insertable<#table_name::table>>::Values {
                (#(#direct_field_assign,)*).values()
            }
        }
    };

    let insert_borrowed = if generate_borrowed_insert {
        let mut impl_generics = item.generics.clone();
        impl_generics.params.push(parse_quote!('insert));
        let (impl_generics, ..) = impl_generics.split_for_impl();

        quote! {
            impl #impl_generics Insertable<#table_name::table>
                for &'insert #struct_name #ty_generics
            #where_clause
            {
                type Values = <(#(#ref_field_ty,)*) as Insertable<#table_name::table>>::Values;

                fn values(self) -> <(#(#ref_field_ty,)*) as Insertable<#table_name::table>>::Values {
                    (#(#ref_field_assign,)*).values()
                }
            }
        }
    } else {
        quote! {}
    };

    wrap_in_dummy_mod(quote! {
        use diesel::insertable::Insertable;
        use diesel::internal::derives::insertable::UndecoratedInsertRecord;
        use diesel::prelude::*;

        #[allow(unused_qualifications)]
        #insert_owned

    #[allow(unused_qualifications)]
        #insert_borrowed

        impl #impl_generics UndecoratedInsertRecord<#table_name::table>
                for #struct_name #ty_generics
            #where_clause
        {
        }
    })
}

fn field_ty_embed(field: &Field, lifetime: Option<TokenStream>) -> TokenStream {
    let field_ty = &field.ty;
    let span = field.span;
    quote_spanned!(span=> #lifetime #field_ty)
}

fn field_expr_embed(field: &Field, lifetime: Option<TokenStream>) -> TokenStream {
    let field_name = &field.name;
    quote!(#lifetime self.#field_name)
}

fn field_ty_serialize_as(
    field: &Field,
    table_name: &Path,
    ty: &Type,
    treat_none_as_default_value: bool,
) -> TokenStream {
    let column_name = field.column_name();
    let span = field.span;
    if treat_none_as_default_value {
        let inner_ty = inner_of_option_ty(ty);

        quote_spanned! {span=>
            std::option::Option<diesel::dsl::Eq<
                #table_name::#column_name,
                #inner_ty,
            >>
        }
    } else {
        quote_spanned! {span=>
            diesel::dsl::Eq<
                #table_name::#column_name,
                #ty,
            >
        }
    }
}

fn field_expr_serialize_as(
    field: &Field,
    table_name: &Path,
    ty: &Type,
    treat_none_as_default_value: bool,
) -> TokenStream {
    let field_name = &field.name;
    let column_name = field.column_name();
    let column = quote!(#table_name::#column_name);
    if treat_none_as_default_value {
        if is_option_ty(ty) {
            quote!(self.#field_name.map(|x| #column.eq(::std::convert::Into::<#ty>::into(x))))
        } else {
            quote!(std::option::Option::Some(#column.eq(::std::convert::Into::<#ty>::into(self.#field_name))))
        }
    } else {
        quote!(#column.eq(::std::convert::Into::<#ty>::into(self.#field_name)))
    }
}

fn field_ty(
    field: &Field,
    table_name: &Path,
    lifetime: Option<TokenStream>,
    treat_none_as_default_value: bool,
) -> TokenStream {
    let column_name = field.column_name();
    let span = field.span;
    if treat_none_as_default_value {
        let inner_ty = inner_of_option_ty(&field.ty);

        quote_spanned! {span=>
            std::option::Option<diesel::dsl::Eq<
                #table_name::#column_name,
                #lifetime #inner_ty,
            >>
        }
    } else {
        let inner_ty = &field.ty;

        quote_spanned! {span=>
            diesel::dsl::Eq<
                #table_name::#column_name,
                #lifetime #inner_ty,
            >
        }
    }
}

fn field_expr(
    field: &Field,
    table_name: &Path,
    lifetime: Option<TokenStream>,
    treat_none_as_default_value: bool,
) -> TokenStream {
    let field_name = &field.name;
    let column_name = field.column_name();

    let column: Expr = parse_quote!(#table_name::#column_name);
    if treat_none_as_default_value {
        if is_option_ty(&field.ty) {
            if lifetime.is_some() {
                quote!(self.#field_name.as_ref().map(|x| #column.eq(x)))
            } else {
                quote!(self.#field_name.map(|x| #column.eq(x)))
            }
        } else {
            quote!(std::option::Option::Some(#column.eq(#lifetime self.#field_name)))
        }
    } else {
        quote!(#column.eq(#lifetime self.#field_name))
    }
}
<commit_msg>Fix indent<commit_after>use attrs::AttributeSpanWrapper;
use field::Field;
use model::Model;
use proc_macro2::TokenStream;
use quote::quote_spanned;
use syn::{DeriveInput, Expr, Path, Type};
use util::{inner_of_option_ty, is_option_ty, wrap_in_dummy_mod};

pub fn derive(item: DeriveInput) -> TokenStream {
    let model = Model::from_item(&item, false);

    let treat_none_as_default_value = model.treat_none_as_default_value();
    let table_name = &model.table_name();
    let struct_name = &item.ident;

    let (impl_generics, ty_generics, where_clause) = item.generics.split_for_impl();

    let mut generate_borrowed_insert = true;

    let mut direct_field_ty = Vec::with_capacity(model.fields().len());
    let mut direct_field_assign = Vec::with_capacity(model.fields().len());
    let mut ref_field_ty = Vec::with_capacity(model.fields().len());
    let mut ref_field_assign = Vec::with_capacity(model.fields().len());

    for field in model.fields() {
        match (field.serialize_as.as_ref(), field.embed()) {
            (None, true) => {
                direct_field_ty.push(field_ty_embed(field, None));
                direct_field_assign.push(field_expr_embed(field, None));
                ref_field_ty.push(field_ty_embed(field, Some(quote!(&'insert))));
                ref_field_assign.push(field_expr_embed(field, Some(quote!(&))));
            }
            (None, false) => {
                direct_field_ty.push(field_ty(
                    field,
                    table_name,
                    None,
                    treat_none_as_default_value,
                ));
                direct_field_assign.push(field_expr(
                    field,
                    table_name,
                    None,
                    treat_none_as_default_value,
                ));
                ref_field_ty.push(field_ty(
                    field,
                    table_name,
                    Some(quote!(&'insert)),
                    treat_none_as_default_value,
                ));
                ref_field_assign.push(field_expr(
                    field,
                    table_name,
                    Some(quote!(&)),
                    treat_none_as_default_value,
                ));
            }
            (Some(AttributeSpanWrapper { item: ty, .. }), false) => {
                direct_field_ty.push(field_ty_serialize_as(
                    field,
                    table_name,
                    ty,
                    treat_none_as_default_value,
                ));
                direct_field_assign.push(field_expr_serialize_as(
                    field,
                    table_name,
                    ty,
                    treat_none_as_default_value,
                ));

                generate_borrowed_insert = false; // as soon as we hit one field with #[diesel(serialize_as)] there is no point in generating the impl of Insertable for borrowed structs
            }
            (Some(AttributeSpanWrapper { attribute_span, .. }), true) => {
                abort!(
                    attribute_span,
                    "`#[diesel(embed)]` cannot be combined with `#[diesel(serialize_as)]`"
                )
            }
        }
    }

    let insert_owned = quote! {
        impl #impl_generics Insertable<#table_name::table> for #struct_name #ty_generics
            #where_clause
        {
            type Values = <(#(#direct_field_ty,)*) as Insertable<#table_name::table>>::Values;

            fn values(self) -> <(#(#direct_field_ty,)*) as Insertable<#table_name::table>>::Values {
                (#(#direct_field_assign,)*).values()
            }
        }
    };

    let insert_borrowed = if generate_borrowed_insert {
        let mut impl_generics = item.generics.clone();
        impl_generics.params.push(parse_quote!('insert));
        let (impl_generics, ..) = impl_generics.split_for_impl();

        quote! {
            impl #impl_generics Insertable<#table_name::table>
                for &'insert #struct_name #ty_generics
            #where_clause
            {
                type Values = <(#(#ref_field_ty,)*) as Insertable<#table_name::table>>::Values;

                fn values(self) -> <(#(#ref_field_ty,)*) as Insertable<#table_name::table>>::Values {
                    (#(#ref_field_assign,)*).values()
                }
            }
        }
    } else {
        quote! {}
    };

    wrap_in_dummy_mod(quote! {
        use diesel::insertable::Insertable;
        use diesel::internal::derives::insertable::UndecoratedInsertRecord;
        use diesel::prelude::*;

        #[allow(unused_qualifications)]
        #insert_owned

        #[allow(unused_qualifications)]
        #insert_borrowed

        impl #impl_generics UndecoratedInsertRecord<#table_name::table>
                for #struct_name #ty_generics
            #where_clause
        {
        }
    })
}

fn field_ty_embed(field: &Field, lifetime: Option<TokenStream>) -> TokenStream {
    let field_ty = &field.ty;
    let span = field.span;
    quote_spanned!(span=> #lifetime #field_ty)
}

fn field_expr_embed(field: &Field, lifetime: Option<TokenStream>) -> TokenStream {
    let field_name = &field.name;
    quote!(#lifetime self.#field_name)
}

fn field_ty_serialize_as(
    field: &Field,
    table_name: &Path,
    ty: &Type,
    treat_none_as_default_value: bool,
) -> TokenStream {
    let column_name = field.column_name();
    let span = field.span;
    if treat_none_as_default_value {
        let inner_ty = inner_of_option_ty(ty);

        quote_spanned! {span=>
            std::option::Option<diesel::dsl::Eq<
                #table_name::#column_name,
                #inner_ty,
            >>
        }
    } else {
        quote_spanned! {span=>
            diesel::dsl::Eq<
                #table_name::#column_name,
                #ty,
            >
        }
    }
}

fn field_expr_serialize_as(
    field: &Field,
    table_name: &Path,
    ty: &Type,
    treat_none_as_default_value: bool,
) -> TokenStream {
    let field_name = &field.name;
    let column_name = field.column_name();
    let column = quote!(#table_name::#column_name);
    if treat_none_as_default_value {
        if is_option_ty(ty) {
            quote!(self.#field_name.map(|x| #column.eq(::std::convert::Into::<#ty>::into(x))))
        } else {
            quote!(std::option::Option::Some(#column.eq(::std::convert::Into::<#ty>::into(self.#field_name))))
        }
    } else {
        quote!(#column.eq(::std::convert::Into::<#ty>::into(self.#field_name)))
    }
}

fn field_ty(
    field: &Field,
    table_name: &Path,
    lifetime: Option<TokenStream>,
    treat_none_as_default_value: bool,
) -> TokenStream {
    let column_name = field.column_name();
    let span = field.span;
    if treat_none_as_default_value {
        let inner_ty = inner_of_option_ty(&field.ty);

        quote_spanned! {span=>
            std::option::Option<diesel::dsl::Eq<
                #table_name::#column_name,
                #lifetime #inner_ty,
            >>
        }
    } else {
        let inner_ty = &field.ty;

        quote_spanned! {span=>
            diesel::dsl::Eq<
                #table_name::#column_name,
                #lifetime #inner_ty,
            >
        }
    }
}

fn field_expr(
    field: &Field,
    table_name: &Path,
    lifetime: Option<TokenStream>,
    treat_none_as_default_value: bool,
) -> TokenStream {
    let field_name = &field.name;
    let column_name = field.column_name();

    let column: Expr = parse_quote!(#table_name::#column_name);
    if treat_none_as_default_value {
        if is_option_ty(&field.ty) {
            if lifetime.is_some() {
                quote!(self.#field_name.as_ref().map(|x| #column.eq(x)))
            } else {
                quote!(self.#field_name.map(|x| #column.eq(x)))
            }
        } else {
            quote!(std::option::Option::Some(#column.eq(#lifetime self.#field_name)))
        }
    } else {
        quote!(#column.eq(#lifetime self.#field_name))
    }
}
<|endoftext|>


<commit_before>use std::io::prelude::*;
use std::io::SeekFrom;
use std::path::Path;

use crate::core::PackageId;
use crate::sources::registry::{MaybeLock, RegistryConfig, RegistryData};
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::{Config, FileLock, Filesystem, Sha256};
use hex;

pub struct LocalRegistry<'cfg> {
    index_path: Filesystem,
    root: Filesystem,
    src_path: Filesystem,
    config: &'cfg Config,
}

impl<'cfg> LocalRegistry<'cfg> {
    pub fn new(root: &Path, config: &'cfg Config, name: &str) -> LocalRegistry<'cfg> {
        LocalRegistry {
            src_path: config.registry_source_path().join(name),
            index_path: Filesystem::new(root.join("index")),
            root: Filesystem::new(root.to_path_buf()),
            config,
        }
    }
}

impl<'cfg> RegistryData for LocalRegistry<'cfg> {
    fn prepare(&self) -> CargoResult<()> {
        Ok(())
    }

    fn index_path(&self) -> &Filesystem {
        &self.index_path
    }

    fn load(
        &self,
        root: &Path,
        path: &Path,
        data: &mut dyn FnMut(&[u8]) -> CargoResult<()>,
    ) -> CargoResult<()> {
        data(&paths::read_bytes(&root.join(path))?)
    }

    fn config(&mut self) -> CargoResult<Option<RegistryConfig>> {
        // Local registries don't have configuration for remote APIs or anything
        // like that
        Ok(None)
    }

    fn update_index(&mut self) -> CargoResult<()> {
        // Nothing to update, we just use what's on disk. Verify it actually
        // exists though. We don't use any locks as we're just checking whether
        // these directories exist.
        let root = self.root.clone().into_path_unlocked();
        if !root.is_dir() {
            failure::bail!("local registry path is not a directory: {}", root.display())
        }
        let index_path = self.index_path.clone().into_path_unlocked();
        if !index_path.is_dir() {
            failure::bail!(
                "local registry index path is not a directory: {}",
                index_path.display()
            )
        }
        Ok(())
    }

    fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> {
        let crate_file = format!("{}-{}.crate", pkg.name(), pkg.version());
        let mut crate_file = self.root.open_ro(&crate_file, self.config, "crate file")?;

        // If we've already got an unpacked version of this crate, then skip the
        // checksum below as it is in theory already verified.
        let dst = format!("{}-{}", pkg.name(), pkg.version());
        if self.src_path.join(dst).into_path_unlocked().exists() {
            return Ok(MaybeLock::Ready(crate_file));
        }

        self.config.shell().status("Unpacking", pkg)?;

        // We don't actually need to download anything per-se, we just need to
        // verify the checksum matches the .crate file itself.
        let mut state = Sha256::new();
        let mut buf = [0; 64 * 1024];
        loop {
            let n = crate_file
                .read(&mut buf)
                .chain_err(|| format!("failed to read `{}`", crate_file.path().display()))?;
            if n == 0 {
                break;
            }
            state.update(&buf[..n]);
        }
        if hex::encode(state.finish()) != checksum {
            failure::bail!("failed to verify the checksum of `{}`", pkg)
        }

        crate_file.seek(SeekFrom::Start(0))?;

        Ok(MaybeLock::Ready(crate_file))
    }

    fn finish_download(
        &mut self,
        _pkg: PackageId,
        _checksum: &str,
        _data: &[u8],
    ) -> CargoResult<FileLock> {
        panic!("this source doesn't download")
    }
}
<commit_msg>Fix race condition in local registry crate downloading.<commit_after>use std::io::prelude::*;
use std::io::SeekFrom;
use std::path::Path;

use crate::core::PackageId;
use crate::sources::registry::{MaybeLock, RegistryConfig, RegistryData};
use crate::util::errors::{CargoResult, CargoResultExt};
use crate::util::paths;
use crate::util::{Config, FileLock, Filesystem, Sha256};
use hex;

pub struct LocalRegistry<'cfg> {
    index_path: Filesystem,
    cache_path: Filesystem,
    root: Filesystem,
    config: &'cfg Config,
}

impl<'cfg> LocalRegistry<'cfg> {
    pub fn new(root: &Path, config: &'cfg Config, name: &str) -> LocalRegistry<'cfg> {
        LocalRegistry {
            cache_path: config.registry_cache_path().join(name),
            index_path: Filesystem::new(root.join("index")),
            root: Filesystem::new(root.to_path_buf()),
            config,
        }
    }
}

impl<'cfg> RegistryData for LocalRegistry<'cfg> {
    fn prepare(&self) -> CargoResult<()> {
        Ok(())
    }

    fn index_path(&self) -> &Filesystem {
        &self.index_path
    }

    fn load(
        &self,
        root: &Path,
        path: &Path,
        data: &mut dyn FnMut(&[u8]) -> CargoResult<()>,
    ) -> CargoResult<()> {
        data(&paths::read_bytes(&root.join(path))?)
    }

    fn config(&mut self) -> CargoResult<Option<RegistryConfig>> {
        // Local registries don't have configuration for remote APIs or anything
        // like that
        Ok(None)
    }

    fn update_index(&mut self) -> CargoResult<()> {
        // Nothing to update, we just use what's on disk. Verify it actually
        // exists though. We don't use any locks as we're just checking whether
        // these directories exist.
        let root = self.root.clone().into_path_unlocked();
        if !root.is_dir() {
            failure::bail!("local registry path is not a directory: {}", root.display())
        }
        let index_path = self.index_path.clone().into_path_unlocked();
        if !index_path.is_dir() {
            failure::bail!(
                "local registry index path is not a directory: {}",
                index_path.display()
            )
        }
        Ok(())
    }

    fn download(&mut self, pkg: PackageId, checksum: &str) -> CargoResult<MaybeLock> {
        let filename = format!("{}-{}.crate", pkg.name(), pkg.version());

        // Attempt to open an read-only lock first to avoid an exclusive write lock.
        //
        // If this fails then we fall through to the exclusive path where we copy
        // the file.
        if let Ok(dst) = self.cache_path.open_ro(&filename, self.config, &filename) {
            let meta = dst.file().metadata()?;
            if meta.len() > 0 {
                return Ok(MaybeLock::Ready(dst));
            }
        }

        self.config.shell().status("Unpacking", pkg)?;

        // Verify the checksum and copy over the .crate.
        let mut buf = Vec::new();
        let mut crate_file_source = self.root.open_ro(&filename, self.config, "crate file")?;
        let _ = crate_file_source
            .read_to_end(&mut buf)
            .chain_err(|| format!("failed to read `{}`", crate_file_source.path().display()))?;

        let mut state = Sha256::new();
        state.update(&buf);
        if hex::encode(state.finish()) != checksum {
            failure::bail!("failed to verify the checksum of `{}`", pkg)
        }

        let mut dst = self.cache_path.open_rw(&filename, self.config, &filename)?;
        dst.write_all(&buf)?;
        dst.seek(SeekFrom::Start(0))?;

        Ok(MaybeLock::Ready(dst))
    }

    fn finish_download(
        &mut self,
        _pkg: PackageId,
        _checksum: &str,
        _data: &[u8],
    ) -> CargoResult<FileLock> {
        panic!("this source doesn't download")
    }
}
<|endoftext|>


<commit_before>#[derive(Debug)]
struct Tree {
    enter: Node,
    left: Option<Box<Tree>>,
    right: Option<Box<Tree>>,
}

//for red-black tree
#[derive(Debug)]
enum Color {
    Black,
    Red,
    White,
}

#[derive(Debug)]
struct Node {
    val: i32,
    color: Color,
}

impl Node {
    fn new(v: &i32) -> Node {
        Node {
            val: *v,
            color: Color::White,
        }
    }
}

impl Tree {
    fn new(v: &i32) -> Tree {
        Tree {
            enter: Node::new(v),
            left: None,
            right: None,
        }
    }

    fn insert(&mut self, v: &i32) {
        let target = if *v > self.enter.val {
            &mut self.right
        } else {
            &mut self.left
        };
        //println!("target is -> {:?}", target);
        match target {
            Some(next) => {
                println!("next is -> {:?}", &next);
                next.insert(v)
            }
            None => {
                let new_node = Node::new(v);
                let new_tree = Tree {
                    enter: new_node,
                    left: None,
                    right: None,
                };
                *target = Some(Box::new(new_tree));
            }
        }
    }

    fn look_up(&mut self, v: &i32) -> Result<&mut Self, String> {
        if *v == self.enter.val {
            return Ok(self);
        } else if *v > self.enter.val {
            if let Some(_) = self.right {
                let next = self.right.as_mut().unwrap();
                return next.look_up(v);
            } else {
                Err("not find".to_string())
            }
        } else {
            if let Some(_) = self.left {
                let next = self.right.as_mut().unwrap();
                return next.look_up(v);
            } else {
                Err("not find".to_string())
            }
        }
    }
}

fn main() {
    let mut a = Tree::new(&3);
    a.insert(&2);
    a.insert(&1);

    println!("{:?}", a);
}
<commit_msg>a bit<commit_after>#[derive(Debug)]
struct Tree {
    enter: Node,
    left: Option<Box<Tree>>,
    right: Option<Box<Tree>>,
}

//for red-black tree
#[derive(Debug)]
enum Color {
    Black,
    Red,
    White,
}

#[derive(Debug)]
struct Node {
    val: i32,
    color: Color,
}

impl Node {
    fn new(v: &i32) -> Node {
        Node {
            val: *v,
            color: Color::White,
        }
    }
}

impl Tree {
    fn new(v: &i32) -> Tree {
        Tree {
            enter: Node::new(v),
            left: None,
            right: None,
        }
    }

    fn insert(&mut self, v: &i32) {
        let target = if *v > self.enter.val {
            &mut self.right
        } else {
            &mut self.left
        };
        //println!("target is -> {:?}", target);
        match target {
            Some(next) => {
                println!("next is -> {:?}", &next);
                next.insert(v)
            }
            None => {
                let new_node = Node::new(v);
                let new_tree = Tree {
                    enter: new_node,
                    left: None,
                    right: None,
                };
                *target = Some(Box::new(new_tree));
            }
        }
    }

    fn look_up(&mut self, v: &i32) -> Result<&mut Self, String> {
        if *v == self.enter.val {
            return Ok(self);
        } else if *v > self.enter.val {
            if let Some(_) = self.right {
                let next = self.right.as_mut().unwrap();
                return next.look_up(v);
            } else {
                Err("not find".to_string())
            }
        } else {
            if let Some(_) = self.left {
                let next = self.right.as_mut().unwrap();
                return next.look_up(v);
            } else {
                Err("not find".to_string())
            }
        }
    }

    fn look_up_while(&mut self, v: &i32) -> Result<&mut Self, String> {}
}

fn main() {
    let mut a = Tree::new(&3);
    a.insert(&2);
    a.insert(&1);

    println!("{:?}", a);
}
<|endoftext|>


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

#[allow(unused_imports)] use syntax::ast::TokenTree;
#[allow(unused_imports)] use syntax::codemap::{Span, mk_sp, BytePos};
#[allow(unused_imports)] use syntax::ext::base::ExtCtxt;
#[allow(unused_imports)] use syntax::parse::{token, ParseSess, lexer};
#[allow(unused_imports)] use syntax::ext::build::AstBuilder;
#[allow(unused_imports)] use syntax::ext::quote::rt::{ToTokens, ExtParseUtils};

use std::collections::hashmap::HashMap;

use node;
use std::gc::Gc;

#[allow(dead_code)]
pub struct Parser<'a> {
  pub sess: &'a ParseSess,
  reader: Box<lexer::Reader:>,
  token: token::Token,
  span: Span,

  last_token: Option<Box<token::Token>>,
  last_span: Span,
}

impl<'a> Parser<'a> {
  #[allow(dead_code)]
  pub fn new<'a>(cx: &'a ExtCtxt, tts: &[TokenTree]) -> Parser<'a> {
    let sess = cx.parse_sess();
    let ttsvec = tts.iter().map(|x| (*x).clone()).collect();
    let mut reader = box lexer::new_tt_reader(
        &sess.span_diagnostic, None, ttsvec) as Box<lexer::Reader>;

    let tok0 = reader.next_token();
    let token = tok0.tok;
    let span = tok0.sp;

    Parser {
      sess: sess,
      reader: reader,

      token: token,
      span: span,

      last_token: None,
      last_span: span,
    }
  }

  /// Parse the platform tree from passed in tokens.
  pub fn parse_platformtree(&mut self) -> Option<node::PlatformTree> {
    let mut nodes: Vec<Gc<node::Node>> = Vec::new();
    let mut failed = false;
    loop {
      if self.token == token::EOF {
        break
      }

      let node = match self.parse_node() {
        Some(node) => box(GC) node,
        None => {
          failed = true;
          self.bump();
          continue
        }
      };

      nodes.push(node);
    }

    if failed {
      None
    } else {
      let some_named = self.collect_node_names(&HashMap::new(), &nodes);

      if some_named.is_none() {
        None
      } else {
        Some(node::PlatformTree::new(nodes, some_named.unwrap()))
      }
    }
  }

  fn collect_node_names(&self, map: &HashMap<String, Gc<node::Node>>,
      nodes: &Vec<Gc<node::Node>>) -> Option<HashMap<String, Gc<node::Node>>> {
    let mut local_map: HashMap<String, Gc<node::Node>> = HashMap::new();
    for (k,v) in map.iter() {
      local_map.insert(k.clone(), *v);
    }
    for n in nodes.iter() {
      let collected_sub = self.collect_node_names(&local_map, &n.subnodes);
      if collected_sub.is_none() {
        return None;
      } else {
        for (k,v) in collected_sub.unwrap().iter() {
          local_map.insert(k.clone(), *v);
        }
      }
      match n.name {
        Some(ref name) => {
          if local_map.contains_key(name) {
            self.sess.span_diagnostic.span_err(n.name_span, format!(
                "duplicate `{}` definition", name).as_slice());

            self.sess.span_diagnostic.span_warn(
                local_map.get(name).name_span,
                "previously defined here");
            return None;
          } else {
            local_map.insert(name.clone(), *n);
          }
        },
        None => (),
      }
    }
    Some(local_map)
  }

  fn parse_node(&mut self) -> Option<node::Node> {
    let name_span: Option<Span>;
    let node_name: Option<String>;

    //  we're here
    // /
    // v
    // NAME @ PATH { ... }
    //      ^-- peeking here
    if self.reader.peek().tok == token::AT {
      name_span = Some(self.span);
      node_name = match self.expect_ident() {
        Some(name) => Some(name),
        None => return None,
      };
      if !self.expect(&token::AT) {
        return None;
      }
    } else {
      node_name = None;
      name_span = None;
    }

    let node_span: Span;
    let node_path_span: Span;
    let attributes: HashMap<String, node::Attribute>;
    let subnodes: Vec<Gc<node::Node>>;

    // NAME is resolved, if it was there anyway.
    //    we're here
    //          |
    //          v
    //   NAME @ PATH { ... }
    node_path_span = self.span;
    if node_name == None {
      node_span = self.span;
    } else {
      node_span = mk_sp(name_span.unwrap().lo, self.span.hi);
    }

    let node_path = match self.token {
      token::IDENT(_, _) => {
        token::to_str(&self.bump())
      },
      token::LIT_INT_UNSUFFIXED(u) => {
        self.bump();
        u.to_str()
      }
      ref other => {
        self.error(format!("expected node path but found `{}`",
            token::to_str(other)));
        return None;
      }
    };

    //    we're here
    //             |
    //             v
    // NAME @ PATH { ... }
    // it's either a body, or a semicolon (no body)
    match self.bump() {
      token::LBRACE => {
        let (a, s) = match self.parse_node_body() {
          Some((attrs, subnodes)) => (attrs, subnodes),
          // TODO(farcaller): eat everything up to '}' and continue if failed
          // we can still parse further nodes.
          None => return None,
        };
        attributes = a;
        subnodes = s;

        if !self.expect(&token::RBRACE) {
          return None;
        }
      },
      token::SEMI => {
        attributes = HashMap::new();
        subnodes = Vec::new();
      },
      ref other => {
        self.error(format!("expected `\\{` or `;` but found `{}`",
            token::to_str(other)));
        return None;
      }
    }

    let mut node = node::Node::new(node_name, node_span, node_path, node_path_span);
    node.attributes = attributes;
    node.subnodes = subnodes;
    Some(node)
  }

  fn parse_node_body(&mut self)
      -> Option<(HashMap<String, node::Attribute>, Vec<Gc<node::Node>>)> {
    let mut attrs = HashMap::new();
    let mut subnodes = Vec::new();

    loop {
      // break early if at brace
      if self.token == token::RBRACE {
        break;
      }

      // we're here
      // |
      // v
      // ATTR = VAL ;
      // NAME @ PATH
      // PATH { ... }
      // PATH ;
      //      ^-- peeking here
      if self.reader.peek().tok == token::EQ {
        // we're here
        // |
        // v
        // ATTR = VAL ;
        let name_span = self.span;
        let some_name = match self.expect_ident() {
          Some(name) => name,
          None => return None,
        };

        if attrs.contains_key(&some_name) {
          self.error(format!("key `{}` is already defined", some_name));
          return None;
        }

        self.bump(); // bump token::EQ

        // we're here
        //        |
        //        v
        // ATTR = VAL ;
        let attr_value_span = self.span;
        let attr_value = match self.parse_attribute_value() {
          Some(value) => value,
          None => return None,
        };

        //   we're here
        //            |
        //            v
        // ATTR = VAL ;
        if !self.expect(&token::SEMI) {
          return None;
        }

        attrs.insert(some_name, node::Attribute::new(
            attr_value, name_span, attr_value_span));
      } else {
        // this should be a subnode
        let oldsp = self.span;
        let oldtok = self.token.clone();
        let node = match self.parse_node() {
          Some(node) => node,
          None => {
            self.span = oldsp;
            self.error(format!("expected `=` or node but found `{}`",
                token::to_str(&oldtok)));
            return None;
          },
        };

        subnodes.push(box(GC) node);
      }
    }

    Some((attrs, subnodes))
  }

  fn parse_attribute_value(&mut self) -> Option<node::AttributeValue> {
    match self.token {
      token::LIT_STR(string_val) => {
        self.bump();
        let string = token::get_ident(string_val).get().to_str();
        Some(node::StrValue(string))
      },
      token::LIT_INT_UNSUFFIXED(intval) => {
        self.bump();
        Some(node::UIntValue(intval as uint))
      },
      token::BINOP(token::AND) => {
        self.bump();
        let name = match self.expect_ident() {
          Some(name) => name,
          None => return None,
        };
        Some(node::RefValue(name))
      },
      ref other => {
        self.error(format!("expected string but found `{}`",
            token::to_str(other)));
        None
      }
    }
  }

  fn error(&self, m: String) {
    self.sess.span_diagnostic.span_err(self.span, m.as_slice());
  }

  /// Bumps a token.
  ///
  /// This moves current token to last token, pops a new token from backlog or
  /// reader and returns the last token (i.e. the 'current' token at the time of
  /// method call).
  fn bump(&mut self) -> token::Token {
    let tok = self.token.clone();
    self.last_span = self.span;
    self.last_token = Some(box tok.clone());

    let next = self.reader.next_token();

    self.span = next.sp;
    self.token = next.tok;

    tok
  }

  /// Expects that the current token is t. Bumps on success.
  fn expect(&mut self, t: &token::Token) -> bool {
    if self.token == *t {
      self.bump();
      true
    } else {
      let token_str = token::to_str(t);
      let this_token_str = token::to_str(&self.token);
      self.error(format!("expected `{}` but found `{}`", token_str,
          this_token_str));
      false
    }
  }

  /// Expects that the current token is IDENT, returns its string value. Bumps
  /// on success.
  fn expect_ident(&mut self) -> Option<String> {
    let tok_str = token::to_str(&self.token);
    match self.token {
      token::IDENT(_, _) => {
        self.bump();
        Some(tok_str)
      },
      _ => {
        self.error(format!("expected identifier but found `{}`", tok_str));
        None
      },
    }
  }
}
<commit_msg>Cleaned up imports.<commit_after>// Zinc, the bare metal stack for rust.
// Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::collections::hashmap::HashMap;
use std::gc::Gc;
use syntax::ast::TokenTree;
use syntax::codemap::{Span, mk_sp};
use syntax::ext::base::ExtCtxt;
use syntax::parse::{token, ParseSess, lexer};

use node;

#[allow(dead_code)]
pub struct Parser<'a> {
  pub sess: &'a ParseSess,
  reader: Box<lexer::Reader:>,
  token: token::Token,
  span: Span,

  last_token: Option<Box<token::Token>>,
  last_span: Span,
}

impl<'a> Parser<'a> {
  #[allow(dead_code)]
  pub fn new<'a>(cx: &'a ExtCtxt, tts: &[TokenTree]) -> Parser<'a> {
    let sess = cx.parse_sess();
    let ttsvec = tts.iter().map(|x| (*x).clone()).collect();
    let mut reader = box lexer::new_tt_reader(
        &sess.span_diagnostic, None, ttsvec) as Box<lexer::Reader>;

    let tok0 = reader.next_token();
    let token = tok0.tok;
    let span = tok0.sp;

    Parser {
      sess: sess,
      reader: reader,

      token: token,
      span: span,

      last_token: None,
      last_span: span,
    }
  }

  /// Parse the platform tree from passed in tokens.
  pub fn parse_platformtree(&mut self) -> Option<node::PlatformTree> {
    let mut nodes: Vec<Gc<node::Node>> = Vec::new();
    let mut failed = false;
    loop {
      if self.token == token::EOF {
        break
      }

      let node = match self.parse_node() {
        Some(node) => box(GC) node,
        None => {
          failed = true;
          self.bump();
          continue
        }
      };

      nodes.push(node);
    }

    if failed {
      None
    } else {
      let some_named = self.collect_node_names(&HashMap::new(), &nodes);

      if some_named.is_none() {
        None
      } else {
        Some(node::PlatformTree::new(nodes, some_named.unwrap()))
      }
    }
  }

  fn collect_node_names(&self, map: &HashMap<String, Gc<node::Node>>,
      nodes: &Vec<Gc<node::Node>>) -> Option<HashMap<String, Gc<node::Node>>> {
    let mut local_map: HashMap<String, Gc<node::Node>> = HashMap::new();
    for (k,v) in map.iter() {
      local_map.insert(k.clone(), *v);
    }
    for n in nodes.iter() {
      let collected_sub = self.collect_node_names(&local_map, &n.subnodes);
      if collected_sub.is_none() {
        return None;
      } else {
        for (k,v) in collected_sub.unwrap().iter() {
          local_map.insert(k.clone(), *v);
        }
      }
      match n.name {
        Some(ref name) => {
          if local_map.contains_key(name) {
            self.sess.span_diagnostic.span_err(n.name_span, format!(
                "duplicate `{}` definition", name).as_slice());

            self.sess.span_diagnostic.span_warn(
                local_map.get(name).name_span,
                "previously defined here");
            return None;
          } else {
            local_map.insert(name.clone(), *n);
          }
        },
        None => (),
      }
    }
    Some(local_map)
  }

  fn parse_node(&mut self) -> Option<node::Node> {
    let name_span: Option<Span>;
    let node_name: Option<String>;

    //  we're here
    // /
    // v
    // NAME @ PATH { ... }
    //      ^-- peeking here
    if self.reader.peek().tok == token::AT {
      name_span = Some(self.span);
      node_name = match self.expect_ident() {
        Some(name) => Some(name),
        None => return None,
      };
      if !self.expect(&token::AT) {
        return None;
      }
    } else {
      node_name = None;
      name_span = None;
    }

    let node_span: Span;
    let node_path_span: Span;
    let attributes: HashMap<String, node::Attribute>;
    let subnodes: Vec<Gc<node::Node>>;

    // NAME is resolved, if it was there anyway.
    //    we're here
    //          |
    //          v
    //   NAME @ PATH { ... }
    node_path_span = self.span;
    if node_name == None {
      node_span = self.span;
    } else {
      node_span = mk_sp(name_span.unwrap().lo, self.span.hi);
    }

    let node_path = match self.token {
      token::IDENT(_, _) => {
        token::to_str(&self.bump())
      },
      token::LIT_INT_UNSUFFIXED(u) => {
        self.bump();
        u.to_str()
      }
      ref other => {
        self.error(format!("expected node path but found `{}`",
            token::to_str(other)));
        return None;
      }
    };

    //    we're here
    //             |
    //             v
    // NAME @ PATH { ... }
    // it's either a body, or a semicolon (no body)
    match self.bump() {
      token::LBRACE => {
        let (a, s) = match self.parse_node_body() {
          Some((attrs, subnodes)) => (attrs, subnodes),
          // TODO(farcaller): eat everything up to '}' and continue if failed
          // we can still parse further nodes.
          None => return None,
        };
        attributes = a;
        subnodes = s;

        if !self.expect(&token::RBRACE) {
          return None;
        }
      },
      token::SEMI => {
        attributes = HashMap::new();
        subnodes = Vec::new();
      },
      ref other => {
        self.error(format!("expected `\\{` or `;` but found `{}`",
            token::to_str(other)));
        return None;
      }
    }

    let mut node = node::Node::new(node_name, node_span, node_path, node_path_span);
    node.attributes = attributes;
    node.subnodes = subnodes;
    Some(node)
  }

  fn parse_node_body(&mut self)
      -> Option<(HashMap<String, node::Attribute>, Vec<Gc<node::Node>>)> {
    let mut attrs = HashMap::new();
    let mut subnodes = Vec::new();

    loop {
      // break early if at brace
      if self.token == token::RBRACE {
        break;
      }

      // we're here
      // |
      // v
      // ATTR = VAL ;
      // NAME @ PATH
      // PATH { ... }
      // PATH ;
      //      ^-- peeking here
      if self.reader.peek().tok == token::EQ {
        // we're here
        // |
        // v
        // ATTR = VAL ;
        let name_span = self.span;
        let some_name = match self.expect_ident() {
          Some(name) => name,
          None => return None,
        };

        if attrs.contains_key(&some_name) {
          self.error(format!("key `{}` is already defined", some_name));
          return None;
        }

        self.bump(); // bump token::EQ

        // we're here
        //        |
        //        v
        // ATTR = VAL ;
        let attr_value_span = self.span;
        let attr_value = match self.parse_attribute_value() {
          Some(value) => value,
          None => return None,
        };

        //   we're here
        //            |
        //            v
        // ATTR = VAL ;
        if !self.expect(&token::SEMI) {
          return None;
        }

        attrs.insert(some_name, node::Attribute::new(
            attr_value, name_span, attr_value_span));
      } else {
        // this should be a subnode
        let oldsp = self.span;
        let oldtok = self.token.clone();
        let node = match self.parse_node() {
          Some(node) => node,
          None => {
            self.span = oldsp;
            self.error(format!("expected `=` or node but found `{}`",
                token::to_str(&oldtok)));
            return None;
          },
        };

        subnodes.push(box(GC) node);
      }
    }

    Some((attrs, subnodes))
  }

  fn parse_attribute_value(&mut self) -> Option<node::AttributeValue> {
    match self.token {
      token::LIT_STR(string_val) => {
        self.bump();
        let string = token::get_ident(string_val).get().to_str();
        Some(node::StrValue(string))
      },
      token::LIT_INT_UNSUFFIXED(intval) => {
        self.bump();
        Some(node::UIntValue(intval as uint))
      },
      token::BINOP(token::AND) => {
        self.bump();
        let name = match self.expect_ident() {
          Some(name) => name,
          None => return None,
        };
        Some(node::RefValue(name))
      },
      ref other => {
        self.error(format!("expected string but found `{}`",
            token::to_str(other)));
        None
      }
    }
  }

  fn error(&self, m: String) {
    self.sess.span_diagnostic.span_err(self.span, m.as_slice());
  }

  /// Bumps a token.
  ///
  /// This moves current token to last token, pops a new token from backlog or
  /// reader and returns the last token (i.e. the 'current' token at the time of
  /// method call).
  fn bump(&mut self) -> token::Token {
    let tok = self.token.clone();
    self.last_span = self.span;
    self.last_token = Some(box tok.clone());

    let next = self.reader.next_token();

    self.span = next.sp;
    self.token = next.tok;

    tok
  }

  /// Expects that the current token is t. Bumps on success.
  fn expect(&mut self, t: &token::Token) -> bool {
    if self.token == *t {
      self.bump();
      true
    } else {
      let token_str = token::to_str(t);
      let this_token_str = token::to_str(&self.token);
      self.error(format!("expected `{}` but found `{}`", token_str,
          this_token_str));
      false
    }
  }

  /// Expects that the current token is IDENT, returns its string value. Bumps
  /// on success.
  fn expect_ident(&mut self) -> Option<String> {
    let tok_str = token::to_str(&self.token);
    match self.token {
      token::IDENT(_, _) => {
        self.bump();
        Some(tok_str)
      },
      _ => {
        self.error(format!("expected identifier but found `{}`", tok_str));
        None
      },
    }
  }
}
<|endoftext|>