<commit_before>// Author: Alex Chernyakhovsky (achernya@mit.edu)

// TODO(achernya): Per the documentation on doc.rust-lang.org, std::io
// is not yet ready, so use old_io until 1.0-final.
#![feature(old_io)]

// std::env contains a lot of nice functions that otherwise would
// require std::os to use; std::os has lots of deprecated functions.
#![feature(env)]

// TODO(achernya): Remove this feature when std::env moves over to
// std::path.
#![feature(old_path)]

use std::env;
use std::old_io as io;

// println_stderr is like println, but to stderr.
macro_rules! println_stderr(
    ($($arg:tt)*) => (
        match writeln!(&mut io::stderr(), $($arg)* ) {
            Ok(_) => {},
            Err(x) => panic!("Unable to write to stderr: {}", x),
        }
    )
);

// ShellCommand is a trait that defines a runnable POSIX shell
// command. An implementation is an abstract representation of shell
// commands such as simple invocations, invocations with redirection,
// and even shell pipelines.
trait ShellCommand {
    fn run(&self);
}

fn shell_loop() {
    let mut stdin = io::stdin();
    loop {
        print!("$ ");
        let line = stdin.read_line();
        match line {
            Ok(expr) => handle_command(expr),
            Err(_) => break,
        }
    }
}

fn handle_command(user_expr: String) {
    // Clean up the string by removing the newline at the end
    let expr = &user_expr.trim_matches('\n');
    let components: Vec<&str> = expr.split(' ').collect();
    if builtins(components) {
        return;
    }
}

fn builtins(command: Vec<&str>) -> bool {
    match command[0] {
        "cd" => cd(command),
        "pwd" => pwd(),
        _ => return false,
    }
    return true;
}

fn cd(command: Vec<&str>) {
    // cd is the "change directory" command. It can take either 0 or 1
    // arguments. If given no arguments, then the $HOME directory is
    // chosen.
    let mut dir: Option<Path>;
    match command.len() {
        0 => panic!("invalid cd invocation"),
        1 => dir = env::home_dir(),
        _ => dir = Some(Path::new(command[1]))
    }
    if dir.is_none() {
        println_stderr!("cd: no directory to change to");
        return;
    }
    let directory = dir.unwrap();
    let result = env::set_current_dir(&directory);
    match result {
        Err(err) => {
            println_stderr!("cd: {}: {}", directory.display(), err);
        },
        _ => (),
    }
}

fn pwd() {
    let p = env::current_dir().unwrap_or(Path::new("/"));
    println!("{}", p.display());
}

fn main() {
    // TODO(achernya): is there any initialization we want to do
    // before we enter the shell loop?
    shell_loop();
}
<commit_msg>Use match to set dir directly and make it immutable<commit_after>// Author: Alex Chernyakhovsky (achernya@mit.edu)

// TODO(achernya): Per the documentation on doc.rust-lang.org, std::io
// is not yet ready, so use old_io until 1.0-final.
#![feature(old_io)]

// std::env contains a lot of nice functions that otherwise would
// require std::os to use; std::os has lots of deprecated functions.
#![feature(env)]

// TODO(achernya): Remove this feature when std::env moves over to
// std::path.
#![feature(old_path)]

use std::env;
use std::old_io as io;

// println_stderr is like println, but to stderr.
macro_rules! println_stderr(
    ($($arg:tt)*) => (
        match writeln!(&mut io::stderr(), $($arg)* ) {
            Ok(_) => {},
            Err(x) => panic!("Unable to write to stderr: {}", x),
        }
    )
);

// ShellCommand is a trait that defines a runnable POSIX shell
// command. An implementation is an abstract representation of shell
// commands such as simple invocations, invocations with redirection,
// and even shell pipelines.
trait ShellCommand {
    fn run(&self);
}

fn shell_loop() {
    let mut stdin = io::stdin();
    loop {
        print!("$ ");
        let line = stdin.read_line();
        match line {
            Ok(expr) => handle_command(expr),
            Err(_) => break,
        }
    }
}

fn handle_command(user_expr: String) {
    // Clean up the string by removing the newline at the end
    let expr = &user_expr.trim_matches('\n');
    let components: Vec<&str> = expr.split(' ').collect();
    if builtins(components) {
        return;
    }
}

fn builtins(command: Vec<&str>) -> bool {
    match command[0] {
        "cd" => cd(command),
        "pwd" => pwd(),
        _ => return false,
    }
    return true;
}

fn cd(command: Vec<&str>) {
    // cd is the "change directory" command. It can take either 0 or 1
    // arguments. If given no arguments, then the $HOME directory is
    // chosen.
    let dir: Option<Path> = match command.len() {
        0 => panic!("invalid cd invocation"),
        1 => env::home_dir(),
        _ => Some(Path::new(command[1]))
    };
    if dir.is_none() {
        println_stderr!("cd: no directory to change to");
        return;
    }
    let directory = dir.unwrap();
    let result = env::set_current_dir(&directory);
    match result {
        Err(err) => {
            println_stderr!("cd: {}: {}", directory.display(), err);
        },
        _ => (),
    }
}

fn pwd() {
    let p = env::current_dir().unwrap_or(Path::new("/"));
    println!("{}", p.display());
}

fn main() {
    // TODO(achernya): is there any initialization we want to do
    // before we enter the shell loop?
    shell_loop();
}
<|endoftext|>


<commit_before>fn main() {
    println!("Hello World!");
}<commit_msg>Read ROM file using cli<commit_after>use std::env;
use std::fs;
use std::io::Read;
use std::path::Path;

fn main() {
    if let Some(rom_file_name) = env::args().nth(1) {
        println!("ROM: {}", rom_file_name);
        if let Some(rom) = read_rom(rom_file_name) {
            println!("{:?}", rom);
            return;
        } else {
            println!("Could not read ROM file!");
        }
    }

    println!("Usage: chip8 <rom>");
}

fn read_rom<P: AsRef<Path>>(path: P) -> Option<Vec<u8>> {
    match fs::File::open(path) {
        Ok(mut file) => {
            let mut file_buffer = Vec::new();
            match file.read_to_end(&mut file_buffer) {
                Ok(_) => Some(file_buffer),
                Err(ex) => {
                    println!("Could not read from file: {}", ex);
                    None
                }
            }
        }
        Err(ex) => {
            println!("Could not open file: {}", ex);
            None
        }
    }
}
<|endoftext|>


<commit_before>
extern crate chrono;
extern crate docopt;
extern crate riemann_client;

use riemann_client::Client;
use riemann_client::proto::Event;

use std::process::Command;

use std::io::prelude::*;
use std::net::TcpStream;

use docopt::Docopt;

use std::str::FromStr;

// Write the Docopt usage string. dfrites ?
static USAGE: &'static str = "
Usage: durite -l HOSTNAME [-g GHOSTNAME [-p PORT]] [-r RHOSTNAME [-o RPORT]]
       durite (--help | -h)

Options:
    -h, --help          Show this screen.
    -l HOSTNAME         Hostname to advertise.
    -g GHOSTNAME        Graphite Hostname.
    -r RHOSTNAME        Riemann Hostname.
    -o RPORT            Riemann port [default: 5555]
    -p PORT             Graphite port [default: 2003]
";

#[cfg(not(any(target_os="macos")))]
fn disk_free() -> std::process::Output {
	Command::new("df")
		.arg("--portability").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) })
}

#[cfg(any(target_os="macos"))]
fn disk_free() -> std::process::Output {
	Command::new("df")
		.arg("-k").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) })
}

fn send_content(stream: &mut std::net::TcpStream, hostname: &str, probe_and_value: String, timestamp: i64) {
	let content = format!("durite.{}.{} {}\n", hostname, probe_and_value, timestamp);
	let _ = stream.write(&content.as_bytes());
}

