<commit_before>extern crate mio;

use mio::*;
use mio::net::{SockAddr};
use mio::net::tcp::{TcpSocket, TcpAcceptor};
use mio::buf::{ByteBuf, MutByteBuf, SliceBuf};
use mio::util::Slab;

fn main() {
    const SERVER: Token = Token(1);
    let addr = SockAddr::parse("127.0.0.1:13265").unwrap();
    let server = TcpSocket::v4().unwrap()
        .bind(&addr).unwrap()
        .listen(256).unwrap();

    let mut event_loop = EventLoop::<(), ()>::new().unwrap();
    event_loop.register(&server, SERVER).unwrap();

    struct TcpHandler {
        conns: Slab<TcpSocket>,
        sock: TcpAcceptor
    };

    impl TcpHandler {
        fn accept(&mut self, event_loop: &mut EventLoop<(), ()>) {
            let conn = self.sock.accept();
            let sock = conn.unwrap().unwrap();
            let tok = self.conns.insert(sock).ok().expect("could not add connection to slab");
            event_loop.register_opt(&self.conns[tok], tok, Interest::readable(), PollOpt::edge() | PollOpt::oneshot());
        }
    }

    impl Handler<(), ()> for TcpHandler {
        fn readable(&mut self, event_loop: &mut EventLoop<(), ()>, token: Token, _: ReadHint) {
            match token {
                SERVER => {
                    self.accept(event_loop);
                }
                tok => {
                    println!("tok: {}", tok.as_usize());
                    let mut read_buf = ByteBuf::mut_with_capacity(2048);
                    let mut interest = Interest::readable();
                    match self.conns[tok].read(&mut read_buf) {
                        Ok(NonBlock::WouldBlock) => {
                            panic!("We just got readable, but were unable to read from the socket?");
                        }
                        Ok(NonBlock::Ready(r)) => {
                            let mut buf = read_buf.flip();
                            let mut sl = [0; 2048];
                            buf.read_slice(&mut sl);
                            print!("{}", String::from_utf8(sl.to_vec()).unwrap());
                            // self.interest.remove(Interest::readable());
                            // self.interest.insert(Interest::writable());
                        }
                        Err(e) => {
                            event_loop.shutdown();
                            // println!("not implemented; client err={:?}", e);
                            // interest = Interest::hup();
                            // self.interest.remove(Interest::readable());
                        }
                    }
                    event_loop.reregister(&self.conns[tok], tok, interest, PollOpt::edge() | PollOpt::oneshot());
                }
            }
        }
    }
    let mut tcp_server = TcpHandler {
        conns: Slab::new_starting_at(Token(2), 128),
        sock: server
    };
    let _ = event_loop.run(&mut tcp_server);
}
<commit_msg>wip simplfiying, no use slab<commit_after>extern crate mio;

use mio::*;
use mio::net::{SockAddr};
use mio::net::tcp::{TcpSocket, TcpAcceptor};
use mio::buf::{ByteBuf, MutByteBuf, SliceBuf};
use mio::util::Slab;

fn main() {
    const SERVER: Token = Token(1);
    let addr = SockAddr::parse("127.0.0.1:13265").unwrap();
    let server = TcpSocket::v4().unwrap()
        .bind(&addr).unwrap()
        .listen(256).unwrap();

    let mut event_loop = EventLoop::<(), ()>::new().unwrap();
    event_loop.register(&server, SERVER).unwrap();

    struct TcpHandler {
        conn: Option<TcpSocket>,
        sock: TcpAcceptor
    };

    impl TcpHandler {
        fn accept(&mut self, event_loop: &mut EventLoop<(), ()>) {
            let conn = self.sock.accept();
            let sock = conn.unwrap().unwrap();
            let tok = Token(2);
            self.conn = Some(sock);
            match self.conn {
                Some(ref c) => { event_loop.register_opt(c, tok, Interest::readable(), PollOpt::edge() | PollOpt::oneshot()); }
                None => { }
            }
        }
    }

    impl Handler<(), ()> for TcpHandler {
        fn readable(&mut self, event_loop: &mut EventLoop<(), ()>, token: Token, _: ReadHint) {
            match token {
                SERVER => {
                    self.accept(event_loop);
                }
                tok => {
                    println!("tok: {}", tok.as_usize());
                    let mut read_buf = ByteBuf::mut_with_capacity(2048);
                    let mut interest = Interest::readable();
                    match self.conn {
                        Some(ref c) => {
                            match c.read(&mut read_buf) {
                                Ok(NonBlock::WouldBlock) => {
                                    panic!("We just got readable, but were unable to read from the socket?");
                                }
                                Ok(NonBlock::Ready(r)) => {
                                    let mut buf = read_buf.flip();
                                    let mut sl = [0; 2048];
                                    buf.read_slice(&mut sl);
                                    print!("{}", String::from_utf8(sl.to_vec()).unwrap());
                                    // self.interest.remove(Interest::readable());
                                    // self.interest.insert(Interest::writable());
                                }
                                Err(e) => {
                                    event_loop.shutdown();
                                    // println!("not implemented; client err={:?}", e);
                                    // interest = Interest::hup();
                                    // self.interest.remove(Interest::readable());
                                }
                            }
                            event_loop.reregister(c, tok, interest, PollOpt::edge() | PollOpt::oneshot());
                        },
                        None => { }
                    }
                }
            }
        }
    }
    let mut tcp_server = TcpHandler {
        conn: None,
        sock: server
    };
    let _ = event_loop.run(&mut tcp_server);
}
<|endoftext|>


<commit_before>extern crate futures;
extern crate glob;
extern crate hyper;
extern crate hyper_rustls;
#[macro_use]
extern crate lazy_static;
extern crate libc;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[macro_use]
extern crate structopt;
extern crate tokio_core;
extern crate toml;

mod ghclient;
mod statics;
mod structs;
#[macro_use]
mod syslog;

use statics::CONF_PATH;
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
enum Command {
    /// Gets user public key
    #[structopt(name = "key")]
    Key {
        #[structopt(parse(from_str))]
        user: String,
    },
    /// Executes pam check
    #[structopt(name = "pam")]
    Pam,
    /// Check configuration
    #[structopt(name = "check")]
    Check {
        #[structopt(parse(from_os_str))]
        confpath: std::path::PathBuf,
    },
    /// Cleans caches up
    #[structopt(name = "cleanup")]
    CleanUp,
}

fn main() {
    let command = Command::from_args();

    use std::env;
    use std::process;

    match command {
        Command::Check { confpath } => match structs::Config::new(&confpath) {
            Ok(_) => process::exit(0),
            Err(_) => process::exit(11),
        },
        Command::Key { user } => {
            match structs::Config::new(&CONF_PATH).and_then(|conf| Ok(ghclient::GithubClient::new(&conf)))
                                                  .and_then(|client| client.print_user_public_key(&user))
            {
                Ok(_) => process::exit(0),
                Err(_) => process::exit(21),
            }
        }
        Command::Pam => match env::var("PAM_USER") {
            Ok(user) => match structs::Config::new(&CONF_PATH).and_then(|conf| Ok(ghclient::GithubClient::new(&conf)))
                                                              .and_then(|client| client.check_pam(&user))
            {
                Ok(true) => process::exit(0),
                Ok(false) => process::exit(1),
                Err(_) => process::exit(31),
            },
            Err(_) => process::exit(41),
        },
        Command::CleanUp => {
            match structs::Config::new(&CONF_PATH).and_then(|conf| Ok(ghclient::GithubClient::new(&conf)))
                                                  .and_then(|client| client.clear_all_caches())
            {
                Ok(_) => process::exit(0),
                Err(_) => process::exit(51),
            }
        }
    };
}
<commit_msg>Add subcommand to get version details<commit_after>extern crate futures;
extern crate glob;
extern crate hyper;
extern crate hyper_rustls;
#[macro_use]
extern crate lazy_static;
extern crate libc;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[macro_use]
extern crate structopt;
extern crate tokio_core;
extern crate toml;

mod ghclient;
mod statics;
mod structs;
#[macro_use]
mod syslog;

use statics::CONF_PATH;
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
enum Command {
    /// Gets user public key
    #[structopt(name = "key")]
    Key {
        #[structopt(parse(from_str))]
        user: String,
    },
    /// Executes pam check
    #[structopt(name = "pam")]
    Pam,
    /// Check configuration
    #[structopt(name = "check")]
    Check {
        #[structopt(parse(from_os_str))]
        confpath: std::path::PathBuf,
    },
    /// Cleans caches up
    #[structopt(name = "cleanup")]
    CleanUp,
    /// Displays version details
    #[structopt(name = "version")]
    Version,
}

fn main() {
    let command = Command::from_args();

    use std::env;
    use std::process;

    match command {
        Command::Check { confpath } => match structs::Config::new(&confpath) {
            Ok(_) => process::exit(0),
            Err(_) => process::exit(11),
        },
        Command::Key { user } => {
            match structs::Config::new(&CONF_PATH).and_then(|conf| Ok(ghclient::GithubClient::new(&conf)))
                                                  .and_then(|client| client.print_user_public_key(&user))
            {
                Ok(_) => process::exit(0),
                Err(_) => process::exit(21),
            }
        }
        Command::Pam => match env::var("PAM_USER") {
            Ok(user) => match structs::Config::new(&CONF_PATH).and_then(|conf| Ok(ghclient::GithubClient::new(&conf)))
                                                              .and_then(|client| client.check_pam(&user))
            {
                Ok(true) => process::exit(0),
                Ok(false) => process::exit(1),
                Err(_) => process::exit(31),
            },
            Err(_) => process::exit(41),
        },
        Command::CleanUp => {
            match structs::Config::new(&CONF_PATH).and_then(|conf| Ok(ghclient::GithubClient::new(&conf)))
                                                  .and_then(|client| client.clear_all_caches())
            {
                Ok(_) => process::exit(0),
                Err(_) => process::exit(51),
            }
        }
        Command::Version => {
            println!("{}",
                     concat!(env!("CARGO_PKG_VERSION"),
                             include_str!(concat!(env!("OUT_DIR"), "/commit-info.txt"))));
        }
    };
}
<|endoftext|>


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

