<commit_before>#![allow(dead_code)]

// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]

#[macro_use] extern crate error_chain;
#[macro_use] extern crate glium;
extern crate rand;

#[cfg(test)]
#[macro_use]
mod test_utils;

mod drawer;
mod errors;
mod graph;
mod map;
mod math;
mod mouse;
mod square;
mod state;
mod timer;
mod visible_graph;

use drawer::Drawer;
use graph::Graph;
use map::{Map, Player};
use math::{apply, compose};
use mouse::Mouse;
use square::SquareGrid;
use state::{MAX_GOOP, Occupied, State};
use visible_graph::GraphPt;

use glium::glutin::{Event, ElementState, MouseButton, VirtualKeyCode};
use glium::Surface;

use std::rc::Rc;
use std::time::Instant;

// This only gives access within this module. Make this `pub use errors::*;`
// instead if the types must be accessible from other modules (e.g., within
// a `links` section).
use errors::*;

fn main() {
    if let Err(ref e) = run() {
        use ::std::io::Write;
        let stderr = &mut ::std::io::stderr();
        let errmsg = "Error writing to stderr";

        writeln!(stderr, "error: {}", e).expect(errmsg);

        for e in e.iter().skip(1) {
            writeln!(stderr, "caused by: {}", e).expect(errmsg);
        }

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

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

fn run() -> Result<()> {
    use glium::DisplayBuild;

    let display = glium::glutin::WindowBuilder::new()
        .with_title("rbattle".to_string())
        .build_glium()
        .chain_err(|| "unable to open window")?;

    let graph = SquareGrid::new(15, 15);
    let sources = vec![16, 45];
    let colors = vec![(0x9f, 0x20, 0xb1), (0xb1, 0x20, 0x44),
                      (0x20, 0xb1, 0x21), (0x20, 0x67, 0xb1),
                      (0xe0, 0x6f, 0x3a)];
    let map = Rc::new(Map::new(graph, sources, colors));
    let drawer = Drawer::new(&display, &map)
        .chain_err(|| "failed to construct Drawer for map")?;

    let mut state = State::new(map.clone());

    state.nodes[45] = Some(Occupied {
        player: Player(2),
        outflows: map.graph.neighbors(45),
        goop: MAX_GOOP
    });

    state.nodes[30] = Some(Occupied {
        player: Player(2),
        outflows: vec![15],
        goop: 0
    });

    state.nodes[16] = Some(Occupied {
        player: Player(0),
        outflows: map.graph.neighbors(16),
        goop: MAX_GOOP
    });

    state.nodes[17] = Some(Occupied {
        player: Player(1),
        outflows: vec![],
        goop: 2
    });

    let mut mouse = Mouse::new(map.clone());

    let mut turn = 0;
    let start = Instant::now();

    // True if we should run a game step on every frame.
    let mut free_running = false;

    loop {
        // It seems like glium always makes a frame take a full 16ms, regardless
        // of how much work we ask it to do, but I don't see anything in the
        // documentation about this. We're leaning on that for now to keep
        // timing consistent, but we'll need to add something to control timing
        // explicitly to avoid depending on this behavior.
        let mut frame = display.draw();
        frame.clear_color(1.0, 1.0, 1.0, 1.0);
        let status = drawer.draw(&mut frame, &state, &mouse);
        frame.finish()
            .chain_err(|| "drawing finish failed")?;

        let window_to_game = status?;
        let window_to_graph = compose(map.game_to_graph, window_to_game);

        let mut single_step = false;
        for event in display.poll_events() {
            match event {
                Event::Closed => return Ok(()),
                Event::KeyboardInput(ElementState::Pressed, _,
                                     Some(VirtualKeyCode::Space)) => {
                    free_running = false;
                    single_step = true;
                }
                Event::KeyboardInput(ElementState::Pressed, _,
                                     Some(VirtualKeyCode::Return)) => {
                    free_running = true;
                }
                Event::MouseMoved(x, y) => {
                    let graph_pos = apply(window_to_graph, [x as f32, y as f32]);
                    mouse.move_to(GraphPt(graph_pos));
                }
                Event::MouseInput(ElementState::Pressed, MouseButton::Left) => {
                    mouse.click();
                }
                Event::MouseInput(ElementState::Released, MouseButton::Left) => {
                    if let Some(action) = mouse.release() {
                        state.take_action(action);
                    }
                }
                _ => ()
            }
        }

        if free_running || single_step {
            println!("Turn {} at {:9.3}s:", turn, elapsed_since(&start));

            let start_generation = Instant::now();
            state.advance();
            println!("    advance to next state: {:9.6}s:", elapsed_since(&start_generation));
            turn += 1;
        }
    }
}

/// Return the number of seconds that have elasped since `instant`. Partial
/// seconds are returned as fractional values.
fn elapsed_since(instant: &Instant) -> f64 {
    let elapsed = instant.elapsed();
    elapsed.as_secs() as f64 +
        (elapsed.subsec_nanos() as f64 / 1e9)
}
<commit_msg>Ditch prematurely committed `use timer`.<commit_after>#![allow(dead_code)]

// `error_chain!` can recurse deeply
#![recursion_limit = "1024"]

#[macro_use] extern crate error_chain;
#[macro_use] extern crate glium;
extern crate rand;

#[cfg(test)]
#[macro_use]
mod test_utils;

mod drawer;
mod errors;
mod graph;
mod map;
mod math;
mod mouse;
mod square;
mod state;
mod visible_graph;

use drawer::Drawer;
use graph::Graph;
use map::{Map, Player};
use math::{apply, compose};
use mouse::Mouse;
use square::SquareGrid;
use state::{MAX_GOOP, Occupied, State};
use visible_graph::GraphPt;

use glium::glutin::{Event, ElementState, MouseButton, VirtualKeyCode};
use glium::Surface;

use std::rc::Rc;
use std::time::Instant;

// This only gives access within this module. Make this `pub use errors::*;`
// instead if the types must be accessible from other modules (e.g., within
// a `links` section).
use errors::*;

fn main() {
    if let Err(ref e) = run() {
        use ::std::io::Write;
        let stderr = &mut ::std::io::stderr();
        let errmsg = "Error writing to stderr";

        writeln!(stderr, "error: {}", e).expect(errmsg);

        for e in e.iter().skip(1) {
            writeln!(stderr, "caused by: {}", e).expect(errmsg);
        }

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

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

fn run() -> Result<()> {
    use glium::DisplayBuild;

    let display = glium::glutin::WindowBuilder::new()
        .with_title("rbattle".to_string())
        .build_glium()
        .chain_err(|| "unable to open window")?;

    let graph = SquareGrid::new(15, 15);
    let sources = vec![16, 45];
    let colors = vec![(0x9f, 0x20, 0xb1), (0xb1, 0x20, 0x44),
                      (0x20, 0xb1, 0x21), (0x20, 0x67, 0xb1),
                      (0xe0, 0x6f, 0x3a)];
    let map = Rc::new(Map::new(graph, sources, colors));
    let drawer = Drawer::new(&display, &map)
        .chain_err(|| "failed to construct Drawer for map")?;

    let mut state = State::new(map.clone());

    state.nodes[45] = Some(Occupied {
        player: Player(2),
        outflows: map.graph.neighbors(45),
        goop: MAX_GOOP
    });

    state.nodes[30] = Some(Occupied {
        player: Player(2),
        outflows: vec![15],
        goop: 0
    });

    state.nodes[16] = Some(Occupied {
        player: Player(0),
        outflows: map.graph.neighbors(16),
        goop: MAX_GOOP
    });

    state.nodes[17] = Some(Occupied {
        player: Player(1),
        outflows: vec![],
        goop: 2
    });

    let mut mouse = Mouse::new(map.clone());

    let mut turn = 0;
    let start = Instant::now();

    // True if we should run a game step on every frame.
    let mut free_running = false;

    loop {
        // It seems like glium always makes a frame take a full 16ms, regardless
        // of how much work we ask it to do, but I don't see anything in the
        // documentation about this. We're leaning on that for now to keep
        // timing consistent, but we'll need to add something to control timing
        // explicitly to avoid depending on this behavior.
        let mut frame = display.draw();
        frame.clear_color(1.0, 1.0, 1.0, 1.0);
        let status = drawer.draw(&mut frame, &state, &mouse);
        frame.finish()
            .chain_err(|| "drawing finish failed")?;

        let window_to_game = status?;
        let window_to_graph = compose(map.game_to_graph, window_to_game);

        let mut single_step = false;
        for event in display.poll_events() {
            match event {
                Event::Closed => return Ok(()),
                Event::KeyboardInput(ElementState::Pressed, _,
                                     Some(VirtualKeyCode::Space)) => {
                    free_running = false;
                    single_step = true;
                }
                Event::KeyboardInput(ElementState::Pressed, _,
                                     Some(VirtualKeyCode::Return)) => {
                    free_running = true;
                }
                Event::MouseMoved(x, y) => {
                    let graph_pos = apply(window_to_graph, [x as f32, y as f32]);
                    mouse.move_to(GraphPt(graph_pos));
                }
                Event::MouseInput(ElementState::Pressed, MouseButton::Left) => {
                    mouse.click();
                }
                Event::MouseInput(ElementState::Released, MouseButton::Left) => {
                    if let Some(action) = mouse.release() {
                        state.take_action(action);
                    }
                }
                _ => ()
            }
        }

        if free_running || single_step {
            println!("Turn {} at {:9.3}s:", turn, elapsed_since(&start));

            let start_generation = Instant::now();
            state.advance();
            println!("    advance to next state: {:9.6}s:", elapsed_since(&start_generation));
            turn += 1;
        }
    }
}

/// Return the number of seconds that have elasped since `instant`. Partial
/// seconds are returned as fractional values.
fn elapsed_since(instant: &Instant) -> f64 {
    let elapsed = instant.elapsed();
    elapsed.as_secs() as f64 +
        (elapsed.subsec_nanos() as f64 / 1e9)
}
<|endoftext|>


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

#[derive(Debug)]
struct SearchTree<'a, T: 'a> {
    left: Option<Box<&'a SearchTree<'a,T>>>,
    right: Option<Box<&'a SearchTree<'a,T>>>,
    key: T,
}
fn do_nothing() {

}
impl<'a, T> SearchTree<'a, T> where T: std::fmt::Debug + std::cmp::Eq + std::cmp::PartialOrd {
    fn inorder_tree(&self) {
        match self.left {
            Some(ref tree) => tree.inorder_tree(),
            None => do_nothing(),
        }
        println!("self.key = {:#?}", self.key);
        match self.right {
            Some(ref tree) => tree.inorder_tree(),
            None => do_nothing(),
        }
    }

    fn search_tree(&'a self, key: T ) -> Option<&'a SearchTree<'a, T>> {
        if self.key == key {
            return Some(&self);
        }

        if key < self.key {
            match self.left {
                Some(ref tree) => tree.search_tree(key),
                None => None
            }
        } else {
            match self.right {
                Some(ref tree) => tree.search_tree(key),
                None => None
            }
        }
    }
    fn minimum_tree(&'a self) -> &'a SearchTree<'a, T> {
        match self.left {
            Some(ref tree) => tree.minimum_tree(),
            None => &self
        }
    }
}

fn main() {
    let left = SearchTree {
        left: None,
        right: None,
        key: 32,
    };

    let right = SearchTree {
        left: None,
        right: None,
        key: 43,
    };

    let root = SearchTree {
        left: Some(Box::new(&left)),
        right: Some(Box::new(&right)),
        key: 40,
    };

    root.inorder_tree();
    left.inorder_tree();

    let tree = root.search_tree(43);
    match tree {
        Some(t) => println!("t.key = {:#?}", t.key),
        None => println!(" None "),

    }

    let x = create_box_value();
    println!("x = {:#?}", x);

    let y = root.minimum_tree();
    println!("minimum = {:#?}", y);

}

fn create_box_value<'a>() -> Box<i32> {
    Box::new(32)
}
<commit_msg>add insert<commit_after>use std::boxed::Box;

#[derive(Debug)]
struct SearchTree<'a, T: 'a> {
    left: Option<Box<&'a mut SearchTree<'a,T>>>,
    right: Option<Box<&'a mut SearchTree<'a,T>>>,
    key: T,
}

impl<'a, T> SearchTree<'a, T> where T: std::fmt::Debug + std::cmp::Eq + std::cmp::PartialOrd {
    fn inorder_tree(&self) {
        if let Some(ref tree) = self.left {
            tree.inorder_tree();
        }
        println!("self.key = {:#?}", self.key);
        if let Some(ref tree) = self.right {
            tree.inorder_tree();
        }
    }

    fn search_tree(&'a self, key: T ) -> Option<&'a SearchTree<'a, T>> {
        if self.key == key {
            return Some(&self);
        }

        if key < self.key {
            match self.left {
                Some(ref tree) => tree.search_tree(key),
                None => None
            }
        } else {
            match self.right {
                Some(ref tree) => tree.search_tree(key),
                None => None
            }
        }
    }
    fn minimum_tree(&'a self) -> &'a SearchTree<'a, T> {
        match self.left {
            Some(ref tree) => tree.minimum_tree(),
            None => &self
        }
    }

    fn maximum_tree(&'a self) -> &'a SearchTree<'a, T> {
        match self.right {
            Some(ref tree) => tree.maximum_tree(),
            None => &self
        }
    }

    fn insert_tree(&'a mut self, tree:&'a SearchTree<'a, T>) {

        if self.key <= tree.key {
            if let Some(ref mut left) = self.left {
                left.insert_tree(tree);
            } else {
                self.left = Some(Box::new(tree));
            }
        } else {
            if let Some(ref mut right) = self.right {
                right.insert_tree(tree);
            } else {
                self.right = Some(Box::new(tree));
            }
        }
    }

}

fn main() {
    let left = SearchTree {
        left: None,
        right: None,
        key: 32,
    };

    let right = SearchTree {
        left: None,
        right: None,
        key: 43,
    };

    let mut root = SearchTree {
        left: Some(Box::new(&left)),
        right: Some(Box::new(&right)),
        key: 40,
    };

    root.inorder_tree();

    let tree = root.search_tree(43);
    match tree {
        Some(t) => println!("t.key = {:#?}", t.key),
        None => println!(" None "),

    }

    let min = root.minimum_tree();
    println!("min = {:#?}", min);

    let max = root.maximum_tree();
    println!("max = {:#?}", max);

    let will_insert_tree = SearchTree {
        left: None,
        right: None,
        key: 41,
    };

    root.insert_tree(&will_insert_tree);

    println!("root = {:#?}", root);

}

<|endoftext|>


<commit_before>#![feature(custom_derive)]
#![feature(plugin)]
#![plugin(rocket_codegen)]

extern crate rocket;

use std::fmt;

use rocket::http::Status;
use rocket::request::{self, Request, FromRequest};
use rocket::response::content;
use rocket::{Outcome, Response};

struct IndexData(String);

impl<'a, 'r> FromRequest<'a, 'r> for IndexData {
    type Error = ();
    fn from_request(request: &'a Request<'r>) -> request::Outcome<IndexData, ()> {
        Outcome::Success(IndexData(format!("{}", request)))
    }
}

impl fmt::Display for IndexData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[get("/")]
fn index() -> content::HTML<&'static str> {
    content::HTML("<!DOCTYPE html>

            <title>HTTPTIN</title>

HTTPTIN - HTTP tester in Rust and Rocket

    ")
}

#[get("/test")]
fn test(data: IndexData) -> String {
    format!("<!DOCTYPE html><title>HTTPTIN></title>{}", data)
}

#[get("/ip")]
fn origin() -> String {
    String::from("Remote address decoding is not implemented yet")
}

#[derive(Serialize)]
struct GetData {
    args: String,
    headers: String,
}

#[get("/get")]
fn get() -> content::JSON<&'static str> {
    content::JSON("{agrs: {}}")
}

#[get("/status/")]
pub fn status<'r>(code: u16) -> Response<'r> {
    Response::build().status(Status::raw(code)).finalize()
}

fn main() {
    rocket::ignite().mount("/", routes![index, origin, get, status, test]).launch();
}
<commit_msg>Checkpoint<commit_after>#![feature(custom_derive)]
#![feature(plugin)]
#![plugin(rocket_codegen)]

extern crate rocket;

use std::fmt;

use rocket::http::Status;
use rocket::request::{self, Request, FromRequest};
use rocket::response::content;
use rocket::{Outcome, Response};

struct IndexData(String);

impl<'a, 'r> FromRequest<'a, 'r> for IndexData {
    type Error = ();
    fn from_request(request: &'a Request<'r>) -> request::Outcome<IndexData, ()> {
        Outcome::Success(IndexData(format!("{}", request)))
    }
}

impl fmt::Display for IndexData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[get("/")]
fn index() -> content::HTML<&'static str> {
    content::HTML("<!DOCTYPE html>

            <title>HTTPTIN</title>

HTTPTIN - HTTP tester in Rust and Rocket

    ")
}

#[get("/test")]
fn test(data: IndexData) -> content::HTML<String> {
    content::HTML(format!("<!DOCTYPE html>

            <title>HTTPTIN></title>

        {}
    ",
                          data))
}

#[get("/ip")]
fn origin() -> String {
    String::from("Remote address decoding is not implemented yet")
}

#[derive(Serialize)]
struct GetData {
    args: String,
    headers: String,
}

#[get("/get")]
fn get() -> content::JSON<&'static str> {
    content::JSON("{agrs: {}}")
}

#[get("/status/")]
pub fn status<'r>(code: u16) -> Response<'r> {
    Response::build().status(Status::raw(code)).finalize()
}

fn main() {
    rocket::ignite().mount("/", routes![index, origin, get, status, test]).launch();
}
<|endoftext|>


<commit_before>// Copyright 2016 rust-fuzz developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use anyhow::Result;
use structopt::StructOpt;

#[macro_use]
mod templates;
mod options;
mod project;
mod utils;

static FUZZ_TARGETS_DIR_OLD: &'static str = "fuzzers";
static FUZZ_TARGETS_DIR: &'static str = "fuzz_targets";

// It turns out that `clap`'s `long_about()` makes `cargo fuzz --help`
// unreadable, and its `before_help()` injects our long about text before the
// version, so change the default template slightly.
const LONG_ABOUT_TEMPLATE: &'static str = "\
{bin} {version}
{about}

USAGE:
    {usage}

{before-help}

{all-args}

{after-help}";

const RUN_BEFORE_HELP: &'static str = "\
The fuzz target name is the same as the name of the fuzz target script in
fuzz/fuzz_targets/, i.e. the name picked when running `cargo fuzz add`.

This will run the script inside the fuzz target with varying inputs until it
finds a crash, at which point it will save the crash input to the artifact
directory, print some output, and exit. Unless you configure it otherwise (see
libFuzzer options below), this will run indefinitely.";

const RUN_AFTER_HELP: &'static str = "\

A full list of libFuzzer options can be found at
http://llvm.org/docs/LibFuzzer.html#options

You can also get this by running `cargo fuzz run fuzz_target -- -help=1`

Some useful options (to be used as `cargo fuzz run fuzz_target -- <options>`)
include:

  * `-max_len=<len>`: Will limit the length of the input string to `<len>`

  * `-runs=<number>`: Will limit the number of tries (runs) before it gives up

  * `-max_total_time=<time>`: Will limit the amount of time to fuzz before it
    gives up

  * `-timeout=<time>`: Will limit the amount of time for a single run before it
    considers that run a failure

  * `-only_ascii`: Only provide ASCII input

  * `-dict=<file>`: Use a keyword dictionary from specified file. See
    http://llvm.org/docs/LibFuzzer.html#dictionaries\
";

/// A trait for running our various commands.
trait RunCommand {
    /// Run this command!
    fn run_command(&mut self) -> Result<()>;
}

#[derive(Clone, Debug, StructOpt)]
#[structopt(
    setting(structopt::clap::AppSettings::SubcommandRequiredElseHelp),
    setting(structopt::clap::AppSettings::GlobalVersion),
    version(option_env!("CARGO_PKG_VERSION").unwrap_or("0.0.0")),
    about(option_env!("CARGO_PKG_DESCRIPTION").unwrap_or("")),
    // Cargo passes in the subcommand name to the invoked executable. Use a
    // hidden, optional positional argument to deal with it.
    arg(structopt::clap::Arg::with_name("dummy")
        .possible_value("fuzz")
        .required(false)
        .hidden(true)),
)]
enum Command {
    /// Initialize the fuzz directory
    Init(options::Init),