fn main() {

	// Parse argv and exit the program with an error message if it fails.
	let args = Docopt::new(USAGE)
		.and_then(|d| d.argv(std::env::args().into_iter()).parse())
		.unwrap_or_else(|e| e.exit());

    let graphite_connect_string: Option<String> = if args.get_str("-g") != "" {
        Some(format!("{}:{}", args.get_str("-g"), args.get_str("-p")))
    } else {
        None
    };

    let mut riemann_connection: Option<Client> = if args.get_str("-r") != "" {
        match Client::connect(&(args.get_str("-r"), u16::from_str(args.get_str("-o")).unwrap())) {
            Ok(c) => Some(c),
            Err(e) => {println!("Oups: {:?}", e); None}
        }
    } else {
        None
    };

    println!("Connect string is {:?}", graphite_connect_string);
    let my_hostname = args.get_str("-l");

	while true {
	    let dt = chrono::UTC::now();
	    let timestamp = dt.timestamp();
	    let o = disk_free();
		let stdout = String::from_utf8(o.stdout).
			ok().
			unwrap();

		let lines = stdout.split("\n");

        for line in lines {
            if line.starts_with("/") {
                let values: Vec<&str> = line.split(" ").filter(|e| {
                    e.len() != 0
                }).collect();

                let disk = values[0];
                // du reports kbytes
                let all: u64 = u64::from_str(values[1]).unwrap() / 1024;
                let available: u64 = u64::from_str(values[3]).unwrap() / 1024;
                if values.len() > 8 {
                }
                // let w = values[8].to_string();
                // let mut st: StatFs = Default::default();
                // let mp = CString::new(w.into_bytes()).unwrap();
                // unsafe {
                //  let o = statfs(mp.as_ptr(), &mut st);
                //  println!("o{} {:?}", o, st.f_bfree);
                // }

                // {:6E} 6 digit, lower exponential format

                match graphite_connect_string {
                    Some(ref connect_string) => {
                        let cs: &str = connect_string.as_ref();
                        match TcpStream::connect(cs) {
                            Ok(mut stream) => {
                                send_content(&mut stream, my_hostname, format!("{}.available {:3.3}", disk, available), timestamp);
                                send_content(&mut stream, my_hostname, format!("{}.all {}", disk, all), timestamp);
                            },
                            Err(e) => println!("Unable to connect to {}: {:?}\nIgnoring this data point.", connect_string, e)
                        }
                    },
                    None => {}
                }
                match riemann_connection {
                    Some(ref mut client) => {
                        client.event({
                                let mut event = Event::new();
                                event.set_service(format!("durite {} disk {} percent used", my_hostname, disk).to_string());
                                let percent_used: u64 = 100 - 100*(available/all);
                                event.set_metric_d(percent_used as f64 / 100 as f64);
                                event
                            }).unwrap();
                    },
                    None => {}
                }
            }
        }
	 	std::thread::sleep_ms(10000);
	}
}
<commit_msg>Integer arithmetic<commit_after>
extern crate chrono;
extern crate docopt;
extern crate riemann_client;

use riemann_client::Client;
use riemann_client::proto::Event;

use std::process::Command;

use std::io::prelude::*;
use std::net::TcpStream;

use docopt::Docopt;

use std::str::FromStr;

// Write the Docopt usage string. dfrites ?
static USAGE: &'static str = "
Usage: durite -l HOSTNAME [-g GHOSTNAME [-p PORT]] [-r RHOSTNAME [-o RPORT]]
       durite (--help | -h)

Options:
    -h, --help          Show this screen.
    -l HOSTNAME         Hostname to advertise.
    -g GHOSTNAME        Graphite Hostname.
    -r RHOSTNAME        Riemann Hostname.
    -o RPORT            Riemann port [default: 5555]
    -p PORT             Graphite port [default: 2003]
";

#[cfg(not(any(target_os="macos")))]
fn disk_free() -> std::process::Output {
	Command::new("df")
		.arg("--portability").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) })
}

#[cfg(any(target_os="macos"))]
fn disk_free() -> std::process::Output {
	Command::new("df")
		.arg("-k").output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) })
}

fn send_content(stream: &mut std::net::TcpStream, hostname: &str, probe_and_value: String, timestamp: i64) {
	let content = format!("durite.{}.{} {}\n", hostname, probe_and_value, timestamp);
	let _ = stream.write(&content.as_bytes());
}