#[macro_use]
extern crate ecs;
use ecs::*;
use ecs::system::{EntityProcess, EntitySystem};

extern crate shader_version;
extern crate input;
extern crate event;
extern crate graphics;
extern crate sdl2_window;
extern crate window;
extern crate opengl_graphics;
extern crate quack;

use window::WindowSettings;

use std::collections::HashMap;
use std::default::Default;
use std::rand;
use std::rand::Rng;
use event::{Event, ReleaseEvent, UpdateEvent, PressEvent, RenderEvent, RenderArgs, UpdateArgs};
use quack::Set;
use std::cell::RefCell;
use std::cell::Cell;
use std::rc::Rc;
use input::keyboard;

use opengl_graphics::{
    Gl,
};
use sdl2_window::Sdl2Window;

const WINDOW_W: f64 = 800.0;
const WINDOW_H: f64 = 600.0;
const WINDOW_PADDING: f64 = 20.0;
const VIEW_W: f64 = (WINDOW_W - 2.0 * WINDOW_PADDING);
const VIEW_H: f64 = (WINDOW_H - 2.0 * WINDOW_PADDING);

pub struct ShimmerSystem;

impl System for ShimmerSystem {
    type Components = Components;
    type Services = ();
}

pub struct DrawSystem {
    gl: Option<RefCell<Gl>>,
    event: Option<RefCell<Event>>
}

impl EntityProcess for ShimmerSystem {
    fn process(&mut self, entities: EntityIter<Components>, data: &mut DataHelper<Components, ()>) {
        for e in entities {
            let color = &mut data.colors[e];
            let ref mut rng = rand::thread_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);
        }
    }
}

impl System for DrawSystem {
    type Components = Components;
    type Services = ();
    fn is_active(&self) -> bool { false }
}

impl EntityProcess for DrawSystem {
    fn process(&mut self, entities: EntityIter<Components>, data: &mut DataHelper<Components, ()>) {
        use graphics::*;
        use ShapeVarient::*;
        let pad = WINDOW_PADDING;
        if let (Some(ref gl_cell), Some(ref event)) = (self.gl, self.event) {
            let mut gl = gl_cell.borrow_mut();
            let e = event.borrow();
            if let Some(render) = e.render_args() {
                let view_width = render.width as f64 - 2.0 * pad;
                let view_height = render.height as f64 - 2.0 * pad;
                gl.draw([pad as i32, pad as i32, view_width as i32, view_height as i32], |c, gl| { // viewport
                    graphics::clear([0.2, 0.2, 0.2, 1.0], gl);
                    graphics::rectangle([0.0, 1.0, 0.0, 1.0],
                                        [0.0, 0.0, view_width, view_height],
                                        c.transform,
                                        gl);
                    graphics::rectangle([0.0, 0.0, 0.0, 1.0],
                                        [1.0, 1.0, view_width - 2.0,  view_height - 2.0],
                                        c.transform,
                                        gl);
                    for e in entities {
                        let position = &data.positions[e];
                        let shape = &data.shapes[e];
                        let color = &data.colors[e];
                        match shape.varient {
                            Circle(rad) => {
                                graphics::ellipse([color.r, color.g, color.b, 1.0],
                                                  [
                                                      position.x,
                                                      position.y,
                                                      2.0*rad, 2.0*rad
                                                  ],
                                                  c.transform,
                                                  gl);
                            },
                            Square(w, h) => {
                                graphics::rectangle([color.r, color.g, color.b, 1.0],
                                                    [
                                                        position.x,
                                                        position.y,
                                                        w, h
                                                    ],
                                                    c.transform,
                                                    gl);
                            },
                            Point => {
                                graphics::rectangle([color.r, color.g, color.b, 1.0],
                                                    [
                                                        position.x,
                                                        position.y,
                                                        1.0f64, 1.0f64
                                                    ],
                                                    c.transform,
                                                    gl);
                            }
                        }
                    }
                });
            } // if let Some(render)
        } //gl cell
    }
}

pub struct MoveSystem {
    event: Option<RefCell<Event>>
}

impl System for MoveSystem {
    type Components = Components;
    type Services = ();
}

impl EntityProcess for MoveSystem {
    fn process(&mut self, entities: EntityIter<Components>, data: &mut DataHelper<Components, ()>) {
        use graphics::*;
        use ShapeVarient::*;
        use ClampVarient::*;
        for e in entities {
            let (vx, vy) = {
                let v = &data.velocities[e];
                (v.x, v.y)
            };
            let shape = data.shapes[e].clone();
            let clamp = data.clamps[e].clone();
            if let Some(ref event) = self.event {
                let e = event.borrow();
                if let Some(update) = e.update_args() {
                    let dt = update.dt;
                    let view_width = WINDOW_W as f64 - 2.0 * WINDOW_PADDING;
                    let view_height = WINDOW_H as f64 - 2.0 * WINDOW_PADDING;

                    let (px, py) = {
                        let position = &mut(data.positions[e]);
                        position.x += vx * dt;
                        position.y += vy * dt;
                        (position.x, position.y)
                    };

                    let (w, h) = match shape.varient {
                        Circle(r) => (r*2.0, r*2.0),
                        Square(w,h) => (w, h),
                        Point => (0.0, 0.0)
                    };

                    let velocity_mult = match clamp.varient {
                      Bounce => -1.0,
                      Stop => 0.0,
                      _ => 1.0
                    };

                    match clamp.varient {
                      Bounce | Stop => {
                        if px + w > view_width {
                          {
                              let position = &mut(data.positions[e]);
                              position.x = view_width - w;
                          }
                          let velocity  = &mut(data.velocities[e]);
                          velocity.x *= velocity_mult;
                        } else if px < 0.0 {
                          {
                              let position = &mut(data.positions[e]);
                              position.x = 0.0;
                          }
                          let velocity  = &mut(data.velocities[e]);
                          velocity.x *= velocity_mult;
                        }
                        if py + h > view_height {
                          {
                              let position = &mut(data.positions[e]);
                              position.y = view_height - h;
                          }
                          let velocity  = &mut(data.velocities[e]);
                          velocity.y *= velocity_mult;
                        } else if py < 0.0 {
                          {
                              let position = &mut(data.positions[e]);
                              position.y = 0.0;
                          }
                          let velocity  = &mut(data.velocities[e]);
                          velocity.y *= velocity_mult;
                        }
                      },
                      Remove => {
                        if px > view_width
                        || px + w < 0.0 {
                            println!("Should remove, went off horizontal edge");
                        }
                        if py > view_height
                        || py + h < 0.0 {
                            println!("Should remove, went off vertical edge");
                        }
                      }
                    }
                }
            }
        }
    }
}

pub struct ControlSystem {
    event: Option<RefCell<Event>>
}

impl System for ControlSystem {
    type Components = Components;
    type Services = ();
}

impl EntityProcess for ControlSystem {
    fn process(&mut self, entities: EntityIter<Components>, data: &mut DataHelper<Components, ()>) {
        const PADDLE_V: f64 = 800.0;
    }
}

//fn control_system(event: &Event,
//              controllers: &mut Components<PlayerController>,
//              velocities: &mut Components<Velocity>) {
//
//
//    for (eid, controller) in controllers.iter_mut() {
//        event.press(|button| {
//            if button == Keyboard(controller.up) {
//                velocities.get_mut(eid).y = -PADDLE_V;
//            } else if button == Keyboard(controller.down) {
//                velocities.get_mut(eid).y = PADDLE_V;
//            }
//        });
//        event.release(|button| {
//            if button == Keyboard(controller.up)
//            || button == Keyboard(controller.down) {
//                velocities.get_mut(eid).y = 0.0;
//            }
//        });
//    }
//}

#[derive(Clone, PartialEq, Debug)]
pub enum ClampVarient {
    Bounce,
    Stop,
    Remove // Acts when item leaves window.
}

#[derive(Clone, PartialEq, Debug)]
pub struct WindowClamp {
    varient: ClampVarient
}

#[derive(Clone, PartialEq, Debug)]
pub struct PlayerController {
    up: keyboard::Key,
    down: keyboard::Key
}

#[derive(Clone, PartialEq, Debug)]
pub struct Position {
    x: f64,
    y: f64
}

#[derive(Clone, PartialEq, Debug)]
pub struct Shimmer;

#[derive(Clone, PartialEq, Debug)]
pub struct Color {
    r: f32,
    g: f32,
    b: f32
}

#[derive(Clone, PartialEq, Debug)]
pub enum ShapeVarient {
    Point,
    Circle(f64), // radius
    Square(f64, f64), // width, height
}

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

#[derive(Clone, PartialEq, Debug)]
pub struct Shape {
    varient: ShapeVarient,
    border: Option<f64>
}

#[derive(Clone, PartialEq, Debug)]
pub struct Velocity {
    x: f64,
    y: f64
}

components! {
    Components {
        #[hot] positions: Position,
        #[hot] shapes: Shape,
        #[hot] velocities: Velocity,
        #[hot] colors: Color,
        #[hot] shimmers: Shimmer,
        #[hot] player_controllers: PlayerController,
        #[hot] clamps: WindowClamp
    }
}

systems! {
    Systems<Components, ()> {
        shimmer: EntitySystem<ShimmerSystem> = EntitySystem::new( ShimmerSystem,
            aspect!(<Components> all: [colors, shimmers])
        ),
        moves: EntitySystem<MoveSystem> = EntitySystem::new(
            MoveSystem{ event: None },
            aspect!(<Components> all: [positions, shapes, velocities, clamps])
        ),
        draw: EntitySystem<DrawSystem> = EntitySystem::new(
            DrawSystem{ gl: None, event: None },
            aspect!(<Components> all: [positions, shapes, colors])
        )
    }
}