    /// Add a new fuzz target
    Add(options::Add),

    /// Build fuzz targets
    Build(options::Build),

    /// Print debugging output for fuzz inputs
    Fmt(options::Fmt),

    /// List all the existing fuzz targets
    List(options::List),

    #[structopt(
        template(LONG_ABOUT_TEMPLATE),
        before_help(RUN_BEFORE_HELP),
        after_help(RUN_AFTER_HELP)
    )]
    /// Run a fuzz target
    Run(options::Run),

    /// Minify a corpus
    Cmin(options::Cmin),

    /// Minify a test case
    Tmin(options::Tmin),
}

impl RunCommand for Command {
    fn run_command(&mut self) -> Result<()> {
        match self {
            Command::Init(x) => x.run_command(),
            Command::Add(x) => x.run_command(),
            Command::Build(x) => x.run_command(),
            Command::List(x) => x.run_command(),
            Command::Fmt(x) => x.run_command(),
            Command::Run(x) => x.run_command(),
            Command::Cmin(x) => x.run_command(),
            Command::Tmin(x) => x.run_command(),
        }
    }
}

fn main() -> Result<()> {
    Command::from_args().run_command()
}
<commit_msg>Wordsmith the short help text for `cargo fuzz fmt` a little<commit_after>// Copyright 2016 rust-fuzz developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use anyhow::Result;
use structopt::StructOpt;

