<commit_before>extern crate rand;
extern crate sdl2;
extern crate cgmath;

mod device;
mod rasterization;
mod tests;

use cgmath::Point2;
use rand::distributions::{IndependentSample, Range};

use device::Device;
use rasterization::triangle;

pub fn main() {
    let mut device = Device::new("rust software render", 800, 600);

    let color_range = Range::new(0, std::u32::MAX);
    let x_range = Range::new(-50f32, device.x_size as f32 + 50f32);
    let y_range = Range::new(-50f32, device.y_size as f32 + 50f32);
    let mut rng = rand::thread_rng();

    let cnt = 16000;
    let mut points: Vec<Point2<f32>> = vec![];
    let mut colors: Vec<u32> = vec![];
    for _ in 0..cnt {
        points.push(Point2::new(x_range.ind_sample(&mut rng), y_range.ind_sample(&mut rng)));
        points.push(Point2::new(x_range.ind_sample(&mut rng), y_range.ind_sample(&mut rng)));
        points.push(Point2::new(x_range.ind_sample(&mut rng), y_range.ind_sample(&mut rng)));
        colors.push(color_range.ind_sample(&mut rng));
    }

    while device.keyboard() {
        device.clear(0xFFFFFF);
        for i in 0..cnt {
            triangle(&mut device.cbuffer,
                     device.x_size,
                     device.y_size,
                     points[i*3 + 0], points[i*3 + 1], points[i*3 + 2], colors[i]);
        }
        device.present();
        device.draw_fps();
    }
}
<commit_msg>3d triangle<commit_after>extern crate sdl2;
extern crate cgmath;

mod device;
mod rasterization;
mod tests;

use cgmath::*;
// use cgmath::matrix::to_matrix4;

use device::Device;
use rasterization::triangle;

pub fn main() {
    let mut device = Device::new("rust software render", 800, 600);

    // 1-2-3 1-3-4
    let p1 = Vector4::new(-5.0_f32,  5.0_f32, 0.0_f32, 1.0_f32);
    let p2 = Vector4::new( 5.0_f32,  5.0_f32, 0.0_f32, 1.0_f32);
    let p3 = Vector4::new( 5.0_f32, -5.0_f32, 0.0_f32, 1.0_f32);
    let p4 = Vector4::new(-5.0_f32, -5.0_f32, 0.0_f32, 1.0_f32);

    let eye = Point3::new(0.0_f32, 0.0_f32, -20.0_f32);
	let center = Point3::new(0.0_f32, 0.0_f32, 0.0_f32);
	let up = Vector3::new(0.0_f32, 1.0_f32, 0.0_f32);
    let fovy = deg(130.0_f32);
    let aspect = 800.0_f32/600.0_f32;
    let near = 0.1_f32;
    let far = 100.0_f32;

    let mat_view = Matrix4::<f32>::look_at(&eye, &center, &up);
    let mat_proj = perspective(fovy, aspect, near, far);

    let mut angle = rad(0.0_f32);
    let add_angle = rad(2.0_f32 * std::f32::consts::PI / 180.0_f32);
    while device.keyboard() {
        device.clear(0xFFFFFF);

        angle = angle + add_angle;
        let mat_world = Matrix4::from(Matrix3::from_angle_y(angle));
        let mat = mat_proj * mat_view * mat_world;
        // let mat = mat_world * mat_view * mat_proj;
        let mut points: Vec<Point2<f32>> = vec![];
        for p in &[p1, p2, p3, p4] {
            let p_screen = mat.mul_v(&p);
            points.push(
                Point2::new(
                    (p_screen.x/p_screen.w + 1.0_f32) * 800_f32 * 0.5_f32,
                    (p_screen.y/p_screen.w + 1.0_f32) * 600_f32 * 0.5_f32));
        }

        triangle(&mut device.cbuffer,
                 device.x_size,
                 device.y_size,
                 points[0], points[1], points[2], 0xFF00FF);
        triangle(&mut device.cbuffer,
                 device.x_size,
                 device.y_size,
                 points[0], points[2], points[3], 0x00FFFF);
        device.present();
        device.draw_fps();
    }
}
<|endoftext|>


<commit_before>#![feature(std_misc, exit_status)]
extern crate rustc_serialize;
extern crate unix_socket;

use std::io;
use std::io::{Read, Write, BufRead, BufReader};
use std::fs;
use std::path::Path;
use std::net::TcpStream;
use std::env;
use std::error::Error;
use std::clone::Clone;
use std::thread::spawn;
use std::sync::mpsc::{Select,channel, Sender, Receiver};

use rustc_serialize::{json, Decodable};
use unix_socket::UnixListener;

#[derive(RustcDecodable, RustcEncodable, Clone)]
pub struct Config  {
      path     : String
    , host     : String
    , port     : u16
    , nick     : String
    , user     : String
    , realname : String
    , channel  : String
}

fn strip_prefix<'a>(prefix : &str, s : &'a str) -> Option<&'a str>{
    if s.starts_with(prefix) {
        Some(&s[s.len()..])
    } else {
        None
    }
}

fn local_ipc(conf : &Config, tx : &Sender<String>) {
    let path = Path::new(&conf.path);

    // Delete old socket if necessary
    fs::remove_file(path);

    // Bind to socket
    let stream = UnixListener::bind(&path).unwrap();
    let mut id = 0usize;
    for client in stream.incoming() {
        let tx = tx.clone();
        spawn(move|| {
            println!("Client {} connected", id);
            let reader = BufReader::new(client.unwrap());
            for line in reader.lines() {
                let line = line.unwrap();
                if line.len() == 0 {
                    continue;
                }
                println!("{}: {}", id, line);
                tx.send(line).unwrap();
            }
            println!("Client {} disconnected", id);
        });
        id += 1;
    }
}

fn irc_client(conf : &Config, rx : &Receiver<String>) -> Result<(), io::Error> {

    let mut stream = try!(TcpStream::connect((&conf.host[..], conf.port)));

    // Connect
    try!(writeln!(&stream, "USER {} 0 * :{}", conf.user, conf.realname));
    try!(writeln!(&stream, "NICK {}", conf.nick));
    try!(writeln!(&stream, "JOIN {}", conf.channel));

    let (irc_tx, irc_rx) = channel::<String>();

    let reader = BufReader::new(try!(stream.try_clone()));
    // Receieve network
    spawn(move|| {
        for line in reader.lines() {
            irc_tx.send(line.unwrap()).unwrap();
        }
    });

    let sel = Select::new();
    let mut rx     = sel.handle(rx);
    let mut irc_rx = sel.handle(&irc_rx);
    unsafe {
        rx.add();
        irc_rx.add();
    }

    loop {
        let ret = sel.wait();
        if ret == rx.id() {
            let msg = rx.recv().unwrap();
            try!(stream.write(format!("PRIVMSG {} :{}\n", conf.channel, msg).as_bytes()));
        } else if ret == irc_rx.id() {
            let msg = irc_rx.recv().unwrap();
            let s = msg[..].trim_right();
            println!("{}", s);
            strip_prefix("PING ", s).and_then(|s| writeln!(stream, "PONG {}", s).ok());
        }
    }
}

fn get_config() -> Result<Config, String> {
    let raw_path = env::args().nth(1).unwrap_or("/etc/irc-relay.json".to_owned());
    let path = Path::new(&raw_path);
    println!("{}", path.display());

    let mut raw_file_utf8 = String::new();
    try!(fs::File::open(path)
        .map_err(|x| format!("{}: {}", raw_path, x)))
        .read_to_string(&mut raw_file_utf8);

    let json_object = try!(json::Json::from_str(&raw_file_utf8)
        .map_err(|x| format!("{}: {}", raw_path, x)));
    let mut decoder = json::Decoder::new(json_object);
    Decodable::decode(&mut decoder)
        .map_err(|x| format!("{}: {}", raw_path, x))

}

fn main() {
    let conf = match get_config() {
        Ok(s) => s,
        Err(e) => {
            println!("Error reading config: {}", e);
            env::set_exit_status(1);
            return;
        }
    };

    let (tx, rx) = channel::<String>();

    let c = conf.clone();
    spawn(move || local_ipc(&c, &tx));

    loop {
        match irc_client(&conf, &rx) {
            Err(e) => println!("Error: {}\nReconnecting..", e),
            Ok(_)  => ()
        }
    }
}
<commit_msg>Fixes<commit_after>#![feature(exit_status, std_misc, scoped)]
extern crate rustc_serialize;
extern crate unix_socket;

use std::io;
use std::io::{Read, Write, BufRead, BufReader};
use std::fs;
use std::net::TcpStream;
use std::env;
use std::error::Error;
use std::clone::Clone;
use std::thread;
use std::sync::mpsc::{channel, Sender, Receiver};

use rustc_serialize::{json, Decodable};
use unix_socket::UnixListener;

#[derive(RustcDecodable, RustcEncodable)]
struct Config  {
      path     : String
    , host     : String
    , port     : u16
    , nick     : String
    , user     : String
    , realname : String
    , channel  : String
}

fn strip_prefix<'a>(prefix : &str, s : &'a str) -> Option<&'a str>{
    if s.starts_with(prefix) {
        Some(&s[s.len()..])
    } else {
        None
    }
}

fn local_ipc(conf : &Config, tx : &Sender<String>) {
    // Delete old socket if necessary
    let _ = fs::remove_file(&conf.path);

    // Bind to socket
    let stream = UnixListener::bind(&conf.path).unwrap();
    let mut id = 0usize;
    for client in stream.incoming() {
        let tx = tx.clone();
        thread::spawn(move || {
            println!("Client {} connected", id);
            let reader = BufReader::new(client.unwrap());
            for line in reader.lines() {
                let line = line.unwrap();
                if line.len() == 0 {
                    continue;
                }
                println!("{}: {}", id, line);
                tx.send(line).unwrap();
            }
            println!("Client {} disconnected", id);
        });
        id += 1;
    }
}

fn irc_client(conf : &Config, rx : &Receiver<String>) -> Result<(), io::Error> {

    let stream = try!(TcpStream::connect((&conf.host[..], conf.port)));

    // Connect
    try!(writeln!(&stream, "USER {} 0 * :{}", conf.user, conf.realname));
    try!(writeln!(&stream, "NICK {}", conf.nick));
    try!(writeln!(&stream, "JOIN {}", conf.channel));

    let (irc_tx, irc_rx) = channel::<String>();

    let reader = BufReader::new(try!(stream.try_clone()));
    // Receieve network
    let guard = thread::scoped(move || {
        for line in reader.lines() {
            irc_tx.send(line.unwrap()).unwrap();
        }
    });

    loop {
        select! (
            msg = rx.recv() => {
                try!(writeln!(&stream, "PRIVMSG {} :{}", conf.channel, msg.unwrap()));
            },
            msg = irc_rx.recv() => {
                let s = msg.unwrap();
                let s = s[..].trim_right();
                println!("{}", s);
                strip_prefix("PING ", s).and_then(|s| writeln!(&stream, "PONG {}", s).ok());
            }
        )
    }
}

fn get_config() -> Result<Config, String> {
    let path = env::args().nth(1).unwrap_or("/etc/irc-relay.json".to_owned());

    let mut raw_file_utf8 = String::new();
    let _ = try!(fs::File::open(&path)
        .map_err(|x| format!("{}: {}", path, x)))
        .read_to_string(&mut raw_file_utf8);

    let json_object = try!(json::Json::from_str(&raw_file_utf8)
        .map_err(|x| format!("{}: {}", path, x)));
    let mut decoder = json::Decoder::new(json_object);
    Decodable::decode(&mut decoder)
        .map_err(|x| format!("{}: {}", path, x))

}