fn make_ball(world: &mut World<Systems>) {
    const BALL_R: f64 = 20.0;
    let x = (VIEW_W - BALL_R) / 2.0;
    let y = (VIEW_H - BALL_R) / 2.0;

    let entity = world.create_entity(|entity: BuildData<Components>, data: &mut Components| {
        data.positions.add(&entity,
            Position{
                x: x,
                y: y
        });
        data.velocities.add(&entity,
            Velocity{
                x: 300.0,
                y: 200.0,
        });
        data.shimmers.add(&entity, Shimmer);
        data.shapes.add(&entity,
            Shape {
                varient: ShapeVarient::Circle(BALL_R),
                border: None
        });
        data.colors.add(&entity,
            Color{
                r: 1.0,
                g: 0.5,
                b: 0.2
        });
        data.clamps.add(&entity,
            WindowClamp {
               varient: ClampVarient::Bounce
        });
    });
}

fn make_player(world: &mut World<Systems>, p1: bool) {
    const FROM_WALL: f64 = 40.0;
    const PADDLE_W: f64 = 20.0;
    const PADDLE_H: f64 = 150.0;
    let x = if p1 {
        FROM_WALL
    } else {
        VIEW_W - FROM_WALL - PADDLE_W
    };
    let y = (VIEW_H - PADDLE_H) / 2.0;
    let entity = world.create_entity(|entity: BuildData<Components>, data: &mut Components| {
        data.positions.add(&entity,
            Position{
                x: x,
                y: y
        });
        data.shapes.add(&entity,
            Shape {
                varient: ShapeVarient::Square(PADDLE_W, PADDLE_H),
                border: None
        });
        data.colors.add(&entity,
            Color{
                r: 1.0,
                g: 0.5,
                b: 1.0
        });
        data.player_controllers.add(&entity,
            PlayerController {
                up: if p1 { keyboard::Key::W } else { keyboard::Key::I },
                down: if p1 { keyboard::Key::S } else { keyboard::Key::K },
        });
    });
}

fn main() {
    let opengl = shader_version::OpenGL::_3_2;
    let window = Sdl2Window::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::<Systems>::new();
    world.systems.draw.gl = Some(RefCell::new(gl));
    make_ball(&mut world);
    make_player(&mut world, true);
    make_player(&mut world, false);
    let mut event_cell = RefCell::new(Event::Update(UpdateArgs { dt: 0.0 }));

    world.systems.moves.event = Some(event_cell.clone());
    world.systems.draw.event = Some(event_cell.clone());

    for e in event::events(window) {
        use event::{ ReleaseEvent, UpdateEvent, PressEvent, RenderEvent };
        *(event_cell.as_unsafe_cell().get()) = e;
        world.update();
//
//        if let Some(args) = e.update_args() {
//            meta.update.set(e);
//            world.update();
//        }
//        if let Some(args) = e.render_args() {
//            meta.render.set(args);
//            process!(world, draw);
//        }
//        if let Some(args) = e.press_args() {
//            meta.press.set(args);
//            process!(world, draw);
//        }
//        if let Some(args) = e.release_args() {
//            meta.release.set(args);
//            process!(world, draw);
//        }
    }
}
<commit_msg>Control system<commit_after>#![allow(unused_variables, unused_imports)]

#[macro_use]
extern crate ecs;
use ecs::*;
use ecs::system::{EntityProcess, EntitySystem};

extern crate shader_version;
extern crate input;
extern crate event;
extern crate graphics;
extern crate sdl2_window;
extern crate window;
extern crate opengl_graphics;
extern crate quack;

use window::WindowSettings;

use std::collections::HashMap;
use std::default::Default;
use std::rand;
use std::rand::Rng;
use event::{Event, ReleaseEvent, UpdateEvent, PressEvent, RenderEvent, RenderArgs, UpdateArgs};
use quack::Set;
use std::cell::RefCell;
use std::cell::Cell;
use std::rc::Rc;
use input::keyboard;

use opengl_graphics::{
    Gl,
};
use sdl2_window::Sdl2Window;

const WINDOW_W: f64 = 800.0;
const WINDOW_H: f64 = 600.0;
const WINDOW_PADDING: f64 = 20.0;
const VIEW_W: f64 = (WINDOW_W - 2.0 * WINDOW_PADDING);
const VIEW_H: f64 = (WINDOW_H - 2.0 * WINDOW_PADDING);

pub struct ShimmerSystem;

impl System for ShimmerSystem {
    type Components = Components;
    type Services = Services;
}

pub struct DrawSystem {
    gl: Option<RefCell<Gl>>,
}

impl EntityProcess for ShimmerSystem {
    fn process(&mut self, entities: EntityIter<Components>, data: &mut DataHelper<Components, Services>) {
        for e in entities {
            let color = &mut data.colors[e];
            let ref mut rng = rand::thread_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);
        }
    }
}

impl System for DrawSystem {
    type Components = Components;
    type Services = Services;
}

impl EntityProcess for DrawSystem {
    fn process(&mut self, entities: EntityIter<Components>, data: &mut DataHelper<Components, Services>) {
        use graphics::*;
        use ShapeVarient::*;
        let pad = WINDOW_PADDING;
        if let Some(ref gl_cell) = self.gl {
            let mut gl = gl_cell.borrow_mut();
            let event = data.services.event.borrow();
            if let Some(render) = event.render_args() {
                let view_width = render.width as f64 - 2.0 * pad;
                let view_height = render.height as f64 - 2.0 * pad;
                gl.draw([pad as i32, pad as i32, view_width as i32, view_height as i32], |c, gl| { // viewport
                    graphics::clear([0.2, 0.2, 0.2, 1.0], gl);
                    graphics::rectangle([0.0, 1.0, 0.0, 1.0],
                                        [0.0, 0.0, view_width, view_height],
                                        c.transform,
                                        gl);
                    graphics::rectangle([0.0, 0.0, 0.0, 1.0],
                                        [1.0, 1.0, view_width - 2.0,  view_height - 2.0],
                                        c.transform,
                                        gl);
                    for e in entities {
                        let position = &data.positions[e];
                        let shape = &data.shapes[e];
                        let color = &data.colors[e];
                        match shape.varient {
                            Circle(rad) => {
                                graphics::ellipse([color.r, color.g, color.b, 1.0],
                                                  [
                                                      position.x,
                                                      position.y,
                                                      2.0*rad, 2.0*rad
                                                  ],
                                                  c.transform,
                                                  gl);
                            },
                            Square(w, h) => {
                                graphics::rectangle([color.r, color.g, color.b, 1.0],
                                                    [
                                                        position.x,
                                                        position.y,
                                                        w, h
                                                    ],
                                                    c.transform,
                                                    gl);
                            },
                            Point => {
                                graphics::rectangle([color.r, color.g, color.b, 1.0],
                                                    [
                                                        position.x,
                                                        position.y,
                                                        1.0f64, 1.0f64
                                                    ],
                                                    c.transform,
                                                    gl);
                            }
                        }
                    }
                });
            } // if let Some(render)
        } //gl cell
    }
}

pub struct MoveSystem;

impl System for MoveSystem {
    type Components = Components;
    type Services = Services;
}

impl EntityProcess for MoveSystem {
    fn process(&mut self, entities: EntityIter<Components>, data: &mut DataHelper<Components, Services>) {
        use graphics::*;
        use ShapeVarient::*;
        use ClampVarient::*;
        for e in entities {
            let (vx, vy) = {
                let v = &data.velocities[e];
                (v.x, v.y)
            };
            let shape = data.shapes[e].clone();
            let clamp = data.clamps[e].clone();
            let event = data.services.event.clone();
            let event =  event.borrow();
                if let Some(update) = event.update_args() {
                    let dt = update.dt;
                    let view_width = WINDOW_W as f64 - 2.0 * WINDOW_PADDING;
                    let view_height = WINDOW_H as f64 - 2.0 * WINDOW_PADDING;

                    let (px, py) = {
                        let position = &mut(data.positions[e]);
                        position.x += vx * dt;
                        position.y += vy * dt;
                        (position.x, position.y)
                    };

                    let (w, h) = match shape.varient {
                        Circle(r) => (r*2.0, r*2.0),
                        Square(w,h) => (w, h),
                        Point => (0.0, 0.0)
                    };

                    let velocity_mult = match clamp.varient {
                      Bounce => -1.0,
                      Stop => 0.0,
                      _ => 1.0
                    };

                    match clamp.varient {
                      Bounce | Stop => {
                        if px + w > view_width {
                          {
                              let position = &mut(data.positions[e]);
                              position.x = view_width - w;
                          }
                          let velocity  = &mut(data.velocities[e]);
                          velocity.x *= velocity_mult;
                        } else if px < 0.0 {
                          {
                              let position = &mut(data.positions[e]);
                              position.x = 0.0;
                          }
                          let velocity  = &mut(data.velocities[e]);
                          velocity.x *= velocity_mult;
                        }
                        if py + h > view_height {
                          {
                              let position = &mut(data.positions[e]);
                              position.y = view_height - h;
                          }
                          let velocity  = &mut(data.velocities[e]);
                          velocity.y *= velocity_mult;
                        } else if py < 0.0 {
                          {
                              let position = &mut(data.positions[e]);
                              position.y = 0.0;
                          }
                          let velocity  = &mut(data.velocities[e]);
                          velocity.y *= velocity_mult;
                        }
                      },
                      Remove => {
                        if px > view_width
                        || px + w < 0.0 {
                            println!("Should remove, went off horizontal edge");
                        }
                        if py > view_height
                        || py + h < 0.0 {
                            println!("Should remove, went off vertical edge");
                        }
                      }
                }
            }
        }
    }
}

pub struct ControlSystem;

impl System for ControlSystem {
    type Components = Components;
    type Services = Services;
}

impl EntityProcess for ControlSystem {
    fn process(&mut self, entities: EntityIter<Components>, data: &mut DataHelper<Components, Services>) {
        use input::Button::Keyboard;
        const PADDLE_V: f64 = 800.0;
        for e in entities {
            let (vx, vy) = {
                let v = &data.velocities[e];
                (v.x, v.y)
            };
            let event = data.services.event.clone();
            let event =  event.borrow();
            let (up, down) = {
                let controller  = &(data.player_controllers[e]);
                (Keyboard(controller.up), Keyboard(controller.down))
            };
            let velocity = &mut(data.velocities[e]);
            event.press(|button| {
                if button == up {
                    velocity.y = -PADDLE_V;
                } else if button == down {
                    velocity.y = PADDLE_V;
                }
            });
            event.release(|button| {
                if button == up
                || button == down {
                    velocity.y = 0.0;
                }
            });
        }
    }
}