#[macro_use]
mod templates;
mod options;
mod project;
mod utils;

static FUZZ_TARGETS_DIR_OLD: &'static str = "fuzzers";
static FUZZ_TARGETS_DIR: &'static str = "fuzz_targets";

// It turns out that `clap`'s `long_about()` makes `cargo fuzz --help`
// unreadable, and its `before_help()` injects our long about text before the
// version, so change the default template slightly.
const LONG_ABOUT_TEMPLATE: &'static str = "\
{bin} {version}
{about}

USAGE:
    {usage}

{before-help}

{all-args}

{after-help}";

const RUN_BEFORE_HELP: &'static str = "\
The fuzz target name is the same as the name of the fuzz target script in
fuzz/fuzz_targets/, i.e. the name picked when running `cargo fuzz add`.

This will run the script inside the fuzz target with varying inputs until it
finds a crash, at which point it will save the crash input to the artifact
directory, print some output, and exit. Unless you configure it otherwise (see
libFuzzer options below), this will run indefinitely.";

const RUN_AFTER_HELP: &'static str = "\

A full list of libFuzzer options can be found at
http://llvm.org/docs/LibFuzzer.html#options

You can also get this by running `cargo fuzz run fuzz_target -- -help=1`

Some useful options (to be used as `cargo fuzz run fuzz_target -- <options>`)
include:

  * `-max_len=<len>`: Will limit the length of the input string to `<len>`

  * `-runs=<number>`: Will limit the number of tries (runs) before it gives up

  * `-max_total_time=<time>`: Will limit the amount of time to fuzz before it
    gives up

  * `-timeout=<time>`: Will limit the amount of time for a single run before it
    considers that run a failure

  * `-only_ascii`: Only provide ASCII input

  * `-dict=<file>`: Use a keyword dictionary from specified file. See
    http://llvm.org/docs/LibFuzzer.html#dictionaries\
";

/// A trait for running our various commands.
trait RunCommand {
    /// Run this command!
    fn run_command(&mut self) -> Result<()>;
}

#[derive(Clone, Debug, StructOpt)]
#[structopt(
    setting(structopt::clap::AppSettings::SubcommandRequiredElseHelp),
    setting(structopt::clap::AppSettings::GlobalVersion),
    version(option_env!("CARGO_PKG_VERSION").unwrap_or("0.0.0")),
    about(option_env!("CARGO_PKG_DESCRIPTION").unwrap_or("")),
    // Cargo passes in the subcommand name to the invoked executable. Use a
    // hidden, optional positional argument to deal with it.
    arg(structopt::clap::Arg::with_name("dummy")
        .possible_value("fuzz")
        .required(false)
        .hidden(true)),
)]
enum Command {
    /// Initialize the fuzz directory
    Init(options::Init),

    /// Add a new fuzz target
    Add(options::Add),

    /// Build fuzz targets
    Build(options::Build),

    /// Print the `std::fmt::Debug` output for an input
    Fmt(options::Fmt),

    /// List all the existing fuzz targets
    List(options::List),

    #[structopt(
        template(LONG_ABOUT_TEMPLATE),
        before_help(RUN_BEFORE_HELP),
        after_help(RUN_AFTER_HELP)
    )]
    /// Run a fuzz target
    Run(options::Run),

    /// Minify a corpus
    Cmin(options::Cmin),

    /// Minify a test case
    Tmin(options::Tmin),
}

impl RunCommand for Command {
    fn run_command(&mut self) -> Result<()> {
        match self {
            Command::Init(x) => x.run_command(),
            Command::Add(x) => x.run_command(),
            Command::Build(x) => x.run_command(),
            Command::List(x) => x.run_command(),
            Command::Fmt(x) => x.run_command(),
            Command::Run(x) => x.run_command(),
            Command::Cmin(x) => x.run_command(),
            Command::Tmin(x) => x.run_command(),
        }
    }
}

fn main() -> Result<()> {
    Command::from_args().run_command()
}
<|endoftext|>


<commit_before>#![feature(slice_patterns)]

extern crate getopts;

use std::fs;
use std::io;
use std::io::{Read, Write};

use getopts::Options;

mod optimizer;
mod parser;
mod runner;
mod structs;

use parser::parse;
use runner::State;
use structs::OpStream;

fn main() {
    let mut opts = Options::new();
    opts.optflag("n", "dry-run", "don't actually run");
    opts.optflag("0", "no-optimize", "don't optimize");
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(std::env::args().skip(1)) {
        Ok(m) => m,
        Err(f) => {
            writeln!(&mut io::stderr(), "{}", f).unwrap();
            std::process::exit(2);
        }
    };
    if matches.opt_present("h") {
        write!(&mut io::stderr(), "{}", opts.usage("Usage: brain_rust [options] FILE... ")).unwrap();
        return;
    }

    let dry_run = matches.opt_present("n");
    let no_optimize = matches.opt_present("0");

    for filename in &matches.free[..] {
        let buffer = match read_file(filename) {
            Ok(v) => v,
            Err(e) => {
                writeln!(&mut io::stderr(), "Error while reading {}: {}", filename, e).unwrap();
                continue;
            }
        };
        let ops = match parse(&buffer[..]) {
            Ok(v) => v,
            Err(e) => {
                writeln!(&mut io::stderr(), "Error while parsing {}: {}", filename, e).unwrap();
                continue;
            }
        };
        let mut opstream = OpStream { ops: ops };
        if !no_optimize {
            opstream.optimize();
        }
        if !dry_run {
            State::new(&mut io::stdin(), &mut io::stdout()).run(opstream.get());
        }
    }
}

fn read_file(filename: &str) -> Result<Vec<u8>, io::Error> {
    let mut buffer = Vec::new();
    fs::File::open(filename)
        .map(|file| io::BufReader::new(file))
        .and_then(|mut reader| reader.read_to_end(&mut buffer))
        .map(|_| buffer)
}
<commit_msg>refactor: remove useless BufReader<commit_after>#![feature(slice_patterns)]

extern crate getopts;

use std::fs;
use std::io;
use std::io::{Read, Write};

use getopts::Options;

mod optimizer;
mod parser;
mod runner;
mod structs;

use parser::parse;
use runner::State;
use structs::OpStream;

fn main() {
    let mut opts = Options::new();
    opts.optflag("n", "dry-run", "don't actually run");
    opts.optflag("0", "no-optimize", "don't optimize");
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(std::env::args().skip(1)) {
        Ok(m) => m,
        Err(f) => {
            writeln!(&mut io::stderr(), "{}", f).unwrap();
            std::process::exit(2);
        }
    };
    if matches.opt_present("h") {
        write!(&mut io::stderr(), "{}", opts.usage("Usage: brain_rust [options] FILE... ")).unwrap();
        return;
    }

    let dry_run = matches.opt_present("n");
    let no_optimize = matches.opt_present("0");

    for filename in &matches.free[..] {
        let buffer = match read_file(filename) {
            Ok(v) => v,
            Err(e) => {
                writeln!(&mut io::stderr(), "Error while reading {}: {}", filename, e).unwrap();
                continue;
            }
        };
        let ops = match parse(&buffer[..]) {
            Ok(v) => v,
            Err(e) => {
                writeln!(&mut io::stderr(), "Error while parsing {}: {}", filename, e).unwrap();
                continue;
            }
        };
        let mut opstream = OpStream { ops: ops };
        if !no_optimize {
            opstream.optimize();
        }
        if !dry_run {
            State::new(&mut io::stdin(), &mut io::stdout()).run(opstream.get());
        }
    }
}

fn read_file(filename: &str) -> Result<Vec<u8>, io::Error> {
    let mut buffer = Vec::new();
    fs::File::open(filename)
        .map(|mut file| file.read_to_end(&mut buffer))
        .map(|_| buffer)
}
<|endoftext|>


<commit_before>#![cfg_attr(feature = "deny-warnings", deny(warnings))]

use rustc_tools_util::VersionInfo;

const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.

Usage:
    cargo clippy [options] [--] [<opts>...]

Common options:
    -h, --help               Print this message
    -V, --version            Print version info and exit

Other options are the same as `cargo check`.

To allow or deny a lint from the command line you can use `cargo clippy --`
with:

    -W --warn OPT       Set lint warnings
    -A --allow OPT      Set lint allowed
    -D --deny OPT       Set lint denied
    -F --forbid OPT     Set lint forbidden

You can use tool lints to allow or deny lints from your code, eg.:

    #[allow(clippy::needless_lifetimes)]
"#;

fn show_help() {
    println!("{}", CARGO_CLIPPY_HELP);
}

fn show_version() {
    let version_info = rustc_tools_util::get_version_info!();
    println!("{}", version_info);
}