fn main() {

	// Parse argv and exit the program with an error message if it fails.
	let args = Docopt::new(USAGE)
		.and_then(|d| d.argv(std::env::args().into_iter()).parse())
		.unwrap_or_else(|e| e.exit());

    let graphite_connect_string: Option<String> = if args.get_str("-g") != "" {
        Some(format!("{}:{}", args.get_str("-g"), args.get_str("-p")))
    } else {
        None
    };

    let mut riemann_connection: Option<Client> = if args.get_str("-r") != "" {
        match Client::connect(&(args.get_str("-r"), u16::from_str(args.get_str("-o")).unwrap())) {
            Ok(c) => Some(c),
            Err(e) => {println!("Oups: {:?}", e); None}
        }
    } else {
        None
    };

    println!("Connect string is {:?}", graphite_connect_string);
    let my_hostname = args.get_str("-l");

	while true {
	    let dt = chrono::UTC::now();
	    let timestamp = dt.timestamp();
	    let o = disk_free();
		let stdout = String::from_utf8(o.stdout).
			ok().
			unwrap();

		let lines = stdout.split("\n");

        for line in lines {
            if line.starts_with("/") {
                let values: Vec<&str> = line.split(" ").filter(|e| {
                    e.len() != 0
                }).collect();

                let disk = values[0];
                // du reports kbytes
                let all: u64 = u64::from_str(values[1]).unwrap() / 1024;
                let available: u64 = u64::from_str(values[3]).unwrap() / 1024;
                if values.len() > 8 {
                }
                // let w = values[8].to_string();
                // let mut st: StatFs = Default::default();
                // let mp = CString::new(w.into_bytes()).unwrap();
                // unsafe {
                //  let o = statfs(mp.as_ptr(), &mut st);
                //  println!("o{} {:?}", o, st.f_bfree);
                // }

                // {:6E} 6 digit, lower exponential format

                match graphite_connect_string {
                    Some(ref connect_string) => {
                        let cs: &str = connect_string.as_ref();
                        match TcpStream::connect(cs) {
                            Ok(mut stream) => {
                                send_content(&mut stream, my_hostname, format!("{}.available {:3.3}", disk, available), timestamp);
                                send_content(&mut stream, my_hostname, format!("{}.all {}", disk, all), timestamp);
                            },
                            Err(e) => println!("Unable to connect to {}: {:?}\nIgnoring this data point.", connect_string, e)
                        }
                    },
                    None => {}
                }
                match riemann_connection {
                    Some(ref mut client) => {
                        client.event({
                                let mut event = Event::new();
                                event.set_service(format!("durite {} disk {} percent used", my_hostname, disk).to_string());
                                let percent_used: u64 = 100 - (available *100)/(all * 100);
                                event.set_metric_d(percent_used as f64 / 100 as f64);
                                event
                            }).unwrap();
                    },
                    None => {}
                }
            }
        }
	 	std::thread::sleep_ms(10000);
	}
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate nom;

use std::str;
use nom::{
    IResult,
    ErrorKind,
    is_hex_digit
};

fn is_pn_chars_base(c: char) -> bool {
    let u = c as u32;
    match u {
        0x41    ... 0x5A   | 0x61   ... 0x7A   |
        0xC0    ... 0xD6   | 0xD8   ... 0xF6   |
        0xF8    ... 0x2FF  | 0x370  ... 0x37D  |
        0x37F   ... 0x1FFF | 0x200C ... 0x200D |
        0x2C00  ... 0x2FEF | 0x3001 ... 0xD7FF |
        0xF900  ... 0xFDCF | 0xFDF0 ... 0xFFFD |
        0x10000 ... 0xEFFFF
          => true,
        _ => false,
    }
}
fn is_pn_chars_u(c: char) -> bool {
    is_pn_chars_base(c) || c == '_'
}
fn is_pn_chars(c: char) -> bool {
    let u = c as u32;
    match u {
        0x2d | 0xB7 | 0x30...0x39 | 0x300...0x36F | 0x203F...0x2040
          => true,
        _ => is_pn_chars_base(c),
    }
}
fn is_pn_local_esc(c: char) -> bool {
    match "_~.-!$&'()*+,;=/?#@%".find(c) {
        Some(_) => true,
        _       => false,
    }
}

/* [163s] PN_CHARS_BASE */
named!(pn_chars_base<&str, &str>, verify!(
    take_s!(1),
    |val:&str| {
        if let Some(c) = val.chars().next() {
            return is_pn_chars_base(c)
        }
        false
    }
));

/* [164s] PN_CHARS_U */
named!(pn_chars_u<&str, &str>, verify!(
    take_s!(1),
    |val:&str| {
        if let Some(c) = val.chars().next() {
            return is_pn_chars_u(c)
        }
        false
    }
));

/* [166s] PN_CHARS */
named!(pn_chars<&str, &str>, verify!(
    take_s!(1),
    |val:&str| {
        if let Some(c) = val.chars().next() {
            return is_pn_chars(c)
        }
        false
    }
));

/* [167s] PN_PREFIX */
named!(pn_prefix<&str, &str>, do_parse!(
    base:  pn_chars_base    >>
    chars: many0!(
        alt!(pn_chars)
    ) >>
    colon: verify!(take_s!(1), |val:&str| val == ":") >>
    (base) // TODO: Fix me
));

/* [169s] PLX */
named!(plx<&str, &str>, alt!(percent | pn_local_esc));

/* [170s] PERCENT */
named!(percent<&str, &str>, verify!(
    take_s!(3),
    |val:&str| {
        let bytes = val.as_bytes();
        bytes[0] == 0x25 && is_hex_digit(bytes[1]) && is_hex_digit(bytes[2])
    }
));

/* [172s]  PN_LOCAL_ESC */
named!(pn_local_esc<&str, &str>, verify!(
    take_s!(2),
    |val:&str| {
        let c1 = val.chars().nth(0).unwrap();
        let c2 = val.chars().nth(1).unwrap();
        c1 == '\\' && is_pn_local_esc(c2)
    }
));

fn main() {
    assert_eq!(pn_chars_base("a%2Ab")  , IResult::Done("%2Ab" , "a")      );
    assert_eq!(pn_chars_u("_a")        , IResult::Done("a"    , "_")      );
    assert_eq!(pn_chars("-_a")         , IResult::Done("_a"   , "-")      );
    assert_eq!(pn_chars(":a2Ab")       , IResult::Error(ErrorKind::Verify));
    assert_eq!(plx("%2Abc")            , IResult::Done("bc"   , "%2A")    );
    assert_eq!(plx("\\.%2A")           , IResult::Done("%2A"  , "\\.")    );
    assert_eq!(percent("%2Abc")        , IResult::Done("bc"   , "%2A")    );
    assert_eq!(pn_local_esc("\\.a b c"), IResult::Done("a b c", "\\.")    );
}
<commit_msg>Implement PN_PREFIX<commit_after>#[macro_use]
extern crate nom;

use std::str;
use nom::{
    IResult,
    ErrorKind,
    is_hex_digit
};

fn is_pn_chars_base(c: char) -> bool {
    let u = c as u32;
    match u {
        0x41    ... 0x5A   | 0x61   ... 0x7A   |
        0xC0    ... 0xD6   | 0xD8   ... 0xF6   |
        0xF8    ... 0x2FF  | 0x370  ... 0x37D  |
        0x37F   ... 0x1FFF | 0x200C ... 0x200D |
        0x2C00  ... 0x2FEF | 0x3001 ... 0xD7FF |
        0xF900  ... 0xFDCF | 0xFDF0 ... 0xFFFD |
        0x10000 ... 0xEFFFF
          => true,
        _ => false,
    }
}
fn is_pn_chars_u(c: char) -> bool {
    is_pn_chars_base(c) || c == '_'
}
fn is_pn_chars(c: char) -> bool {
    let u = c as u32;
    match u {
        0x2d | 0xB7 | 0x30...0x39 | 0x300...0x36F | 0x203F...0x2040
          => true,
        _ => is_pn_chars_base(c),
    }
}
fn is_pn_local_esc(c: char) -> bool {
    match "_~.-!$&'()*+,;=/?#@%".find(c) {
        Some(_) => true,
        _       => false,
    }
}

/* [163s] PN_CHARS_BASE */
named!(pn_chars_base<&str, &str>, verify!(
    take_s!(1),
    |val:&str| {
        if let Some(c) = val.chars().next() {
            return is_pn_chars_base(c)
        }
        false
    }
));

/* [164s] PN_CHARS_U */
named!(pn_chars_u<&str, &str>, verify!(
    take_s!(1),
    |val:&str| {
        if let Some(c) = val.chars().next() {
            return is_pn_chars_u(c)
        }
        false
    }
));

/* [166s] PN_CHARS */
named!(pn_chars<&str, &str>, verify!(
    take_s!(1),
    |val:&str| {
        if let Some(c) = val.chars().next() {
            return is_pn_chars(c)
        }
        false
    }
));

/* [167s] PN_PREFIX */
named!(pn_prefix<&str, &str>, verify!(
    take_until!(":"),
    |val:&str| {
        let len = val.char_indices().count();
        val.char_indices().all(|(idx, c)| {
            if idx == 0 {
                is_pn_chars_base(c)
            } else if idx == len - 1 {
                c != '.'
            } else {
                is_pn_chars(c) || c == '.'
            }
        })
    }
));

/* [169s] PLX */
named!(plx<&str, &str>, alt!(percent | pn_local_esc));

/* [170s] PERCENT */
named!(percent<&str, &str>, verify!(
    take_s!(3),
    |val:&str| {
        let bytes = val.as_bytes();
        bytes[0] == 0x25 && is_hex_digit(bytes[1]) && is_hex_digit(bytes[2])
    }
));

/* [172s]  PN_LOCAL_ESC */
named!(pn_local_esc<&str, &str>, verify!(
    take_s!(2),
    |val:&str| {
        let c1 = val.chars().nth(0).unwrap();
        let c2 = val.chars().nth(1).unwrap();
        c1 == '\\' && is_pn_local_esc(c2)
    }
));

fn main() {
    assert_eq!(pn_chars_base("a%2Ab")  , IResult::Done("%2Ab" , "a")      );
    assert_eq!(pn_chars_u("_a")        , IResult::Done("a"    , "_")      );
    assert_eq!(pn_chars("-_a")         , IResult::Done("_a"   , "-")      );
    assert_eq!(pn_chars(":a2Ab")       , IResult::Error(ErrorKind::Verify));
    assert_eq!(pn_prefix("hog.e:")     , IResult::Done(":"    , "hog.e")  );
    assert_eq!(pn_prefix("hoge.:")     , IResult::Error(ErrorKind::Verify));
    assert_eq!(plx("%2Abc")            , IResult::Done("bc"   , "%2A")    );
    assert_eq!(plx("\\.%2A")           , IResult::Done("%2A"  , "\\.")    );
    assert_eq!(percent("%2Abc")        , IResult::Done("bc"   , "%2A")    );
    assert_eq!(pn_local_esc("\\.a b c"), IResult::Done("a b c", "\\.")    );
}
<|endoftext|>


<commit_before>extern crate curl;
extern crate env_logger;
extern crate futures;
extern crate tokio_core;
extern crate tokio_curl;
extern crate threadpool;
#[macro_use]
extern crate clap;

mod args;

use args::{Config, parse_args};

use curl::easy::Easy;
use futures::{Future, lazy};
use futures::future::{ok, join_all};
use tokio_core::reactor::Core;
use tokio_curl::{Perform, Session};
use std::rc::Rc;
use std::cell::RefCell;
use threadpool::ThreadPool;
use std::sync::mpsc::channel;

struct Worker {
    event_loop: Rc<RefCell<Core>>,
}

impl Worker {
    pub fn new(event_loop: Rc<RefCell<Core>>) -> Self {
        Worker { event_loop: event_loop }
    }

    pub fn send_request(&self, url: String) -> Perform {
        let lp = self.event_loop.borrow();

        let session = Session::new(lp.handle());
        let mut a = Easy::new();
        a.get(true).unwrap();
        a.url(&url).unwrap();
        a.write_function(|data| Ok(data.len())).unwrap();
        session.perform(a)
    }
}

/// Delegates and manages all the work.
struct Boss {
    /// Number of requests successfully completed
    pub requests_completed: usize,
    /// Number of active connections
    pub connections: usize,

    thread_pool: ThreadPool,
    num_threads: usize,
}

impl Boss {
    pub fn new(num_threads: usize) -> Self {
        Boss {
            requests_completed: 0,
            connections: 0,
            thread_pool: ThreadPool::new(num_threads),
            num_threads: num_threads,
        }
    }

    /// Should return a future
    pub fn start_workforce(&self, desired_connections: usize, url: String) {

        let jobs = desired_connections;
        let (tx, rx) = channel();
        for _ in 0..self.num_threads {
            let tx = tx.clone();
            let url = url.clone();
            self.thread_pool.execute(move || {
                let lp = Core::new().unwrap();
                let lp = Rc::new(RefCell::new(lp));

                let worker = Worker::new(lp.clone());
                let mut futures = Vec::new();
                for _ in 0..jobs {
                    let url = url.clone();
                    let future = worker.send_request(url)
                        .then(|x| {
                            tx.send(1).unwrap();
                            x
                        });
                    futures.push(future);
                }
                let future = join_all(futures);
                lp.borrow_mut().run(future).unwrap();
            });
        }

        let res = rx.iter().take(jobs * self.num_threads).fold(0, |a, b| a + b);
        println!("{}", res);
    }
}

fn start(config: Config) {
    let boss = Boss::new(config.num_threads);
    boss.start_workforce(config.num_connections, config.url)
}

fn main() {
    env_logger::init().unwrap();
    let config = parse_args();
    start(config);
}
<commit_msg>use barrier for sync<commit_after>extern crate curl;
extern crate env_logger;
extern crate futures;
extern crate tokio_core;
extern crate tokio_curl;
extern crate threadpool;
#[macro_use]
extern crate clap;

mod args;

use args::{Config, parse_args};

use curl::easy::Easy;
use futures::{Async, Future, lazy, Poll};
use futures::future::{ok, join_all};
use tokio_core::reactor::Core;
use tokio_curl::{Perform, PerformError, Session};
use std::rc::Rc;
use std::cell::RefCell;
use threadpool::ThreadPool;
use std::sync::{Arc, Barrier};

struct Worker {
    event_loop: Rc<RefCell<Core>>,
}

impl Worker {
    pub fn new(event_loop: Rc<RefCell<Core>>
) -> Self {
        Worker { event_loop: event_loop }
    }

    /// Schedule work, but do not actually run it.
    /// Instead, return a future.
    pub fn schedule_work(&self, url: String, num_connections: usize) ->
            Box<Future<Item = usize, Error = PerformError>> {
        let mut futures = Vec::new();
        for _ in 0..num_connections {
            let url = url.clone();
            let future = self.send_request(url)
                .then(|x| {
                    // tx.send(1).unwrap();
                    x
                });
            futures.push(future);
        }
        Box::new(join_all(futures).then(|x| x.map(|vec| vec.len())))
    }

    fn send_request(&self, url: String) -> Perform {
        let lp = self.event_loop.borrow();

        let session = Session::new(lp.handle());
        let mut a = Easy::new();
        a.get(true).unwrap();
        a.url(&url).unwrap();
        a.write_function(|data| Ok(data.len())).unwrap();
        session.perform(a)
    }
}

/// Delegates and manages all the work.
struct Boss {
    /// Number of requests successfully completed
    pub requests_completed: usize,
    /// Number of active connections
    pub connections: usize,

    thread_pool: ThreadPool,
    num_threads: usize,
}

impl Boss {
    pub fn new(num_threads: usize) -> Self {
        Boss {
            requests_completed: 0,
            connections: 0,
            thread_pool: ThreadPool::new(num_threads),
            num_threads: num_threads,
        }
    }

    /// Should return a future
    pub fn start_workforce(&self, desired_connections: usize, url: String) {

        let jobs = desired_connections;
        // let (tx, rx) = channel();
        // create a barrier that wait all jobs plus the starter thread
        let barrier = Arc::new(Barrier::new(self.num_threads + 1));
        for _ in 0..self.num_threads {
            let barrier = barrier.clone();
            // let tx = tx.clone();
            let url = url.clone();
            self.thread_pool.execute(move || {
                let lp = Core::new().unwrap();
                let lp = Rc::new(RefCell::new(lp));

                let worker = Worker::new(lp.clone());
                let future = worker.schedule_work(url, jobs);
                let res = lp.borrow_mut().run(future).unwrap();
                println!("{}", res);

                // then wait for the other threads
                barrier.wait();
            });
        }

        // let res = rx.iter().take(jobs * self.num_threads).fold(0, |a, b| a + b);
        // println!("{}", res);
        // wait for the threads to finish the work
        barrier.wait();
    }
}

fn start(config: Config) {
    let boss = Boss::new(config.num_threads);
    boss.start_workforce(config.num_connections, config.url)
}

fn main() {
    env_logger::init().unwrap();
    let config = parse_args();
    start(config);
}
<|endoftext|>


<commit_before>//! The main entry point for the SpaceAPi server.
//!
//! Running this code starts a HTTP server instance. The default port is 3000, but you can set your
//! own favorite port by exporting the `PORT` environment variable.

#![feature(box_syntax)]

extern crate spaceapi;
extern crate spaceapi_server;

use std::sync::{Mutex,Arc};

use std::net::Ipv4Addr;
use spaceapi::{Status, Location, Contact, Optional};
use spaceapi_server::SpaceapiServer;
use spaceapi_server::datastore::DataStore;
use spaceapi_server::redis_store::RedisStore;

fn main() {
    let host = Ipv4Addr::new(127, 0, 0, 1);

    // TODO: Create variables for all params
    let status = Status::new(
        "coredump".to_string(),
        "https://www.coredump.ch/logo.png".to_string(),
        "https://www.coredump.ch/".to_string(),
        Location {
            address: Optional::Value("Spinnereistrasse 2, 8640 Rapperswil, Switzerland".to_string()),
            lat: 47.22936,
            lon: 8.82949,
        },
        Contact {
            irc: Optional::Value("irc://freenode.net/#coredump".to_string()),
            twitter: Optional::Value("@coredump_ch".to_string()),
            foursquare: Optional::Value("525c20e5498e875d8231b1e5".to_string()),
            email: Optional::Value("danilo@coredump.ch".to_string()),
        },
        vec![
            "email".to_string(),
            "twitter".to_string(),
        ],
    );

    let datastore = Arc::new(Mutex::new( box RedisStore::new().unwrap() as Box<DataStore> ));
    let server = SpaceapiServer::new(host, status, datastore);
    server.serve();
}
<commit_msg>don't use box syntax<commit_after>//! The main entry point for the SpaceAPi server.
//!
//! Running this code starts a HTTP server instance. The default port is 3000, but you can set your
//! own favorite port by exporting the `PORT` environment variable.

extern crate spaceapi;
extern crate spaceapi_server;

use std::sync::{Mutex,Arc};

use std::net::Ipv4Addr;
use spaceapi::{Status, Location, Contact, Optional};
use spaceapi_server::SpaceapiServer;
use spaceapi_server::datastore::DataStore;
use spaceapi_server::redis_store::RedisStore;

fn main() {
    let host = Ipv4Addr::new(127, 0, 0, 1);

    // TODO: Create variables for all params
    let status = Status::new(
        "coredump".to_string(),
        "https://www.coredump.ch/logo.png".to_string(),
        "https://www.coredump.ch/".to_string(),
        Location {
            address: Optional::Value("Spinnereistrasse 2, 8640 Rapperswil, Switzerland".to_string()),
            lat: 47.22936,
            lon: 8.82949,
        },
        Contact {
            irc: Optional::Value("irc://freenode.net/#coredump".to_string()),
            twitter: Optional::Value("@coredump_ch".to_string()),
            foursquare: Optional::Value("525c20e5498e875d8231b1e5".to_string()),
            email: Optional::Value("danilo@coredump.ch".to_string()),
        },
        vec![
            "email".to_string(),
            "twitter".to_string(),
        ],
    );

    let datastore = Arc::new(Mutex::new( Box::new( RedisStore::new().unwrap()) as Box<DataStore> ));
    let server = SpaceapiServer::new(host, status, datastore);
    server.serve();
}
<|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 file = try!(fs::File::open(filename));
    let mut reader = io::BufReader::new(file);
    let mut buffer = Vec::new();
    try!(reader.read_to_end(&mut buffer));
    Ok(buffer)
}
<commit_msg>style: properly use Result.map in read_file<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(|file| io::BufReader::new(file))
        .and_then(|mut reader| reader.read_to_end(&mut buffer))
        .map(|_| buffer)
}
<|endoftext|>