#[derive(Clone, PartialEq, Debug)]
pub enum ClampVarient {
    Bounce,
    Stop,
    Remove // Acts when item leaves window.
}

#[derive(Clone, PartialEq, Debug)]
pub struct WindowClamp {
    varient: ClampVarient
}

#[derive(Clone, PartialEq, Debug)]
pub struct PlayerController {
    up: keyboard::Key,
    down: keyboard::Key
}

#[derive(Clone, PartialEq, Debug)]
pub struct Position {
    x: f64,
    y: f64
}

#[derive(Clone, PartialEq, Debug)]
pub struct Shimmer;

#[derive(Clone, PartialEq, Debug)]
pub struct Color {
    r: f32,
    g: f32,
    b: f32
}

#[derive(Clone, PartialEq, Debug)]
pub enum ShapeVarient {
    Point,
    Circle(f64), // radius
    Square(f64, f64), // width, height
}

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

#[derive(Clone, PartialEq, Debug)]
pub struct Shape {
    varient: ShapeVarient,
    border: Option<f64>
}

#[derive(Clone, PartialEq, Debug)]
pub struct Velocity {
    x: f64,
    y: f64
}

components! {
    Components {
        #[hot] positions: Position,
        #[hot] shapes: Shape,
        #[hot] velocities: Velocity,
        #[hot] colors: Color,
        #[hot] shimmers: Shimmer,
        #[hot] player_controllers: PlayerController,
        #[hot] clamps: WindowClamp
    }
}

systems! {
    Systems<Components, Services> {
        shimmer: EntitySystem<ShimmerSystem> = EntitySystem::new( ShimmerSystem,
            aspect!(<Components> all: [colors, shimmers])
        ),
        control: EntitySystem<ControlSystem> = EntitySystem::new(
            ControlSystem,
            aspect!(<Components> all: [player_controllers, velocities])
        ),
        moves: EntitySystem<MoveSystem> = EntitySystem::new(
            MoveSystem,
            aspect!(<Components> all: [positions, shapes, velocities, clamps])
        ),
        draw: EntitySystem<DrawSystem> = EntitySystem::new(
            DrawSystem{ gl: None },
            aspect!(<Components> all: [positions, shapes, colors])
        )
    }
}

services! {
    Services {
        event: RefCell<Event> =
            RefCell::new(Event::Update(UpdateArgs { dt: 3.14 }))
    }
}

fn make_ball(world: &mut World<Systems>) {
    const BALL_R: f64 = 20.0;
    let x = (VIEW_W - BALL_R) / 2.0;
    let y = (VIEW_H - BALL_R) / 2.0;

    let entity = world.create_entity(|entity: BuildData<Components>, data: &mut Components| {
        data.positions.add(&entity,
            Position{
                x: x,
                y: y
        });
        data.velocities.add(&entity,
            Velocity{
                x: 300.0,
                y: 200.0,
        });
        data.shimmers.add(&entity, Shimmer);
        data.shapes.add(&entity,
            Shape {
                varient: ShapeVarient::Circle(BALL_R),
                border: None
        });
        data.colors.add(&entity,
            Color{
                r: 1.0,
                g: 0.5,
                b: 0.2
        });
        data.clamps.add(&entity,
            WindowClamp {
               varient: ClampVarient::Bounce
        });
    });
}

fn make_player(world: &mut World<Systems>, p1: bool) {
    const FROM_WALL: f64 = 40.0;
    const PADDLE_W: f64 = 20.0;
    const PADDLE_H: f64 = 150.0;
    let x = if p1 {
        FROM_WALL
    } else {
        VIEW_W - FROM_WALL - PADDLE_W
    };
    let y = (VIEW_H - PADDLE_H) / 2.0;
    let entity = world.create_entity(|entity: BuildData<Components>, data: &mut Components| {
        data.positions.add(&entity,
            Position{
                x: x,
                y: y
        });
        data.velocities.add(&entity,
            Velocity{
                x: 0.0,
                y: 0.0,
        });
        data.shapes.add(&entity,
            Shape {
                varient: ShapeVarient::Square(PADDLE_W, PADDLE_H),
                border: None
        });
        data.colors.add(&entity,
            Color{
                r: 1.0,
                g: 0.5,
                b: 1.0
        });
        data.player_controllers.add(&entity,
            PlayerController {
                up: if p1 { keyboard::Key::W } else { keyboard::Key::I },
                down: if p1 { keyboard::Key::S } else { keyboard::Key::K },
        });
        data.clamps.add(&entity,
            WindowClamp {
               varient: ClampVarient::Stop
        });
    });
}

fn main() {
    let opengl = shader_version::OpenGL::_3_2;
    let window = Sdl2Window::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::<Systems>::new();
    world.systems.draw.gl = Some(RefCell::new(gl));
    make_ball(&mut world);
    make_player(&mut world, true);
    make_player(&mut world, false);

    for e in event::events(window) {
        use event::{ ReleaseEvent, UpdateEvent, PressEvent, RenderEvent};
        *(world.data.services.event.borrow_mut()) = e;
        world.update();
    }
}
<|endoftext|>


<commit_before>use crate::utils::printing;
use structopt::StructOpt;

mod commands;
mod utils;

/// Personal CLI.
#[derive(StructOpt)]
enum Commands {
    /// Reproduce my machine's configuration.
    Setup,

    /// Upgrade what's installed on my machine.
    Upgrade,

    /// Clean up my machine's state.
    End,

    /// Start a study session.
    Study,
}

fn main() {
    match Commands::from_args() {
        Commands::Setup => {
            printing::heading("Reproducing my machine's configuration.");
            commands::setup();
        }
        Commands::Upgrade => {
            printing::heading("Upgrading what's installed on my machine.");
            commands::upgrade();
        }
        Commands::End => {
            printing::heading("Cleaning up my machine's state.");
            commands::end();
        }
        Commands::Study => {
            printing::heading("Starting a study session.");
            commands::study();
        }
    }
}
<commit_msg>Keep public facing API descriptions consistent<commit_after>use crate::utils::printing;
use structopt::StructOpt;

mod commands;
mod utils;

/// Personal CLI.
#[derive(StructOpt)]
enum Commands {
    /// Reproduce my machine's configuration.
    Setup,

    /// Upgrade what's installed on my machine.
    Upgrade,

    /// Clean up my machine's state.
    End,

    /// Start one of my study sessions.
    Study,
}

fn main() {
    match Commands::from_args() {
        Commands::Setup => {
            printing::heading("Reproducing my machine's configuration.");
            commands::setup();
        }
        Commands::Upgrade => {
            printing::heading("Upgrading what's installed on my machine.");
            commands::upgrade();
        }
        Commands::End => {
            printing::heading("Cleaning up my machine's state.");
            commands::end();
        }
        Commands::Study => {
            printing::heading("Starting one of my study sessions.");
            commands::study();
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2015 Jan Likar.
//
// 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.

extern crate cargo;
extern crate docopt;
extern crate rustc_serialize;
extern crate cargo_clone;

use cargo::core::SourceId;
use cargo::util::{Config, CliResult};

use docopt::Docopt;

#[derive(RustcDecodable, Debug)]
pub struct Options {
    flag_verbose: bool,
    flag_quiet: bool,
    flag_color: Option<String>,
    flag_version: bool,

    arg_crate: Option<String>,
    flag_vers: Option<String>,

    flag_path: Option<String>,
}

pub const USAGE: &'static str = "
Clone source code of a Rust crate

Usage:
    cargo clone [options] [<crate>]

Options:
    --vers VERS               Specify a version to clone from crates.io
    -h, --help                Print this message
    -V, --version             Print version information
    -v, --verbose             Use verbose output
    -q, --quiet               Less output printed to stdout
    --color WHEN              Coloring: auto, always, never
";

fn main() {
    let options: Options = Docopt::new(USAGE)
                                  .and_then(|d| d.version(Some(version())).decode())
                                  .unwrap_or_else(|e| e.exit());

    let config = Config::default().expect("Unable to get config");

    if let Err(e) = execute(options, config) {
        println!("{}", e.to_string())
    }
}

fn version() -> String {
    format!("cargo-clone {}.{}.{}{}",
            option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
            option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
            option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
            option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""))
}

pub fn execute(options: Options, config: Config) -> CliResult<Option<()>> {
    try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
    try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));

    // Make a SourceId for the central Registry (usually crates.io)
    let source_id = try!(SourceId::for_central(&config));

    try!(cargo_clone::ops::clone(&options.arg_crate, &source_id, options.flag_vers, config));

    Ok(None)
}
<commit_msg>Improve error handling<commit_after>// Copyright 2015 Jan Likar.
//
// 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.

extern crate cargo;
extern crate docopt;
extern crate rustc_serialize;
extern crate cargo_clone;

use std::io::{self, Write};

use cargo::core::SourceId;
use cargo::util::{Config, CliResult};

use docopt::Docopt;

#[derive(RustcDecodable, Debug)]
pub struct Options {
    flag_verbose: bool,
    flag_quiet: bool,
    flag_color: Option<String>,
    flag_version: bool,

    arg_crate: Option<String>,
    flag_vers: Option<String>,

    flag_path: Option<String>,
}

pub const USAGE: &'static str = "
Clone source code of a Rust crate

Usage:
    cargo clone [options] [<crate>]

Options:
    --vers VERS               Specify a version to clone from crates.io
    -h, --help                Print this message
    -V, --version             Print version information
    -v, --verbose             Use verbose output
    -q, --quiet               Less output printed to stdout
    --color WHEN              Coloring: auto, always, never
";

fn main() {
    let options: Options = Docopt::new(USAGE)
                                  .and_then(|d| d.version(Some(version())).decode())
                                  .unwrap_or_else(|e| e.exit());

    let config = Config::default().expect("Unable to get config");

    if let Err(e) = execute(options, config) {
        write!(io::stderr(), "{}\n", e.to_string()).unwrap();
        std::process::exit(101);
    }
}