pub fn main() {
    // Check for version and help flags even when invoked as 'cargo-clippy'
    if std::env::args().any(|a| a == "--help" || a == "-h") {
        show_help();
        return;
    }

    if std::env::args().any(|a| a == "--version" || a == "-V") {
        show_version();
        return;
    }

    if let Err(code) = process(std::env::args().skip(2)) {
        std::process::exit(code);
    }
}

fn process<I>(mut old_args: I) -> Result<(), i32>
where
    I: Iterator<Item = String>,
{
    let mut args = vec!["check".to_owned()];

    let mut fix = false;
    let mut unstable_options = false;

    for arg in old_args.by_ref() {
        match arg.as_str() {
            "--fix" => {
                fix = true;
                continue;
            },
            "--" => break,
            // Cover -Zunstable-options and -Z unstable-options
            s if s.ends_with("unstable-options") => unstable_options = true,
            _ => {},
        }

        args.push(arg);
    }

    if fix {
        if !unstable_options {
            panic!("Usage of `--fix` requires `-Z unstable-options`");
        } else {
            args[0] = "fix".to_owned();
        }
    }

    let path_env = if unstable_options {
        "RUSTC_WORKSPACE_WRAPPER"
    } else {
        "RUSTC_WRAPPER"
    };

    let clippy_args: String = old_args.map(|arg| format!("{}__CLIPPY_HACKERY__", arg)).collect();

    let mut path = std::env::current_exe()
        .expect("current executable path invalid")
        .with_file_name("clippy-driver");
    if cfg!(windows) {
        path.set_extension("exe");
    }

    let target_dir = std::env::var_os("CLIPPY_DOGFOOD")
        .map(|_| {
            std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(
                || std::ffi::OsString::from("clippy_dogfood"),
                |d| {
                    std::path::PathBuf::from(d)
                        .join("target")
                        .join("dogfood")
                        .into_os_string()
                },
            )
        })
        .map(|p| ("CARGO_TARGET_DIR", p));

    // Run the dogfood tests directly on nightly cargo. This is required due
    // to a bug in rustup.rs when running cargo on custom toolchains. See issue #3118.
    if std::env::var_os("CLIPPY_DOGFOOD").is_some() && cfg!(windows) {
        args.insert(0, "+nightly".to_string());
    }

    let exit_status = std::process::Command::new("cargo")
        .args(&args)
        .env(path_env, path)
        .env("CLIPPY_ARGS", clippy_args)
        .envs(target_dir)
        .spawn()
        .expect("could not run cargo")
        .wait()
        .expect("failed to wait for cargo?");

    if exit_status.success() {
        Ok(())
    } else {
        Err(exit_status.code().unwrap_or(-1))
    }
}
<commit_msg>dogfood tasted bad<commit_after>#![cfg_attr(feature = "deny-warnings", deny(warnings))]

use rustc_tools_util::VersionInfo;

const CARGO_CLIPPY_HELP: &str = r#"Checks a package to catch common mistakes and improve your Rust code.

Usage:
    cargo clippy [options] [--] [<opts>...]

Common options:
    -h, --help               Print this message
    -V, --version            Print version info and exit

Other options are the same as `cargo check`.

To allow or deny a lint from the command line you can use `cargo clippy --`
with:

    -W --warn OPT       Set lint warnings
    -A --allow OPT      Set lint allowed
    -D --deny OPT       Set lint denied
    -F --forbid OPT     Set lint forbidden

You can use tool lints to allow or deny lints from your code, eg.:

    #[allow(clippy::needless_lifetimes)]
"#;

fn show_help() {
    println!("{}", CARGO_CLIPPY_HELP);
}

fn show_version() {
    let version_info = rustc_tools_util::get_version_info!();
    println!("{}", version_info);
}

pub fn main() {
    // Check for version and help flags even when invoked as 'cargo-clippy'
    if std::env::args().any(|a| a == "--help" || a == "-h") {
        show_help();
        return;
    }

    if std::env::args().any(|a| a == "--version" || a == "-V") {
        show_version();
        return;
    }

    if let Err(code) = process(std::env::args().skip(2)) {
        std::process::exit(code);
    }
}

fn process<I>(mut old_args: I) -> Result<(), i32>
where
    I: Iterator<Item = String>,
{
    let mut args = vec!["check".to_owned()];

    let mut fix = false;
    let mut unstable_options = false;

    for arg in old_args.by_ref() {
        match arg.as_str() {
            "--fix" => {
                fix = true;
                continue;
            },
            "--" => break,
            // Cover -Zunstable-options and -Z unstable-options
            s if s.ends_with("unstable-options") => unstable_options = true,
            _ => {},
        }

        args.push(arg);
    }

    if fix {
        if unstable_options {
            args[0] = "fix".to_owned();
        } else {
            panic!("Usage of `--fix` requires `-Z unstable-options`");
        }
    }

    let path_env = if unstable_options {
        "RUSTC_WORKSPACE_WRAPPER"
    } else {
        "RUSTC_WRAPPER"
    };

    let clippy_args: String = old_args.map(|arg| format!("{}__CLIPPY_HACKERY__", arg)).collect();

    let mut path = std::env::current_exe()
        .expect("current executable path invalid")
        .with_file_name("clippy-driver");
    if cfg!(windows) {
        path.set_extension("exe");
    }

    let target_dir = std::env::var_os("CLIPPY_DOGFOOD")
        .map(|_| {
            std::env::var_os("CARGO_MANIFEST_DIR").map_or_else(
                || std::ffi::OsString::from("clippy_dogfood"),
                |d| {
                    std::path::PathBuf::from(d)
                        .join("target")
                        .join("dogfood")
                        .into_os_string()
                },
            )
        })
        .map(|p| ("CARGO_TARGET_DIR", p));

    // Run the dogfood tests directly on nightly cargo. This is required due
    // to a bug in rustup.rs when running cargo on custom toolchains. See issue #3118.
    if std::env::var_os("CLIPPY_DOGFOOD").is_some() && cfg!(windows) {
        args.insert(0, "+nightly".to_string());
    }

    let exit_status = std::process::Command::new("cargo")
        .args(&args)
        .env(path_env, path)
        .env("CLIPPY_ARGS", clippy_args)
        .envs(target_dir)
        .spawn()
        .expect("could not run cargo")
        .wait()
        .expect("failed to wait for cargo?");

    if exit_status.success() {
        Ok(())
    } else {
        Err(exit_status.code().unwrap_or(-1))
    }
}
<|endoftext|>


<commit_before>use std::io;
use std::fmt;

enum Op {
    Add,
    Sub,
    Mul,
    Div,
}

impl fmt::String for Op {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Op::Add => write!(f, "Add"),
            Op::Sub => write!(f, "Sub"),
            Op::Mul => write!(f, "Mul"),
            Op::Div => write!(f, "Div"),
        }
    }
}

enum Token {
    BinOp(Op),
    Number(i64),
    EOL,
    EOF,
}

impl fmt::String for Token {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Token::BinOp(ref op) => write!(f, "BinOp: {}", op),
            Token::Number(n) => write!(f, "Number: {}", n),
            Token::EOF => write!(f, "EOF"),
            Token::EOL => write!(f, "EOL"),
        }
    }
}

struct Lexer<R: io::Reader> {
    curr_char: io::IoResult<char>,
    reader: R,
}

impl<R: io::Reader> Lexer<R> {
    fn new(r: R) -> Lexer<R> {
        let mut lexer = Lexer {
            curr_char: Result::Ok(' '),
            reader: r,
        };
        lexer.get_char();
        return lexer;
    }

    fn get_token(&mut self) -> Result<Token, &'static str> {
        match self.curr_char {
            Ok(' ') => { self.get_char(); self.get_token() },
            Ok('+') => { self.get_char(); Ok(Token::BinOp(Op::Add)) },
            Ok('-') => { self.get_char(); Ok(Token::BinOp(Op::Sub)) },
            Ok('*') => { self.get_char(); Ok(Token::BinOp(Op::Mul)) },
            Ok('/') => { self.get_char(); Ok(Token::BinOp(Op::Div)) },
            Ok('\n') => { self.get_char(); Ok(Token::EOL) },
            Ok(c) if c.is_digit(10) => Ok(Token::Number(self.get_number())),
            Ok(c) => { self.get_char(); Err("Unknown symbol") },
            Err(..) => Ok(Token::EOF),
        }
    }

    fn get_number(&mut self) -> i64 {
        let mut number = 0i64;
        loop {
            match self.curr_char {
                Ok(c) if c.is_digit(10) => {
                    number = 10 * number + c as i64 - '0' as i64
                },
                _ => { return number },
            }
            self.get_char();
        }
    }

    fn get_char(&mut self) {
        self.curr_char = match self.reader.read_byte() {
            Ok(c) => Ok(c as char),
            Err(e) => Err(e),
        }
    }
}

fn main() {
    let mut lexer = Lexer::new(io::stdin());
    let mut stack: Vec<i64> = Vec::new();
    loop {
        let token = lexer.get_token();
        println!("{}", token.as_ref().unwrap());
        match token {
            Ok(Token::Number(n)) => stack.push(n),
            Ok(Token::BinOp(op)) => {
                let rhs = stack.pop().unwrap();
                let lhs = stack.pop().unwrap();
                match op {
                    Op::Add => stack.push(lhs + rhs),
                    Op::Sub => stack.push(lhs - rhs),
                    Op::Mul => stack.push(lhs * rhs),
                    Op::Div => stack.push(lhs / rhs),
                }
            }
            Ok(Token::EOL) => {
                match stack.len() {
                    1 => println!("{}", stack.pop().unwrap()),
                    0 => { },
                    _ => panic!("Invalid postfix expression!"),
                }
            }
            Ok(Token::EOF) => { break },
            Err(ref e) => { panic!("{}", e) },
        }
    }
}
<commit_msg>test added<commit_after>#[macro_use] extern crate log;
use std::io;
use std::fmt;

#[derive(Show, PartialEq)]
enum Op {
    Add,
    Sub,
    Mul,
    Div,
}

impl fmt::String for Op {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Op::Add => write!(f, "Add"),
            Op::Sub => write!(f, "Sub"),
            Op::Mul => write!(f, "Mul"),
            Op::Div => write!(f, "Div"),
        }
    }
}