<commit_before>#![allow(non_snake_case)]

extern crate gl;
extern crate glutin;
extern crate winapi;

use glutin::GlContext;
use glutin::os::windows::WindowExt;
use std::ops::Deref;
use std::os::raw::c_void;
use std::ptr;
use winapi::Interface;
use winapi::shared::dxgi::IDXGIDevice;
use winapi::shared::minwindef::TRUE;
use winapi::shared::winerror::HRESULT;
use winapi::shared::winerror::SUCCEEDED;
use winapi::shared::windef::HWND;
use winapi::um::d3d11::D3D11_CREATE_DEVICE_BGRA_SUPPORT;
use winapi::um::d3d11::D3D11_SDK_VERSION;
use winapi::um::d3d11::D3D11CreateDevice;
use winapi::um::d3dcommon::D3D_DRIVER_TYPE_HARDWARE;
use winapi::um::dcomp::IDCompositionDevice;
use winapi::um::dcomp::DCompositionCreateDevice;
use winapi::um::unknwnbase::IUnknown;

fn main() {
    let mut events_loop = glutin::EventsLoop::new();
    let window = glutin::WindowBuilder::new()
        .with_title("Hello, world!")
        .with_dimensions(1024, 768);
    let context = glutin::ContextBuilder::new()
        .with_vsync(true);
    let gl_window = glutin::GlWindow::new(window, context, &events_loop).unwrap();

    unsafe {
        gl_window.make_current().unwrap();
    }

    unsafe {
        gl::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _);
        gl::ClearColor(0.0, 1.0, 0.0, 1.0);

        initialize_direct_composition_device(gl_window.window().get_hwnd() as _).unwrap();
    }