fn version() -> String {
    format!("cargo-clone {}.{}.{}{}",
            option_env!("CARGO_PKG_VERSION_MAJOR").unwrap_or("X"),
            option_env!("CARGO_PKG_VERSION_MINOR").unwrap_or("X"),
            option_env!("CARGO_PKG_VERSION_PATCH").unwrap_or("X"),
            option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""))
}

pub fn execute(options: Options, config: Config) -> CliResult<Option<()>> {
    try!(config.shell().set_verbosity(options.flag_verbose, options.flag_quiet));
    try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));

    // Make a SourceId for the central Registry (usually crates.io)
    let source_id = try!(SourceId::for_central(&config));

    try!(cargo_clone::ops::clone(&options.arg_crate, &source_id, options.flag_vers, config));

    Ok(None)
}
<|endoftext|>


<commit_before>/*
 * Copyright 2017 Michael Krolikowski
 *
 * 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.
 */

#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate nom;
#[macro_use]
extern crate clap;
extern crate regex;
extern crate time;

use clap::{Arg, ArgMatches};
use std::thread::sleep;
use std::process::exit;
use time::{Duration, now_utc};

mod errors;

use errors::*;

mod logfile;

use logfile::*;

mod dateregex;

use dateregex::*;

fn relog(date_extraction_regex: &str, date_format: &str, filename: &str) -> Result<()> {
    let log_entry_parser = LogEntryParser::new(date_extraction_regex, date_format)?;
    let mut log_file = LogFile::new(filename, &log_entry_parser)?.peekable();

    let start_date_sys = now_utc();
    let mut start_date_log = {
        log_file.peek().and_then(|l| l.date)
    };
    for log_entry in log_file {
        let current_date_sys = now_utc();
        let current_date_log = log_entry.date;

        let sleep_duration = {
            match (start_date_log, current_date_log) {
                (Some(start_date_log), Some(current_date_log)) => std::cmp::max(Duration::zero(), (current_date_log - start_date_log) - (current_date_sys - start_date_sys)),
                _ => Duration::zero()
            }
        };

        if start_date_log.is_none() {
            start_date_log = current_date_log
        }

        if sleep_duration > Duration::zero() {
            if let Ok(sleep_duration) = sleep_duration.to_std() {
                sleep(sleep_duration)
            }
        }
        println!("{}", log_entry.line);
    }

    Ok(())
}

fn run() -> Result<()> {
    let matches: ArgMatches = app_from_crate!()
        .arg(Arg::with_name("date_extraction_regex")
            .short("r")
            .long("regex")
            .value_name("regex")
            .help("regex to extract date from log messages (default is generated from date format)"))
        .arg(Arg::with_name("date_format")
            .short("f")
            .long("format")
            .value_name("format")
            .default_value("%Y-%m-%d %H:%M:%S")
            .help("date format of logfile as specified in strftime(3)"))
        .arg(Arg::with_name("logfile")
            .help("logfile to read")
            .required(true))
        .get_matches();

    let date_format = matches.value_of("date_format").ok_or(Error::from("date_format missing"))?;
    let logfile = matches.value_of("logfile").ok_or(Error::from("logfile missing"))?;
    let date_extraction_regex = matches
        .value_of("date_extraction_regex")
        .ok_or(Error::from("date_extraction_regex missing"))
        .map(String::from)
        .or(
            regex_from_date_format(&date_format.as_bytes())
                .to_result()
                .chain_err(|| "failed to create regex from date_format")
        )?;

    relog(&date_extraction_regex, date_format, logfile)
}

fn main() {
    if let Err(ref e) = run() {
        println!("Error: {}", e);
        exit(1);
    }
}
<commit_msg>colored help message, use of quick_main! macro<commit_after>/*
 * Copyright 2017 Michael Krolikowski
 *
 * 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.
 */

#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate nom;
#[macro_use]
extern crate clap;
extern crate regex;
extern crate time;

use clap::{AppSettings, Arg, ArgMatches};
use std::thread::sleep;
use time::{Duration, now_utc};

mod errors;

use errors::*;

mod logfile;

use logfile::*;

mod dateregex;

use dateregex::*;

fn relog(date_extraction_regex: &str, date_format: &str, filename: &str) -> Result<()> {
    let log_entry_parser = LogEntryParser::new(date_extraction_regex, date_format)?;
    let mut log_file = LogFile::new(filename, &log_entry_parser)?.peekable();

    let start_date_sys = now_utc();
    let mut start_date_log = {
        log_file.peek().and_then(|l| l.date)
    };
    for log_entry in log_file {
        let current_date_sys = now_utc();
        let current_date_log = log_entry.date;

        let sleep_duration = {
            match (start_date_log, current_date_log) {
                (Some(start_date_log), Some(current_date_log)) => std::cmp::max(Duration::zero(), (current_date_log - start_date_log) - (current_date_sys - start_date_sys)),
                _ => Duration::zero()
            }
        };

        if start_date_log.is_none() {
            start_date_log = current_date_log
        }

        if sleep_duration > Duration::zero() {
            if let Ok(sleep_duration) = sleep_duration.to_std() {
                sleep(sleep_duration)
            }
        }
        println!("{}", log_entry.line);
    }

    Ok(())
}

fn run() -> Result<()> {
    let matches: ArgMatches = app_from_crate!()
        .global_setting(AppSettings::ColoredHelp)
        .arg(Arg::with_name("date_extraction_regex")
            .short("r")
            .long("regex")
            .value_name("regex")
            .help("regex to extract date from log messages (default is generated from date format)"))
        .arg(Arg::with_name("date_format")
            .short("f")
            .long("format")
            .value_name("format")
            .default_value("%Y-%m-%d %H:%M:%S")
            .help("date format of logfile as specified in strftime(3)"))
        .arg(Arg::with_name("logfile")
            .help("logfile to read")
            .required(true))
        .get_matches();

    let date_format = matches.value_of("date_format").ok_or(Error::from("date_format missing"))?;
    let logfile = matches.value_of("logfile").ok_or(Error::from("logfile missing"))?;
    let date_extraction_regex = matches
        .value_of("date_extraction_regex")
        .ok_or(Error::from("date_extraction_regex missing"))
        .map(String::from)
        .or(
            regex_from_date_format(&date_format.as_bytes())
                .to_result()
                .chain_err(|| "failed to create regex from date_format")
        )?;

    relog(&date_extraction_regex, date_format, logfile)
}

quick_main!(run);
<|endoftext|>


<commit_before>#![allow(unknown_lints)]
#![allow(unused_doc_comment)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "allocator", feature(alloc_system, global_allocator, allocator_api))]
#[cfg(feature = "allocator")]
extern crate alloc_system;
#[cfg(feature = "allocator")]
use alloc_system::System;
#[cfg(feature = "allocator")]
#[global_allocator]
static A: System = System;

extern crate amy;
extern crate base32;
extern crate base64;
extern crate bincode;
extern crate byteorder;
extern crate chrono;
#[macro_use]
extern crate error_chain;
extern crate fnv;
extern crate fs_extra;
extern crate getopts;
extern crate http_range;
extern crate httparse;
#[macro_use]
extern crate lazy_static;
extern crate memmap;
extern crate metrohash;
extern crate net2;
extern crate nix;
extern crate num_bigint;
extern crate openssl;
extern crate rand;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate shellexpand;
extern crate toml;
extern crate url;
extern crate vecio;

extern crate adns;
extern crate synapse_bencode as bencode;
extern crate synapse_rpc as rpc_lib;
extern crate synapse_session as session;

#[macro_use]
mod log;
mod args;
mod buffers;
mod handle;
mod torrent;
mod util;
mod socket;
mod disk;
mod tracker;
mod control;
mod listener;
mod rpc;
mod throttle;
mod config;
mod stat;
mod init;

// We need to do this for the log macros
use log::LogLevel;
use std::sync::{atomic, Arc, Mutex};
use std::process;

pub const DHT_EXT: (usize, u8) = (7, 1);
pub const EXT_PROTO: (usize, u8) = (5, 0x10);
pub const UT_META_ID: u8 = 9;
pub const UT_PEX_ID: u8 = 11;

/// Throttler max token amount
pub const THROT_TOKS: usize = 2 * 1024 * 1024;

pub static SHUTDOWN: atomic::AtomicBool = atomic::ATOMIC_BOOL_INIT;

lazy_static! {
    pub static ref CONFIG: config::Config = { config::Config::load() };
    pub static ref PEER_ID: [u8; 20] = {
        use rand::{self, Rng};

        let mut pid = [0u8; 20];
        let prefix = b"-SY0001-";
        for i in 0..prefix.len() {
            pid[i] = prefix[i];
        }

        let mut rng = rand::thread_rng();
        for i in prefix.len()..20 {
            pid[i] = rng.gen::<u8>();
        }
        pid
    };
    pub static ref DL_TOKEN: Arc<Mutex<String>> = { Arc::new(Mutex::new(util::random_string(20))) };
}

fn main() {
    let args = args::args();
    match init::init(args) {
        Ok(()) => {}
        Err(()) => {
            error!("Failed to initialize synapse!");
            process::exit(1);
        }
    }
    info!("Initialized, starting!");
    match init::run() {
        Ok(()) => process::exit(0),
        Err(()) => process::exit(1),
    }
}
<commit_msg>Update peer ID<commit_after>#![allow(unknown_lints)]
#![allow(unused_doc_comment)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "allocator", feature(alloc_system, global_allocator, allocator_api))]
#[cfg(feature = "allocator")]
extern crate alloc_system;
#[cfg(feature = "allocator")]
use alloc_system::System;
#[cfg(feature = "allocator")]
#[global_allocator]
static A: System = System;