fn main() {
    let conf = match get_config() {
        Ok(s) => s,
        Err(e) => {
            println!("Error reading config: {}", e);
            env::set_exit_status(1);
            return;
        }
    };
    let (tx, rx) = channel::<String>();

    let guard = thread::scoped(|| {
        let tx = tx;
        local_ipc(&conf, &tx)
    });

    loop {
        match irc_client(&conf, &rx) {
            Err(e) => println!("Error: {}\nReconnecting..", e),
            Ok(_)  => ()
        }
    }
}
<|endoftext|>


<commit_before>#![feature(from_utf8_error_as_bytes)]

extern crate clap;
extern crate flate2;
extern crate reqwest;
#[macro_use] extern crate serde_derive;
extern crate sha2;
extern crate tar;
extern crate toml;

mod app;
mod cache;
mod config;
mod error;
mod installation;
mod package;
mod repository;
mod utils;

pub type Essentials<'a> = (
    &'a config::Config,
    &'a cache::Cache,
    &'a repository::RepositoryList
);

use std::path::Path;

fn main() {
    // Get the configs.
    let config = Path::new("~/.config/wiz");
    let config = config::Config::
        read_from(config)
        .map(|x| x.fill_with_default())
        .unwrap_or(config::Config::default());

    // Get the packages which are installed or are going to be installed.
    let cache = Path::new("~/.config/wiz");
    let cache = cache::Cache::
        read_from(cache)
        .unwrap_or(cache::Cache::default());

    // Get the repositories (package lists).
    let repositories = Path::new("~/.config/wiz");
    let repositories = repository::RepositoryList::
        read_from(repositories)
        .unwrap_or(repository::RepositoryList::default());

    let args = app::run();

    match args.subcommand_matches("install") {
        Some(arg) => {
            installation::install_package(
                arg.value_of("package_name").unwrap_or_default(),
                arg.is_present("force"),

                (&config, &cache, &repositories)
            );
        },

        None => {
            println!("no subcommands specified")
        }
    };
}<commit_msg>Kinda a way to catch errors...<commit_after>#![feature(from_utf8_error_as_bytes)]

extern crate clap;
extern crate flate2;
extern crate reqwest;
#[macro_use] extern crate serde_derive;
extern crate sha2;
extern crate tar;
extern crate toml;

mod app;
mod cache;
mod config;
mod error;
mod installation;
mod package;
mod repository;
mod utils;

pub type Essentials<'a> = (
    &'a config::Config,
    &'a cache::Cache,
    &'a repository::RepositoryList
);

use std::path::Path;

fn main() {
    // Get the configs.
    let config = Path::new("~/.config/wiz");
    let config = config::Config::
        read_from(config)
        .map(|x| x.fill_with_default())
        .unwrap_or(config::Config::default());

    // Get the packages which are installed or are going to be installed.
    let cache = Path::new("~/.config/wiz");
    let cache = cache::Cache::
        read_from(cache)
        .unwrap_or(cache::Cache::default());

    // Get the repositories (package lists).
    let repositories = Path::new("~/.config/wiz");
    let repositories = repository::RepositoryList::
        read_from(repositories)
        .unwrap_or(repository::RepositoryList::default());

    let args = app::run();

    let result = (|| match args.subcommand_matches("install") {
        Some(arg) => {
            installation::install_package(
                arg.value_of("package_name").unwrap_or_default(),
                arg.is_present("force"),

                (&config, &cache, &repositories)
            )
        },

        None => {
            println!("no subcommands specified");
            Ok(())
        }
    })();

    match result {
        Ok(_) => (),
        Err(why) => println!("{}", why),
    };
}<|endoftext|>


<commit_before>#![crate_name = "limonite"]
#![crate_type = "bin"]

use std::env;
use std::old_io::BufferedReader;
use std::old_io::File;

use syntax::lexer::Lexer;
use syntax::parser::Parser;

pub mod syntax;

// ToDo: Fill this out with usage and version info?
fn display_info() {
    // Display stuff about limonite.
    println!("Usage: limonite [FILE]");
}

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() != 2 {
        return display_info();
    }

    let ref file_name = args[1];
    let path = Path::new(file_name);
    let file = match File::open(&path) {
        Ok(f)  => f,
        Err(e) => panic!("Failed to open file. File error: {}", e)
    };

    let input_string = BufferedReader::new(file).read_to_string().unwrap();

    let lexer = Lexer::new(&input_string);
    let mut parser = Parser::new(lexer);

    parser.parse();
}
<commit_msg>Updated main to use new io, fs, and path which should stablize soon.<commit_after>#![crate_name = "limonite"]
#![crate_type = "bin"]
#![feature(io, fs, path)]

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

use syntax::lexer::Lexer;
use syntax::parser::Parser;

pub mod syntax;

// ToDo: Fill this out with usage and version info?
fn display_info() {
    // Display stuff about limonite.
    println!("Usage: limonite [FILE]");
}

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() != 2 {
        return display_info();
    }

    let ref file_name = args[1];
    let path = Path::new(file_name);
    let file = match File::open(&path) {
        Ok(f)  => f,
        Err(e) => panic!("Failed to open file. File error: {}", e)
    };

    let mut input_string = String::new();

    if let Err(e) = BufReader::new(file).read_to_string(&mut input_string) {
        panic!("{}", e);
    }

    let lexer = Lexer::new(&input_string);
    let mut parser = Parser::new(lexer);

    parser.parse();
}
<|endoftext|>


<commit_before>#![feature(phase)]
#![feature(if_let)]

#[phase(plugin)]
extern crate rustecs_macros;

extern crate rustecs;
extern crate serialize;
extern crate piston;
extern crate sdl2_game_window;
extern crate opengl_graphics;
use std::cell::RefCell;
use std::default::Default;
use std::rc::Rc;
use std::rand;
use std::rand::Rng;
use std::num::abs;

use opengl_graphics::{
    Gl,
    Texture,
};
use sdl2_game_window::WindowSDL2;
use piston::{
    EventIterator,
    EventSettings,
    WindowSettings,
};
use piston::graphics::{
    AddBorder,
    AddRectangle,
    AddEllipse,
    AddColor,
    Context,
    Draw,
};
use piston::event::{
    UpdateEvent,
    Event,
    Render,
    Update,
    Input,
};
use piston::input::{
    Focus,
};

use rustecs::{
    Entities,
    Components,
};

static WINDOW_W: f64 = 800.0;
static WINDOW_H: f64 = 600.0;

fn drawSystem(event: &Event,
              gl: &mut Gl,
              positions: &mut Components<Position>,
              shapes: &mut Components<Shape>,
              colors: &mut Components<Color>) {
    if let &Render(args) = event {
        let w = args.width as f64;
        let h = args.height as f64;
        gl.viewport(0, 0, w as i32, h as i32);
        let c = Context::abs(w, h);
        // Clear background.
        c.rgb(0.0, 0.0, 0.0).draw(gl);

        for (eid, pos) in positions.iter_mut() {
          let mut shape = Point;
          let mut border = None;
          if shapes.contains_key(eid) {
            shape = shapes.get_mut(eid).shape;
            border = shapes.get_mut(eid).border;
          }
          let (r, g, b) = if colors.contains_key(eid) {
              (colors.get_mut(eid).r, colors.get_mut(eid).g, colors.get_mut(eid).b)
          } else {
              (1.0, 1.0, 1.0)
          };
          let mut drawing = c.rgb(r, g, b);
          match (shape, border) {
              (Point, None)    => drawing.rect(1.0, 1.0, w, h).draw(gl),
              (Point, Some(b)) => drawing.rect(1.0, 1.0, w, h).border_radius(b).draw(gl),

              (Circle(rad), None)    => drawing.ellipse(pos.x, pos.y, rad, rad).draw(gl),
              (Circle(rad), Some(b)) => drawing.ellipse(pos.x, pos.y, rad, rad).border_radius(b).draw(gl),

              (Square(w,h), None)    => drawing.rect(pos.x, pos.y, w, h).draw(gl),
              (Square(w,h), Some(b)) => drawing.rect(pos.x, pos.y, w, h).border_radius(b).draw(gl),
          };
        }
    }
}

fn shimmerSystem(event: &Event,
                 colors: &mut Components<Color>) {
    for (_, color) in colors.iter_mut() {
        let ref mut rng = rand::task_rng();
        color.r = rng.gen_range(0.5, 1.0);
        color.g = rng.gen_range(0.5, 1.0);
        color.b = rng.gen_range(0.5, 1.0);
    }
}