//    let mut running = true;
    let mut running = false;
    while running {
        events_loop.poll_events(|event| {
            match event {
                glutin::Event::WindowEvent{ event, .. } => match event {
                    glutin::WindowEvent::Closed => running = false,
                    glutin::WindowEvent::Resized(w, h) => gl_window.resize(w, h),
                    _ => ()
                },
                _ => ()
            }
        });

        unsafe {
            gl::Clear(gl::COLOR_BUFFER_BIT);
        }

        gl_window.swap_buffers().unwrap();
    }
    println!("Ok")
}

trait ToResult: Sized {
    fn to_result(self) -> Result<(), Self>;
}

impl ToResult for HRESULT {
    fn to_result(self) -> Result<(), Self> {
        if SUCCEEDED(self) {
            Ok(())
        } else {
            Err(self)
        }
    }
}

fn as_void<T>(p: *mut *mut T) -> *mut *mut c_void {
    p as _
}

unsafe fn query_interface<T, U>(p: *mut T) -> Result<*mut U, HRESULT>
    where T: Deref<Target=IUnknown>, U: Interface
{
    let mut ret = ptr::null_mut();
    (*p).QueryInterface(&U::uuidof(), as_void(&mut ret)).to_result()?;
    Ok(ret)
}

/// https://msdn.microsoft.com/en-us/library/windows/desktop/hh449180(v=vs.85).aspx

unsafe fn initialize_direct_composition_device(m_hwnd: HWND) -> Result<(), HRESULT> {
    let mut m_pD3D11Device = ptr::null_mut();
    let mut featureLevelSupported = 0;

    // Create the D3D device object. The D3D11_CREATE_DEVICE_BGRA_SUPPORT
    // flag enables rendering on surfaces using Direct2D.
    D3D11CreateDevice(
        ptr::null_mut(),
        D3D_DRIVER_TYPE_HARDWARE,
        ptr::null_mut(),
        D3D11_CREATE_DEVICE_BGRA_SUPPORT,
        ptr::null_mut(),
        0,
        D3D11_SDK_VERSION,
        &mut m_pD3D11Device,
        &mut featureLevelSupported,
        ptr::null_mut(),
    ).to_result()?;

    // Create the DXGI device used to create bitmap surfaces.
    let pDXGIDevice: *mut IDXGIDevice = query_interface(m_pD3D11Device)?;

    // Create the DirectComposition device object.
    let mut m_pDCompDevice: *mut IDCompositionDevice = ptr::null_mut();
    DCompositionCreateDevice(
        pDXGIDevice, &IDCompositionDevice::uuidof(), as_void(&mut m_pDCompDevice),
    ).to_result()?;

    // Create the composition target object based on the
    // specified application window.
    let mut m_pDCompTarget = ptr::null_mut();
    (*m_pDCompDevice).CreateTargetForHwnd(m_hwnd, TRUE, &mut m_pDCompTarget).to_result()?;

    // FIXME: make/use a type with a destructor, so that this runs even in case of early return
    (*pDXGIDevice).Release();

    Ok(())
}
<commit_msg>Return these pointers we so arduously obtained<commit_after>#![allow(non_snake_case)]

extern crate gl;
extern crate glutin;
extern crate winapi;

use glutin::GlContext;
use glutin::os::windows::WindowExt;
use std::ops::Deref;
use std::os::raw::c_void;
use std::ptr;
use winapi::Interface;
use winapi::shared::dxgi::IDXGIDevice;
use winapi::shared::minwindef::TRUE;
use winapi::shared::winerror::HRESULT;
use winapi::shared::winerror::SUCCEEDED;
use winapi::shared::windef::HWND;
use winapi::um::d3d11::D3D11_CREATE_DEVICE_BGRA_SUPPORT;
use winapi::um::d3d11::D3D11_SDK_VERSION;
use winapi::um::d3d11::D3D11CreateDevice;
use winapi::um::d3d11::ID3D11Device;
use winapi::um::d3dcommon::D3D_DRIVER_TYPE_HARDWARE;
use winapi::um::dcomp::IDCompositionDevice;
use winapi::um::dcomp::IDCompositionTarget;
use winapi::um::dcomp::DCompositionCreateDevice;
use winapi::um::unknwnbase::IUnknown;

fn main() {
    let mut events_loop = glutin::EventsLoop::new();
    let window = glutin::WindowBuilder::new()
        .with_title("Hello, world!")
        .with_dimensions(1024, 768);
    let context = glutin::ContextBuilder::new()
        .with_vsync(true);
    let gl_window = glutin::GlWindow::new(window, context, &events_loop).unwrap();

    unsafe {
        gl_window.make_current().unwrap();
    }

    unsafe {
        gl::load_with(|symbol| gl_window.get_proc_address(symbol) as *const _);
        gl::ClearColor(0.0, 1.0, 0.0, 1.0);

        initialize_direct_composition_device(gl_window.window().get_hwnd() as _).unwrap();
    }

//    let mut running = true;
    let mut running = false;
    while running {
        events_loop.poll_events(|event| {
            match event {
                glutin::Event::WindowEvent{ event, .. } => match event {
                    glutin::WindowEvent::Closed => running = false,
                    glutin::WindowEvent::Resized(w, h) => gl_window.resize(w, h),
                    _ => ()
                },
                _ => ()
            }
        });

        unsafe {
            gl::Clear(gl::COLOR_BUFFER_BIT);
        }

        gl_window.swap_buffers().unwrap();
    }
    println!("Ok")
}

trait ToResult: Sized {
    fn to_result(self) -> Result<(), Self>;
}

impl ToResult for HRESULT {
    fn to_result(self) -> Result<(), Self> {
        if SUCCEEDED(self) {
            Ok(())
        } else {
            Err(self)
        }
    }
}

fn as_void<T>(p: *mut *mut T) -> *mut *mut c_void {
    p as _
}

unsafe fn query_interface<T, U>(p: *mut T) -> Result<*mut U, HRESULT>
    where T: Deref<Target=IUnknown>, U: Interface
{
    let mut ret = ptr::null_mut();
    (*p).QueryInterface(&U::uuidof(), as_void(&mut ret)).to_result()?;
    Ok(ret)
}

/// https://msdn.microsoft.com/en-us/library/windows/desktop/hh449180(v=vs.85).aspx

unsafe fn initialize_direct_composition_device(m_hwnd: HWND)
    -> Result<(*mut ID3D11Device, *mut IDCompositionDevice, *mut IDCompositionTarget), HRESULT>
{
    let mut m_pD3D11Device = ptr::null_mut();
    let mut featureLevelSupported = 0;

    // Create the D3D device object. The D3D11_CREATE_DEVICE_BGRA_SUPPORT
    // flag enables rendering on surfaces using Direct2D.
    D3D11CreateDevice(
        ptr::null_mut(),
        D3D_DRIVER_TYPE_HARDWARE,
        ptr::null_mut(),
        D3D11_CREATE_DEVICE_BGRA_SUPPORT,
        ptr::null_mut(),
        0,
        D3D11_SDK_VERSION,
        &mut m_pD3D11Device,
        &mut featureLevelSupported,
        ptr::null_mut(),
    ).to_result()?;

    // Create the DXGI device used to create bitmap surfaces.
    let pDXGIDevice: *mut IDXGIDevice = query_interface(m_pD3D11Device)?;

    // Create the DirectComposition device object.
    let mut m_pDCompDevice: *mut IDCompositionDevice = ptr::null_mut();
    DCompositionCreateDevice(
        pDXGIDevice, &IDCompositionDevice::uuidof(), as_void(&mut m_pDCompDevice),
    ).to_result()?;

    // Create the composition target object based on the
    // specified application window.
    let mut m_pDCompTarget = ptr::null_mut();
    (*m_pDCompDevice).CreateTargetForHwnd(m_hwnd, TRUE, &mut m_pDCompTarget).to_result()?;

    // FIXME: make/use a type with a destructor, so that this runs even in case of early return
    (*pDXGIDevice).Release();

    Ok((m_pD3D11Device, m_pDCompDevice, m_pDCompTarget))
}
<|endoftext|>