extern crate amy;
extern crate base32;
extern crate base64;
extern crate bincode;
extern crate byteorder;
extern crate chrono;
#[macro_use]
extern crate error_chain;
extern crate fnv;
extern crate fs_extra;
extern crate getopts;
extern crate http_range;
extern crate httparse;
#[macro_use]
extern crate lazy_static;
extern crate memmap;
extern crate metrohash;
extern crate net2;
extern crate nix;
extern crate num_bigint;
extern crate openssl;
extern crate rand;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate shellexpand;
extern crate toml;
extern crate url;
extern crate vecio;

extern crate adns;
extern crate synapse_bencode as bencode;
extern crate synapse_rpc as rpc_lib;
extern crate synapse_session as session;

#[macro_use]
mod log;
mod args;
mod buffers;
mod handle;
mod torrent;
mod util;
mod socket;
mod disk;
mod tracker;
mod control;
mod listener;
mod rpc;
mod throttle;
mod config;
mod stat;
mod init;

// We need to do this for the log macros
use log::LogLevel;
use std::sync::{atomic, Arc, Mutex};
use std::process;

pub const DHT_EXT: (usize, u8) = (7, 1);
pub const EXT_PROTO: (usize, u8) = (5, 0x10);
pub const UT_META_ID: u8 = 9;
pub const UT_PEX_ID: u8 = 11;

/// Throttler max token amount
pub const THROT_TOKS: usize = 2 * 1024 * 1024;

pub static SHUTDOWN: atomic::AtomicBool = atomic::ATOMIC_BOOL_INIT;

lazy_static! {
    pub static ref CONFIG: config::Config = { config::Config::load() };
    pub static ref PEER_ID: [u8; 20] = {
        use rand::{self, Rng};

        let mut pid = [0u8; 20];
        let prefix = b"-SY0002-";
        for i in 0..prefix.len() {
            pid[i] = prefix[i];
        }

        let mut rng = rand::thread_rng();
        for i in prefix.len()..20 {
            pid[i] = rng.gen::<u8>();
        }
        pid
    };
    pub static ref DL_TOKEN: Arc<Mutex<String>> = { Arc::new(Mutex::new(util::random_string(20))) };
}

fn main() {
    let args = args::args();
    match init::init(args) {
        Ok(()) => {}
        Err(()) => {
            error!("Failed to initialize synapse!");
            process::exit(1);
        }
    }
    info!("Initialized, starting!");
    match init::run() {
        Ok(()) => process::exit(0),
        Err(()) => process::exit(1),
    }
}
<|endoftext|>


<commit_before>#![allow(dead_code)]
#![allow(unused)]
#![deny(warnings)]

extern crate crypto;
extern crate rand;
extern crate time;
extern crate hyper;
extern crate iron;
extern crate rustc_serialize;

mod encryption;
mod util;
mod overflow;
mod keypool;
mod node;
mod crack;

// external packages
use time::PreciseTime;
use rand::Rng;
use rand::os::OsRng;
use hyper::server::{Server, Request, Response};
use hyper::client as cl;

// project packages
use encryption::{encrypt, decrypt};
use util::{u8_vector, read_file_from_arg, is_english, load_linux_dictionary};
use overflow::{WrappedStep, WrappedInc};
use keypool::{KeyPool};
use node::{Worker};
use rustc_serialize::json::{self, Json, ToJson};
use crack::crack;

// standar packages
use std::collections::HashMap;
use std::str::from_utf8;
use std::env::args;
use std::sync::mpsc::{Sender, channel};
use std::marker::Sync;
use std::thread;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::process::Command;
use std::io::stdin;
use std::io::prelude::*;
use std::net::SocketAddr;

fn master_repl() {
    println!("Welcome!");
    let reader = stdin();

    print!("> ");
    for line in reader.lock().lines() {
        // parse command
        println!("--> {}", line.unwrap());

        print!("> ");
    }
}

fn slave_repl() {
    loop {}
}

fn main() {
    let role = args().nth(1)
        .expect("Role");

    if "master".to_string() == role {
        master_repl();
    } else if "slave".to_string() == role {
        // slave_repl();
    }

    // let client = cl::Client::new();
    // let mut res: cl::Response = client.get("https://reddit.com").send().unwrap();
    // let mut output = String::new();
    // res.read_to_string(&mut output);
    // println!("{}", output);

    // Load the dictionary
    // let sorted_dictionary = load_linux_dictionary().unwrap();
    // if args().len() != 4 {
    //     panic!("You need to supply three arguments");
    // }
    //
    // // Parse commandline argument
    // let thread_count: i64 = args().nth(2)
    //     .expect("Second argument is the thread count")
    //     .parse()
    //     .expect("You should have given a valid integer.");
    // let role = args().nth(3)
    //     .expect("You need to define the role of the client");

    // // Random number generator
    // let mut rng = OsRng::new() // new and unwrap are Rust idioms
    //     .ok().unwrap();

}
<commit_msg>flushing is important (not a joke)<commit_after>#![allow(dead_code)]
#![allow(unused)]
#![deny(warnings)]

extern crate crypto;
extern crate rand;
extern crate time;
extern crate hyper;
extern crate iron;
extern crate rustc_serialize;

mod encryption;
mod util;
mod overflow;
mod keypool;
mod node;
mod crack;

// external packages
use time::PreciseTime;
use rand::Rng;
use rand::os::OsRng;
use hyper::server::{Server, Request, Response};
use hyper::client as cl;

// project packages
use encryption::{encrypt, decrypt};
use util::{u8_vector, read_file_from_arg, is_english, load_linux_dictionary};
use overflow::{WrappedStep, WrappedInc};
use keypool::{KeyPool};
use node::{Worker};
use rustc_serialize::json::{self, Json, ToJson};
use crack::crack;

// standar packages
use std::collections::HashMap;
use std::str::{from_utf8, FromStr};
use std::env::args;
use std::sync::mpsc::{Sender, channel};
use std::marker::Sync;
use std::thread;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::process::Command;
use std::io::stdin;
use std::io::stdout;
use std::io::prelude::*;
use std::net::{SocketAddrV4, TcpStream, UdpSocket, TcpListener, Ipv4Addr};
use std::net::ToSocketAddrs;

enum Op {
    SendKey,
    SetupSlave(String),
    Err
}

fn parse (value: &'static str) -> Op {
    if value == "send" {
        Op::SendKey
    } else {
        Op::Err
    }
}

fn master_repl() {
    print!("master-ip and port> ");
    stdout().flush();

    let mut raw_ip = String::new();
    stdin().read_line(&mut raw_ip).expect("Expected valid string");
    let tokens = raw_ip.split(":").collect::<Vec<&str>>();

    assert!(tokens.len() == 2);

    let ip = match Ipv4Addr::from_str(tokens[0].trim()) {
        Ok(value) => value,
        Err(e) => panic!("{}", e)
    };

    let port = u64::from_str(tokens[1]);

    let w = Worker::builder(4, ip.clone().to_string().as_str());

    let mut input = String::new();
    loop {
        print!("> ");
        stdout().flush();
        stdin().read_line(&mut input).expect("You did not enter a valid string");
        let splits = input.split(" ");
        let tokens = splits.collect::<Vec<&str>>();

        println!("{}", input);

        // match parse(tokens[0]) {
        //     Op::SendKey => {
        //         1;
        //     }
        //     _ => ()
        // }

    }
}

fn slave_repl() {
    loop {}
}

fn main() {
    let role = args().nth(1)
        .expect("Role");

    if "master".to_string() == role {
        master_repl();
    } else if "slave".to_string() == role {
        // slave_repl();
    }

    // let client = cl::Client::new();
    // let mut res: cl::Response = client.get("https://reddit.com").send().unwrap();
    // let mut output = String::new();
    // res.read_to_string(&mut output);
    // println!("{}", output);

    // Load the dictionary
    // let sorted_dictionary = load_linux_dictionary().unwrap();
    // if args().len() != 4 {
    //     panic!("You need to supply three arguments");
    // }
    //
    // // Parse commandline argument
    // let thread_count: i64 = args().nth(2)
    //     .expect("Second argument is the thread count")
    //     .parse()
    //     .expect("You should have given a valid integer.");
    // let role = args().nth(3)
    //     .expect("You need to define the role of the client");

    // // Random number generator
    // let mut rng = OsRng::new() // new and unwrap are Rust idioms
    //     .ok().unwrap();

}
<|endoftext|>


<commit_before>// Copyright (c) 2015 - 2016, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of yabs, distributed under the BSD
// 3-Clause license. For full terms please see the LICENSE file.

pub static YABS: Prog = Prog {
    name: "yabs",
    vers: "0.1.0",
    yr: "2016",
};

extern crate pgetopts;
extern crate util;
extern crate rpf;

use pgetopts::{Options};
use rpf::*;

use std::env;
use util::*;
use util::build::Desc;

fn print_usage(opts: Options) {
    println!("{}", opts.options());
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut opts = Options::new();
    opts.optflag("n", "new", "Create a new build profile");
    opts.optflag("h", "help", "Print help information");
    opts.optflag("", "version", "Print version information");
    opts.optflag("p", "print", "Print build file in JSON");
    opts.optflag("", "sources", "Print source files");
    opts.optflag("", "profiles", "Print all available profiles in build file");
    opts.optopt("","print-profile", "Print a particular profile from build file in JSON", "PROFILE \
                where profile is the name of the profile to be printed");
    opts.optopt("m","make","Generate Makefile", "");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m },
        Err(e) => {
            YABS.error(e.to_string(), ExitStatus::OptError);
            panic!();
        }
    };

    if matches.opt_present("h") { print_usage(opts); }
    else if matches.opt_present("version") { println!("{} {}", YABS.name, YABS.vers); }
    else {
        if let Some(assumed_file_name) = ext::get_assumed_filename() {
            match build::BuildFile::from_file(&assumed_file_name) {
                Ok(build_file) => {
                    if matches.opt_present("p") {
                        &build_file.print_as_json();
                    } else if matches.opt_present("print-profile") {
                        if let Some(arg) = matches.opt_str("print-profile") {
                            &build_file.print_profile_as_json(arg);
                        }
                    } else if matches.opt_present("profiles") {
                        &build_file.print_available_profiles();
                    } else if matches.opt_present("sources") {
                        &build_file.clone().print_sources();
                    } else if matches.opt_present("make") {
                        if let Some(arg) = matches.opt_str("make") {
                            if let Err(e) = build_file.gen_make(arg) {
                                YABS.error(e.to_string(), ExitStatus::Error);
                            }
                        }
                    }
                },
                Err(e) => {
                    for err in e {
                        println!("error: {}", err.to_string());
                    }
                    YABS.exit(ExitStatus::Error);
                }
            };
        }
    }
}
<commit_msg>yabs: print more information in 'help'<commit_after>// Copyright (c) 2015 - 2016, Alberto Corona <ac@albertocorona.com>
// All rights reserved. This file is part of yabs, distributed under the BSD
// 3-Clause license. For full terms please see the LICENSE file.