fn moveSystem(event: &Event,
              positions: &mut Components<Position>,
              velocities: &mut Components<Velocity>) {
    if let &Update(args) = event {
        let dt = args.dt;
        for (eid, position) in positions.iter_mut() {
            if !velocities.contains_key(eid) {
                continue;
            }

            // If we have both a position and a velocity, integrate.
            let velocity = velocities.get_mut(eid);
            position.x += velocity.x * dt;
            position.y += velocity.y * dt;
            if position.x > WINDOW_W || position.x < 0.0 {
                velocity.x *= -1.0;
            }
            if position.y > WINDOW_H || position.y < 0.0 {
                velocity.y *= -1.0;
            }
        }
    }
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub struct Position {
    x: f64,
    y: f64
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub struct Color {
    r: f32,
    g: f32,
    b: f32
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub enum ShapeVarient {
    Point,
    Circle(f64), // radius
    Square(f64, f64), // width, height
}

impl Default for ShapeVarient {
    fn default() -> ShapeVarient { Point }
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub struct Shape {
    shape: ShapeVarient,
    border: Option<f64>
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub struct Velocity {
    x: f64,
    y: f64
}

world! {
    World,
    components Position, Shape, Velocity, Color;
}

fn main() {
    let opengl = piston::shader_version::opengl::OpenGL_3_2;
    let mut window = WindowSDL2::new(
        opengl,
        WindowSettings {
            title: "Shooter".to_string(),
            size: [WINDOW_W as u32, WINDOW_H as u32],
            fullscreen: false,
            exit_on_esc: true,
            samples: 4,
        }
    );

    let mut gl = Gl::new(opengl);

    let mut world = World::new();

    let num_things: i32 = 300;

    let ref mut rng = rand::task_rng();
    for _ in range(0, num_things) {
        let r = rng.gen_range(10.0, 40.0);
        let shape = if rng.gen() {
            Square(r, r)
        } else {
            Circle(r)
        };
        let border = Some(rng.gen_range(1.0, 3.0));

        let x = (WINDOW_W - r) / 2.0;
        let y = (WINDOW_H - r) / 2.0;

        let e = Entity::new()
            .with_position(
                Position{
                    x: x,
                    y: y
                })
            .with_velocity(
                Velocity {
                    x: rng.gen_range(-80.0, 80.0),
                    y: rng.gen_range(-80.0, 80.0)
                })
            .with_shape(
                Shape {
                    shape: shape,
                    border: border
                })
            .with_color(
                Color{
                    r: 1.0,
                    g: 0.5,
                    b: 0.2
                });
        world.add(e);
    }
    let event_settings = EventSettings {
        updates_per_second: 120,
        max_frames_per_second: 60,
    };

    for e in EventIterator::new(&mut window, &event_settings) {
        moveSystem(&e, &mut world.positions, &mut world.velocities);
        shimmerSystem(&e, &mut world.colors);
        drawSystem(&e, &mut gl, &mut world.positions, &mut world.shapes, &mut world.colors);
    }
}
<commit_msg>Make pong graphical elements<commit_after>#![feature(phase)]
#![feature(if_let)]

#[phase(plugin)]
extern crate rustecs_macros;

extern crate rustecs;
extern crate serialize;
extern crate piston;
extern crate sdl2_game_window;
extern crate opengl_graphics;
use std::default::Default;
use std::rand;
use std::rand::Rng;
use std::num::abs;

use opengl_graphics::{
    Gl,
};
use sdl2_game_window::WindowSDL2;
use piston::{
    EventIterator,
    EventSettings,
    WindowSettings,
};
use piston::graphics::{
    AddBorder,
    AddRectangle,
    AddEllipse,
    AddColor,
    Context,
    Draw,
};
use piston::event::{
    Event,
    Render,
    Update,
    Input,
};

use rustecs::{
    Entities,
    Components,
};

static WINDOW_W: f64 = 800.0;
static WINDOW_H: f64 = 600.0;

fn draw_system(event: &Event,
              gl: &mut Gl,
              positions: &mut Components<Position>,
              shapes: &mut Components<Shape>,
              colors: &mut Components<Color>) {
    if let &Render(args) = event {
        let w = args.width as f64;
        let h = args.height as f64;
        gl.viewport(0, 0, w as i32, h as i32);
        let c = Context::abs(w, h);
        // Clear background.
        c.rgb(0.0, 0.0, 0.0).draw(gl);

        for (eid, pos) in positions.iter_mut() {
          let mut shape = Point;
          let mut border = None;
          if shapes.contains_key(eid) {
            shape = shapes.get_mut(eid).shape;
            border = shapes.get_mut(eid).border;
          }
          let (r, g, b) = if colors.contains_key(eid) {
              (colors.get_mut(eid).r, colors.get_mut(eid).g, colors.get_mut(eid).b)
          } else {
              (1.0, 1.0, 1.0)
          };
          let drawing = c.rgb(r, g, b);
          match (shape, border) {
              (Point, None)    => drawing.rect(1.0, 1.0, w, h).draw(gl),
              (Point, Some(b)) => drawing.rect(1.0, 1.0, w, h).border_radius(b).draw(gl),

              (Circle(rad), None)    => drawing.ellipse(pos.x, pos.y, rad, rad).draw(gl),
              (Circle(rad), Some(b)) => drawing.ellipse(pos.x, pos.y, rad, rad).border_radius(b).draw(gl),

              (Square(w,h), None)    => drawing.rect(pos.x, pos.y, w, h).draw(gl),
              (Square(w,h), Some(b)) => drawing.rect(pos.x, pos.y, w, h).border_radius(b).draw(gl),
          };
        }
    }
}

fn shimmer_system(shimmers: &mut Components<Shimmer>,
                 colors: &mut Components<Color>) {
    for (eid, _) in shimmers.iter_mut() {
        if !colors.contains_key(eid) {
            continue;
        }
        let color = colors.get_mut(eid);
        let ref mut rng = rand::task_rng();
        color.r = rng.gen_range(0.5, 1.0);
        color.g = rng.gen_range(0.5, 1.0);
        color.b = rng.gen_range(0.5, 1.0);
    }
}

fn move_system(event: &Event,
              positions: &mut Components<Position>,
              velocities: &mut Components<Velocity>) {
    if let &Update(args) = event {
        let dt = args.dt;
        for (eid, position) in positions.iter_mut() {
            if !velocities.contains_key(eid) {
                continue;
            }

            // If we have both a position and a velocity, integrate.
            let velocity = velocities.get_mut(eid);
            position.x += velocity.x * dt;
            position.y += velocity.y * dt;
            if position.x > WINDOW_W || position.x < 0.0 {
                velocity.x *= -1.0;
            }
            if position.y > WINDOW_H || position.y < 0.0 {
                velocity.y *= -1.0;
            }
        }
    }
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub struct Position {
    x: f64,
    y: f64
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub struct Shimmer;

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub struct Color {
    r: f32,
    g: f32,
    b: f32
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub enum ShapeVarient {
    Point,
    Circle(f64), // radius
    Square(f64, f64), // width, height
}

impl Default for ShapeVarient {
    fn default() -> ShapeVarient { Point }
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub struct Shape {
    shape: ShapeVarient,
    border: Option<f64>
}

#[deriving(Clone, Decodable, Encodable, PartialEq, Show)]
pub struct Velocity {
    x: f64,
    y: f64
}

world! {
    World,
    components Position, Shape, Velocity, Color, Shimmer;
}

fn make_ball() -> Entity {
    const BALL_R: f64 = 20.0;
    let shape = Circle(BALL_R);
    let x = (WINDOW_W - BALL_R) / 2.0;
    let y = (WINDOW_H - BALL_R) / 2.0;

    fn random_vel() -> f64 {
        let ref mut rng = rand::task_rng();
        rng.gen_range(80.0, 100.0) * if rng.gen() { 1.0 } else { -1.0 }
    }

    Entity::new()
        .with_shimmer(Shimmer)
        .with_position(
            Position{
                x: x,
                y: y
            })
        .with_velocity(
            Velocity {
                x: random_vel(),
                y: random_vel()
            })
        .with_shape(
            Shape {
                shape: shape,
                border: None
            })
        .with_color(
            Color{
                r: 1.0,
                g: 0.5,
                b: 0.2
            })
}

fn make_player(p1: bool) -> Entity {
    const FROM_WALL: f64 = 20.0;
    const PADDLE_W: f64 = 20.0;
    const PADDLE_H: f64 = 150.0;
    let x = if p1 {
        FROM_WALL
    } else {
        WINDOW_W - FROM_WALL - PADDLE_W
    };
    let y = (WINDOW_H - PADDLE_H) / 2.0;
    Entity::new()
        .with_position(
            Position{
                x: x,
                y: y
            })
        .with_shape(
            Shape {
                shape: Square(PADDLE_W, PADDLE_H),
                border: None
            })
        .with_color(
            Color{
                r: 0.5,
                g: 0.2,
                b: 0.8
            })
}

fn main() {
    let opengl = piston::shader_version::opengl::OpenGL_3_2;
    let mut window = WindowSDL2::new(
        opengl,
        WindowSettings {
            title: "Pong".to_string(),
            size: [WINDOW_W as u32, WINDOW_H as u32],
            fullscreen: false,
            exit_on_esc: true,
            samples: 4,
        }
    );

    let mut gl = Gl::new(opengl);
    let mut world = World::new();

    world.add(make_player(true));
    world.add(make_player(false));
    world.add(make_ball());

    let event_settings = EventSettings {
        updates_per_second: 120,
        max_frames_per_second: 60,
    };

    for e in EventIterator::new(&mut window, &event_settings) {
        move_system(&e, &mut world.positions, &mut world.velocities);
        shimmer_system(&mut world.shimmers, &mut world.colors);
        draw_system(&e, &mut gl, &mut world.positions, &mut world.shapes, &mut world.colors);
    }
}
<|endoftext|>


<commit_before>use std::net::UdpSocket;

struct Message {
    id: u16, // 2 bytes
    query_response: u16, // 1 bit
    operation_code: u16, // 4 bits
    authoritative_answer: u16, // 1 bit
    truncation_flag: u16, // 1 bit
    recursion_desired: u16, // 1 bit
    recursion_available: u16, // 1 bit
    unused: u16, // 3 bits
    error_code: u16, // 4 bits
    question_count: u16, // 2 bytes
    answer_count: u16, // 2 bytes
    ns_count: u16, // 2 bytes
    ar_count: u16, // 2 bytes
}

fn unpack(buffer: &[u8]) -> Message {
    let id: u16 = (buffer[0] as u16) << 8 | buffer[1] as u16;
    let body: u16 = (buffer[2] as u16) << 8 | buffer[3] as u16;
    let question_count: u16 = (buffer[4] as u16) << 8 | buffer[5] as u16;
    let answer_count: u16 = (buffer[6] as u16) << 8 | buffer[7] as u16;
    let ns_count: u16 = (buffer[8] as u16) << 8 | buffer[9] as u16;
    let ar_count: u16 = (buffer[10] as u16) << 8 | buffer[11] as u16;

    Message {
        id: id,
        query_response: (body & (1 << 15)) >> 15,
        operation_code: (body & (15 << 11)) >> 11,
        authoritative_answer: (body & (1 >> 10)) >> 10,
        truncation_flag: (body & (1 >> 9)) >> 9,
        recursion_desired: (body & (1 >> 8)) >> 8,
        recursion_available: (body & (1 >> 7)) >> 7,
        unused: (body & (7 << 4)) >> 4,
        error_code: (body & (15 << 0)) >> 0,
        question_count: question_count,
        answer_count: answer_count,
        ns_count: ns_count,
        ar_count: ar_count,
    }
}

fn pack(message: &Message) -> Vec<u8> {
    let mut buffer: Vec<u8> = Vec::new();

    buffer.push((message.id >> 8) as u8);
    buffer.push(message.id as u8);

    let mut body: u16 = 0;

    body = body | message.query_response << 15;
    body = body | message.operation_code << 11;
    body = body | message.authoritative_answer << 10;
    body = body | message.truncation_flag << 9;
    body = body | message.recursion_desired << 8;
    body = body | message.recursion_available << 7;
    body = body | message.unused << 4;
    body = body | message.error_code;

    buffer.push((body >> 8) as u8);
    buffer.push(body as u8);

    buffer.push((message.question_count >> 8) as u8);
    buffer.push(message.question_count as u8);

    buffer.push((message.answer_count >> 8) as u8);
    buffer.push(message.answer_count as u8);

    buffer.push((message.ns_count >> 8) as u8);
    buffer.push(message.ns_count as u8);

    buffer.push((message.ar_count >> 8) as u8);
    buffer.push(message.ar_count as u8);

    buffer
}

fn main() {
    let socket = UdpSocket::bind("127.0.0.1:12043").unwrap();

    let mut buffer: [u8; 512] = [0; 512];
    let (size, source) = socket.recv_from(&mut buffer).unwrap();

    let query_message = unpack(&buffer[..size]);

    let answer_message = Message { query_response: 1, ..query_message };

    let result = pack(&answer_message);

    socket.send_to(&result, &source).unwrap();

    drop(socket);
}
<commit_msg>Read the list of questions from the query message<commit_after>use std::net::UdpSocket;
use std::str;

struct Question {
    name: Vec<String>,
    rrtype: u16,
    class: u16,
}

struct Message {
    id: u16, // 2 bytes
    query_response: u16, // 1 bit
    operation_code: u16, // 4 bits
    authoritative_answer: u16, // 1 bit
    truncation_flag: u16, // 1 bit
    recursion_desired: u16, // 1 bit
    recursion_available: u16, // 1 bit
    unused: u16, // 3 bits
    error_code: u16, // 4 bits
    question_count: u16, // 2 bytes
    answer_count: u16, // 2 bytes
    ns_count: u16, // 2 bytes
    ar_count: u16, // 2 bytes

    questions: Vec<Question>,
}

fn unpack(buffer: &[u8]) -> Message {
    let id: u16 = (buffer[0] as u16) << 8 | buffer[1] as u16;
    let body: u16 = (buffer[2] as u16) << 8 | buffer[3] as u16;
    let question_count: u16 = (buffer[4] as u16) << 8 | buffer[5] as u16;
    let answer_count: u16 = (buffer[6] as u16) << 8 | buffer[7] as u16;
    let ns_count: u16 = (buffer[8] as u16) << 8 | buffer[9] as u16;
    let ar_count: u16 = (buffer[10] as u16) << 8 | buffer[11] as u16;

    let mut offset: usize = 12;

    let mut questions = Vec::with_capacity(question_count as usize);

    for _ in 0..question_count {
        let mut name = Vec::new();

        loop {
            let size: usize = buffer[offset] as usize;

            if size == 0 {
                break;
            }

            name.push(str::from_utf8(&buffer[offset + 1 .. offset + 1 + size]).unwrap().to_string());
            offset += size + 1;
        }

        let rrtype: u16 = (buffer[offset] as u16) << 8 | buffer[offset+1] as u16;
        offset += 2;

        let class: u16 = (buffer[offset] as u16) << 8 | buffer[offset+1] as u16;
        offset += 2;

        questions.push(Question{
            name: name,
            rrtype: rrtype,
            class: class,
        })
    }

    Message {
        id: id,
        query_response: (body & (1 << 15)) >> 15,
        operation_code: (body & (15 << 11)) >> 11,
        authoritative_answer: (body & (1 >> 10)) >> 10,
        truncation_flag: (body & (1 >> 9)) >> 9,
        recursion_desired: (body & (1 >> 8)) >> 8,
        recursion_available: (body & (1 >> 7)) >> 7,
        unused: (body & (7 << 4)) >> 4,
        error_code: (body & (15 << 0)) >> 0,
        question_count: question_count,
        answer_count: answer_count,
        ns_count: ns_count,
        ar_count: ar_count,
        questions: questions,
    }
}

fn pack(message: &Message) -> Vec<u8> {
    let mut buffer: Vec<u8> = Vec::new();

    buffer.push((message.id >> 8) as u8);
    buffer.push(message.id as u8);

    let mut body: u16 = 0;

    body = body | message.query_response << 15;
    body = body | message.operation_code << 11;
    body = body | message.authoritative_answer << 10;
    body = body | message.truncation_flag << 9;
    body = body | message.recursion_desired << 8;
    body = body | message.recursion_available << 7;
    body = body | message.unused << 4;
    body = body | message.error_code;

    buffer.push((body >> 8) as u8);
    buffer.push(body as u8);

    buffer.push((message.question_count >> 8) as u8);
    buffer.push(message.question_count as u8);

    buffer.push((message.answer_count >> 8) as u8);
    buffer.push(message.answer_count as u8);

    buffer.push((message.ns_count >> 8) as u8);
    buffer.push(message.ns_count as u8);

    buffer.push((message.ar_count >> 8) as u8);
    buffer.push(message.ar_count as u8);

    buffer
}

fn main() {
    let socket = UdpSocket::bind("127.0.0.1:12043").unwrap();

    let mut buffer: [u8; 512] = [0; 512];
    let (size, source) = socket.recv_from(&mut buffer).unwrap();

    let query_message = unpack(&buffer[..size]);

    let answer_message = Message { query_response: 1, ..query_message };

    let result = pack(&answer_message);

    socket.send_to(&result, &source).unwrap();

    drop(socket);
}
<|endoftext|>


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

#[derive(Debug, PartialEq, Clone)]
enum Token<'a> {
    Unknown(&'a str), // Invalid test (basically non-ascii)
    Literal(&'a str), // Numeric literal number
    Function(Function<'a>), // Pre-defined function (like cos() )
    Constant(Constant), // Constant like pi or e
    Variable(&'a str), // str arbitrary single char variable name
    Operator(Operator), // Any of the 4 operators (+-*/)
    Open(Vec<Token<'a>>), // Open parens '(' followed by vector of tokens and a Token::Close
    Close, // Closing parens ')'
}
#[derive(Debug, PartialEq, Clone)]
enum Function<'a> {
    Sqrt(Vec<Token<'a>>),
    Ln(Vec<Token<'a>>),
    Log(f64, Vec<Token<'a>>),
    Sin(Vec<Token<'a>>),
    Cos(Vec<Token<'a>>),
    Tan(Vec<Token<'a>>),
    Asin(Vec<Token<'a>>),
    Acos(Vec<Token<'a>>),
    Atan(Vec<Token<'a>>),
    Sinh(Vec<Token<'a>>),
    Cosh(Vec<Token<'a>>),
    Tanh(Vec<Token<'a>>),
    Asinh(Vec<Token<'a>>),
    Acosh(Vec<Token<'a>>),
    Atanh(Vec<Token<'a>>),
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Constant {
	Pi,
	E,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Operator {
    Add,
    Sub,
    Div,
    Mul,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u32)]
enum Assoc {
    Left,
    Right,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u32)]
enum Order {
    AddSub = 1,
    MulDiv = 2,
    IMul = 3, // Implicit multiplication
    Pow = 4,
    Paren = 5,
}

#[derive(Debug, PartialEq, Clone)]
struct Expression<'a> {
    tokens: Vec<Token<'a>>,
    constant: f64,
}

impl<'a> Expression<'a> {
	fn new(tokens: Vec<Token<'a>>, constant: f64) -> Self {
		Expression {tokens: tokens, constant: constant}
	}

	fn push(&mut self, token: Token<'a>) {
		self.tokens.push(token);
	}

	fn update_constant(&mut self, constant: &f64) {
		self.constant += *constant;
	}
}

fn main() {
    println!("Welcome to Rust-Calculus!");
    println!("To evaluate an expression, simply type one in and hit RETURN.");
    println!("To set a variable, simply type VAR_NAME=EXPRESSION and hit RETURN.");
    println!("Valid commands are: sym_int, int, sym_def, and def.");
    println!("Type 'quit' to exit.");
    let mut input = String::new();
    let stdin = io::stdin();
    let mut stdout = io::stdout();
    loop {
    	input.clear();
    	print!(">>>> ");
    	stdout.flush().ok();
        stdin.read_line(&mut input).unwrap();
        input = strip_white_space(&input);
        input = input.to_lowercase();
        if input == "quit" {
        	print!("Exiting...");
        	break;
        }
        let mut expr = parse_input(&input).unwrap();
    }
}

fn strip_white_space(input: &String) -> String {
	input.split_whitespace().collect::<Vec<&str>>().join("")
}

fn parse_input(input: &String) -> Result<Expression, ()> {
	unimplemented!()
}<commit_msg>Got first pass of parser working, now just need to make it iterate repeatedly to develop all sets<commit_after>use std::io;
use std::io::Write;

#[derive(Debug, PartialEq, Clone)]
enum Token {
    Unknown(String), // Invalid test (basically non-ascii)
    Literal(String), // Numeric literal number
    Func(Function), // Pre-defined function (like cos() )
    Const(Constant), // Constant like pi or e
    Var(String), // str arbitrary single char variable name
    Op(Operator), // Any of the 4 operators (+-*/)
    Open, // Open parens '('
    Close, // Closing parens ')'
    Set(Vec<Token>), // [ (, tokens..., ) ]
    Fake,
}

#[derive(Debug, PartialEq, Clone)]
enum Function {
    Sqrt(Vec<Token>),
    Ln(Vec<Token>),
    Log(f64, Vec<Token>),
    Sin(Vec<Token>),
    Cos(Vec<Token>),
    Tan(Vec<Token>),
    Asin(Vec<Token>),
    Acos(Vec<Token>),
    Atan(Vec<Token>),
    Sinh(Vec<Token>),
    Cosh(Vec<Token>),
    Tanh(Vec<Token>),
    Asinh(Vec<Token>),
    Acosh(Vec<Token>),
    Atanh(Vec<Token>),
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Constant {
	Pi,
	E,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Operator {
    Add,
    Sub,
    Div,
    Mul,
    Pow,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u32)]
enum Assoc {
    Left,
    Right,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u32)]
enum Order {
    AddSub = 1,
    MulDiv = 2,
    IMul = 3, // Implicit multiplication
    Pow = 4,
    Paren = 5,
}

#[derive(Debug, PartialEq, Clone)]
struct Expression {
    tokens: Vec<Token>,
    constant: f64,
}

impl Expression {
	fn new(tokens: Vec<Token>, constant: f64) -> Self {
		Expression {tokens: tokens, constant: constant}
	}

	fn push(&mut self, token: Token) {
		self.tokens.push(token);
	}

	fn update_constant(&mut self, constant: &f64) {
		self.constant += *constant;
	}

	fn get_constant(&self) -> f64 {
		self.constant
	}

	fn get_tokens(&self) -> &[Token] {
		self.tokens.as_slice()
	}

	fn get_mut_tokens(&mut self) -> &mut [Token] {
		self.tokens.as_mut_slice()
	}

	fn replace_token(&mut self, index: usize, newToken: Token) {
		self.tokens.remove(index);
		self.tokens.insert(index, newToken);
	}

	fn replace_all_tokens(&mut self, newTokens: Vec<Token>) {
		self.tokens = newTokens
	}

	fn find_first(&self, token: &Token) -> Option<usize> {
		let mut index: usize = 0;
		for t in &self.tokens {
			if t == token {
				return Some(index);
			}
			index += 1;
		}
		None
	}

	fn find_last(&self, token: &Token) -> Option<usize> {
		let mut index: usize = 0;
		let mut found = false;
		for i in (0..self.tokens.len()).rev() {
			if self.tokens.get(i).unwrap() == token {
				index = i;
				return Some(index);
			}
		}
		None
	}

	fn split_at(&self, index: usize) -> (&[Token], &[Token]) {
		self.tokens.split_at(index)
	}

	fn len(&self) -> usize {
		self.tokens.len()
	}
}

fn main() {
    println!("Welcome to Rust-Calculus!");
    println!("To evaluate an expression, simply type one in and hit RETURN.");
    println!("To set a variable, simply type VAR_NAME=EXPRESSION and hit RETURN.");
    println!("Valid commands are: sym_int, int, sym_def, and def.");
    println!("Type 'quit' to exit.");
    let mut input = String::new();
    let stdin = io::stdin();
    let mut stdout = io::stdout();
    loop {
    	input.clear();
    	print!(">>>> ");
    	stdout.flush().ok();
        stdin.read_line(&mut input).unwrap();
        input = strip_white_space(&input);
        input = input.to_lowercase();
        if input == "quit" {
        	print!("Exiting...");
        	break;
        }
        let mut expr = parse_input(&input).unwrap();
        println!("{:?}", &expr);
    }
}

fn strip_white_space(input: &String) -> String {
	input.split_whitespace().collect::<Vec<&str>>().join("")
}

fn parse_input(input: &String) -> Result<Expression, ()> {
	let mut expr: Expression = Expression::new(Vec::new(), 0.0);
	let mut builder: Vec<Token> = Vec::new();
	for c in input.chars() {
		match c {
			'-' => {
				expr.push(Token::Op(Operator::Sub));
			},
			'+' => {
				expr.push(Token::Op(Operator::Add));
			},
			'/' => {
				expr.push(Token::Op(Operator::Div));
			},
			'*' => {
				expr.push(Token::Op(Operator::Mul));
			},
			'^' => {
				expr.push(Token::Op(Operator::Pow));
			},
			'(' => {
				expr.push(Token::Open);
			},
			')' => {
				expr.push(Token::Close);
			},
			_ => continue,
		}
	}
	if let Some(index) = expr.find_first(&Token::Open) { // If we find an index of an Open
		let endSet: usize = expr.find_last(&Token::Close).unwrap();
		let mut lhs: Vec<Token> = Vec::new();
		let mut rhs: Vec<Token> = Vec::new();
		{
			let (temp_lhs, temp_rhs) = expr.split_at(index); // [0, where set should be placed)
			lhs = temp_lhs.to_vec();
			rhs = temp_rhs.to_vec(); // [where set should be placed, len)
			rhs.remove(0);
			// split rhs at endset - 2
			// Left part gets pushed as a Set to lhs
			// Remove index 0 of right part (this is the close we split on) and add that as a vector to lhs
			let (mut left_rhs, mut right_rhs) = rhs.split_at(endSet-2);
			let (mut left_rhs, mut right_rhs) = (left_rhs.to_vec(), right_rhs.to_vec());
			right_rhs.remove(0);
			//rhs.remove(endSet-2); // Sub one because we removed the first element, need to split at endSet -2
			lhs.push(Token::Set(left_rhs));
			lhs.append(&mut right_rhs);
		}
		for i in (0..lhs.len()).rev() {
			if lhs.get(i).unwrap() == &Token::Close {
				lhs.remove(i);
				break;
			}
		}
		expr.replace_all_tokens(lhs);
	}
	Ok(expr)
}<|endoftext|>


<commit_before>fn main(expr: &str) -> i32 {
  return 0; // Let's return dummy values first.
}

#[test]
fn it_adds() {
  let result = main("+1 2");
  assert_eq!(result, 3);
}
<commit_msg>Play a bit with match<commit_after>fn main(expr: &str) -> i32 {
  let result = 0;
  for c in expr.chars() {
    match c {
      '0' ... '9' => println!("number"),
      ' ' => println!("space"),
      '+' => println!("plus"),
      _ => panic!("unsupported character")
    }
  }
  return result;
}

#[test]
fn it_adds() {
  let result = main("+1 2");
  assert_eq!(result, 3);
}
<|endoftext|>


<commit_before>#![cfg_attr(feature="clippy", plugin(clippy))]
#![feature(plugin)]

extern crate flate2;
extern crate rusoto;
extern crate crossbeam;
extern crate chrono;
extern crate syslog;

use std::io;
use std::io::prelude::*;
use std::fs::{File, remove_file};
use std::env;
use std::str::FromStr;
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::s3::{S3Client, PutObjectRequest};
use rusoto::default_tls_client;
use flate2::Compression;
use flate2::write::GzEncoder;
use chrono::prelude::Local;
use chrono::{Datelike, Timelike, Duration};
use crossbeam::scope;
use syslog::{Facility, Severity};

fn main() {

    const MAX_LINES: usize = 50000;
    const MAX_BYTES: usize = 1000000; // 1M (this feels wrong though)
    const MAX_TIMEOUT: i64 = 5; // in seconds

    println!("MAX_LINES: {}    MAX_BYTES: {}    MAX_TIMEOUT: {}",
             MAX_LINES,
             MAX_BYTES,
             MAX_TIMEOUT);

    let reader = io::stdin();
    let mut buffer = reader.lock();
    let mut data = vec![0];
    let mut time = Local::now();
    let mut timeout = time + Duration::seconds(MAX_TIMEOUT);

    loop {
        match buffer.fill_buf() {
            Ok(bytes) => {
                // add the current bytes to our data vector
                data.extend(bytes);
                if data.lines().count() >= MAX_LINES {
                    // send the data to the compress function
                    compress(data.as_slice());
                    // clear our data vector
                    data.clear();
                    // reset our timer
                    time = Local::now();
                    timeout = time + Duration::seconds(MAX_TIMEOUT);
                } else if data.len() >= MAX_BYTES {
                    // send the data to the compress function
                    compress(data.as_slice());
                    // clear our data vector
                    data.clear();
                    // reset our timer
                    time = Local::now();
                    timeout = time + Duration::seconds(MAX_TIMEOUT);
                } else if timeout <= time && !data.is_empty() {
                    // send the data to the compress function
                    compress(data.as_slice());
                    // clear our data vector
                    data.clear();
                    // reset our timer
                    time = Local::now();
                    timeout = time + Duration::seconds(MAX_TIMEOUT);
                } else {
                    // update the time
                    time = Local::now();
                }
            }
            Err(err) => panic!(err),
        }

        // consume the data from the buffer so we don't reprocess it
        buffer.consume(data.len());
    }
}

fn compress(bytes: &[u8]) {
    // our compression routine will be sent to another thread
    scope(|scope| {
        scope.spawn(move || {
            // use our environment variable of hostname. will be essentially the CBID
            let hostname = match env::var("HOSTNAME") {
                Ok(hostname) => hostname,
                Err(err) => panic!("Unable to get hostname. {}", err),
            };

            let timestamp = Local::now();

            // setting the format for how we write out the file.
            let file = format!("{}.{}-{}.raw.gz",
                               timestamp.second(),
                               timestamp.timestamp_subsec_millis(),
                               &hostname);

            let mut output = File::create(&file).unwrap();

            let mut encoder = GzEncoder::new(Vec::new(), Compression::Default);

            encoder.write_all(bytes).unwrap();

            let encoded = encoder.finish().unwrap();

            output.write_all(&encoded).unwrap();

            write_s3(&file);
        });
    });
}

fn write_s3(file: &str) {
    scope(|scope| {
        scope.spawn(move || {

            let timestamp = Local::now();
            let path = format!("{}/{}/{}/{}/{}/{}",
                               timestamp.year(),
                               timestamp.month(),
                               timestamp.day(),
                               timestamp.hour(),
                               timestamp.minute(),
                               &file);

            let provider = match DefaultCredentialsProvider::new() {
                Ok(provider) => provider,
                Err(err) => panic!("Unable to load credentials. {}", err),
            };

            let region = match env::var("AWS_DEFAULT_REGION") {
                Ok(region) => region,
                Err(err) => panic!("environment AWS_DEFAULT_REGION is not set. {}", err),
            };

            let s3 = S3Client::new(default_tls_client().unwrap(),
                                   provider,
                                   Region::from_str(&region).unwrap());

            // Open the gzip'd log file
            let mut log = File::open(&file).unwrap();
            // create a u8 vector
            let mut contents: Vec<u8> = Vec::new();
            // if we can read the contents to the buffer we will attempt to send the log to s3
            match log.read_to_end(&mut contents) {
                Err(err) => panic!("Error opening file to send to S3: {}", err),
                Ok(_) => {
                    // need to build our request
                    let req = PutObjectRequest {
                        bucket: "jkordish-test".to_owned(),
                        key: path.to_owned(),
                        body: Some(contents),
                        ..Default::default()
                    };
                    let result = s3.put_object(&req);
                    match result {
                        Ok(_) => {
                            // print notification to stdout.
                            println!("Successfully wrote {}/{}", req.bucket, &path);
                            // only remove the file if we are successful
                            if remove_file(&file).is_ok() {
                                println!("Removed file {}", &file);
                            }
                        }
                        Err(e) => println!("Could not write file {} {}", &file, e),
                    }
                    // Send some notifications to SYSLOG
                    match syslog::unix(Facility::LOG_SYSLOG) {
                        Err(e) => println!("impossible to connect to syslog: {:?}", e),
                        Ok(writer) => {
                            let success = format!("wrote {}", &path);
                            let failure = format!("unable to write {}", &path);
                            if writer.send_3164(Severity::LOG_ALERT, &success).is_err() {
                                writer.send_3164(Severity::LOG_ERR, &failure);
                            }
                        }
                    }
                }
            }
        });
    });
}
<commit_msg>cleanup compile warnings<commit_after>#![cfg_attr(feature="clippy", plugin(clippy))]
#![feature(plugin)]

extern crate flate2;
extern crate rusoto;
extern crate crossbeam;
extern crate chrono;
extern crate syslog;

use std::io;
use std::io::prelude::*;
use std::fs::{File, remove_file};
use std::env;
use std::str::FromStr;
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::s3::{S3Client, PutObjectRequest};
use rusoto::default_tls_client;
use flate2::Compression;
use flate2::write::GzEncoder;
use chrono::prelude::Local;
use chrono::{Datelike, Timelike, Duration};
use crossbeam::scope;
use syslog::{Facility, Severity};

fn main() {

    const MAX_LINES: usize = 50000;
    const MAX_BYTES: usize = 1000000; // 1M (this feels wrong though)
    const MAX_TIMEOUT: i64 = 5; // in seconds

    println!("MAX_LINES: {}    MAX_BYTES: {}    MAX_TIMEOUT: {}",
             MAX_LINES,
             MAX_BYTES,
             MAX_TIMEOUT);

    let reader = io::stdin();
    let mut buffer = reader.lock();
    let mut data = vec![0];
    let mut time = Local::now();
    let mut timeout = time + Duration::seconds(MAX_TIMEOUT);

    loop {
        match buffer.fill_buf() {
            Ok(bytes) => {
                // add the current bytes to our data vector
                data.extend(bytes);
                if data.lines().count() >= MAX_LINES || data.len() >= MAX_BYTES ||
                   timeout <= time && !data.is_empty() {
                    // send the data to the compress function
                    compress(data.as_slice());
                    // clear our data vector
                    data.clear();
                    // reset our timer
                    time = Local::now();
                    timeout = time + Duration::seconds(MAX_TIMEOUT);
                } else {
                    // update the time
                    time = Local::now();
                }
            }
            Err(err) => panic!(err),
        }

        // consume the data from the buffer so we don't reprocess it
        buffer.consume(data.len());
    }
}

fn compress(bytes: &[u8]) {
    // our compression routine will be sent to another thread
    scope(|scope| {
        scope.spawn(move || {
            // use our environment variable of hostname. will be essentially the CBID
            let hostname = match env::var("HOSTNAME") {
                Ok(hostname) => hostname,
                Err(err) => panic!("Unable to get hostname. {}", err),
            };

            let timestamp = Local::now();

            // setting the format for how we write out the file.
            let file = format!("{}.{}-{}.raw.gz",
                               timestamp.second(),
                               timestamp.timestamp_subsec_millis(),
                               &hostname);

            let mut output = File::create(&file).unwrap();

            let mut encoder = GzEncoder::new(Vec::new(), Compression::Default);

            encoder.write_all(bytes).unwrap();

            let encoded = encoder.finish().unwrap();

            output.write_all(&encoded).unwrap();

            write_s3(&file);
        });
    });
}

fn write_s3(file: &str) {
    scope(|scope| {
        scope.spawn(move || {

            let timestamp = Local::now();
            let path = format!("{}/{}/{}/{}/{}/{}",
                               timestamp.year(),
                               timestamp.month(),
                               timestamp.day(),
                               timestamp.hour(),
                               timestamp.minute(),
                               &file);

            let provider = match DefaultCredentialsProvider::new() {
                Ok(provider) => provider,
                Err(err) => panic!("Unable to load credentials. {}", err),
            };

            let region = match env::var("AWS_DEFAULT_REGION") {
                Ok(region) => region,
                Err(err) => panic!("environment AWS_DEFAULT_REGION is not set. {}", err),
            };

            let s3 = S3Client::new(default_tls_client().unwrap(),
                                   provider,
                                   Region::from_str(&region).unwrap());

            // Open the gzip'd log file
            let mut log = File::open(&file).unwrap();
            // create a u8 vector
            let mut contents: Vec<u8> = Vec::new();
            // if we can read the contents to the buffer we will attempt to send the log to s3
            match log.read_to_end(&mut contents) {
                Err(err) => panic!("Error opening file to send to S3: {}", err),
                Ok(_) => {
                    // need to build our request
                    let req = PutObjectRequest {
                        bucket: "jkordish-test".to_owned(),
                        key: path.to_owned(),
                        body: Some(contents),
                        ..Default::default()
                    };
                    match s3.put_object(&req) {
                        Ok(_) => {
                            // print notification to stdout.
                            println!("Successfully wrote {}/{}", &req.bucket, &path);
                            // only remove the file if we are successful
                            if remove_file(&file).is_ok() {
                                println!("Removed file {}", &file);
                            }
                        }
                        Err(e) => println!("Could not write file {} {}", &file, e),
                    }
                    // Send some notifications to SYSLOG
                    match syslog::unix(Facility::LOG_SYSLOG) {
                        Err(e) => println!("impossible to connect to syslog: {:?}", e),
                        Ok(writer) => {
                            let success = format!("wrote {}/{}", &req.bucket, &path);
                            let failure = format!("unable to write {}/{}", &req.bucket, &path);
                            if writer.send_3164(Severity::LOG_ALERT, &success).is_err() {
                                let _ = writer.send_3164(Severity::LOG_ERR, &failure);
                            }
                        }
                    }
                }
            }
        });
    });
}
<|endoftext|>


<commit_before>extern crate hetu;

use hetu::Ssn;
use hetu::SsnPattern;
use hetu::ParseError;
use hetu::ErrorIndexRange;
use std::env;
use std::process;

pub fn main() {
    let args: Vec<String> = env::args().skip(1).collect();
    if args.len() > 1 && &args[0] == "-p" {
        match SsnPattern::parse(&args[1]) {
            Err(ref err) => {
                eprintln!("Error: {}\n\n  {}\n  {}", err, &args[1], index_arrows(err));
                process::exit(1)
            }
            Ok(pattern) => println!("{}", Ssn::generate_by_pattern(&pattern))
        }
    } else if args.len() == 0 {
        let pattern = SsnPattern::new();
        println!("{}", Ssn::generate_by_pattern(&pattern));
    } else {
        let ssn: &String = &args[0];
        match Ssn::parse(&ssn) {
            Ok(_) => (),
            Err(ref err) => {
                eprintln!("Error: {}\n\n  {}\n  {}", err, &ssn, index_arrows(err));
                process::exit(1)
            }
        }
    }
}

fn index_arrows(err: &ParseError) -> String {
    let mut res: String = String::new();
    for _ in 0..err.start() {
        res.push_str(" ");
    }
    for _ in err.start()..err.end() {
        res.push_str("^");
    }
    res
}
<commit_msg>Add help message to CLI<commit_after>extern crate hetu;

use hetu::Ssn;
use hetu::SsnPattern;
use hetu::ParseError;
use hetu::ErrorIndexRange;
use std::env;
use std::process;

pub fn main() {
    let args: Vec<String> = env::args().skip(1).collect();
    if args.len() == 0 || &args[0] == "-h" || &args[0] == "--help" {
        println!("Validator and generator for Finnish SSN

Usage:
    hetu <ssn>
    hetu -p <pattern>
    hetu [options]

Options:
    -h, --help          Display this message
");
        return
    }
    if args.len() > 1 && &args[0] == "-p" {
        match SsnPattern::parse(&args[1]) {
            Err(ref err) => {
                eprintln!("Error: {}\n\n  {}\n  {}", err, &args[1], index_arrows(err));
                process::exit(1)
            }
            Ok(pattern) => println!("{}", Ssn::generate_by_pattern(&pattern))
        }
    } else if args.len() == 0 {
        let pattern = SsnPattern::new();
        println!("{}", Ssn::generate_by_pattern(&pattern));
    } else {
        let ssn: &String = &args[0];
        match Ssn::parse(&ssn) {
            Ok(_) => (),
            Err(ref err) => {
                eprintln!("Error: {}\n\n  {}\n  {}", err, &ssn, index_arrows(err));
                process::exit(1)
            }
        }
    }
}

fn index_arrows(err: &ParseError) -> String {
    let mut res: String = String::new();
    for _ in 0..err.start() {
        res.push_str(" ");
    }
    for _ in err.start()..err.end() {
        res.push_str("^");
    }
    res
}
<|endoftext|>


<commit_before>#![allow(unused_imports, unused_must_use, dead_code)]

extern crate bencode;
extern crate rand;
extern crate bittorrent;
extern crate hyper;

use std::{env, str, thread};
use std::io::{Read, Write};
use std::collections::HashMap;
use std::net::{Ipv4Addr, TcpStream, SocketAddrV4};
use bencode::{deserialize, deserialize_file, Bencode, TypedMethods, BencodeVecOption};
use rand::{Rng, thread_rng};
use bittorrent::querystring::QueryString;
use bittorrent::metadata::{MetadataDict, Metadata};
use bittorrent::bt_messages::{decode_message, test};
use hyper::Client;
use hyper::header::Connection;

const PEER_ID_LENGTH:usize = 20;
const PEER_ID_PREFIX:&'static str = "-TR1000-";

#[derive(Debug)]
enum Address {
    TCP(Ipv4Addr, u16)
}

fn gen_rand_peer_id (prefix: &str) -> String {
    let rand_length = PEER_ID_LENGTH - prefix.len();
    let rand = thread_rng().gen_ascii_chars()
                           .take(rand_length)
                           .collect::<String>();

    prefix.to_string() + &rand
}

fn ping_tracker (announce: &String, args: Vec<(&str, String)>) -> Option<HashMap<String, Bencode>> {
    let req_addr = announce.to_string() + "?" + &QueryString::from(args).query_string();
    println!("pinging tracker {}", req_addr);
    let client = Client::new();
    let mut res = client.get(&req_addr)
                        .header(Connection::close())
                        .send().unwrap();
    let mut body = Vec::new();
    res.read_to_end(&mut body).unwrap();

    deserialize(&body).to_singleton_dict()
}

fn get_peers <T> (tracker_response: &T) -> Vec<Address> where T:TypedMethods {
    let peers = tracker_response.get_owned_string("peers").unwrap_or_else(||panic!("no peers found"));
    //for now keep the bottom unused value, it's for ipv6. which maybe will be addressed
    (0..peers.len()/6).map(|x| {
        let ip_start = x * 6;
        let ip_end = ip_start + 4;
        let ip_bytes = &peers[ip_start..ip_end];
        let ip = Ipv4Addr::new(ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3]);
        let port = (peers[ip_end] as u16)*256 + peers[ip_end+1] as u16;
        Address::TCP(ip, port)
    }).collect::<Vec<Address>>()
}

/// The peer handshake message, according to protocol
///
fn to_handshake (pstr:&str, info_hash: &[u8; 20], peer_id: &String) -> Vec<u8> {
    let reserved = [0u8; 8];
    let pstr_bytes = pstr.to_string().into_bytes();
    let a = [pstr_bytes.len() as u8];
    let b = pstr_bytes;
    let c = reserved;
    let d = info_hash.clone();
    let e = peer_id.clone().into_bytes();

    [a.iter(),
     b.iter(),
     c.iter(),
     d.iter(),
     e.iter()].iter().flat_map(|y| {
         y.to_owned().map(|x| *x).collect::<Vec<u8>>()
     }).collect::<Vec<u8>>()
}

fn decode_handshake(resp: &[u8]) {
    println!("len: {}", resp.len());
    let (pstrlen, rest) = {
        let (l, r) = resp.split_at(1);
        (l[0], r)
    };
    //let pstr = resp[1..pstrlen+1];
}

fn connect_to_peer (address: Address, metadata: &Metadata, peer_id: &String) -> Result<String, String> {
    println!("connecting to {:?}", address);
    let (ip, port) = match address {
        Address::TCP(ip_address, port) => (ip_address, port)
    };

    let mut stream = match TcpStream::connect(SocketAddrV4::new(ip, port)) {
        Ok(tcp_stream) => tcp_stream,
        Err(err) => return Err(format!("unable to connect to peer {:?}", ip))
    };

    println!("connected to {:?}", address);

    let _ = stream.write_all(&to_handshake("BitTorrent protocol", &metadata.info_hash, peer_id));
    let _ = stream.flush();

    //for now enforce a maximum handshake size of 512 bytes
    let mut buffer = [0; 512];
    match stream.read(&mut buffer) {
        Ok(0) => Err(format!("invalid handshake from peer")),
        Ok(bytes_read) => {
            let something = &buffer[0..bytes_read];
            decode_handshake(&buffer[0..bytes_read]);
            Ok("id".to_string())
            //Ok((&buffer[0..bytes_read], buffer))
        },
        Err(err) => Err(format!("unable to read from peer {:?}", ip))
    }
}

fn init (metadata: &Metadata, listen_port: u32, bytes_dled: u32) {
    let peer_id = gen_rand_peer_id(PEER_ID_PREFIX);
    let bytes_left = metadata.get_total_length() - bytes_dled;

    let info_hash_escaped = QueryString::encode_component(&metadata.info_hash);
    let response = ping_tracker(&metadata.announce, vec![
                                ("info_hash", info_hash_escaped),
                                ("peer_id", peer_id.clone()),
                                ("port", listen_port.to_string()),
                                ("uploaded", 0.to_string()),
                                ("downloaded", bytes_dled.to_string()),
                                ("left", bytes_left.to_string()),
                                ("compact", 1.to_string()),
                                ("event", "started".to_string()),
                                ("num_want", "15".to_string())
                                ]);

    let tracker_resp = match response {
        Some(a) => a,
        None => panic!("no valid bencode response from tracker")
    };

    let peers = get_peers(&tracker_resp);
    println!("{} peers", peers.len());
    let handshake_out = to_handshake("BitTorrent protocol", &metadata.info_hash, &peer_id);

    let mut children = vec![];
    for peer in peers {
        //using Arc makes the borrow checker compain. will have to revisit for maximum memory
        //efficiency :)
        let child_meta = metadata.clone();
        let peer_id = peer_id.clone();
        children.push(thread::spawn(move || {
            connect_to_peer(peer, &child_meta, &peer_id)
        }));
    }

    for child in children {
        let _ = child.join();
    }
}

fn start_torrenting () {
    let path = env::args().nth(1)
                          .unwrap_or_else(||panic!("no path to torrent provided"));

    let content = deserialize_file(path).unwrap_or_else(||panic!("unable to parse bencoded metadata"));

    assert_eq!(content.len(), 1);

    let metadata = match content.first() {
        Some(&Bencode::Dict(ref dict)) => {
            //println!("{:?}", dict);
            dict.to_metadata()
        },
        _ => panic!("no valid information in torrent file")
    }.unwrap();

    init(&metadata, 6887, 0);
}

fn main () {
    start_torrenting();
    //test();
}
<commit_msg>finishing decode_handshake<commit_after>#![allow(unused_imports, unused_must_use, dead_code)]

extern crate bencode;
extern crate rand;
extern crate bittorrent;
extern crate hyper;

use std::{env, str, thread};
use std::io::{Read, Write};
use std::collections::HashMap;
use std::net::{Ipv4Addr, TcpStream, SocketAddrV4};
use bencode::{deserialize, deserialize_file, Bencode, TypedMethods, BencodeVecOption};
use rand::{Rng, thread_rng};
use bittorrent::querystring::QueryString;
use bittorrent::metadata::{MetadataDict, Metadata};
use bittorrent::bt_messages::{decode_message, test};
use hyper::Client;
use hyper::header::Connection;

const PEER_ID_LENGTH:usize = 20;
const PEER_ID_PREFIX:&'static str = "-TR1000-";

#[derive(Debug)]
enum Address {
    TCP(Ipv4Addr, u16)
}

fn gen_rand_peer_id (prefix: &str) -> String {
    let rand_length = PEER_ID_LENGTH - prefix.len();
    let rand = thread_rng().gen_ascii_chars()
                           .take(rand_length)
                           .collect::<String>();

    prefix.to_string() + &rand
}

fn ping_tracker (announce: &String, args: Vec<(&str, String)>) -> Option<HashMap<String, Bencode>> {
    let req_addr = announce.to_string() + "?" + &QueryString::from(args).query_string();
    println!("pinging tracker {}", req_addr);
    let client = Client::new();
    let mut res = client.get(&req_addr)
                        .header(Connection::close())
                        .send().unwrap();
    let mut body = Vec::new();
    res.read_to_end(&mut body).unwrap();

    deserialize(&body).to_singleton_dict()
}

fn get_peers <T> (tracker_response: &T) -> Vec<Address> where T:TypedMethods {
    let peers = tracker_response.get_owned_string("peers").unwrap_or_else(||panic!("no peers found"));
    //for now keep the bottom unused value, it's for ipv6. which maybe will be addressed
    (0..peers.len()/6).map(|x| {
        let ip_start = x * 6;
        let ip_end = ip_start + 4;
        let ip_bytes = &peers[ip_start..ip_end];
        let ip = Ipv4Addr::new(ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3]);
        let port = (peers[ip_end] as u16)*256 + peers[ip_end+1] as u16;
        Address::TCP(ip, port)
    }).collect::<Vec<Address>>()
}

/// The peer handshake message, according to protocol
///
fn to_handshake (pstr:&str, info_hash: &[u8; 20], peer_id: &String) -> Vec<u8> {
    let reserved = [0u8; 8];
    let pstr_bytes = pstr.to_string().into_bytes();
    let a = [pstr_bytes.len() as u8];
    let b = pstr_bytes;
    let c = reserved;
    let d = info_hash.clone();
    let e = peer_id.clone().into_bytes();

    [a.iter(),
     b.iter(),
     c.iter(),
     d.iter(),
     e.iter()].iter().flat_map(|y| {
         y.to_owned().map(|x| *x).collect::<Vec<u8>>()
     }).collect::<Vec<u8>>()
}

fn decode_handshake(resp: &[u8]) -> (u8, &[u8], &[u8], &[u8], &[u8]){
    //i realize this is the goofiest looking block ever... but you cant really destructure a
    //vector so i'm sticking with the tuples for now. maybe i'll make it look normal later
    let (pstrlen, a0) = {
        let (l, r) = resp.split_at(1 as usize);
        (l[0], r)
    };
    let (protocol, a1) = a0.split_at(pstrlen as usize);
    let (reserved, a2) = a1.split_at(8);
    let (info_hash, a3) = a2.split_at(20);
    let (peer_id, _) = a3.split_at(20);

    (pstrlen, protocol, reserved, info_hash, peer_id)
}

fn connect_to_peer (address: Address, metadata: &Metadata, peer_id: &String) -> Result<Vec<u8>, String> {
    println!("connecting to {:?}", address);
    let (ip, port) = match address {
        Address::TCP(ip_address, port) => (ip_address, port)
    };

    let mut stream = match TcpStream::connect(SocketAddrV4::new(ip, port)) {
        Ok(tcp_stream) => tcp_stream,
        Err(err) => return Err(format!("unable to connect to peer {:?}", ip))
    };

    println!("connected to {:?}", address);

    let _ = stream.write_all(&to_handshake("BitTorrent protocol", &metadata.info_hash, peer_id));
    let _ = stream.flush();

    //for now enforce a maximum handshake size of 512 bytes
    let mut buffer = [0; 512];
    match stream.read(&mut buffer) {
        Ok(0) => Err(format!("invalid handshake from peer")),
        Ok(bytes_read) => {
            let something = &buffer[0..bytes_read];
            let (pstrlen, protocol, reserved, info_hash, peer_id) = decode_handshake(&buffer[0..bytes_read]);
            Ok(peer_id.to_owned())
        },
        Err(err) => Err(format!("unable to read from peer {:?}", ip))
    }
}

fn init (metadata: &Metadata, listen_port: u32, bytes_dled: u32) {
    let peer_id = gen_rand_peer_id(PEER_ID_PREFIX);
    let bytes_left = metadata.get_total_length() - bytes_dled;

    let info_hash_escaped = QueryString::encode_component(&metadata.info_hash);
    let response = ping_tracker(&metadata.announce, vec![
                                ("info_hash", info_hash_escaped),
                                ("peer_id", peer_id.clone()),
                                ("port", listen_port.to_string()),
                                ("uploaded", 0.to_string()),
                                ("downloaded", bytes_dled.to_string()),
                                ("left", bytes_left.to_string()),
                                ("compact", 1.to_string()),
                                ("event", "started".to_string()),
                                ("num_want", "15".to_string())
                                ]);

    let tracker_resp = match response {
        Some(a) => a,
        None => panic!("no valid bencode response from tracker")
    };

    let peers = get_peers(&tracker_resp);
    println!("{} peers", peers.len());
    let handshake_out = to_handshake("BitTorrent protocol", &metadata.info_hash, &peer_id);

    let mut children = vec![];
    for peer in peers {
        //using Arc makes the borrow checker compain. will have to revisit for maximum memory
        //efficiency :)
        let child_meta = metadata.clone();
        let peer_id = peer_id.clone();
        children.push(thread::spawn(move || {
            connect_to_peer(peer, &child_meta, &peer_id)
        }));
    }

    for child in children {
        let _ = child.join();
    }
}

fn start_torrenting () {
    let path = env::args().nth(1)
                          .unwrap_or_else(||panic!("no path to torrent provided"));

    let content = deserialize_file(path).unwrap_or_else(||panic!("unable to parse bencoded metadata"));

    assert_eq!(content.len(), 1);

    let metadata = match content.first() {
        Some(&Bencode::Dict(ref dict)) => {
            //println!("{:?}", dict);
            dict.to_metadata()
        },
        _ => panic!("no valid information in torrent file")
    }.unwrap();

    init(&metadata, 6887, 0);
}

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


<commit_before>use std::ops::{Add, Sub};

#[derive(Clone, Copy, Debug)]
pub struct Vec2 {
	pub x: f32,
	pub y: f32
}

impl Vec2 {
	pub fn new(x: f32, y: f32) -> Vec2 {
		return Vec2 {x: x, y: y}
	}

	pub fn zero() -> Vec2 {
		return Vec2 {x: 0.0, y: 0.0}
	}

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

	pub fn set_zero(&mut self) {
		self.set(0.0, 0.0)
	}

	pub fn dot(&mut self, o: Vec2) -> f32 {
		return self.x * o.x + self.y * o.y;
	}

	pub fn length(self) -> f32 {
		return f32::sqrt(self.x * self.x + self.y * self.y);
	}

	pub fn multiply(self, n: f32) -> Vec2 {
		return Vec2 {x: self.x * n, y: self.y * n};
	}

	pub fn divide(self, n: f32) -> Vec2 {
		return Vec2 {x: self.x / n, y: self.y / n};
	}

	pub fn cross(self, o: Vec2) -> f32 {
		return self.x * o.y - self.y * o.x;
	}

	pub fn normal(self) -> Vec2 {
		let length = self.length();
		if length == 0.0 {
			panic!("Cannot find normal when length is zero");
		}
		return self.divide(length);
	}
}

impl Add for Vec2 {
	type Output = Vec2;

	fn add(self, _rhs: Vec2) -> Vec2 {
		return Vec2::new(self.x + _rhs.x, self.y + _rhs.y);
	}
}

impl Sub for Vec2 {
	type Output = Vec2;

	fn sub(self, _rhs: Vec2) -> Vec2 {
		return Vec2::new(self.x - _rhs.x, self.y - _rhs.y);
	}
}

/*
	Has the following format
	[a11 a12]
	[a21 a22]
*/
pub struct Mat22 {
	pub c1: Vec2,
	pub c2: Vec2
}

impl Mat22 {
	pub fn new(a11: f32, a12: f32, a21: f32, a22: f32) -> Mat22 {
		return Mat22 {
			c1: Vec2::new(a11, a21),
			c2: Vec2::new(a12, a22)
		}
	}
}
<commit_msg>Add Neg for Vec2<commit_after>use std::ops::{Add, Sub, Neg};

#[derive(Clone, Copy, Debug)]
pub struct Vec2 {
	pub x: f32,
	pub y: f32
}

impl Vec2 {
	pub fn new(x: f32, y: f32) -> Vec2 {
		return Vec2 {x: x, y: y}
	}

	pub fn zero() -> Vec2 {
		return Vec2 {x: 0.0, y: 0.0}
	}

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

	pub fn set_zero(&mut self) {
		self.set(0.0, 0.0)
	}

	pub fn dot(&mut self, o: Vec2) -> f32 {
		return self.x * o.x + self.y * o.y;
	}

	pub fn length(self) -> f32 {
		return f32::sqrt(self.x * self.x + self.y * self.y);
	}

	pub fn multiply(self, n: f32) -> Vec2 {
		return Vec2 {x: self.x * n, y: self.y * n};
	}

	pub fn divide(self, n: f32) -> Vec2 {
		return Vec2 {x: self.x / n, y: self.y / n};
	}

	pub fn cross(self, o: Vec2) -> f32 {
		return self.x * o.y - self.y * o.x;
	}

	pub fn normal(self) -> Vec2 {
		let length = self.length();
		if length == 0.0 {
			panic!("Cannot find normal when length is zero");
		}
		return self.divide(length);
	}
}

impl Add for Vec2 {
	type Output = Vec2;

	fn add(self, _rhs: Vec2) -> Vec2 {
		return Vec2::new(self.x + _rhs.x, self.y + _rhs.y);
	}
}

impl Sub for Vec2 {
	type Output = Vec2;

	fn sub(self, _rhs: Vec2) -> Vec2 {
		return Vec2::new(self.x - _rhs.x, self.y - _rhs.y);
	}
}

impl Neg for Vec2 {
	type Output = Vec2;

	fn neg(self) -> Vec2 {
		Vec2::new(-self.x, -self.y)
    }
}

/*
	Has the following format
	[a11 a12]
	[a21 a22]
*/
pub struct Mat22 {
	pub c1: Vec2,
	pub c2: Vec2
}

impl Mat22 {
	pub fn new(a11: f32, a12: f32, a21: f32, a22: f32) -> Mat22 {
		return Mat22 {
			c1: Vec2::new(a11, a21),
			c2: Vec2::new(a12, a22)
		}
	}
}
<|endoftext|>


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

//!
//! # State machine
//!
//! The `StateMachine` trait is implemented by anything that represents a state machine (aka a finite state automaton). These
//! consist of one or more states that are transitioned between upon matching a symbol from the input.
//!
//! State machines in this library can optionally attach output symbols to states. A state with an output symbol is an 'accepting'
//! state: it matches a substring of the output.
//!

use std::rc::*;

///
/// Identifies a state in a state machine
///
pub type StateId = u32;

///
/// Trait implemented by objects that represent a state machine, whose transitions depend on a particular symbol type
///
/// These state machines can be nondeterministic - which is to say, have more than one transition per state. They always
/// start in state 0.
///
pub trait StateMachine<InputSymbol, OutputSymbol> {
    ///
    /// Returns the number of states in this state machine
    ///
    fn count_states(&self) -> StateId;

    ///
    /// Returns the transitions for a particular symbol
    ///
    fn get_transitions_for_state(&self, state: StateId) -> Vec<(InputSymbol, StateId)>;

    ///
    /// If a state is an accepting state, then this returns the output symbol that should be produced if this is the longest match
    ///
    fn output_symbol_for_state(&self, state: StateId) -> Option<&OutputSymbol>;
}

///
/// Trait implemented by state machines that can be altered
///
pub trait MutableStateMachine<InputSymbol, OutputSymbol> : StateMachine<InputSymbol, OutputSymbol> {
    ///
    /// Adds a transition from a particular state to another on seeing a symbol
    ///
    fn add_transition(&mut self, state: StateId, for_symbol: InputSymbol, new_state: StateId);

    ///
    /// Ensures that a state with the specified ID exists in this state machine
    ///
    fn create_state(&mut self, state: StateId);

    ///
    /// Sets the output symbol to use for a particular state
    ///
    fn set_output_symbol(&mut self, state: StateId, new_output_symbol: OutputSymbol);

    ///
    /// Joins two states in this state machine
    ///
    /// This means that `first_state` will follow the transitions for `second_state` - that is, any transition that appears
    /// in `second_state` will also appear in `first_state` - including transitions that are added after this call.
    ///
    /// The reverse is not true: `second_state` does not acquire the transitions from `first_state`.
    ///
    /// This could be considered as creating an empty or 'epsilon' transition between the first state and the second state,
    /// which is useful for building NDFAs from regular languages.
    ///
    /// These semantics mean that callers don't have to treat empty transitions as special cases, and also ensure that state
    /// 0 is always the sole start state for the automaton.
    ///
    fn join_states(&mut self, first_state: StateId, second_state: StateId);
}

///
/// Trait used to indicate that a particular state machine is deterministic (has at most one
/// transition per symbol from the original)
///
pub trait DeterministicStateMachine<InputSymbol, OutputSymbol> : StateMachine<InputSymbol, OutputSymbol> { }

///
/// Trait implemented by things that can be converted into a non-deterministic state machine with a specific symbol for
/// the output state.
///
pub trait ToNdfa<InputSymbol> {
    fn to_ndfa<OutputSymbol>(&self, output: OutputSymbol) -> Box<StateMachine<InputSymbol, OutputSymbol>>;
}

///
/// Any reference to a state machine is also a state machine
///
impl<InputSymbol, OutputSymbol> StateMachine<InputSymbol, OutputSymbol> for Rc<StateMachine<InputSymbol, OutputSymbol>> {
    #[inline]
    fn count_states(&self) -> StateId {
        (**self).count_states()
    }

    #[inline]
    fn get_transitions_for_state(&self, state: StateId) -> Vec<(InputSymbol, StateId)> {
        (**self).get_transitions_for_state(state)
    }

    #[inline]
    fn output_symbol_for_state(&self, state: StateId) -> Option<&OutputSymbol> {
        (**self).output_symbol_for_state(state)
    }
}

impl<InputSymbol, OutputSymbol> StateMachine<InputSymbol, OutputSymbol> for Rc<DeterministicStateMachine<InputSymbol, OutputSymbol>> {
    #[inline]
    fn count_states(&self) -> StateId {
        (**self).count_states()
    }

    #[inline]
    fn get_transitions_for_state(&self, state: StateId) -> Vec<(InputSymbol, StateId)> {
        (**self).get_transitions_for_state(state)
    }

    #[inline]
    fn output_symbol_for_state(&self, state: StateId) -> Option<&OutputSymbol> {
        (**self).output_symbol_for_state(state)
    }
}

impl<InputSymbol, OutputSymbol> DeterministicStateMachine<InputSymbol, OutputSymbol> for Rc<DeterministicStateMachine<InputSymbol, OutputSymbol>> {
}
<commit_msg>Add comment about what states needs to exist<commit_after>//
//   Copyright 2016 Andrew Hunter
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

//!
//! # State machine
//!
//! The `StateMachine` trait is implemented by anything that represents a state machine (aka a finite state automaton). These
//! consist of one or more states that are transitioned between upon matching a symbol from the input.
//!
//! State machines in this library can optionally attach output symbols to states. A state with an output symbol is an 'accepting'
//! state: it matches a substring of the output.
//!

use std::rc::*;

///
/// Identifies a state in a state machine
///
pub type StateId = u32;

///
/// Trait implemented by objects that represent a state machine, whose transitions depend on a particular symbol type
///
/// These state machines can be nondeterministic - which is to say, have more than one transition per state. They always
/// start in state 0.
///
pub trait StateMachine<InputSymbol, OutputSymbol> {
    ///
    /// Returns the number of states in this state machine
    ///
    /// Note that if state x exists then state x-1 is also expected to exist provided x > 0. This means that this returns the
    /// first unused state in this state machine.
    ///
    fn count_states(&self) -> StateId;

    ///
    /// Returns the transitions for a particular symbol
    ///
    fn get_transitions_for_state(&self, state: StateId) -> Vec<(InputSymbol, StateId)>;

    ///
    /// If a state is an accepting state, then this returns the output symbol that should be produced if this is the longest match
    ///
    fn output_symbol_for_state(&self, state: StateId) -> Option<&OutputSymbol>;
}

///
/// Trait implemented by state machines that can be altered
///
pub trait MutableStateMachine<InputSymbol, OutputSymbol> : StateMachine<InputSymbol, OutputSymbol> {
    ///
    /// Adds a transition from a particular state to another on seeing a symbol
    ///
    fn add_transition(&mut self, state: StateId, for_symbol: InputSymbol, new_state: StateId);

    ///
    /// Ensures that a state with the specified ID exists in this state machine
    ///
    fn create_state(&mut self, state: StateId);

    ///
    /// Sets the output symbol to use for a particular state
    ///
    fn set_output_symbol(&mut self, state: StateId, new_output_symbol: OutputSymbol);

    ///
    /// Joins two states in this state machine
    ///
    /// This means that `first_state` will follow the transitions for `second_state` - that is, any transition that appears
    /// in `second_state` will also appear in `first_state` - including transitions that are added after this call.
    ///
    /// The reverse is not true: `second_state` does not acquire the transitions from `first_state`.
    ///
    /// This could be considered as creating an empty or 'epsilon' transition between the first state and the second state,
    /// which is useful for building NDFAs from regular languages.
    ///
    /// These semantics mean that callers don't have to treat empty transitions as special cases, and also ensure that state
    /// 0 is always the sole start state for the automaton.
    ///
    fn join_states(&mut self, first_state: StateId, second_state: StateId);
}

///
/// Trait used to indicate that a particular state machine is deterministic (has at most one
/// transition per symbol from the original)
///
pub trait DeterministicStateMachine<InputSymbol, OutputSymbol> : StateMachine<InputSymbol, OutputSymbol> { }

///
/// Trait implemented by things that can be converted into a non-deterministic state machine with a specific symbol for
/// the output state.
///
pub trait ToNdfa<InputSymbol> {
    fn to_ndfa<OutputSymbol>(&self, output: OutputSymbol) -> Box<StateMachine<InputSymbol, OutputSymbol>>;
}

///
/// Any reference to a state machine is also a state machine
///
impl<InputSymbol, OutputSymbol> StateMachine<InputSymbol, OutputSymbol> for Rc<StateMachine<InputSymbol, OutputSymbol>> {
    #[inline]
    fn count_states(&self) -> StateId {
        (**self).count_states()
    }

    #[inline]
    fn get_transitions_for_state(&self, state: StateId) -> Vec<(InputSymbol, StateId)> {
        (**self).get_transitions_for_state(state)
    }

    #[inline]
    fn output_symbol_for_state(&self, state: StateId) -> Option<&OutputSymbol> {
        (**self).output_symbol_for_state(state)
    }
}

impl<InputSymbol, OutputSymbol> StateMachine<InputSymbol, OutputSymbol> for Rc<DeterministicStateMachine<InputSymbol, OutputSymbol>> {
    #[inline]
    fn count_states(&self) -> StateId {
        (**self).count_states()
    }

    #[inline]
    fn get_transitions_for_state(&self, state: StateId) -> Vec<(InputSymbol, StateId)> {
        (**self).get_transitions_for_state(state)
    }

    #[inline]
    fn output_symbol_for_state(&self, state: StateId) -> Option<&OutputSymbol> {
        (**self).output_symbol_for_state(state)
    }
}

impl<InputSymbol, OutputSymbol> DeterministicStateMachine<InputSymbol, OutputSymbol> for Rc<DeterministicStateMachine<InputSymbol, OutputSymbol>> {
}
<|endoftext|>


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

// ignore-windows
// ignore-android
// ignore-emscripten

#![feature(libc)]

extern crate libc;

use std::env;
use std::fs::File;
use std::io;
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::os::unix::prelude::*;
use std::process::{Command, Stdio};
use std::thread;

fn main() {
    let args = env::args().collect::<Vec<_>>();
    if args.len() == 1 {
        parent()
    } else {
        child(&args)
    }
}

fn parent() {
    let file = File::open(file!()).unwrap();
    let tcp1 = TcpListener::bind("127.0.0.1:0").unwrap();
    let tcp2 = tcp1.try_clone().unwrap();
    let addr = tcp1.local_addr().unwrap();
    let t = thread::spawn(move || TcpStream::connect(addr).unwrap());
    let tcp3 = tcp1.accept().unwrap().0;
    let tcp4 = t.join().unwrap();
    let tcp5 = tcp3.try_clone().unwrap();
    let tcp6 = tcp4.try_clone().unwrap();
    let udp1 = UdpSocket::bind("127.0.0.1:0").unwrap();
    let udp2 = udp1.try_clone().unwrap();

    let mut child = Command::new(env::args().next().unwrap())
                            .arg("100")
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn().unwrap();
    let pipe1 = child.stdin.take().unwrap();
    let pipe2 = child.stdout.take().unwrap();
    let pipe3 = child.stderr.take().unwrap();

    let status = Command::new(env::args().next().unwrap())
                        .arg(file.as_raw_fd().to_string())
                        .arg(tcp1.as_raw_fd().to_string())
                        .arg(tcp2.as_raw_fd().to_string())
                        .arg(tcp3.as_raw_fd().to_string())
                        .arg(tcp4.as_raw_fd().to_string())
                        .arg(tcp5.as_raw_fd().to_string())
                        .arg(tcp6.as_raw_fd().to_string())
                        .arg(udp1.as_raw_fd().to_string())
                        .arg(udp2.as_raw_fd().to_string())
                        .arg(pipe1.as_raw_fd().to_string())
                        .arg(pipe2.as_raw_fd().to_string())
                        .arg(pipe3.as_raw_fd().to_string())
                        .status()
                        .unwrap();
    assert!(status.success());
    child.wait().unwrap();
}

fn child(args: &[String]) {
    let mut b = [0u8; 2];
    for arg in &args[1..] {
        let fd: libc::c_int = arg.parse().unwrap();
        unsafe {
            assert_eq!(libc::read(fd, b.as_mut_ptr() as *mut _, 2), -1);
            assert_eq!(io::Error::last_os_error().raw_os_error(),
                       Some(libc::EBADF));
        }
    }
}
<commit_msg>Haiku: add workaround for missing F_DUPFD_CLOEXEC<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-windows
// ignore-android
// ignore-emscripten
// ignore-haiku

#![feature(libc)]

extern crate libc;

use std::env;
use std::fs::File;
use std::io;
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::os::unix::prelude::*;
use std::process::{Command, Stdio};
use std::thread;

fn main() {
    let args = env::args().collect::<Vec<_>>();
    if args.len() == 1 {
        parent()
    } else {
        child(&args)
    }
}

fn parent() {
    let file = File::open(file!()).unwrap();
    let tcp1 = TcpListener::bind("127.0.0.1:0").unwrap();
    let tcp2 = tcp1.try_clone().unwrap();
    let addr = tcp1.local_addr().unwrap();
    let t = thread::spawn(move || TcpStream::connect(addr).unwrap());
    let tcp3 = tcp1.accept().unwrap().0;
    let tcp4 = t.join().unwrap();
    let tcp5 = tcp3.try_clone().unwrap();
    let tcp6 = tcp4.try_clone().unwrap();
    let udp1 = UdpSocket::bind("127.0.0.1:0").unwrap();
    let udp2 = udp1.try_clone().unwrap();

    let mut child = Command::new(env::args().next().unwrap())
                            .arg("100")
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn().unwrap();
    let pipe1 = child.stdin.take().unwrap();
    let pipe2 = child.stdout.take().unwrap();
    let pipe3 = child.stderr.take().unwrap();

    let status = Command::new(env::args().next().unwrap())
                        .arg(file.as_raw_fd().to_string())
                        .arg(tcp1.as_raw_fd().to_string())
                        .arg(tcp2.as_raw_fd().to_string())
                        .arg(tcp3.as_raw_fd().to_string())
                        .arg(tcp4.as_raw_fd().to_string())
                        .arg(tcp5.as_raw_fd().to_string())
                        .arg(tcp6.as_raw_fd().to_string())
                        .arg(udp1.as_raw_fd().to_string())
                        .arg(udp2.as_raw_fd().to_string())
                        .arg(pipe1.as_raw_fd().to_string())
                        .arg(pipe2.as_raw_fd().to_string())
                        .arg(pipe3.as_raw_fd().to_string())
                        .status()
                        .unwrap();
    assert!(status.success());
    child.wait().unwrap();
}

fn child(args: &[String]) {
    let mut b = [0u8; 2];
    for arg in &args[1..] {
        let fd: libc::c_int = arg.parse().unwrap();
        unsafe {
            assert_eq!(libc::read(fd, b.as_mut_ptr() as *mut _, 2), -1);
            assert_eq!(io::Error::last_os_error().raw_os_error(),
                       Some(libc::EBADF));
        }
    }
}
<|endoftext|>