#[derive(Show, PartialEq)]
enum Token {
    BinOp(Op),
    Number(i64),
    EOL,
    EOF,
}

impl fmt::String for Token {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Token::BinOp(ref op) => write!(f, "BinOp: {}", op),
            Token::Number(n) => write!(f, "Number: {}", n),
            Token::EOF => write!(f, "EOF"),
            Token::EOL => write!(f, "EOL"),
        }
    }
}

struct Lexer<R: io::Reader> {
    curr_char: io::IoResult<char>,
    reader: R,
}

impl<R: io::Reader> Lexer<R> {
    fn new(r: R) -> Lexer<R> {
        let mut lexer = Lexer {
            curr_char: Result::Ok(' '),
            reader: r,
        };
        lexer.get_char();
        return lexer;
    }

    fn get_token(&mut self) -> Result<Token, &'static str> {
        match self.curr_char {
            Ok(' ') => { self.get_char(); self.get_token() },
            Ok('+') => { self.get_char(); Ok(Token::BinOp(Op::Add)) },
            Ok('-') => { self.get_char(); Ok(Token::BinOp(Op::Sub)) },
            Ok('*') => { self.get_char(); Ok(Token::BinOp(Op::Mul)) },
            Ok('/') => { self.get_char(); Ok(Token::BinOp(Op::Div)) },
            Ok('\n') => { self.get_char(); Ok(Token::EOL) },
            Ok(c) if c.is_digit(10) => Ok(Token::Number(self.get_number())),
            Ok(c) => { self.get_char(); Err("Unknown symbol") },
            Err(..) => Ok(Token::EOF),
        }
    }

    fn get_number(&mut self) -> i64 {
        let mut number = 0i64;
        loop {
            match self.curr_char {
                Ok(c) if c.is_digit(10) => {
                    number = 10 * number + c as i64 - '0' as i64
                },
                _ => { return number },
            }
            self.get_char();
        }
    }

    fn get_char(&mut self) {
        self.curr_char = match self.reader.read_byte() {
            Ok(c) => Ok(c as char),
            Err(e) => Err(e),
        };
        debug!("curr_char: {}", self.curr_char.as_ref().unwrap());
    }
}

fn main() {
    let mut lexer = Lexer::new(io::stdin());
    let mut stack: Vec<i64> = Vec::new();
    loop {
        let token = lexer.get_token();
        println!("{}", token.as_ref().unwrap());
        match token {
            Ok(Token::Number(n)) => stack.push(n),
            Ok(Token::BinOp(op)) => {
                let rhs = stack.pop().unwrap();
                let lhs = stack.pop().unwrap();
                match op {
                    Op::Add => stack.push(lhs + rhs),
                    Op::Sub => stack.push(lhs - rhs),
                    Op::Mul => stack.push(lhs * rhs),
                    Op::Div => stack.push(lhs / rhs),
                }
            }
            Ok(Token::EOL) => {
                match stack.len() {
                    1 => println!("{}", stack.pop().unwrap()),
                    0 => { },
                    _ => panic!("Invalid postfix expression!"),
                }
            }
            Ok(Token::EOF) => { break },
            Err(ref e) => { panic!("{}", e) },
        }
    }
}

struct MockReader {
    ch: char
}

impl Reader for MockReader {
    fn read_byte(&mut self) -> io::IoResult<u8> {
        Ok('+' as u8)
    }
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<usize> {
        Ok(0)
    }
}

#[test]
fn test_add_token() {
    let mut lexer = Lexer::new(MockReader{ch: '+'});
    let token = lexer.get_token();
    assert_eq!(token, Ok(Token::BinOp(Op::Add)));
}
<|endoftext|>


<commit_before>#![feature(conservative_impl_trait)]

extern crate cgmath;
extern crate png;

use std::fs::File;

use cgmath::prelude::*;
use cgmath::vec3;
use png::HasParameters;

use camera::Camera;
use light::Light;
use material::Material;
use math::*;
use primitive::Primitive;
use raytracer::Raytracer;
use scene::Scene;
use texture::checkerboard;

mod camera;
mod color;
mod intersection;
mod light;
mod material;
#[macro_use] mod math;
mod primitive;
mod ray;
mod raytracer;
mod scene;
mod texture;

fn main() {
    let raytracer = Raytracer {
        scene: example_scene(),
        camera: Camera::new(Point::zero(), Vector::unit_z(), 90.0f32.to_radians()),
    };

    let (w, h) = (512, 512);
    let mut output_data = Vec::with_capacity(w * h);
    for y in 0 .. h {
        for x in 0 .. w {
            let screen_coords = (x as f32 / w as f32, y as f32 / h as f32);
            let ray = raytracer.camera.primary_ray(screen_coords);
            let result = raytracer.trace(ray, 10);

            let (r, g, b) = result.color.as_bytes();
            output_data.push(r);
            output_data.push(g);
            output_data.push(b);
        }
    }

    // TODO: add command line options to configure this.
    let output = File::create("output.png").expect("Couldn't create output file.");

    let mut encoder = png::Encoder::new(output, w as u32, h as u32);
    encoder.set(png::ColorType::RGB).set(png::BitDepth::Eight);
    encoder.write_header()
        .unwrap()
        .write_image_data(&output_data)
        .unwrap();
}

fn example_scene() -> Scene {
    let mut scene = Scene::new(vec3(0.05, 0.05, 0.10).into());

    scene.add_primitive(
        Primitive::plane(
            Material::solid(
                checkerboard(color!(1.0), color!(0.0), (0.5, 0.5)),
                1.0,
            ),
            vec3(0.0, -1.0, 0.0),
            Vector::unit_y(),
        )
    );

    scene.add_primitive(
        Primitive::sphere(
            Material::solid(color!(1.0, 0.0, 0.0), 1.0),
            vec3(0.0, 0.0, 2.0),
            1.0,
        )
    );

    scene.add_light(
        Light::point(vec3(1.5, 1.5, 1.5).into(), vec3(0.0, 1.0, 0.5)),
    );

    scene
}
<commit_msg>Add reflectivity to the example scene<commit_after>#![feature(conservative_impl_trait)]

extern crate cgmath;
extern crate png;

use std::fs::File;

use cgmath::prelude::*;
use cgmath::vec3;
use png::HasParameters;

use camera::Camera;
use light::Light;
use material::Material;
use math::*;
use primitive::Primitive;
use raytracer::Raytracer;
use scene::Scene;
use texture::checkerboard;

mod camera;
mod color;
mod intersection;
mod light;
mod material;
#[macro_use] mod math;
mod primitive;
mod ray;
mod raytracer;
mod scene;
mod texture;

fn main() {
    let raytracer = Raytracer {
        scene: example_scene(),
        camera: Camera::new(Point::zero(), Vector::unit_z(), 90.0f32.to_radians()),
    };

    let (w, h) = (512, 512);
    let mut output_data = Vec::with_capacity(w * h);
    for y in 0 .. h {
        for x in 0 .. w {
            let screen_coords = (x as f32 / w as f32, y as f32 / h as f32);
            let ray = raytracer.camera.primary_ray(screen_coords);
            let result = raytracer.trace(ray, 10);

            let (r, g, b) = result.color.as_bytes();
            output_data.push(r);
            output_data.push(g);
            output_data.push(b);
        }
    }

    // TODO: add command line options to configure this.
    let output = File::create("output.png").expect("Couldn't create output file.");

    let mut encoder = png::Encoder::new(output, w as u32, h as u32);
    encoder.set(png::ColorType::RGB).set(png::BitDepth::Eight);
    encoder.write_header()
        .unwrap()
        .write_image_data(&output_data)
        .unwrap();
}

fn example_scene() -> Scene {
    let mut scene = Scene::new(color::Color::from_u32(0x8cbed6));

    scene.add_primitive(
        Primitive::plane(
            Material::solid(
                checkerboard(color!(1.0), color!(0.0), (0.5, 0.5)),
                1.0,
            ),
            vec3(0.0, -1.0, 0.0),
            Vector::unit_y(),
        )
    );

    scene.add_primitive(
        Primitive::sphere(
            Material::dielectric(color!(0.35, 0.99, 0.35), 1.0, 1.0),
            vec3(0.0, 0.0, 2.0),
            1.0,
        )
    );

    scene.add_light(
        Light::point(vec3(2.0, 2.0, 2.0).into(), vec3(0.0, 1.0, 0.5)),
    );

    scene
}
<|endoftext|>


<commit_before>mod cpu;

use std::io::Result;
use std::io::prelude::*;
use std::fs::File;

fn main() {
	let cpu = cpu::Core::new(64);
	println!("Hello, CPU at {}", cpu.pc);
	match write_data(&cpu) {
		Ok(_) => return (),
		Err(e) => panic!(e),
	};
}

fn write_data(core: &cpu::Core) -> Result<()> {
	let mut buffer = try!(File::create("cpustate.txt"));
	try!(write!(buffer, "{:04x} {:04x} {:04x}", core.pc, core.sp, core.status_register()));
	Ok(())
}

// cpu state (all registers, flags etc.)
// initialize
//      m68ki_build_opcode_table();
//		m68ki_jump(0);
//		REG_SP = m68ki_read_imm_32();
//		REG_PC = m68ki_read_imm_32();
//		m68ki_jump(REG_PC);

// execute instruction (modifies CPU state)
/*
			/* Record previous program counter */
			REG_PPC = REG_PC;

			/* Read an instruction and call its handler */
			REG_IR = m68ki_read_imm_16();
			// include all 64k entries?
			m68ki_instruction_jump_table[REG_IR]();
			USE_CYCLES(CYC_INSTRUCTION[REG_IR]);
*/

<commit_msg>Fix register output width<commit_after>mod cpu;

use std::io::Result;
use std::io::prelude::*;
use std::fs::File;

fn main() {
	let cpu = cpu::Core::new(64);
	println!("Hello, CPU at {}", cpu.pc);
	match write_data(&cpu) {
		Ok(_) => return (),
		Err(e) => panic!(e),
	};
}

fn write_data(core: &cpu::Core) -> Result<()> {
	let mut buffer = try!(File::create("cpustate.txt"));
	try!(writeln!(buffer, "PC:{:08x} SP:{:08x} SR:{:08x}", core.pc, core.sp, core.status_register()));
	Ok(())
}