<commit_before>extern crate getopts;
use getopts::{optopt, optflag, OptGroup};
use std::os;

use device_info::{DefaultDevice, DefaultInterface, UserDefinedDevice, UserDefinedName, DeviceInfo};
mod device_info;

enum ParseArgsResult {
    HelpRequested,
    DevicesObtained(DeviceInfo),
    CommandLineError(getopts::Fail_)
}

// Returns either a Devices struct filled either with the default values, or None if the help option is present
fn parse_args(opts: &[OptGroup], args: &[String]) -> ParseArgsResult {
    match getopts::getopts(args, opts) {
        Err(e) => CommandLineError(e),

        Ok(options) => {
            if options.opt_present("h") {
                HelpRequested
            } else {
                DevicesObtained(DeviceInfo::new(match options.opt_str("d") {
                                                    Some(s) => UserDefinedDevice(s),
                                                    None => DefaultDevice
                                                },
                                                match options.opt_str("i") {
                                                    Some(s) => UserDefinedName(s),
                                                    None => DefaultInterface,
                                                }))
            }
        }
    }
}

fn main() {
    println!("Hello, world!")
}
<commit_msg>Add some simple wrapper code<commit_after>extern crate getopts;
use getopts::{optopt, optflag, OptGroup};
use std::os;

use device_info::{DefaultDevice, DefaultInterface, UserDefinedDevice, UserDefinedName, DeviceInfo};
mod device_info;

enum ParseArgsResult {
    HelpRequested,
    DevicesObtained(DeviceInfo),
    CommandLineError(getopts::Fail_)
}

// Returns either a Devices struct filled either with the default values, or None if the help option is present
fn parse_args(opts: &[OptGroup], args: &[String]) -> ParseArgsResult {
    match getopts::getopts(args, opts) {
        Err(e) => CommandLineError(e),

        Ok(options) => {
            if options.opt_present("h") {
                HelpRequested
            } else {
                DevicesObtained(DeviceInfo::new(match options.opt_str("d") {
                                                    Some(s) => UserDefinedDevice(s),
                                                    None => DefaultDevice
                                                },
                                                match options.opt_str("i") {
                                                    Some(s) => UserDefinedName(s),
                                                    None => DefaultInterface,
                                                }))
            }
        }
    }
}

fn main() {
    let opts = [
        optopt("d", "device", "set the cloning device", "<cloning device>"),
        optflag("h", "help", "print this help"),
        optopt("i", "interface", "set the interface name", "<interface name>")
    ];

    let args = os::args();
    let prog_name = args[0].as_slice();

    match parse_args(opts, args.as_slice()) {
        HelpRequested => {
            println!("{}", getopts::usage(format!("{}: A virtual ethernet device creator", prog_name).as_slice(), opts));
        },

        CommandLineError(e) => {
            println!("{}", e);
        },

        DevicesObtained(d) => {
            println!("Selected {}", d);
        }
    };
}
<|endoftext|>


<commit_before>extern crate iron;
extern crate router;

use std::io::Read;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;

use iron::prelude::*;
use iron::status;
use router::Router;

#[derive(Debug)]
struct Index;

impl Index {
    fn new() -> Index {
        Index
    }
}

fn index_not_found_response() -> Response {
    let mut response = Response::with((status::NotFound, "{\"message\": \"Index not found\"}"));
    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
    return response;
}