pub static YABS: Prog = Prog {
    name: "yabs",
    vers: "0.1.0",
    yr: "2016",
};

extern crate pgetopts;
extern crate util;
extern crate rpf;

use pgetopts::Options;
use rpf::*;

use std::env;
use util::*;
use util::build::Desc;

fn print_usage(opts: Options) {
    print!("{0}: {1} {2} {3}\n   or: {1} {2}\nRun yabs with {2} on {3}",
           "Usage".bold(),
           YABS.name,
           "[OPTION]".underline(),
           "PROFILE".underline());
    println!("{}", opts.options());
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let mut opts = Options::new();
    opts.optflag("h", "help", "Print help information");
    opts.optopt("m", "make", "Generate Makefile", "");
    opts.optflag("n", "new", "Create a new build profile");
    opts.optflag("p", "print", "Print build file in JSON");
    opts.optopt("",
                "print-profile",
                "Print a particular profile from build file in JSON",
                "PROFILE where profile is the name of the profile to be printed");
    opts.optflag("", "profiles", "Print all available profiles in build file");
    opts.optflag("", "sources", "Print source files");
    opts.optflag("", "version", "Print version information");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(e) => {
            YABS.error(e.to_string(), ExitStatus::OptError);
            panic!();
        }
    };

    if matches.opt_present("h") {
        print_usage(opts);
    } else if matches.opt_present("version") {
        YABS.copyright("Copyright (C) 2015-2016\n",
                       &["Alberto Corona"]);
    } else {
        if let Some(assumed_file_name) = ext::get_assumed_filename() {
            match build::BuildFile::from_file(&assumed_file_name) {
                Ok(build_file) => {
                    if matches.opt_present("p") {
                        &build_file.print_as_json();
                    } else if matches.opt_present("print-profile") {
                        if let Some(arg) = matches.opt_str("print-profile") {
                            &build_file.print_profile_as_json(arg);
                        }
                    } else if matches.opt_present("profiles") {
                        &build_file.print_available_profiles();
                    } else if matches.opt_present("sources") {
                        &build_file.clone().print_sources();
                    } else if matches.opt_present("make") {
                        if let Some(arg) = matches.opt_str("make") {
                            if let Err(e) = build_file.gen_make(arg) {
                                YABS.error(e.to_string(), ExitStatus::Error);
                            }
                        }
                    }
                }
                Err(e) => {
                    for err in e {
                        println!("error: {}", err.to_string());
                    }
                    YABS.exit(ExitStatus::Error);
                }
            };
        }
    }
}
<|endoftext|>


<commit_before>extern crate libc;
extern crate x11;

use std::ffi::CString;
use std::mem::zeroed;

use libc::{c_int, c_uint};

use x11::xlib;

static GRABMODEASYNC : c_int = 1;

static MOD1MASK : c_uint = (1<<3);
static BUTTONPRESSMASK : c_uint = (1 << 2);
static BUTTONRELEASEMASK : c_uint = (1 << 3);
static POINTERMOTIONMASK : c_uint = (1 << 6);

fn max(a : c_int, b : c_int) -> c_uint { if a > b { a as c_uint } else { b as c_uint } }

fn main() {
    let mut arg0 = 0x0 as i8;
    let display : *mut xlib::Display = unsafe { xlib::XOpenDisplay(&mut arg0) };

    let mut attr: xlib::XWindowAttributes = unsafe { zeroed() };
    let mut start: xlib::XButtonEvent = unsafe { zeroed() };

    if display.is_null() {
        std::process::exit(1);
    }

    let f1 = CString::new("F1").unwrap();
    unsafe {
        xlib::XGrabKey(display, xlib::XKeysymToKeycode(display, xlib::XStringToKeysym(f1.as_ptr())) as c_int, MOD1MASK,
        xlib::XDefaultRootWindow(display), true as c_int, GRABMODEASYNC, GRABMODEASYNC);

        xlib::XGrabButton(display, 1, MOD1MASK, xlib::XDefaultRootWindow(display), true as c_int,
        BUTTONPRESSMASK|BUTTONRELEASEMASK|POINTERMOTIONMASK, GRABMODEASYNC, GRABMODEASYNC,
        0, 0);
        xlib::XGrabButton(display, 3, MOD1MASK, xlib::XDefaultRootWindow(display), true as c_int,
        BUTTONPRESSMASK|BUTTONRELEASEMASK|POINTERMOTIONMASK, GRABMODEASYNC, GRABMODEASYNC,
        0, 0);
    };

    start.subwindow = 0;

    let mut event: xlib::XEvent = unsafe { zeroed() };

    loop {
        unsafe {
            xlib::XNextEvent(display, &mut event);

            match event.get_type() {
                xlib::KeyPress => {
                    let xkey: xlib::XKeyEvent = From::from(event);
                    if xkey.subwindow != 0 {
                        xlib::XRaiseWindow(display, xkey.subwindow);
                    }
                },
                xlib::ButtonPress => {
                    let xbutton: xlib::XButtonEvent = From::from(event);
                    if xbutton.subwindow != 0 {
                        xlib::XGetWindowAttributes(display, xbutton.subwindow, &mut attr);
                        start = xbutton;
                    }
                },
                xlib::MotionNotify => {
                    if start.subwindow != 0 {
                        let xbutton: xlib::XButtonEvent = From::from(event);
                        let xdiff : c_int = xbutton.x_root - start.x_root;
                        let ydiff : c_int = xbutton.y_root - start.y_root;
                        xlib::XMoveResizeWindow(display, start.subwindow,
                                          attr.x + (if start.button==1 { xdiff } else { 0 }),
                                          attr.y + (if start.button==1 { ydiff } else { 0 }),
                                          max(1, attr.width + (if start.button==3 { xdiff } else { 0 })),
                                          max(1, attr.height + (if start.button==3 { ydiff } else { 0 })));
                    }
                },
                xlib::ButtonRelease => {
                    start.subwindow = 0;
                },
                _ => {}
            };
        }
    }
}
<commit_msg>Use constants defined in xlib<commit_after>extern crate libc;
extern crate x11;

use std::ffi::CString;
use std::mem::zeroed;

use libc::{c_int, c_uint};

use x11::xlib;

fn max(a : c_int, b : c_int) -> c_uint { if a > b { a as c_uint } else { b as c_uint } }

fn main() {
    let mut arg0 = 0x0 as i8;
    let display : *mut xlib::Display = unsafe { xlib::XOpenDisplay(&mut arg0) };

    let mut attr: xlib::XWindowAttributes = unsafe { zeroed() };
    let mut start: xlib::XButtonEvent = unsafe { zeroed() };

    if display.is_null() {
        std::process::exit(1);
    }

    let f1 = CString::new("F1").unwrap();
    unsafe {
        xlib::XGrabKey(display, xlib::XKeysymToKeycode(display, xlib::XStringToKeysym(f1.as_ptr())) as c_int, xlib::Mod1Mask,
        xlib::XDefaultRootWindow(display), true as c_int, xlib::GrabModeAsync, xlib::GrabModeAsync);

        xlib::XGrabButton(display, 1, xlib::Mod1Mask, xlib::XDefaultRootWindow(display), true as c_int,
        (xlib::ButtonPressMask|xlib::ButtonReleaseMask|xlib::PointerMotionMask) as c_uint, xlib::GrabModeAsync, xlib::GrabModeAsync,
        0, 0);
        xlib::XGrabButton(display, 3, xlib::Mod1Mask, xlib::XDefaultRootWindow(display), true as c_int,
        (xlib::ButtonPressMask|xlib::ButtonReleaseMask|xlib::PointerMotionMask) as c_uint, xlib::GrabModeAsync, xlib::GrabModeAsync,
        0, 0);
    };

    start.subwindow = 0;

    let mut event: xlib::XEvent = unsafe { zeroed() };

    loop {
        unsafe {
            xlib::XNextEvent(display, &mut event);

            match event.get_type() {
                xlib::KeyPress => {
                    let xkey: xlib::XKeyEvent = From::from(event);
                    if xkey.subwindow != 0 {
                        xlib::XRaiseWindow(display, xkey.subwindow);
                    }
                },
                xlib::ButtonPress => {
                    let xbutton: xlib::XButtonEvent = From::from(event);
                    if xbutton.subwindow != 0 {
                        xlib::XGetWindowAttributes(display, xbutton.subwindow, &mut attr);
                        start = xbutton;
                    }
                },
                xlib::MotionNotify => {
                    if start.subwindow != 0 {
                        let xbutton: xlib::XButtonEvent = From::from(event);
                        let xdiff : c_int = xbutton.x_root - start.x_root;
                        let ydiff : c_int = xbutton.y_root - start.y_root;
                        xlib::XMoveResizeWindow(display, start.subwindow,
                                                attr.x + (if start.button==1 { xdiff } else { 0 }),
                                                attr.y + (if start.button==1 { ydiff } else { 0 }),
                                                max(1, attr.width + (if start.button==3 { xdiff } else { 0 })),
                                                max(1, attr.height + (if start.button==3 { ydiff } else { 0 })));
                    }
                },
                xlib::ButtonRelease => {
                    start.subwindow = 0;
                },
                _ => {}
            };
        }
    }
}
<|endoftext|>


<commit_before>extern crate mio;

use std::io::Write;
use std::io::Read;
use std::rc::{Rc};
use std::cell::{RefCell};
use mio::tcp::*;
mod server;
mod broker;
mod message;