// cpu state (all registers, flags etc.)
// initialize
//      m68ki_build_opcode_table();
//		m68ki_jump(0);
//		REG_SP = m68ki_read_imm_32();
//		REG_PC = m68ki_read_imm_32();
//		m68ki_jump(REG_PC);

// execute instruction (modifies CPU state)
/*
			/* Record previous program counter */
			REG_PPC = REG_PC;

			/* Read an instruction and call its handler */
			REG_IR = m68ki_read_imm_16();
			// include all 64k entries?
			m68ki_instruction_jump_table[REG_IR]();
			USE_CYCLES(CYC_INSTRUCTION[REG_IR]);
*/

<|endoftext|>


<commit_before>extern crate regex;
extern crate readline;

mod errors;
mod atom;
mod parser;

use parser::*;
use atom::*;
use errors::Error;
use errors::Error::*;

use std::collections::HashMap;
use std::string::String;
type EvalResult = Result<Eval, Error>;
type Function = Fn(&Vec<Eval>) -> EvalResult;
type FunctionMap = HashMap<String, Box<Function>>;

fn nil_func(_: &Vec<Eval>) -> EvalResult {
    return Ok(Eval::Atom(Atom::Nil));
}

struct Env {
    func_map: FunctionMap,
    def_map: HashMap<String, Eval>
}

fn add(v: &Vec<Eval>) -> EvalResult {
    let mut result = 0;

    for i in v {
        if let Eval::Atom(Atom::Integer(d)) = *i {
                result += d
        } else {
            return Err(Error::UnexpectedType);
        }
    }

    return Ok(Eval::Atom(Atom::Integer(result)));
}

fn sub(v: &Vec<Eval>) -> EvalResult {
    if v.len() < 1 {
        return Err(Error::InvalidArguments)
    }

    let mut result = match v[0] {
        Eval::Atom(Atom::Integer(d)) => d,
        _ => return Err(Error::UnexpectedType)
    };

    for i in v.iter().skip(1) {
        match *i {
            Eval::Atom(Atom::Integer(d)) => result -= d,
            _ => return Err(Error::UnexpectedType)
        }
    }

    return Ok(Eval::Atom(Atom::Integer(result)));
}

fn equals(args: &Vec<Eval>) -> EvalResult {
    let v = &args[0];

    for i in args.iter().skip(1) {
        if v != i {
            return Ok(Eval::Atom(Atom::Boolean(false)));
        }
    }
    Ok(Eval::Atom(Atom::Boolean(true)))
}

fn default_env() -> Env {
    let mut env = Env{func_map: HashMap::new(), def_map: HashMap::new()};

    env.func_map.insert("nil".to_string(), Box::new(nil_func) as Box<Function>);
    env.func_map.insert("+".to_string(), Box::new(add) as Box<Function>);
    env.func_map.insert("-".to_string(), Box::new(sub) as Box<Function>);
    env.func_map.insert("=".to_string(), Box::new(equals) as Box<Function>);

    return env;
}

fn define(args: Vec<Eval>, env: &mut Env) -> EvalResult {
    if args.len() != 2 {
        return Err(Error::InvalidArguments);
    }

    if let Eval::Atom(Atom::Symbol(ref key)) = args[0] {
        env.def_map.insert(key.clone(), args[1].clone());
        Ok(Eval::Atom(Atom::Nil))
    } else {
        Err(Error::InvalidArguments)
    }
}

fn set(args: Vec<Eval>, env: &mut Env) -> EvalResult {
    // FIXME: get rid of the clones
    if args.len() != 2 {
        return Err(InvalidArguments);
    }

    if let Eval::Atom(Atom::Symbol(ref key)) = args[0] {
        if env.def_map.contains_key(key) {
            let entry = env.def_map.entry((*key).clone()).or_insert(Eval::Atom(Atom::Nil));
            *entry = args[1].clone();
            return Ok(args[1].clone())
        }
    }
    Err(InvalidArguments)
}

fn get(args: Vec<Eval>, env: &Env) -> EvalResult {
    if args.len() != 1 {
        return Err(Error::InvalidArguments);
    }

    if let Eval::Atom(Atom::Symbol(ref s)) = args[0] {
        if let Some(a) = env.def_map.get(s) {
            Ok(a.clone())
        } else {
            Ok(Eval::Atom(Atom::Nil))
        }
    } else {
        Err(Error::InvalidArguments)
    }
}

fn eval_args(list: &Vec<Node>, env: &mut Env) -> Result<Vec<Eval>, Error> {
    let mut args = vec![];

    for i in list.iter().skip(1) {
        let atom = try!(eval(i, env));
        args.push(atom);
    }
    return Ok(args);
}
#[derive(Debug, Clone, PartialEq)]
enum Eval {
    Atom(Atom),
    Node(Node)
}

fn quote(v: &Vec<Node>) -> Result<Eval, Error> {
    return Ok(Eval::Node(v[1].clone()));
}

fn eval(node: &Node, env: &mut Env) -> Result<Eval, Error> {
    match node {
        &Node::List(ref list) => {
            match list[0] {
                Node::Atom(ref atom) => {
                    if let &Atom::Symbol(ref s) = atom {
                        match s.as_ref() {
                            "def" => {
                                let args = try!(eval_args(&list, env));
                                return define(args, env);
                            },
                            "quote" => {
                                return quote(&list);
                            },
                            "set!" => {
                                return set( try!(eval_args(&list, env)), env);
                            },
                            "get" => {
                                return get( try!(eval_args(&list, env)), env);
                            },
                            "if" => {
                                let predicate = try!(eval(&list[1], env));

                                let truthy = match predicate {
                                    Eval::Atom(Atom::Boolean(b)) => b,
                                    Eval::Atom(Atom::Nil) => false,
                                    _ => true
                                };

                                if truthy {
                                    return eval(&list[2], env);
                                } else if list.len() > 2 {
                                    return eval(&list[3], env);
                                } else {
                                    return Ok(Eval::Atom(Atom::Boolean(false)))
                                }
                            },
                            _ => ()
                        };

                        let args = try!(eval_args(&list, env));
                        if let Some(f) = env.func_map.get(s) {
                            f(&args)
                        } else {
                            Ok(Eval::Atom(Atom::Nil))
                        }
                    } else {
                        Err(Error::NotAFunction)
                    }
                },
                Node::List(_) => panic!("derp")
            }
        },
        &Node::Atom(ref atom) => Ok(Eval::Atom(atom.clone()))
    }
}

fn repl() {
    println!("Rust Lisp!");
    let mut env = default_env();

    loop {
        match readline::readline(">") {
            Some(s) => {
                if let Ok(p) = parser::tokenize(&s) {
                    match eval(&p, &mut env) {
                        Ok(r) => println!("{:?}", r),
                        Err(e) => println!("Error in evaluation: {:?}", e)
                    }
                } else {
                    println!("Error in parsing");
                }
            },
            None => {
                println!("Exiting...");
                break;
            }
        }
    }
}

pub fn main() {
    repl();
}

#[cfg(test)]
mod test {
    use parser::*;
    use super::default_env;
    use super::eval;
    use atom::Atom;

    fn teval(s: &str) -> Atom {
        eval(&tokenize(s).unwrap(), &mut default_env()).unwrap()
    }

    fn make_atom_node(s: &str) -> Node {
        return Node::Atom(Atom::parse(s));
    }

    fn as_list(n: &Node) -> &Vec<Node> {
        match n {
            &Node::List(ref l) => l,
            _ => panic!("don't get here!")
        }
    }

    fn as_atom(n: &Node) -> &Atom {
        match n {
            &Node::Atom(ref a) => a,
            _ => panic!("not here!")
        }
    }

    fn atom(s: &str) -> Atom {
        Atom::parse(s)
    }

    #[test]
    fn simple_read_tokens() {
        let x = tokenize("(+ 1 2)").unwrap();

        let l = as_list(&x);

        assert_eq!(3, l.len());

        let xx : Vec<Node> = vec![make_atom_node("+"), make_atom_node("1"), make_atom_node("2")];

        for pair in xx.iter().zip(l.iter()) {
            assert_eq!(pair.0, pair.1);
        }
    }

    #[test]
    fn nested_read_tokens() {
        let x = tokenize("(+ 1 (* 2 2))").unwrap();

        let l = as_list(&x);

        assert_eq!( atom("+"), *as_atom(&l[0]));
        assert_eq!( atom("1"), *as_atom(&l[1]));

        let l2 = as_list(&l[2]);

        assert_eq!( 3, l.len());
        assert_eq!( atom("*"), *as_atom(&l2[0]));
        assert_eq!( atom("2"), *as_atom(&l2[1]));
        assert_eq!( atom("2"), *as_atom(&l2[2]));
    }

    #[test]
    fn subexp_token_test() {
        let x = tokenize("(+ 1 (+ 2 3) 4)").unwrap();

        let l = as_list(&x);

        assert_eq!( atom("+"), *as_atom(&l[0]));
        assert_eq!( atom("1"), *as_atom(&l[1]));

        let l2 = as_list(&l[2]);

        assert_eq!( 3, l2.len());
        assert_eq!( atom("+"), *as_atom(&l2[0]));
        assert_eq!( atom("2"), *as_atom(&l2[1]));
        assert_eq!( atom("3"), *as_atom(&l2[2]));

        assert_eq!(atom("4"), *as_atom(&l[3]));
    }

    #[test]
    fn if_special_form() {
        let x = eval(&tokenize("(if (= 1 1) true false)").unwrap(), &mut default_env()).unwrap();

        assert_eq!(Atom::Boolean(true), x);
    }

    #[test]
    fn if_special_form_false() {
        let x = eval(&tokenize("(if (= 1 2) true false)").unwrap(), &mut default_env()).unwrap();

        assert_eq!(Atom::Boolean(false), x);
    }

    #[test]
    fn if_no_else() {
        let x = teval("(if (= 1 1) true)");

        assert_eq!(Atom::Boolean(true), x);
    }

    #[test]
    #[should_panic]
    fn unmatched_bracket() {
        tokenize("(+ 1").unwrap();
    }

    #[test]
    #[should_panic]
    fn eof() {
         tokenize("").unwrap();
    }
}
<commit_msg>fix tests<commit_after>extern crate regex;
extern crate readline;