fn main() {
    let mut indices = Arc::new(Mutex::new(HashMap::new()));
    indices.lock().unwrap().insert("wagtail", Index::new());

    let mut router = Router::new();

    router.get("/", |_: &mut Request| -> IronResult<Response> {
        Ok(Response::with((status::Ok, "Hello World!")))
    });

    {
        let indices = indices.clone();

        router.get("/:index/_count", move |req: &mut Request| -> IronResult<Response> {
            let ref index = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            if !indices.lock().unwrap().contains_key(index) {
                return Ok(index_not_found_response());
            }

            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            // TODO

            let mut response = Response::with((status::Ok, "{\"count\": 0}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.get("/:index/_search", move |req: &mut Request| -> IronResult<Response> {
            let ref index = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            if !indices.lock().unwrap().contains_key(index) {
                return Ok(index_not_found_response());
            }

            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            // TODO

            let mut response = Response::with((status::Ok, "{\"hits\": {\"total\": 0, \"hits\": []}}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.put("/:index/:mapping/:doc", move |req: &mut Request| -> IronResult<Response> {
            let ref index = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            if !indices.lock().unwrap().contains_key(index) {
                return Ok(index_not_found_response());
            }

            let ref mapping = req.extensions.get::<Router>().unwrap().find("mapping").unwrap_or("");
            let ref doc = req.extensions.get::<Router>().unwrap().find("doc").unwrap_or("");

            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            // TODO

            let mut response = Response::with((status::Ok, "{}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    Iron::new(router).http("localhost:9200").unwrap();
}
<commit_msg>Added Mapping struct<commit_after>extern crate iron;
extern crate router;

use std::io::Read;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;

use iron::prelude::*;
use iron::status;
use router::Router;

#[derive(Debug)]
struct Mapping;

impl Mapping {
    fn new() -> Mapping {
        Mapping
    }
}

#[derive(Debug)]
struct Index {
    pub mappings: HashMap<&'static str, Mapping>,
}

impl Index {
    fn new() -> Index {
        Index{
            mappings: HashMap::new(),
        }
    }
}

fn index_not_found_response() -> Response {
    let mut response = Response::with((status::NotFound, "{\"message\": \"Index not found\"}"));
    response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
    return response;
}

fn main() {
    let mut indices = Arc::new(Mutex::new(HashMap::new()));
    let mut wagtail_index = Index::new();
    wagtail_index.mappings.insert("wagtaildocs_document", Mapping::new());
    indices.lock().unwrap().insert("wagtail", wagtail_index);

    let mut router = Router::new();

    router.get("/", |_: &mut Request| -> IronResult<Response> {
        Ok(Response::with((status::Ok, "Hello World!")))
    });

    {
        let indices = indices.clone();

        router.get("/:index/_count", move |req: &mut Request| -> IronResult<Response> {
            let ref index = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            if !indices.lock().unwrap().contains_key(index) {
                return Ok(index_not_found_response());
            }

            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            // TODO

            let mut response = Response::with((status::Ok, "{\"count\": 0}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.get("/:index/_search", move |req: &mut Request| -> IronResult<Response> {
            let ref index = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            if !indices.lock().unwrap().contains_key(index) {
                return Ok(index_not_found_response());
            }

            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            // TODO

            let mut response = Response::with((status::Ok, "{\"hits\": {\"total\": 0, \"hits\": []}}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    {
        let indices = indices.clone();

        router.put("/:index/:mapping/:doc", move |req: &mut Request| -> IronResult<Response> {
            let ref index = req.extensions.get::<Router>().unwrap().find("index").unwrap_or("");
            if !indices.lock().unwrap().contains_key(index) {
                return Ok(index_not_found_response());
            }

            let ref mapping = req.extensions.get::<Router>().unwrap().find("mapping").unwrap_or("");
            if !indices.lock().unwrap().get(index).unwrap().mappings.contains_key(mapping) {
                let mut response = Response::with((status::NotFound, "{\"message\": \"Mapping not found\"}"));
                response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
                return Ok(response);
            }

            let ref doc = req.extensions.get::<Router>().unwrap().find("doc").unwrap_or("");

            let mut payload = String::new();
            req.body.read_to_string(&mut payload).unwrap();

            // TODO

            let mut response = Response::with((status::Ok, "{}"));
            response.headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);
            Ok(response)
        });
    }

    Iron::new(router).http("localhost:9200").unwrap();
}
<|endoftext|>


<commit_before>extern crate env_logger;
#[macro_use]
extern crate hyper;
extern crate serde;
extern crate serde_json;

use std::env;
use std::io::Read;

use hyper::Client;
use hyper::header::Connection;

use serde_json::value::*;

header! { (XAuthKey, "X-Auth-Key") => [String] }
header! { (XAuthEmail, "X-Auth-Email") => [String] }

// TODO(colemickens): none of the implementations handle paging properly

fn main() {
    env_logger::init().unwrap();

    let cloudflare_apikey = env::var("CLOUDFLARE_APIKEY").expect("missing apikey");
    let cloudflare_email = env::var("CLOUDFLARE_EMAIL").expect("missing email");

    let zones_url = "https://api.cloudflare.com/client/v4/zones";

    let client = Client::new();

    let mut auth_headers = hyper::header::Headers::new();

    auth_headers.set(XAuthKey(cloudflare_apikey.to_owned()));
    auth_headers.set(XAuthEmail(cloudflare_email.to_owned()));

    let res = client
        .get(zones_url)
        .header(Connection::close())
        .headers(auth_headers)
        .send()
        .unwrap();

    let json: serde_json::value::Value = serde_json::from_iter(res.bytes()).unwrap();

    let status = json
        .as_object().unwrap()
        .get("success").unwrap()
        .as_boolean().unwrap();
    if !status {
        println!("failed request!");
    }

    let zone_ids = json
        .as_object().unwrap()
        .get("result").unwrap()
        .as_array().unwrap()
        .iter()
        .map(|ref id| id.find("id").unwrap()
            .as_string().unwrap());

    for id in zone_ids {
        println!("{}", id);
    }

    // println!("Response: {}", res.status);
    // println!("Headers:\n{}", res.headers);
}
<commit_msg>reorganize for great success<commit_after>extern crate env_logger;
#[macro_use]
extern crate hyper;
extern crate serde;
extern crate serde_json;

use std::env;
use std::io::Read;

use hyper::Client;
use hyper::header::Connection;

use serde_json::value::*;

header! { (XAuthKey, "X-Auth-Key") => [String] }
header! { (XAuthEmail, "X-Auth-Email") => [String] }

// TODO(colemickens): none of the implementations handle paging properly

fn main() {
    env_logger::init().unwrap();

    let cloudflare_apikey = env::var("CLOUDFLARE_APIKEY").expect("missing apikey");
    let cloudflare_email = env::var("CLOUDFLARE_EMAIL").expect("missing email");

    let client = Client::new();

    let mut auth_headers = hyper::header::Headers::new();
    auth_headers.set(XAuthKey(cloudflare_apikey.to_owned()));
    auth_headers.set(XAuthEmail(cloudflare_email.to_owned()));

    let zones_url = "https://api.cloudflare.com/client/v4/zones";
    let mut zones_response = client
        .get(zones_url)
        .header(Connection::close())
        .headers(auth_headers)
        .send().unwrap();

    if zones_response.status != hyper::status::StatusCode::Ok {
         println!("she's gonna blow!");
         println!("exit early"); // TODO(colemickens): fix
    }

    let zones_json: serde_json::value::Value = serde_json::from_iter(zones_response.by_ref().bytes()).unwrap();

    let status = zones_json
        .as_object().unwrap()
        .get("success").unwrap()
        .as_boolean().unwrap();
    if !status {
        println!("request sent 200, but cloudflare reported !success"); // TODO(colemickens): this is inaccurate due to above "fix" todo
    }

    let zone_ids = zones_json
        .as_object().unwrap()
        .get("result").unwrap()
        .as_array().unwrap()
        .iter()
        .map(|ref id|
            id.find("id").unwrap()
            .as_string().unwrap());

    for id in zone_ids {
        println!("{}", id);
    }
}
<|endoftext|>


<commit_before>extern crate hyper;
extern crate getopts;
extern crate serde;
extern crate serde_json;
use std::io::Read;
use std::env;
use hyper::Client;
use serde_json::Value;
use getopts::Options;
const KEY: &'static str = "1e940957819058fe3ec7c59d43c09504b400110db7faa0509";
fn main() {
    let wordclient = Client::new();
    let args: Vec<String> = env::args().collect();
    let parser = Options::new();
    let opts = parser.parse(&args[1..]).unwrap();
    for word in opts.free {
        println!("{}:",word.to_uppercase());
        let url = format!("http://api.wordnik.com/v4/word.json/{word}/definitions?api_key={key}",key = KEY, word = word);
        println!("{}",url);
        let mut resp = wordclient.get(&url).send().unwrap();
        let mut body = String::new();
        resp.read_to_string(&mut body).unwrap();
        println!("{}",body);
        let word: Value = serde_json::from_str(&body).unwrap();
        println!("{}",word.as_array().unwrap()[0].as_object().unwrap().get("text").unwrap().as_string().unwrap());
    }
}
<commit_msg>Removed prints<commit_after>extern crate hyper;
extern crate getopts;
extern crate serde;
extern crate serde_json;
use std::io::Read;
use std::env;
use hyper::Client;
use serde_json::Value;
use getopts::Options;
const KEY: &'static str = "1e940957819058fe3ec7c59d43c09504b400110db7faa0509";
fn main() {
    let wordclient = Client::new();
    let args: Vec<String> = env::args().collect();
    let parser = Options::new();
    let opts = parser.parse(&args[1..]).unwrap();
    for word in opts.free {
        println!("{}:",word.to_uppercase());
        let url = format!("http://api.wordnik.com/v4/word.json/{word}/definitions?api_key={key}",key = KEY, word = word);
        let mut resp = wordclient.get(&url).send().unwrap();
        let mut body = String::new();
        resp.read_to_string(&mut body).unwrap();
        let word: Value = serde_json::from_str(&body).unwrap();
        println!("{}",word.as_array().unwrap()[0].as_object().unwrap().get("text").unwrap().as_string().unwrap());
    }
}
<|endoftext|>


<commit_before>fn main() {
    println!("Hello, world!");
}
<commit_msg>Starting out simple...<commit_after>struct System {
    memory: [u8; 4096],
    registers: [u8; 16],
    pc: u16,
    index: u16
}

impl System {
    fn new() -> Self {
        System {
            memory: [0; 4096],
            registers: [0; 16],
            pc: 0,
            index: 0
        }
    }
}

fn main() {
    let system = System::new();
    println!("{}, {}, {}, {}", system.memory[0], system.registers[0],
        system.pc, system.index);
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::io::{self, stdin, stdout, Write};
use std::iter::Peekable;
use std::str::CharIndices;

// TODO(tsion): Use the readline library.
fn prompt(line: &mut String) -> io::Result<usize> {
    let current_dir = try!(std::env::current_dir());
    print!("{}> ", current_dir.display());
    try!(stdout().flush());
    stdin().read_line(line)
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum Ast {
    Empty,
    Call { command: String, args: Vec<String> }
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum Token {
    Newline,
    Whitespace,
    Text(String),
}

#[derive(Clone)]
struct Lexer<'a> {
    input: &'a str,
    iter: Peekable<CharIndices<'a>>,
}

impl<'a> Lexer<'a> {
    fn new(input: &str) -> Lexer {
        Lexer {
            input: input,
            iter: input.char_indices().peekable(),
        }
    }

    fn pos(&mut self) -> usize {
        self.iter.peek().map(|p| p.0).unwrap_or(self.input.len())
    }

    fn peek_char(&mut self) -> Option<char> {
        self.iter.peek().map(|p| p.1)
    }

    fn is_whitespace(c: char) -> bool {
        c == ' ' || c == '\t'
    }

    fn lex_whitespace(&mut self) -> Token {
        while let Some(c) = self.peek_char() {
            if !Lexer::is_whitespace(c) { break; }
            self.iter.next();
        }

        Token::Whitespace
    }

    fn lex_unquoted_text(&mut self) -> Token {
        let start = self.pos();

        while let Some(c) = self.peek_char() {
            if Lexer::is_whitespace(c) || c == '\r' || c == '\n' { break; }
            self.iter.next();
        }

        let end = self.pos();

        // TODO(tsion): Do this without allocation.
        Token::Text(String::from(&self.input[start..end]))
    }
}

impl<'a> Iterator for Lexer<'a> {
    type Item = Token;

    fn next(&mut self) -> Option<Token> {
        self.peek_char().map(|peek_char| {
            match peek_char {
                '\r' | '\n'                  => Token::Newline,
                c if Lexer::is_whitespace(c) => self.lex_whitespace(),
                _                            => self.lex_unquoted_text(),
            }
        })
    }
}

#[derive(Clone)]
struct Parser<'a> {
    lexer: Lexer<'a>,
}

impl<'a> Parser<'a> {
    fn new(input: &str) -> Parser {
        Parser { lexer: Lexer::new(input) }
    }

    fn parse(&mut self) -> Ast {
        match self.lexer.next() {
            Some(Token::Whitespace) | Some(Token::Newline) => self.parse(),
            Some(Token::Text(command)) => self.parse_call(command),
            None => Ast::Empty,
        }
    }

    fn parse_call(&mut self, command: String) -> Ast {
        let mut args = vec![];

        for token in &mut self.lexer {
            match token {
                Token::Newline    => break,
                Token::Whitespace => {},
                Token::Text(arg)  => { args.push(arg); },
            }
        }

        Ast::Call { command: command, args: args }
    }
}

struct Builtin {
    name: &'static str,
    min_args: usize,
    max_args: usize,
    func: fn(&[String]) -> io::Result<()>,
}

fn builtin_cd(args: &[String]) -> io::Result<()> {
    if let Some(path) = args.get(0) {
        std::env::set_current_dir(path)
    } else if let Some(home) = std::env::home_dir() {
        std::env::set_current_dir(home)
    } else {
        Err(io::Error::new(io::ErrorKind::Other, "cd: couldn't find home dir"))
    }
}

fn builtin_exit(args: &[String]) -> io::Result<()> {
    if let Some(exit_code_str) = args.get(0) {
        if let Ok(exit_code) = exit_code_str.parse() {
            std::process::exit(exit_code);
        } else {
            Err(io::Error::new(io::ErrorKind::Other, "exit: couldn't parse exit code as integer"))
        }
    } else {
        std::process::exit(0);
    }
}

fn execute(ast: &Ast) -> io::Result<()> {
    let mut builtins = HashMap::new();

    builtins.insert("cd", Builtin {
        name: "cd",
        min_args: 0,
        max_args: 1,
        func: builtin_cd,
    });

    builtins.insert("exit", Builtin {
        name: "exit",
        min_args: 0,
        max_args: 1,
        func: builtin_exit,
    });

    match *ast {
        Ast::Empty => Ok(()),

        Ast::Call { ref command, ref args } => {
            if let Some(builtin) = builtins.get(&command[..]) {
                if args.len() < builtin.min_args {
                    return Err(io::Error::new(io::ErrorKind::Other,
                                              format!("{}: not enough arguments", builtin.name)));
                }

                if args.len() > builtin.max_args {
                    return Err(io::Error::new(io::ErrorKind::Other,
                                              format!("{}: too many arguments", builtin.name)));
                }

                (builtin.func)(args)
            } else {
                std::process::Command::new(command).args(args).status().map(|_| ())
            }
        },
    }
}

fn main() {
    let mut line = String::new();
    loop {
        prompt(&mut line).unwrap();
        let ast = Parser::new(&line).parse();
        if let Err(e) = execute(&ast) {
            println!("shroom: error: {}", e);
        }
        line.clear();
    }
}
<commit_msg>Check and return exit codes for commands.<commit_after>use std::collections::HashMap;
use std::io::{self, Write};
use std::iter::Peekable;
use std::process::{Command, ExitStatus};
use std::str::CharIndices;

// TODO(tsion): Use the readline library.
fn prompt(line: &mut String) -> io::Result<usize> {
    let current_dir = try!(std::env::current_dir());
    print!("{}> ", current_dir.display());
    try!(io::stdout().flush());
    io::stdin().read_line(line)
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum Ast {
    Empty,
    Call { command: String, args: Vec<String> }
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum Token {
    Newline,
    Whitespace,
    Text(String),
}

#[derive(Clone)]
struct Lexer<'a> {
    input: &'a str,
    iter: Peekable<CharIndices<'a>>,
}

impl<'a> Lexer<'a> {
    fn new(input: &str) -> Lexer {
        Lexer {
            input: input,
            iter: input.char_indices().peekable(),
        }
    }

    fn pos(&mut self) -> usize {
        self.iter.peek().map(|p| p.0).unwrap_or(self.input.len())
    }

    fn peek_char(&mut self) -> Option<char> {
        self.iter.peek().map(|p| p.1)
    }

    fn is_whitespace(c: char) -> bool {
        c == ' ' || c == '\t'
    }

    fn lex_whitespace(&mut self) -> Token {
        while let Some(c) = self.peek_char() {
            if !Lexer::is_whitespace(c) { break; }
            self.iter.next();
        }

        Token::Whitespace
    }

    fn lex_unquoted_text(&mut self) -> Token {
        let start = self.pos();

        while let Some(c) = self.peek_char() {
            if Lexer::is_whitespace(c) || c == '\r' || c == '\n' { break; }
            self.iter.next();
        }

        let end = self.pos();

        // TODO(tsion): Do this without allocation.
        Token::Text(String::from(&self.input[start..end]))
    }
}

impl<'a> Iterator for Lexer<'a> {
    type Item = Token;

    fn next(&mut self) -> Option<Token> {
        self.peek_char().map(|peek_char| {
            match peek_char {
                '\r' | '\n'                  => { self.iter.next(); Token::Newline },
                c if Lexer::is_whitespace(c) => self.lex_whitespace(),
                _                            => self.lex_unquoted_text(),
            }
        })
    }
}

#[derive(Clone)]
struct Parser<'a> {
    lexer: Lexer<'a>,
}

impl<'a> Parser<'a> {
    fn new(input: &str) -> Parser {
        Parser { lexer: Lexer::new(input) }
    }

    fn parse(&mut self) -> Ast {
        match self.lexer.next() {
            Some(Token::Whitespace) | Some(Token::Newline) => self.parse(),
            Some(Token::Text(command)) => self.parse_call(command),
            None => Ast::Empty,
        }
    }

    fn parse_call(&mut self, command: String) -> Ast {
        let mut args = vec![];

        for token in &mut self.lexer {
            match token {
                Token::Newline    => break,
                Token::Whitespace => {},
                Token::Text(arg)  => { args.push(arg); },
            }
        }

        Ast::Call { command: command, args: args }
    }
}

struct Builtin {
    name: &'static str,
    min_args: usize,
    max_args: usize,
    func: fn(&[String]) -> i32,
}

fn result_to_exit_code(result: io::Result<()>) -> i32 {
    match result {
        Ok(()) => 0,
        Err(e) => {
            writeln!(&mut io::stderr(), "cd: {}", e).unwrap();
            1
        },
    }
}

fn builtin_cd(args: &[String]) -> i32 {
    if let Some(path) = args.get(0) {
        result_to_exit_code(std::env::set_current_dir(path))
    } else if let Some(home) = std::env::home_dir() {
        result_to_exit_code(std::env::set_current_dir(home))
    } else {
        writeln!(&mut io::stderr(), "cd: couldn't find home dir").unwrap();
        1
    }
}

fn builtin_exit(args: &[String]) -> i32 {
    if let Some(exit_code_str) = args.get(0) {
        if let Ok(exit_code) = exit_code_str.parse() {
            std::process::exit(exit_code);
        } else {
            writeln!(&mut io::stderr(), "exit: couldn't parse exit code as integer").unwrap();
            1
        }
    } else {
        std::process::exit(0);
    }
}

fn execute(ast: &Ast) -> i32 {
    let mut builtins = HashMap::new();

    builtins.insert("cd", Builtin {
        name: "cd",
        min_args: 0,
        max_args: 1,
        func: builtin_cd,
    });

    builtins.insert("exit", Builtin {
        name: "exit",
        min_args: 0,
        max_args: 1,
        func: builtin_exit,
    });

    match *ast {
        Ast::Empty => 0,

        Ast::Call { ref command, ref args } => {
            if let Some(builtin) = builtins.get(&command[..]) {
                if args.len() < builtin.min_args {
                    writeln!(&mut io::stderr(), "{}: not enough arguments", builtin.name).unwrap();
                    1
                } else if args.len() > builtin.max_args {
                    writeln!(&mut io::stderr(), "{}: too many arguments", builtin.name).unwrap();
                    1
                } else {
                    (builtin.func)(args)
                }
            } else {
                match Command::new(command).args(args).status() {
                    Ok(exit_status) => {
                        #[cfg(unix)]
                        fn exit_signal(exit_status: &ExitStatus) -> Option<i32> {
                            use std::os::unix::process::ExitStatusExt;
                            exit_status.signal()
                        }

                        #[cfg(not(unix))]
                        fn exit_signal(_exit_status: &ExitStatus) -> Option<i32> {
                            None
                        }

                        if let Some(code) = exit_status.code() {
                            code
                        } else if let Some(signal) = exit_signal(&exit_status) {
                            128 + signal
                        } else {
                            127
                        }
                    },

                    Err(e) => {
                        writeln!(&mut io::stderr(), "shroom: {}", e).unwrap();
                        127
                    },
                }
            }
        },
    }
}

fn main() {
    let mut line = String::new();
    loop {
        prompt(&mut line).unwrap();
        let ast = Parser::new(&line).parse();
        let exit_code = execute(&ast);
        if exit_code != 0 {
            println!("shroom: exit code: {}", exit_code);
        }
        line.clear();
    }
}
<|endoftext|>