const MQTT_SERVER_TOKEN: mio::Token = mio::Token(0);

fn main() {
    let address = "0.0.0.0:1883".parse().unwrap();
    let listener = TcpListener::bind(&address).expect(&format!("Could not bind to {}", address));
    let mut event_loop = mio::EventLoop::new().expect("Could not create MIO event loop");
    event_loop.register(&listener, MQTT_SERVER_TOKEN).expect("Could not register listener");
    event_loop.run(&mut MioHandler::new(listener)).expect("Could not run event loop");
}

struct MioHandler {
    listener: TcpListener,
    connections: mio::util::Slab<Rc<RefCell<Connection>>>,
    mqtt_streams: mio::util::Slab<server::Stream>,
    server: server::Server<Connection>,
}

struct Connection {
    socket: mio::tcp::TcpStream,
}

impl MioHandler {
    fn new(listener: TcpListener) -> Self {
        let max_conns = 1024 * 32;
        let connections_slab = mio::util::Slab::new_starting_at(mio::Token(1), max_conns);
        let mqtt_stream_slab = mio::util::Slab::new_starting_at(mio::Token(1), max_conns);

        MioHandler {
            listener: listener,
            connections: connections_slab,
            mqtt_streams: mqtt_stream_slab,
            server: server::Server::new(),
        }
    }
}

impl mio::Handler for MioHandler {
    type Timeout = ();
    type Message = ();

    fn ready(&mut self,
             event_loop: &mut mio::EventLoop<MioHandler>,
             token: mio::Token,
             events: mio::EventSet) {
        match token {
            MQTT_SERVER_TOKEN => {
                assert!(events.is_readable());

                match self.listener.accept() {
                    Ok(Some(socket)) => {
                        let token = self.connections
                            .insert_with(|_| Rc::new(RefCell::new(Connection::new(socket))))
                            .expect("Could not insert new connection in slab");
                        self.mqtt_streams.
                            insert_with(|_| server::Stream::new())
                            .expect("Could not insert new stream into slab");
                        let connection = &self.connections[token].clone();
                        event_loop.register_opt(
                            &connection.borrow().socket,
                            token,
                            mio::EventSet::readable(),
                            mio::PollOpt::edge()).expect("Could not register connection with event loop");
                    }
                    Ok(None) => {
                        println!("The server socket wasn't actually ready");
                    }
                    Err(e) => {
                        println!("listener.accept errored: {}", e);
                        event_loop.shutdown();
                    }
                }
            }
            _ => {
                assert!(events.is_readable());
                let still_connected = connection_ready(&mut self.server,
                                                       &mut self.mqtt_streams[token],
                                                       self.connections[token].clone());
                if !still_connected {
                    event_loop.deregister(&self.connections[token].borrow().socket)
                        .expect("Could not deregister connection with event loop");
                    self.server.unsubscribe_all(self.connections[token].clone());
                    self.connections[token].borrow_mut().socket.flush().expect("Could not flush socket");
                    self.connections.remove(token).expect("Could not remove connection from slab");
                }
            }
        }
    }
}

fn connection_ready(server: &mut server::Server<Connection>,
                    stream: &mut server::Stream,
                    connection: Rc<RefCell<Connection>>) -> bool {
    let connection = connection.clone();
    let read_result = connection.borrow_mut().read(stream.buffer());

    match read_result {
        Ok(length) => {
            if length >= stream.total_buffer_len() {
                panic!(format!("Too many bytes ({}) for puny stream buffer ({})",
                               length, stream.total_buffer_len()));
            }
            stream.handle_messages(length, server, connection.clone())
        },
        _ => panic!("Error reading bytes from stream"),
    }
}

impl Connection {
    fn new(socket: mio::tcp::TcpStream) -> Self {
        Connection { socket: socket }
    }

    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
        self.socket.read(buffer)
    }
}

impl broker::Subscriber for Connection {
    fn new_message(&mut self, bytes: &[u8]) {
        self.socket.write_all(bytes).expect("Error writing to socket");
    }
}
<commit_msg>Added a comment<commit_after>extern crate mio;

use std::io::Write;
use std::io::Read;
use std::rc::{Rc};
use std::cell::{RefCell};
use mio::tcp::*;
mod server;
mod broker;
mod message;

const MQTT_SERVER_TOKEN: mio::Token = mio::Token(0);

fn main() {
    let address = "0.0.0.0:1883".parse().unwrap();
    let listener = TcpListener::bind(&address).expect(&format!("Could not bind to {}", address));
    let mut event_loop = mio::EventLoop::new().expect("Could not create MIO event loop");
    event_loop.register(&listener, MQTT_SERVER_TOKEN).expect("Could not register listener");
    event_loop.run(&mut MioHandler::new(listener)).expect("Could not run event loop");
}

struct MioHandler {
    listener: TcpListener,
    connections: mio::util::Slab<Rc<RefCell<Connection>>>,
    mqtt_streams: mio::util::Slab<server::Stream>,
    server: server::Server<Connection>,
}

struct Connection {
    socket: mio::tcp::TcpStream,
}

impl MioHandler {
    fn new(listener: TcpListener) -> Self {
        let max_conns = 1024 * 32;
        let connections_slab = mio::util::Slab::new_starting_at(mio::Token(1), max_conns);
        let mqtt_stream_slab = mio::util::Slab::new_starting_at(mio::Token(1), max_conns);

        MioHandler {
            listener: listener,
            connections: connections_slab,
            mqtt_streams: mqtt_stream_slab,
            server: server::Server::new(),
        }
    }
}

impl mio::Handler for MioHandler {
    type Timeout = ();
    type Message = ();

    fn ready(&mut self,
             event_loop: &mut mio::EventLoop<MioHandler>,
             token: mio::Token,
             events: mio::EventSet) {
        match token {
            MQTT_SERVER_TOKEN => {
                assert!(events.is_readable());

                match self.listener.accept() {
                    Ok(Some(socket)) => {
                        //the reason why I'm doing the horrible thing of two slabs and two
                        //insertions per connection is to avoid borrowing problems.
                        //That way the mqtt stream and the connection have distinct lifetimes
                        //(though not really) and be passed as mutable borrow simultaneously
                        //to connection_ready

                        let token = self.connections
                            .insert_with(|_| Rc::new(RefCell::new(Connection::new(socket))))
                            .expect("Could not insert new connection in slab");
                        self.mqtt_streams.
                            insert_with(|_| server::Stream::new())
                            .expect("Could not insert new stream into slab");
                        let connection = &self.connections[token].clone();
                        event_loop.register_opt(
                            &connection.borrow().socket,
                            token,
                            mio::EventSet::readable(),
                            mio::PollOpt::edge()).expect("Could not register connection with event loop");
                    }
                    Ok(None) => {
                        println!("The server socket wasn't actually ready");
                    }
                    Err(e) => {
                        println!("listener.accept errored: {}", e);
                        event_loop.shutdown();
                    }
                }
            }
            _ => {
                assert!(events.is_readable());
                let still_connected = connection_ready(&mut self.server,
                                                       &mut self.mqtt_streams[token],
                                                       self.connections[token].clone());
                if !still_connected {
                    event_loop.deregister(&self.connections[token].borrow().socket)
                        .expect("Could not deregister connection with event loop");
                    self.server.unsubscribe_all(self.connections[token].clone());
                    self.connections[token].borrow_mut().socket.flush().expect("Could not flush socket");
                    self.connections.remove(token).expect("Could not remove connection from slab");
                }
            }
        }
    }
}

fn connection_ready(server: &mut server::Server<Connection>,
                    stream: &mut server::Stream,
                    connection: Rc<RefCell<Connection>>) -> bool {
    let connection = connection.clone();
    let read_result = connection.borrow_mut().read(stream.buffer());

    match read_result {
        Ok(length) => {
            if length >= stream.total_buffer_len() {
                panic!(format!("Too many bytes ({}) for puny stream buffer ({})",
                               length, stream.total_buffer_len()));
            }
            stream.handle_messages(length, server, connection.clone())
        },
        _ => panic!("Error reading bytes from stream"),
    }
}

impl Connection {
    fn new(socket: mio::tcp::TcpStream) -> Self {
        Connection { socket: socket }
    }

    fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
        self.socket.read(buffer)
    }
}

impl broker::Subscriber for Connection {
    fn new_message(&mut self, bytes: &[u8]) {
        self.socket.write_all(bytes).expect("Error writing to socket");
    }
}
<|endoftext|>


<commit_before>extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
        println!("Guess the number!");

        let secret_number = rand::thread_rng().gen_range(1, 101);

        println!("The secret number is: {}", secret_number);

        loop {
            println!("Please input your guess.");

            let mut guess = String::new();

            io::stdin().read_line(&mut guess)
                .ok()
                .expect("Failed to read line");

            let guess: u32 = match guess.trim().parse() {
                    Ok(num) => num,
                    Err(_)  => continue,
            };

            println!("You guessed: {}", guess);

            match guess.cmp(&secret_number) {
                Ordering::Less      => println!("Too small!"),
                Ordering::Greater   => println!("Too big!"),
                Ordering::Equal     => {
                    println!("You win!");
                    break;
                }
            }
        }
}
<commit_msg>Don't output secret number<commit_after>extern crate rand;

use std::io;
use std::cmp::Ordering;
use rand::Rng;

fn main() {
        println!("Guess the number!");

        let secret_number = rand::thread_rng().gen_range(1, 101);

        loop {
            println!("Please input your guess.");

            let mut guess = String::new();

            io::stdin().read_line(&mut guess)
                .ok()
                .expect("Failed to read line");

            let guess: u32 = match guess.trim().parse() {
                    Ok(num) => num,
                    Err(_)  => continue,
            };

            println!("You guessed: {}", guess);

            match guess.cmp(&secret_number) {
                Ordering::Less      => println!("Too small!"),
                Ordering::Greater   => println!("Too big!"),
                Ordering::Equal     => {
                    println!("You win!");
                    break;
                }
            }
        }
}
<|endoftext|>