mod errors;
mod atom;
mod parser;

use parser::*;
use atom::*;
use errors::Error;
use errors::Error::*;

use std::collections::HashMap;
use std::string::String;

type EvalResult = Result<Eval, Error>;
type Function = Fn(&Vec<Eval>) -> EvalResult;
type FunctionMap = HashMap<String, Box<Function>>;

#[derive(Debug, Clone, PartialEq)]
enum Eval {
    Atom(Atom),
    Node(Node)
}

fn nil_func(_: &Vec<Eval>) -> EvalResult {
    Ok(Eval::Atom(Atom::Nil))
}

struct Env {
    func_map: FunctionMap,
    def_map: HashMap<String, Eval>
}

fn add(v: &Vec<Eval>) -> EvalResult {
    let mut result = 0;

    for i in v {
        if let Eval::Atom(Atom::Integer(d)) = *i {
                result += d
        } else {
            return Err(Error::UnexpectedType)
        }
    }

    Ok(Eval::Atom(Atom::Integer(result)))
}

fn sub(v: &Vec<Eval>) -> EvalResult {
    if v.len() < 1 {
        return Err(Error::InvalidArguments)
    }

    let mut result = match v[0] {
        Eval::Atom(Atom::Integer(d)) => d,
        _ => return Err(Error::UnexpectedType)
    };

    for i in v.iter().skip(1) {
        match *i {
            Eval::Atom(Atom::Integer(d)) => result -= d,
            _ => return Err(Error::UnexpectedType)
        }
    }

    Ok(Eval::Atom(Atom::Integer(result)))
}

fn equals(args: &Vec<Eval>) -> EvalResult {
    let v = &args[0];

    for i in args.iter().skip(1) {
        if v != i {
            return Ok(Eval::Atom(Atom::Boolean(false)))
        }
    }
    Ok(Eval::Atom(Atom::Boolean(true)))
}

fn default_env() -> Env {
    let mut env = Env{func_map: HashMap::new(), def_map: HashMap::new()};

    env.func_map.insert("nil".to_string(), Box::new(nil_func) as Box<Function>);
    env.func_map.insert("+".to_string(), Box::new(add) as Box<Function>);
    env.func_map.insert("-".to_string(), Box::new(sub) as Box<Function>);
    env.func_map.insert("=".to_string(), Box::new(equals) as Box<Function>);

    env
}

fn define(args: Vec<Eval>, env: &mut Env) -> EvalResult {
    if args.len() != 2 {
        return Err(Error::InvalidArguments);
    }

    if let Eval::Atom(Atom::Symbol(ref key)) = args[0] {
        env.def_map.insert(key.clone(), args[1].clone());
        Ok(Eval::Atom(Atom::Nil))
    } else {
        Err(Error::InvalidArguments)
    }
}

fn set(args: Vec<Eval>, env: &mut Env) -> EvalResult {
    // FIXME: get rid of the clones
    if args.len() != 2 {
        return Err(InvalidArguments)
    }

    if let Eval::Atom(Atom::Symbol(ref key)) = args[0] {
        if env.def_map.contains_key(key) {
            let entry = env.def_map.entry((*key).clone()).or_insert(Eval::Atom(Atom::Nil));
            *entry = args[1].clone();
            return Ok(args[1].clone())
        }
    }
    Err(InvalidArguments)
}

fn get(args: Vec<Eval>, env: &Env) -> EvalResult {
    if args.len() != 1 {
        return Err(Error::InvalidArguments)
    }

    if let Eval::Atom(Atom::Symbol(ref s)) = args[0] {
        if let Some(a) = env.def_map.get(s) {
            Ok(a.clone())
        } else {
            Ok(Eval::Atom(Atom::Nil))
        }
    } else {
        Err(Error::InvalidArguments)
    }
}

fn eval_args(list: &Vec<Node>, env: &mut Env) -> Result<Vec<Eval>, Error> {
    let mut args = vec![];

    for i in list.iter().skip(1) {
        let atom = try!(eval(i, env));
        args.push(atom);
    }
    Ok(args)
}

fn quote(v: &Vec<Node>) -> Result<Eval, Error> {
    Ok(Eval::Node(v[1].clone()))
}

fn eval(node: &Node, env: &mut Env) -> Result<Eval, Error> {
    match node {
        &Node::List(ref list) => {
            match list[0] {
                Node::Atom(ref atom) => {
                    if let &Atom::Symbol(ref s) = atom {
                        match s.as_ref() {
                            "def" => {
                                let args = try!(eval_args(&list, env));
                                return define(args, env);
                            },
                            "quote" => {
                                return quote(&list);
                            },
                            "set!" => {
                                return set( try!(eval_args(&list, env)), env);
                            },
                            "get" => {
                                return get( try!(eval_args(&list, env)), env);
                            },
                            "if" => {
                                let predicate = try!(eval(&list[1], env));

                                let truthy = match predicate {
                                    Eval::Atom(Atom::Boolean(b)) => b,
                                    Eval::Atom(Atom::Nil) => false,
                                    _ => true
                                };

                                if truthy {
                                    return eval(&list[2], env);
                                } else if list.len() > 2 {
                                    return eval(&list[3], env);
                                } else {
                                    return Ok(Eval::Atom(Atom::Boolean(false)))
                                }
                            },
                            _ => ()
                        };

                        let args = try!(eval_args(&list, env));
                        if let Some(f) = env.func_map.get(s) {
                            f(&args)
                        } else {
                            Ok(Eval::Atom(Atom::Nil))
                        }
                    } else {
                        Err(Error::NotAFunction)
                    }
                },
                Node::List(_) => panic!("derp")
            }
        },
        &Node::Atom(ref atom) => Ok(Eval::Atom(atom.clone()))
    }
}

fn repl() {
    println!("Rust Lisp!");
    let mut env = default_env();

    loop {
        match readline::readline(">") {
            Some(s) => {
                if let Ok(p) = parser::tokenize(&s) {
                    match eval(&p, &mut env) {
                        Ok(r) => println!("{:?}", r),
                        Err(e) => println!("Error in evaluation: {:?}", e)
                    }
                } else {
                    println!("Error in parsing");
                }
            },
            None => {
                println!("Exiting...");
                break;
            }
        }
    }
}

pub fn main() {
    repl();
}

#[cfg(test)]
mod test {
    use parser::*;
    use super::default_env;
    use super::eval;
    use atom::Atom;
    use super::Eval;

    fn teval(s: &str) -> Eval {
        eval(&tokenize(s).unwrap(), &mut default_env()).unwrap()
    }

    fn make_atom_node(s: &str) -> Node {
        return Node::Atom(Atom::parse(s));
    }

    fn as_list(n: &Node) -> &Vec<Node> {
        match n {
            &Node::List(ref l) => l,
            _ => panic!("don't get here!")
        }
    }

    fn as_atom(n: &Node) -> &Atom {
        match n {
            &Node::Atom(ref a) => a,
            _ => panic!("not here!")
        }
    }

    fn atom(s: &str) -> Atom {
        Atom::parse(s)
    }

    #[test]
    fn simple_read_tokens() {
        let x = tokenize("(+ 1 2)").unwrap();

        let l = as_list(&x);

        assert_eq!(3, l.len());

        let xx : Vec<Node> = vec![make_atom_node("+"), make_atom_node("1"), make_atom_node("2")];

        for pair in xx.iter().zip(l.iter()) {
            assert_eq!(pair.0, pair.1);
        }
    }

    #[test]
    fn nested_read_tokens() {
        let x = tokenize("(+ 1 (* 2 2))").unwrap();

        let l = as_list(&x);

        assert_eq!( atom("+"), *as_atom(&l[0]));
        assert_eq!( atom("1"), *as_atom(&l[1]));

        let l2 = as_list(&l[2]);

        assert_eq!( 3, l.len());
        assert_eq!( atom("*"), *as_atom(&l2[0]));
        assert_eq!( atom("2"), *as_atom(&l2[1]));
        assert_eq!( atom("2"), *as_atom(&l2[2]));
    }

    #[test]
    fn subexp_token_test() {
        let x = tokenize("(+ 1 (+ 2 3) 4)").unwrap();

        let l = as_list(&x);

        assert_eq!( atom("+"), *as_atom(&l[0]));
        assert_eq!( atom("1"), *as_atom(&l[1]));

        let l2 = as_list(&l[2]);

        assert_eq!( 3, l2.len());
        assert_eq!( atom("+"), *as_atom(&l2[0]));
        assert_eq!( atom("2"), *as_atom(&l2[1]));
        assert_eq!( atom("3"), *as_atom(&l2[2]));

        assert_eq!(atom("4"), *as_atom(&l[3]));
    }

    #[test]
    fn if_special_form() {
        let x = eval(&tokenize("(if (= 1 1) true false)").unwrap(), &mut default_env()).unwrap();

        assert_eq!(Eval::Atom(Atom::Boolean(true)), x);
    }

    #[test]
    fn if_special_form_false() {
        let x = eval(&tokenize("(if (= 1 2) true false)").unwrap(), &mut default_env()).unwrap();

        assert_eq!(Eval::Atom(Atom::Boolean(false)), x);
    }

    #[test]
    fn if_no_else() {
        let x = teval("(if (= 1 1) true)");

        assert_eq!(Eval::Atom(Atom::Boolean(true)), x);
    }

    #[test]
    #[should_panic]
    fn unmatched_bracket() {
        tokenize("(+ 1").unwrap();
    }

    #[test]
    #[should_panic]
    fn eof() {
         tokenize("").unwrap();
    }
}
<|endoftext|>


<commit_before>const NUM_DIRECTIONS: usize = 4;
const NUM_ROOMS: usize = 2;

use RoomId::*;
use Direction::*;

#[derive(Debug, Copy, Clone)]
enum RoomId {
  Hallway,
  AudienceChamber,
}

#[derive(Debug)]
struct Map<'a> {
  rooms: [Room<'a>; NUM_ROOMS]
}

impl<'a> Map<'a> {
  pub fn new() -> Self {
    Self { rooms: [Room::new(); NUM_ROOMS] }
  }

  pub fn room(&mut self, id: RoomId) -> &mut Room<'a> {
    &mut self.rooms[id as usize]
  }

  pub fn connect(&mut self, from: RoomId, d: Direction, to: RoomId) -> &mut Self {
    self.room(from).set_exit(d, to);
    self.room(to).set_exit(d.opposite(), from);
    self
  }
}

#[derive(Debug, Copy, Clone)]
enum Direction {
  North,
  South,
  East,
  West,
}

impl Direction {
  pub fn opposite(self) -> Self {
    match self {
      North => South,
      South => North,
      East => West,
      West => East,
    }
  }
}

#[derive(Debug, Copy, Clone)]
struct Room<'a> {
  exits: [Option<RoomId>; NUM_DIRECTIONS],
  name: &'a str,
  description: &'a str,
}

impl<'a> Room<'a> {
  pub fn new() -> Self {
    Self {
      exits: [None; NUM_DIRECTIONS],
      name: "",
      description: "",
    }
  }

  pub fn get_exit(self, d: Direction) -> Option<RoomId> {
    self.exits[d as usize]
  }

  pub fn set_exit(&mut self, d: Direction, r: RoomId) -> &mut Self {
    self.exits[d as usize] = Some(r);
    self
  }

  pub fn describe(&mut self, name: &'a str, desc: &'a str) -> &mut Self {
    self.name = name;
    self.description = desc;
    self
  }
}

fn main() {
  let mut map = Map::new();

  map.room(Hallway).describe("Hallway", "");
  map.room(AudienceChamber).describe("Audience Chamber", "");

  map.connect(Hallway, South, AudienceChamber);

  println!("Map is {:?}", map);
}
<commit_msg>Just use static lifetimes for Room strings.<commit_after>const NUM_DIRECTIONS: usize = 4;
const NUM_ROOMS: usize = 2;

use RoomId::*;
use Direction::*;

#[derive(Debug, Copy, Clone)]
enum RoomId {
  Hallway,
  AudienceChamber,
}

#[derive(Debug)]
struct Map {
  rooms: [Room; NUM_ROOMS]
}

impl Map {
  pub fn new() -> Self {
    Self { rooms: [Room::new(); NUM_ROOMS] }
  }

  pub fn room(&mut self, id: RoomId) -> &mut Room {
    &mut self.rooms[id as usize]
  }

  pub fn connect(&mut self, from: RoomId, d: Direction, to: RoomId) -> &mut Self {
    self.room(from).set_exit(d, to);
    self.room(to).set_exit(d.opposite(), from);
    self
  }
}

#[derive(Debug, Copy, Clone)]
enum Direction {
  North,
  South,
  East,
  West,
}

impl Direction {
  pub fn opposite(self) -> Self {
    match self {
      North => South,
      South => North,
      East => West,
      West => East,
    }
  }
}

#[derive(Debug, Copy, Clone)]
struct Room {
  exits: [Option<RoomId>; NUM_DIRECTIONS],
  name: &'static str,
  description: &'static str,
}

impl Room {
  pub fn new() -> Self {
    Self {
      exits: [None; NUM_DIRECTIONS],
      name: "",
      description: "",
    }
  }

  pub fn get_exit(self, d: Direction) -> Option<RoomId> {
    self.exits[d as usize]
  }

  pub fn set_exit(&mut self, d: Direction, r: RoomId) -> &mut Self {
    self.exits[d as usize] = Some(r);
    self
  }

  pub fn describe(&mut self, name: &'static str, desc: &'static str) -> &mut Self {
    self.name = name;
    self.description = desc;
    self
  }
}

fn main() {
  let mut map = Map::new();

  map.room(Hallway).describe("Hallway", "");
  map.room(AudienceChamber).describe("Audience Chamber", "");

  map.connect(Hallway, South, AudienceChamber);

  println!("Map is {:?}", map);
}
<|endoftext|>


<commit_before>use std::fs::File;
use std::io;
use std::io::Read;
use std::env;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Instruction {
    Right,
    Left,
    Increment,
    Decrement,
    Output,
    Input,
    JumpOpen(usize),
    JumpClose(usize),
    Comment(char),
    End,
}

impl From<char> for Instruction {
    fn from(c: char) -> Instruction {
        match c {
            '>' => Instruction::Right,
            '<' => Instruction::Left,
            '+' => Instruction::Increment,
            '-' => Instruction::Decrement,
            '.' => Instruction::Output,
            ',' => Instruction::Input,
            '[' => Instruction::JumpOpen(0),
            ']' => Instruction::JumpClose(0),
            c => Instruction::Comment(c),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct Programme {
    instructions: Vec<Instruction>,
    index: usize,
}

impl Programme {

    fn parse<S>(source: S) -> Programme
        where S: Into<String>
    {

        let s = source.into();

        let mut instructions = Vec::new();
        let mut braces = Vec::new();

        let mut instr_id = 0;
        for c in s.chars() {

            let mut instr = Instruction::from(c);

            match instr {
                Instruction::Comment(_) => continue,
                Instruction::JumpOpen(_) => braces.push(instr_id),
                Instruction::JumpClose(_) => {
                    let i_open = braces.pop().unwrap();
                    instructions[i_open] = Instruction::JumpOpen(instr_id - i_open);
                    instr = Instruction::JumpClose(instr_id - i_open);
                },
                _ => {},
            }
            instructions.push(instr);
            instr_id += 1;

        }

        instructions.push(Instruction::End);

        Programme{instructions: instructions, index: 0}

    }

    fn step(&mut self, ms: &mut MachineState) {
        match self.instructions[self.index] {
            Instruction::Right => ms.index += 1,
            Instruction::Left => ms.index -= 1,
            Instruction::Increment => ms.cells[ms.index] = ms.cells[ms.index].wrapping_add(1),
            Instruction::Decrement => ms.cells[ms.index] = ms.cells[ms.index].wrapping_sub(1),
            Instruction::Output => print!("{}", ms.cells[ms.index] as char),
            Instruction::Input => ms.cells[ms.index] = match io::stdin().bytes().next() {
                Some(r) => r.unwrap_or(0),
                None => 0,
            },
            Instruction::JumpOpen(offset) => if ms.cells[ms.index] == 0 {
                self.index += offset;
            },
            Instruction::JumpClose(offset) => if ms.cells[ms.index] != 0 {
                self.index -= offset + 1;
            },
            Instruction::Comment(_) => {},
            Instruction::End => return,
        }
        self.index += 1;
    }

    fn execute(&mut self, mut ms: &mut MachineState) {
        while self.instructions[self.index] != Instruction::End {
            self.step(&mut ms);
        }
    }

}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct MachineState {
    cells: Vec<u8>,
    index: usize,
}

fn main() {

    let argv: Vec<String> = env::args().collect();

    let mut file = File::open(&argv[1]).unwrap();
    let mut buffer = String::new();
    file.read_to_string(&mut buffer).unwrap();

    let mut prgm = Programme::parse(buffer);

    let mut state = MachineState{
        cells: vec![0u8; 256],
        .. MachineState::default()
    };

    prgm.execute(&mut state);

}
<commit_msg>rename MachineState::cells to tape<commit_after>use std::fs::File;
use std::io;
use std::io::Read;
use std::env;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum Instruction {
    Right,
    Left,
    Increment,
    Decrement,
    Output,
    Input,
    JumpOpen(usize),
    JumpClose(usize),
    Comment(char),
    End,
}

impl From<char> for Instruction {
    fn from(c: char) -> Instruction {
        match c {
            '>' => Instruction::Right,
            '<' => Instruction::Left,
            '+' => Instruction::Increment,
            '-' => Instruction::Decrement,
            '.' => Instruction::Output,
            ',' => Instruction::Input,
            '[' => Instruction::JumpOpen(0),
            ']' => Instruction::JumpClose(0),
            c => Instruction::Comment(c),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct Programme {
    instructions: Vec<Instruction>,
    index: usize,
}

impl Programme {

    fn parse<S>(source: S) -> Programme
        where S: Into<String>
    {

        let s = source.into();

        let mut instructions = Vec::new();
        let mut braces = Vec::new();

        let mut instr_id = 0;
        for c in s.chars() {

            let mut instr = Instruction::from(c);

            match instr {
                Instruction::Comment(_) => continue,
                Instruction::JumpOpen(_) => braces.push(instr_id),
                Instruction::JumpClose(_) => {
                    let i_open = braces.pop().unwrap();
                    instructions[i_open] = Instruction::JumpOpen(instr_id - i_open);
                    instr = Instruction::JumpClose(instr_id - i_open);
                },
                _ => {},
            }
            instructions.push(instr);
            instr_id += 1;

        }

        instructions.push(Instruction::End);

        Programme{instructions: instructions, index: 0}

    }

    fn step(&mut self, ms: &mut MachineState) {
        match self.instructions[self.index] {
            Instruction::Right => ms.index += 1,
            Instruction::Left => ms.index -= 1,
            Instruction::Increment => ms.tape[ms.index] = ms.tape[ms.index].wrapping_add(1),
            Instruction::Decrement => ms.tape[ms.index] = ms.tape[ms.index].wrapping_sub(1),
            Instruction::Output => print!("{}", ms.tape[ms.index] as char),
            Instruction::Input => ms.tape[ms.index] = match io::stdin().bytes().next() {
                Some(r) => r.unwrap_or(0),
                None => 0,
            },
            Instruction::JumpOpen(offset) => if ms.tape[ms.index] == 0 {
                self.index += offset;
            },
            Instruction::JumpClose(offset) => if ms.tape[ms.index] != 0 {
                self.index -= offset + 1;
            },
            Instruction::Comment(_) => {},
            Instruction::End => return,
        }
        self.index += 1;
    }

    fn execute(&mut self, mut ms: &mut MachineState) {
        while self.instructions[self.index] != Instruction::End {
            self.step(&mut ms);
        }
    }

}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct MachineState {
    tape: Vec<u8>,
    index: usize,
}

fn main() {

    let argv: Vec<String> = env::args().collect();

    let mut file = File::open(&argv[1]).unwrap();
    let mut buffer = String::new();
    file.read_to_string(&mut buffer).unwrap();

    let mut prgm = Programme::parse(buffer);

    let mut state = MachineState{
        tape: vec![0u8; 256],
        .. MachineState::default()
    };

    prgm.execute(&mut state);

}
<|endoftext|>