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

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

use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::keyboard::Scancode;
use sdl2::rect::Rect;
use sdl2::render::Renderer;
use sdl2::Sdl;
use sdl2::TimerSubsystem;
use sdl2::VideoSubsystem;

use std::default::Default;
use std::f32;
use std::path::Path;
use std::thread;

pub struct Ui {
    width: f32,
    height: f32,
    sdl_ctx: Sdl,
    renderer: Renderer<'static>
}

impl Ui {
    pub fn new(width: f32, height: f32, sdl_ctx: Sdl, renderer: Renderer<'static>) -> Ui {
        Ui {
            width: width,
            height: height,
            sdl_ctx: sdl_ctx,
            renderer: renderer
        }
    }

    pub fn poll_event(&self) -> Option<Event> {
        let mut event_pump = self.sdl_ctx.event_pump().unwrap();
        return event_pump.poll_event();
    }
}

pub struct Ball {
    pub x: f32,         // x pixel co-ordinate of top left corner
    pub y: f32,         // y pixel co-ordinate of top left corner
    pub width: f32,     // pixels
    pub height: f32,    // pixels
    pub speed: f32,     // pixels per second
    pub vx: f32,        // pixels per second
    pub vy: f32         // pixels per second
}

impl Ball {
    pub fn new(x: f32, y: f32, width: f32, height: f32,
               speed: f32, vx: f32, vy: f32) -> Ball {
        Ball {
            x: x,
            y: y,
            width: width,
            height: height,
            speed: speed,
            vx: vx,
            vy: vy
        }
    }
}

pub struct Paddle {
    pub x: f32,         // x pixel co-ordinate of top left corner
    pub y: f32,         // y pixel co-ordinate of top left corner
    pub width: f32,     // pixels
    pub height: f32,    // pixels
    pub vy: f32,        // pixels per second
    pub score: u32
}

impl Paddle {
    pub fn new(x: f32, y: f32, width: f32, height: f32, vy: f32,
               score: u32) -> Paddle {
        Paddle {
            x: x,
            y: y,
            width: width,
            height: height,
            vy: vy,
            score: score}
    }
}

pub struct Game {
    ui: Ui,
    fps: u32,
    ball: Ball,
    lpaddle: Paddle,
    rpaddle: Paddle,
    running: bool
}

impl Game {

    /// Create initial game state.
    pub fn new(ui: Ui, fps: u32, ball: Ball, lpaddle: Paddle,
               rpaddle: Paddle) -> Game {
        Game {
            ui: ui,
            fps: fps,
            ball: ball,
            lpaddle: lpaddle,
            rpaddle: rpaddle,
            running: false,
        }
    }

    /// Start the game and block until finished.
    pub fn start(&mut self) {
        self.running = true;
        let mut time_last_invocation = clock_ticks::precise_time_ms();
        while self.running {
            let time_this_invocation = clock_ticks::precise_time_ms();
            let delta_time = time_this_invocation - time_last_invocation;
            self.update(delta_time as f32 / 1000.);
            self.cap_fps(delta_time);
            time_last_invocation = time_this_invocation;
        }
    }

    /// Called once per frame.
    fn update(&mut self, dt_sec: f32) {
        self.handle_input();
        self.update_ball_position(dt_sec);
        self.check_for_ball_and_wall_collisions();
        self.redraw()
    }

    fn handle_input(&mut self) {
        match self.ui.poll_event() {
            Some(event) => {
                match event {
                    Event::Quit{..} => {
                        self.running = false;
                    },
                    Event::KeyDown{keycode,..} => match keycode {
                        Option::Some(Keycode::Escape) => {
                            self.running = false;
                        },
                        _ => {}
                    },
                    _ => {}
                }
            },
            None => {}
        }
    }

    fn update_ball_position(&mut self, dt_sec: f32) {
        let ball = &mut self.ball;
        ball.x += ball.vx * dt_sec;
        ball.y += ball.vy * dt_sec;
    }

    fn check_for_ball_and_wall_collisions(&mut self) {
        let ball = &mut self.ball;

        // Left or right wall.
        if ball.x <= 0. && ball.vx < -0. {
            ball.x = 0.;
            ball.vx = -ball.vx;
        } else if ball.x + ball.width >= self.ui.width && ball.vx > 0. {
            ball.x = self.ui.width - ball.width;
            ball.vx = -ball.vx;
        }

        // Top or bottom wall.
        if ball.y <= 0. && ball.vy < -0. {
            ball.y = 0.;
            ball.vy = -ball.vy;
        } else if ball.y + ball.height >= self.ui.height && ball.vy > 0. {
            ball.y = self.ui.height - ball.height;
            ball.vy = -ball.vy;
        }
    }

    fn redraw(&mut self) {
        // Clear the screen.
        self.ui.renderer.clear();

        // Draw the ball.
        let ball = &mut self.ball;
        let ball_rect = Rect::new_unwrap(ball.x as i32,
                                    ball.y as i32,
                                    ball.width as u32,
                                    ball.height as u32);
        self.ui.renderer.fill_rect(ball_rect);

        // Draw the left paddle.
        let lpaddle = &mut self.lpaddle;
        let lpaddle_rect = Rect::new_unwrap(lpaddle.x as i32,
                                    lpaddle.y as i32,
                                    lpaddle.width as u32,
                                    lpaddle.height as u32);
        self.ui.renderer.fill_rect(lpaddle_rect);

        // Draw the right paddle.
        let rpaddle = &mut self.rpaddle;
        let rpaddle_rect = Rect::new_unwrap(rpaddle.x as i32,
                                    rpaddle.y as i32,
                                    rpaddle.width as u32,
                                    rpaddle.height as u32);
        self.ui.renderer.fill_rect(rpaddle_rect);

        // Flip backbuffer to front.
        self.ui.renderer.present();
    }

    // Ensure we run no faster than the desired fps by introducing
    // a delay if necessary.
    fn cap_fps(&self, took_ms: u64) {
        let max_ms = 1000 / self.fps as u64;
        if max_ms > took_ms {
            thread::sleep_ms((max_ms - took_ms) as u32);
        }
    }
}

struct GameBuilder {
    screen_width: f32,
    screen_height: f32,
    fps: u32,
    ball_speed: f32,
    paddle_speed: f32
}

impl GameBuilder {

    pub fn new() -> GameBuilder {
        GameBuilder {
            screen_width: 480.,
            screen_height: 320.,
            fps: 40,
            ball_speed: 320.,
            paddle_speed: 640.
        }
    }

    pub fn with_dimensions(mut self, width: f32, height: f32) -> GameBuilder {
        self.screen_width = width;
        self.screen_height = height;
        self
    }

    pub fn with_fps(mut self, fps: u32) -> GameBuilder {
        self.fps = fps;
        self
    }

    pub fn with_ball_speed_per_sec(mut self, ball_speed: f32) -> GameBuilder {
        self.ball_speed = ball_speed;
        self
    }

    pub fn with_paddle_speed_per_sec(mut self, paddle_speed: f32) -> GameBuilder {
        self.paddle_speed = paddle_speed;
        self
    }

    fn create_ui(&self) -> Ui {
        let sdl_ctx = sdl2::init().unwrap();
        let video_subsystem = sdl_ctx.video().unwrap();
        let window = video_subsystem.window("pong",
                self.screen_width as u32, self.screen_height as u32)
                .position_centered()
                .build()
                .unwrap();
        let renderer = window.renderer().build().unwrap();
        Ui::new(self.screen_width, self.screen_height, sdl_ctx, renderer)
    }

    fn create_ball(&self) -> Ball {
        let width = 10.;
        let height = 10.;

        // Place ball at center of screen.
        let x = (self.screen_width - width) / 2.;
        let y = (self.screen_height - height) / 2.;

        let speed = self.ball_speed;
        let mut rng = rand::thread_rng();

        // Launch at an angle less than or equal to 45 degrees.
        let angle = Range::new(0., f32::consts::PI/4.).ind_sample(&mut rng);
        let dir = [-1., 1.];

        // Use the sine of the angle to determine the vertical speed. Then,
        // choose a direction (up or down) to select a vertical velocity.
        let up_or_down = rand::sample(&mut rng, dir.into_iter(),1)[0];
        let vy = angle.sin() * speed * up_or_down;
        let left_or_right = rand::sample(&mut rng, dir.into_iter(),1)[0];

        // Use Pythagoras to determine the horizontal speed. Then, choose a
        // direction (left or right) to select a horizontal velocity.
        let vx = ((speed * speed) - (vy * vy)).sqrt() * left_or_right;
        Ball::new(x, y, width, height, speed, vx, vy)
    }

    fn create_left_paddle(&self) -> Paddle {
        let width = 10.;
        let height = 60.;
        let x = 0.;
        let y = (self.screen_height - height) / 2.;
        let vy = 0.;
        let score = 0;
        Paddle::new(x, y, width, height, vy, score)
    }

    fn create_right_paddle(&self) -> Paddle {
        let width = 10.;
        let height = 60.;
        let x = self.screen_width - width;;
        let y = (self.screen_height - height) / 2.;
        let vy = 0.;
        let score = 0;
        Paddle::new(x, y, width, height, vy, score)
    }

    pub fn build(&self) -> Game {
        Game::new(self.create_ui(),
                  self.fps,
                  self.create_ball(),
                  self.create_left_paddle(),
                  self.create_right_paddle())
    }
}

fn main() {
    let mut game = GameBuilder::new()
        .with_dimensions(480., 320.)
        .with_fps(40)
        .with_ball_speed_per_sec(320.)
        .with_paddle_speed_per_sec(320.)
        .build();
    game.start();
}
<commit_msg>Left paddle moves, no no collision detection.<commit_after>extern crate clock_ticks;
extern crate rand;
extern crate sdl2;

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

use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::keyboard::Scancode;
use sdl2::rect::Rect;
use sdl2::render::Renderer;
use sdl2::Sdl;
use sdl2::TimerSubsystem;
use sdl2::VideoSubsystem;

use std::default::Default;
use std::f32;
use std::path::Path;
use std::thread;

pub struct Ui {
    width: f32,
    height: f32,
    sdl_ctx: Sdl,
    renderer: Renderer<'static>
}

impl Ui {
    pub fn new(width: f32, height: f32, sdl_ctx: Sdl, renderer: Renderer<'static>) -> Ui {
        Ui {
            width: width,
            height: height,
            sdl_ctx: sdl_ctx,
            renderer: renderer
        }
    }

    pub fn poll_event(&self) -> Option<Event> {
        let mut event_pump = self.sdl_ctx.event_pump().unwrap();
        return event_pump.poll_event();
    }
}

pub struct Ball {
    pub x: f32,         // x pixel co-ordinate of top left corner
    pub y: f32,         // y pixel co-ordinate of top left corner
    pub width: f32,     // pixels
    pub height: f32,    // pixels
    pub speed: f32,     // pixels per second
    pub vx: f32,        // pixels per second
    pub vy: f32         // pixels per second
}

impl Ball {
    pub fn new(x: f32, y: f32, width: f32, height: f32,
               speed: f32, vx: f32, vy: f32) -> Ball {
        Ball {
            x: x,
            y: y,
            width: width,
            height: height,
            speed: speed,
            vx: vx,
            vy: vy
        }
    }
}

pub struct Paddle {
    pub x: f32,         // x pixel co-ordinate of top left corner
    pub y: f32,         // y pixel co-ordinate of top left corner
    pub width: f32,     // pixels
    pub height: f32,    // pixels
    pub speed: f32,     // pixels per second
    pub vy: f32,        // pixels per second
    pub score: u32
}

impl Paddle {
    pub fn new(x: f32, y: f32, width: f32, height: f32, speed: f32, vy: f32,
               score: u32) -> Paddle {
        Paddle {
            x: x,
            y: y,
            width: width,
            height: height,
            speed: speed,
            vy: vy,
            score: score}
    }
}

pub struct Game {
    ui: Ui,
    fps: u32,
    ball: Ball,
    lpaddle: Paddle,
    rpaddle: Paddle,
    running: bool
}

impl Game {

    /// Create initial game state.
    pub fn new(ui: Ui, fps: u32, ball: Ball, lpaddle: Paddle,
               rpaddle: Paddle) -> Game {
        Game {
            ui: ui,
            fps: fps,
            ball: ball,
            lpaddle: lpaddle,
            rpaddle: rpaddle,
            running: false,
        }
    }

    /// Start the game and block until finished.
    pub fn start(&mut self) {
        self.running = true;
        let mut time_last_invocation = clock_ticks::precise_time_ms();
        while self.running {
            let time_this_invocation = clock_ticks::precise_time_ms();
            let delta_time = time_this_invocation - time_last_invocation;
            self.update(delta_time as f32 / 1000.);
            self.cap_fps(delta_time);
            time_last_invocation = time_this_invocation;
        }
    }

    /// Called once per frame.
    fn update(&mut self, dt_sec: f32) {
        self.handle_input(dt_sec);
        self.update_ball_position(dt_sec);
        self.check_for_ball_and_wall_collisions();
        self.redraw()
    }

    fn handle_input(&mut self, dt_sec: f32) {
        match self.ui.poll_event() {
            Some(event) => {
                match event {
                    Event::Quit{..} => {
                        self.running = false;
                    },
                    Event::KeyDown{keycode,..} => match keycode {
                        Option::Some(Keycode::Escape) => {
                            self.running = false;
                        },
                        Option::Some(Keycode::Up) => {
                            let lpaddle = &mut self.lpaddle;
                            lpaddle.y -= lpaddle.speed * dt_sec;
                            if lpaddle.y < 0. { lpaddle.y = 0.; }
                        },
                        Option::Some(Keycode::Down) => {
                            let lpaddle = &mut self.lpaddle;
                            lpaddle.y += lpaddle.speed * dt_sec;
                            if lpaddle.y + lpaddle.height > self.ui.height {
                                lpaddle.y = self.ui.height - lpaddle.height;
                            }
                        },
                        _ => {}
                    },
                    _ => {}
                }
            },
            None => {}
        }
    }

    fn update_ball_position(&mut self, dt_sec: f32) {
        let ball = &mut self.ball;
        ball.x += ball.vx * dt_sec;
        ball.y += ball.vy * dt_sec;
    }

    fn check_for_ball_and_wall_collisions(&mut self) {
        let ball = &mut self.ball;

        // Left or right wall.
        if ball.x <= 0. && ball.vx < -0. {
            ball.x = 0.;
            ball.vx = -ball.vx;
        } else if ball.x + ball.width >= self.ui.width && ball.vx > 0. {
            ball.x = self.ui.width - ball.width;
            ball.vx = -ball.vx;
        }

        // Top or bottom wall.
        if ball.y <= 0. && ball.vy < -0. {
            ball.y = 0.;
            ball.vy = -ball.vy;
        } else if ball.y + ball.height >= self.ui.height && ball.vy > 0. {
            ball.y = self.ui.height - ball.height;
            ball.vy = -ball.vy;
        }
    }

    fn redraw(&mut self) {
        // Clear the screen.
        self.ui.renderer.clear();

        // Draw the ball.
        let ball = &mut self.ball;
        let ball_rect = Rect::new_unwrap(ball.x as i32,
                                    ball.y as i32,
                                    ball.width as u32,
                                    ball.height as u32);
        self.ui.renderer.fill_rect(ball_rect);

        // Draw the left paddle.
        let lpaddle = &mut self.lpaddle;
        let lpaddle_rect = Rect::new_unwrap(lpaddle.x as i32,
                                    lpaddle.y as i32,
                                    lpaddle.width as u32,
                                    lpaddle.height as u32);
        self.ui.renderer.fill_rect(lpaddle_rect);

        // Draw the right paddle.
        let rpaddle = &mut self.rpaddle;
        let rpaddle_rect = Rect::new_unwrap(rpaddle.x as i32,
                                    rpaddle.y as i32,
                                    rpaddle.width as u32,
                                    rpaddle.height as u32);
        self.ui.renderer.fill_rect(rpaddle_rect);

        // Flip backbuffer to front.
        self.ui.renderer.present();
    }

    // Ensure we run no faster than the desired fps by introducing
    // a delay if necessary.
    fn cap_fps(&self, took_ms: u64) {
        let max_ms = 1000 / self.fps as u64;
        if max_ms > took_ms {
            thread::sleep_ms((max_ms - took_ms) as u32);
        }
    }
}

struct GameBuilder {
    screen_width: f32,
    screen_height: f32,
    fps: u32,
    ball_speed: f32,
    paddle_speed: f32
}

impl GameBuilder {

    pub fn new() -> GameBuilder {
        GameBuilder {
            screen_width: 480.,
            screen_height: 320.,
            fps: 40,
            ball_speed: 320.,
            paddle_speed: 640.
        }
    }

    pub fn with_dimensions(mut self, width: f32, height: f32) -> GameBuilder {
        self.screen_width = width;
        self.screen_height = height;
        self
    }

    pub fn with_fps(mut self, fps: u32) -> GameBuilder {
        self.fps = fps;
        self
    }

    pub fn with_ball_speed_per_sec(mut self, ball_speed: f32) -> GameBuilder {
        self.ball_speed = ball_speed;
        self
    }

    pub fn with_paddle_speed_per_sec(mut self, paddle_speed: f32) -> GameBuilder {
        self.paddle_speed = paddle_speed;
        self
    }

    fn create_ui(&self) -> Ui {
        let sdl_ctx = sdl2::init().unwrap();
        let video_subsystem = sdl_ctx.video().unwrap();
        let window = video_subsystem.window("pong",
                self.screen_width as u32, self.screen_height as u32)
                .position_centered()
                .build()
                .unwrap();
        let renderer = window.renderer().build().unwrap();
        Ui::new(self.screen_width, self.screen_height, sdl_ctx, renderer)
    }

    fn create_ball(&self) -> Ball {
        let width = 10.;
        let height = 10.;

        // Place ball at center of screen.
        let x = (self.screen_width - width) / 2.;
        let y = (self.screen_height - height) / 2.;

        let speed = self.ball_speed;
        let mut rng = rand::thread_rng();

        // Launch at an angle less than or equal to 45 degrees.
        let angle = Range::new(0., f32::consts::PI/4.).ind_sample(&mut rng);
        let dir = [-1., 1.];

        // Use the sine of the angle to determine the vertical speed. Then,
        // choose a direction (up or down) to select a vertical velocity.
        let up_or_down = rand::sample(&mut rng, dir.into_iter(),1)[0];
        let vy = angle.sin() * speed * up_or_down;
        let left_or_right = rand::sample(&mut rng, dir.into_iter(),1)[0];

        // Use Pythagoras to determine the horizontal speed. Then, choose a
        // direction (left or right) to select a horizontal velocity.
        let vx = ((speed * speed) - (vy * vy)).sqrt() * left_or_right;
        Ball::new(x, y, width, height, speed, vx, vy)
    }

    fn create_left_paddle(&self) -> Paddle {
        let width = 10.;
        let height = 60.;
        let x = 0.;
        let y = (self.screen_height - height) / 2.;
        let vy = 0.;
        let score = 0;
        Paddle::new(x, y, width, height, self.paddle_speed, vy, score)
    }

    fn create_right_paddle(&self) -> Paddle {
        let width = 10.;
        let height = 60.;
        let x = self.screen_width - width;;
        let y = (self.screen_height - height) / 2.;
        let vy = 0.;
        let score = 0;
        Paddle::new(x, y, width, height, self.paddle_speed, vy, score)
    }

    pub fn build(&self) -> Game {
        Game::new(self.create_ui(),
                  self.fps,
                  self.create_ball(),
                  self.create_left_paddle(),
                  self.create_right_paddle())
    }
}

fn main() {
    let mut game = GameBuilder::new()
        .with_dimensions(480., 320.)
        .with_fps(40)
        .with_ball_speed_per_sec(320.)
        .with_paddle_speed_per_sec(800.)
        .build();
    game.start();
}
<|endoftext|>


<commit_before>extern crate cobalt;
extern crate getopts;

use getopts::Options;
use std::env;
use std::path::{PathBuf};

fn print_version() {
    // TODO parse this from Cargo.toml
    println!("0.0.1");
}

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

    let mut opts = Options::new();
    opts.optopt("s", "source", "Build from example/folder", "[example/folder]");
    opts.optopt("d", "destination", "Build into example/folder/build", "[example/folder]");
    opts.optopt("", "layouts", "Folder to get layouts from", "[_layouts]");
    opts.optopt("", "posts", "Folder to get posts from", "[_posts]");
    opts.optflag("h", "help", "Print this help menu");
    opts.optflag("v", "version", "Display version");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { panic!(f.to_string()) }
    };

    if matches.opt_present("h") {
        println!("{}", opts.usage("\n\tcobalt build"));
        return;
    }

    if matches.opt_present("v") {
        print_version();
        return;
    }

    let source  = PathBuf::from(&matches.opt_str("s").unwrap_or("./".to_string()));
    let dest    = PathBuf::from(&matches.opt_str("d").unwrap_or("./".to_string()));
    let layouts = matches.opt_str("layouts").unwrap_or("_layouts".to_string());
    let posts   = matches.opt_str("posts").unwrap_or("_posts".to_string());

    let command = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        println!("{}", opts.usage("\n\tcobalt build"));
        return;
    };

    match command.as_ref() {
        "build" => {
            println!("building from {} into {}", source.display(), dest.display());
            match cobalt::build(&source, &dest, &layouts, &posts){
                Ok(_) => println!("Build successful"),
                Err(e) => println!("Error: {}", e)
            };
        },

        _ => {
            println!("{}", opts.usage("\n\tcobalt build"));
            return;
        }
    }
}
<commit_msg>only PathBuf is used no need of listing it in curly braces<commit_after>extern crate cobalt;
extern crate getopts;

use getopts::Options;
use std::env;
use std::path::PathBuf;

fn print_version() {
    // TODO parse this from Cargo.toml
    println!("0.0.1");
}

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

    let mut opts = Options::new();
    opts.optopt("s", "source", "Build from example/folder", "[example/folder]");
    opts.optopt("d", "destination", "Build into example/folder/build", "[example/folder]");
    opts.optopt("", "layouts", "Folder to get layouts from", "[_layouts]");
    opts.optopt("", "posts", "Folder to get posts from", "[_posts]");
    opts.optflag("h", "help", "Print this help menu");
    opts.optflag("v", "version", "Display version");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { panic!(f.to_string()) }
    };

    if matches.opt_present("h") {
        println!("{}", opts.usage("\n\tcobalt build"));
        return;
    }

    if matches.opt_present("v") {
        print_version();
        return;
    }

    let source  = PathBuf::from(&matches.opt_str("s").unwrap_or("./".to_string()));
    let dest    = PathBuf::from(&matches.opt_str("d").unwrap_or("./".to_string()));
    let layouts = matches.opt_str("layouts").unwrap_or("_layouts".to_string());
    let posts   = matches.opt_str("posts").unwrap_or("_posts".to_string());

    let command = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        println!("{}", opts.usage("\n\tcobalt build"));
        return;
    };

    match command.as_ref() {
        "build" => {
            println!("building from {} into {}", source.display(), dest.display());
            match cobalt::build(&source, &dest, &layouts, &posts){
                Ok(_) => println!("Build successful"),
                Err(e) => println!("Error: {}", e)
            };
        },

        _ => {
            println!("{}", opts.usage("\n\tcobalt build"));
            return;
        }
    }
}
<|endoftext|>


<commit_before>extern crate yaml_rust;
extern crate regex;

use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::net::TcpListener;
use std::time::Duration;
use std::sync::Arc;
use std::thread;
use std::process::exit;
use yaml_rust::YamlLoader;
use regex::bytes::RegexSetBuilder;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

#[derive(Copy, Clone)]
struct App {
  print_ascii: bool,
  print_binary: bool
}

fn to_hex(bytes: &[u8]) -> String {
  let mut count = 0;
  let mut result = String::with_capacity(67);
  let mut dotline = String::with_capacity(18);

  for byte in bytes.iter() {
    if count != 0 && count%8 == 0 {
      result.push(' ');
      if count%16 == 0 {
        dotline.push('\n');
        result.push_str(&dotline);
        result.reserve(67);
        dotline.truncate(0);
      }
      else { dotline.push(' '); }
    }
    result.push_str(&format!("{:02X} ", byte));
    if *byte > 31 && *byte < 127 { dotline.push(*byte as char) }
    else if *byte == 0 { dotline.push('-'); }
    else { dotline.push('.'); }
    count += 1;
  }
  while count%16 != 0 {
    if count%8 == 0 { result.push(' '); }
    result.push_str("   ");
    count += 1;
  }
  if dotline.len() != 0 { result.push_str(&dotline); }
  result
}

fn main() {
  println!("PortLurker v{}", VERSION);
  println!("Developer: Bart Noordervlet (http://www.github.com/bartnv)");

  let mut app = App { print_ascii: false, print_binary: false };
  let binary_matches = [
    ("SSL3.0 Record Protocol", r"^\x16\x03\x00..\x01"),
    ("TLS1.0 Record Protocol", r"^\x16\x03\x01..\x01"),
    ("TLS1.1 Record Protocol", r"^\x16\x03\x02..\x01"),
    ("TLS1.2 Record Protocol", r"^\x16\x03\x03..\x01"),
    ("SSL3.0 CLIENT_HELLO", r"^\x16....\x01...\x03\x00"),
    ("TLS1.0 CLIENT_HELLO", r"^\x16....\x01...\x03\x01"),
    ("TLS1.1 CLIENT_HELLO", r"^\x16....\x01...\x03\x02"),
    ("TLS1.2 CLIENT_HELLO", r"^\x16....\x01...\x03\x03"),
    ("SMB1 COMMAND NEGOTIATE", r"^....\xffSMB\x72"),
    ("SMB1 NT_STATUS Success", r"^....\xffSMB.[\x00-\x0f]"),
    ("SMB1 NT_STATUS Information", r"^....\xffSMB.[\x40-\x4f]"),
    ("SMB1 NT_STATUS Warning", r"^....\xffSMB.[\x80-\x8f]"),
    ("SMB1 NT_STATUS Error", r"^....\xffSMB.[\xc0-\xcf]"),
    ("SMB2 COMMAND NEGOTIATE", r"^\x00...\xfeSMB........\x00\x00"),
    ("SMB2 NT_STATUS Success", r"^\x00...\xfeSMB....[\x00-\x0f]"),
    ("SMB2 NT_STATUS Information", r"^\x00...\xfeSMB....[\x40-\x4f]"),
    ("SMB2 NT_STATUS Warning", r"^\x00...\xfeSMB....[\x80-\x8f]"),
    ("SMB2 NT_STATUS Error", r"^\x00...\xfeSMB....[\xc0-\xcf]"),
    ("MS-TDS PRELOGIN Request", r"^\x12\x01\x00.\x00\x00"),
    ("MS-TDS LOGIN Requst", r"^\x10\x01\x00.\x00\x00")
  ];
  let io_timeout = Duration::new(300, 0); // 5 minutes

  let mut file = File::open("config.yml").unwrap();
  let mut config_str = String::new();
  file.read_to_string(&mut config_str).unwrap();
  let docs = YamlLoader::load_from_str(&config_str).unwrap();
  let config = &docs[0];
  //println!("{:?}", config);
  if config["general"].is_badvalue() {
    println!("No 'general' section found in configuration file");
    exit(-1);
  }
  if config["ports"].is_badvalue() {
    println!("No 'ports' section found in configuration file");
    exit(-1);
  }
  if !config["general"]["print_ascii"].is_badvalue() {
    if config["general"]["print_ascii"].as_bool().unwrap() {
      app.print_ascii = true;
      println!("Printing ASCII);
    }
  }
  if !config["general"]["print_binary"].is_badvalue() {
    if config["general"]["print_binary"].as_bool().unwrap() {
      app.print_binary = true;
      println!("Printing binary in hexadecimal");
    }
  }
  let app = app; // Revert to immutable

  let mut patterns = Vec::with_capacity(binary_matches.len());
  for &(_, pattern) in binary_matches.into_iter() {
    patterns.push(pattern);
  }
  let regexset = RegexSetBuilder::new(patterns)
    .unicode(false)
    .dot_matches_new_line(false)
    .build().unwrap();

  println!("Starting listeners on the following ports:");

  for port in config["ports"].as_vec().unwrap() {
    if !port["tcp"].is_badvalue() {
      let portno = port["tcp"].as_i64().unwrap();
      println!("TCP port {}", portno);
      let mut banner = Arc::new(String::new());
      if let Some(x) = port["banner"].as_str() {
        Arc::get_mut(& mut banner).unwrap().push_str(x);
        println!("  with banner: {}", *banner);
      }
      let regexset = regexset.clone();
      thread::spawn(move || {
        let server = TcpListener::bind(("0.0.0.0", portno as u16)).unwrap();
        for res in server.incoming() {
          let mut stream = match res {
            Ok(stream) => stream,
            Err(e) => { println!("ACCEPT ERROR TCP {}: {}", portno, e.to_string()); continue; }
          };
          stream.set_read_timeout(Some(io_timeout)).expect("Failed to set read timeout on TCPStream");
          stream.set_write_timeout(Some(io_timeout)).expect("Failed to set write timeout on TCPStream");
          let addr = stream.peer_addr().unwrap();
          println!("CONNECT TCP {} from {}", portno, addr);
          let regexset = regexset.clone();
          let banner = banner.clone();
          thread::spawn(move || {
            if banner.len() > 0 {
              match stream.write((*banner).as_bytes()) {
                Ok(_) => {
                  for line in (*banner).lines() {
                    println!("> {}", line);
                  }
                }
                Err(e) => {
                  if e.kind() == io::ErrorKind::WouldBlock { println!("WRITE TIMEOUT TCP {} from {}", portno, addr); }
                  else { println!("WRITE ERROR TCP {} from {}: {}", portno, addr, e.to_string()); }
                  return;
                }
              }
            }
            let mut buf: [u8; 2048] = [0; 2048];
            loop {
              match stream.read(&mut buf) {
                Ok(c) => {
                  if c == 0 {
                    println!("CLOSE TCP {} from {}", portno, addr);
                    break;
                  }
                  let mut printables = Vec::new();
                  let mut found = false;
                  let mut mbfound = false;
                  let mut mbstring = String::new();
                  let mut start = 0;
                  for i in 0..c {
                    if (buf[i] > 31 && buf[i] < 127) || buf[i] == 10 || buf[i] == 13 {
                      if !found {
                        start = i;
                        found = true;
                      }
                    }
                    else {
                      if found {
                        if (i-start == 1) {
                          if (start > 0) && (buf[start-1] == 0) {
                            mbstring.push(buf[i-1] as char);
                            if !mbfound { mbfound = true; }
                          }
                        }
                        else { printables.push(&buf[start..i]); }
                        found = false;
                      }
                      else if mbfound {
                        mbstring.push('\n');
                        mbfound = false;
                      }
                    }
                  }
                  if found { printables.push(&buf[start..c]); }
                  if printables.len() == 1 && printables[0].len() == c {
                    if app.print_ascii {
                      let data = String::from_utf8_lossy(printables[0]);
                      for line in data.lines() {
                        println!("| {}", line);
                      }
                    }
                    else { println!("! Read {} bytes of printable ASCII", c); }
                  }
                  else {
                    println!("! Read {} bytes of binary", c);
                    for id in regexset.matches(&buf[..c]).into_iter() {
                      println!("^ Matches pattern {}", binary_matches[id].0);
                    }
                    for printable in printables {
                      if printable.len() > 3 {
                        let data = String::from_utf8_lossy(printable);
                        for line in data.lines() {
                          println!("$ {}", line);
                        }
                      }
                    }
                    for line in mbstring.lines() {
                      if line.len() > 3 { println!("% {}", line); }
                    }
                    if app.print_binary {
                      let hex = to_hex(&buf[..c]);
                      for line in hex.lines() { println!(". {}", line); }
                    }
                  }
                }
                Err(e) => {
                  if e.kind() == io::ErrorKind::WouldBlock { println!("READ TIMEOUT TCP {} from {}", portno, addr); }
                  else { println!("READ ERROR TCP {} from {}: {}", portno, addr, e.to_string()); }
                  break;
                }
              }
              match stream.take_error() {
                Ok(opt) => {
                  if opt.is_some() {
                    println!("ERROR TCP {} from {}: {}", portno, addr, opt.unwrap().to_string());
                    break;
                  }
                }
                Err(_) => {
                  println!("This shouldn't happen...");
                  break;
                }
              }
            }
          });
        }
      });
    }
    else if !port["udp"].is_badvalue() {
      println!("UDP port {}", port["udp"].as_i64().unwrap());
    }
    else {
      println!("Invalid port specification in configuration file");
    }
  }

  loop { thread::sleep(Duration::new(60, 0)); }
}
<commit_msg>Update main.rs<commit_after>extern crate yaml_rust;
extern crate regex;

use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::net::TcpListener;
use std::time::Duration;
use std::sync::Arc;
use std::thread;
use std::process::exit;
use yaml_rust::YamlLoader;
use regex::bytes::RegexSetBuilder;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const AUTHORS: &'static str = env!("CARGO_PKG_AUTHORS");

#[derive(Copy, Clone)]
struct App {
  print_ascii: bool,
  print_binary: bool
}

fn to_hex(bytes: &[u8]) -> String {
  let mut count = 0;
  let mut result = String::with_capacity(67);
  let mut dotline = String::with_capacity(18);

  for byte in bytes.iter() {
    if count != 0 && count%8 == 0 {
      result.push(' ');
      if count%16 == 0 {
        dotline.push('\n');
        result.push_str(&dotline);
        result.reserve(67);
        dotline.truncate(0);
      }
      else { dotline.push(' '); }
    }
    result.push_str(&format!("{:02X} ", byte));
    if *byte > 31 && *byte < 127 { dotline.push(*byte as char) }
    else if *byte == 0 { dotline.push('-'); }
    else { dotline.push('.'); }
    count += 1;
  }
  while count%16 != 0 {
    if count%8 == 0 { result.push(' '); }
    result.push_str("   ");
    count += 1;
  }
  if dotline.len() != 0 { result.push_str(&dotline); }
  result
}

fn main() {
  println!("PortLurker v{}", VERSION);
  println!("{}", AUTHORS);

  let mut app = App { print_ascii: false, print_binary: false };
  let binary_matches = [
    ("SSL3.0 Record Protocol", r"^\x16\x03\x00..\x01"),
    ("TLS1.0 Record Protocol", r"^\x16\x03\x01..\x01"),
    ("TLS1.1 Record Protocol", r"^\x16\x03\x02..\x01"),
    ("TLS1.2 Record Protocol", r"^\x16\x03\x03..\x01"),
    ("SSL3.0 CLIENT_HELLO", r"^\x16....\x01...\x03\x00"),
    ("TLS1.0 CLIENT_HELLO", r"^\x16....\x01...\x03\x01"),
    ("TLS1.1 CLIENT_HELLO", r"^\x16....\x01...\x03\x02"),
    ("TLS1.2 CLIENT_HELLO", r"^\x16....\x01...\x03\x03"),
    ("SMB1 COMMAND NEGOTIATE", r"^....\xffSMB\x72"),
    ("SMB1 NT_STATUS Success", r"^....\xffSMB.[\x00-\x0f]"),
    ("SMB1 NT_STATUS Information", r"^....\xffSMB.[\x40-\x4f]"),
    ("SMB1 NT_STATUS Warning", r"^....\xffSMB.[\x80-\x8f]"),
    ("SMB1 NT_STATUS Error", r"^....\xffSMB.[\xc0-\xcf]"),
    ("SMB2 COMMAND NEGOTIATE", r"^\x00...\xfeSMB........\x00\x00"),
    ("SMB2 NT_STATUS Success", r"^\x00...\xfeSMB....[\x00-\x0f]"),
    ("SMB2 NT_STATUS Information", r"^\x00...\xfeSMB....[\x40-\x4f]"),
    ("SMB2 NT_STATUS Warning", r"^\x00...\xfeSMB....[\x80-\x8f]"),
    ("SMB2 NT_STATUS Error", r"^\x00...\xfeSMB....[\xc0-\xcf]"),
    ("MS-TDS PRELOGIN Request", r"^\x12\x01\x00.\x00\x00"),
    ("MS-TDS LOGIN Requst", r"^\x10\x01\x00.\x00\x00")
  ];
  let io_timeout = Duration::new(300, 0); // 5 minutes

  let mut file = File::open("config.yml").unwrap();
  let mut config_str = String::new();
  file.read_to_string(&mut config_str).unwrap();
  let docs = YamlLoader::load_from_str(&config_str).unwrap();
  let config = &docs[0];
  //println!("{:?}", config);
  if config["general"].is_badvalue() {
    println!("No 'general' section found in configuration file");
    exit(-1);
  }
  if config["ports"].is_badvalue() {
    println!("No 'ports' section found in configuration file");
    exit(-1);
  }
  if !config["general"]["print_ascii"].is_badvalue() {
    if config["general"]["print_ascii"].as_bool().unwrap() {
      app.print_ascii = true;
      println!("Printing ASCII);
    }
  }
  if !config["general"]["print_binary"].is_badvalue() {
    if config["general"]["print_binary"].as_bool().unwrap() {
      app.print_binary = true;
      println!("Printing binary in hexadecimal");
    }
  }
  let app = app; // Revert to immutable

  let mut patterns = Vec::with_capacity(binary_matches.len());
  for &(_, pattern) in binary_matches.into_iter() {
    patterns.push(pattern);
  }
  let regexset = RegexSetBuilder::new(patterns)
    .unicode(false)
    .dot_matches_new_line(false)
    .build().unwrap();

  println!("Starting listeners on the following ports:");

  for port in config["ports"].as_vec().unwrap() {
    if !port["tcp"].is_badvalue() {
      let portno = port["tcp"].as_i64().unwrap();
      println!("TCP port {}", portno);
      let mut banner = Arc::new(String::new());
      if let Some(x) = port["banner"].as_str() {
        Arc::get_mut(& mut banner).unwrap().push_str(x);
        println!("  with banner: {}", *banner);
      }
      let regexset = regexset.clone();
      thread::spawn(move || {
        let server = TcpListener::bind(("0.0.0.0", portno as u16)).unwrap();
        for res in server.incoming() {
          let mut stream = match res {
            Ok(stream) => stream,
            Err(e) => { println!("ACCEPT ERROR TCP {}: {}", portno, e.to_string()); continue; }
          };
          stream.set_read_timeout(Some(io_timeout)).expect("Failed to set read timeout on TCPStream");
          stream.set_write_timeout(Some(io_timeout)).expect("Failed to set write timeout on TCPStream");
          let addr = stream.peer_addr().unwrap();
          println!("CONNECT TCP {} from {}", portno, addr);
          let regexset = regexset.clone();
          let banner = banner.clone();
          thread::spawn(move || {
            if banner.len() > 0 {
              match stream.write((*banner).as_bytes()) {
                Ok(_) => {
                  for line in (*banner).lines() {
                    println!("> {}", line);
                  }
                }
                Err(e) => {
                  if e.kind() == io::ErrorKind::WouldBlock { println!("WRITE TIMEOUT TCP {} from {}", portno, addr); }
                  else { println!("WRITE ERROR TCP {} from {}: {}", portno, addr, e.to_string()); }
                  return;
                }
              }
            }
            let mut buf: [u8; 2048] = [0; 2048];
            loop {
              match stream.read(&mut buf) {
                Ok(c) => {
                  if c == 0 {
                    println!("CLOSE TCP {} from {}", portno, addr);
                    break;
                  }
                  let mut printables = Vec::new();
                  let mut found = false;
                  let mut mbfound = false;
                  let mut mbstring = String::new();
                  let mut start = 0;
                  for i in 0..c {
                    if (buf[i] > 31 && buf[i] < 127) || buf[i] == 10 || buf[i] == 13 {
                      if !found {
                        start = i;
                        found = true;
                      }
                    }
                    else {
                      if found {
                        if (i-start == 1) {
                          if (start > 0) && (buf[start-1] == 0) {
                            mbstring.push(buf[i-1] as char);
                            if !mbfound { mbfound = true; }
                          }
                        }
                        else { printables.push(&buf[start..i]); }
                        found = false;
                      }
                      else if mbfound {
                        mbstring.push('\n');
                        mbfound = false;
                      }
                    }
                  }
                  if found { printables.push(&buf[start..c]); }
                  if printables.len() == 1 && printables[0].len() == c {
                    if app.print_ascii {
                      let data = String::from_utf8_lossy(printables[0]);
                      for line in data.lines() {
                        println!("| {}", line);
                      }
                    }
                    else { println!("! Read {} bytes of printable ASCII", c); }
                  }
                  else {
                    println!("! Read {} bytes of binary", c);
                    for id in regexset.matches(&buf[..c]).into_iter() {
                      println!("^ Matches pattern {}", binary_matches[id].0);
                    }
                    for printable in printables {
                      if printable.len() > 3 {
                        let data = String::from_utf8_lossy(printable);
                        for line in data.lines() {
                          println!("$ {}", line);
                        }
                      }
                    }
                    for line in mbstring.lines() {
                      if line.len() > 3 { println!("% {}", line); }
                    }
                    if app.print_binary {
                      let hex = to_hex(&buf[..c]);
                      for line in hex.lines() { println!(". {}", line); }
                    }
                  }
                }
                Err(e) => {
                  if e.kind() == io::ErrorKind::WouldBlock { println!("READ TIMEOUT TCP {} from {}", portno, addr); }
                  else { println!("READ ERROR TCP {} from {}: {}", portno, addr, e.to_string()); }
                  break;
                }
              }
              match stream.take_error() {
                Ok(opt) => {
                  if opt.is_some() {
                    println!("ERROR TCP {} from {}: {}", portno, addr, opt.unwrap().to_string());
                    break;
                  }
                }
                Err(_) => {
                  println!("This shouldn't happen...");
                  break;
                }
              }
            }
          });
        }
      });
    }
    else if !port["udp"].is_badvalue() {
      println!("UDP port {}", port["udp"].as_i64().unwrap());
    }
    else {
      println!("Invalid port specification in configuration file");
    }
  }

  loop { thread::sleep(Duration::new(60, 0)); }
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate glium;
extern crate image;
extern crate zip;
extern crate cgmath;
extern crate notify;

use cgmath::{Vector, Vector2, Vector3};
use cgmath::{Basis3};
use cgmath::{Matrix, SquareMatrix, Matrix3, Matrix4};
use cgmath::{Angle, Rad, Deg};
use cgmath::{Rotation, Rotation3};
use cgmath::{PerspectiveFov};

use glium::glutin::{Event, MouseButton, ElementState};
use glium::debug::DebugCallbackBehavior;

//use glium::texture::{Texture2d, RawImage2d};
use glium::uniforms::Sampler;
//use glium::buffer::{Buffer, BufferMode, BufferSlice};

mod lightfield;
use lightfield::Lightfield;

mod reloading_program;
use reloading_program::ReloadingProgram;

fn main() {
    use glium::{DisplayBuild, Surface};
    let display = glium::glutin::WindowBuilder::new()
        .with_vsync()
        .build_glium_debug(DebugCallbackBehavior::PrintAll)
        .unwrap();

    #[derive(Copy, Clone)]
    struct Vertex {
        position: [f32; 2],
        tex_coords: [f32; 2],
    }

    implement_vertex!(Vertex, position, tex_coords);

    let vertex1 = Vertex { position: [-0.5, -0.5], tex_coords: [0.0, 0.0] };
    let vertex2 = Vertex { position: [ 0.0,  0.5], tex_coords: [0.0, 1.0] };
    let vertex3 = Vertex { position: [ 0.5, -0.25], tex_coords: [1.0, 0.0] };
    let shape = vec![vertex1, vertex2, vertex3];

    let vertex_buffer = glium::VertexBuffer::new(&display, &shape).unwrap();
    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);

    let mut reloading_program = ReloadingProgram::from_source(&display, "shaders/lightfield.vsh", "shaders/lightfield.fsh", None);

    let lf = Lightfield::new(&display, "chess.jpg.zip");
    let lf_sampler = Sampler::new(&lf.tex);

    let mut cursor_pos          = Vector2::new(0f32, 0f32);
    let mut cursor_startpos     = Vector2::new(0f32, 0f32);
    let mut cursor_totaloff     = Vector2::new(0f32, 0f32);
    let mut cursor_totaloff_old = Vector2::new(0f32, 0f32);
    let mut mouse_pressed = false;
    let mut mat_model = Matrix4::<f32>::identity();
    let mut mat_view = Matrix4::<f32>::identity();
    mat_view[3][2] = -5.0;
    let mut window_size = display.get_window().unwrap().get_inner_size_pixels().unwrap();
    let mut shaders_broken = false;
    loop {
        if shaders_broken {
            println!("Shaders are broken, waiting for updated shader before resuming...");
            reloading_program.wait_for_change();
        }
        let program = match reloading_program.current() {
            &Err(ref err) => {
                println!("Error compiling shader: {:?}.", err);
                shaders_broken = true;
                continue
            }
            &Ok(ref prog) => {
                shaders_broken = false;
                prog
            }
        };

        for ev in display.poll_events() {
            match ev {
                Event::Closed => return,
                Event::Resized(w,h) => {
                    window_size = (w,h);
                },
                Event::MouseMoved(m) => {
                    cursor_pos.x = m.0 as f32 / window_size.0 as f32 - 0.5;
                    cursor_pos.y = m.1 as f32 / window_size.1 as f32 - 0.5;
                },
                Event::MouseInput(ElementState::Pressed,  MouseButton::Left) => {
                    cursor_startpos = cursor_pos;
                    mouse_pressed = true;
                },
                Event::MouseInput(ElementState::Released, MouseButton::Left) => {
                    cursor_totaloff_old = cursor_totaloff;
                    mouse_pressed = false;
                },
                _ => ()
            }
        }
        if mouse_pressed {
            let offset = Vector2::from((cursor_startpos - cursor_pos));
            cursor_totaloff = cursor_totaloff_old + offset;
            //println!("{:?}", cursor_totaloff);
            let yaw   = Rad::<f32>::full_turn() * cursor_totaloff.x;
            let pitch   = Rad::<f32>::full_turn() * cursor_totaloff.y;
            mat_model = Matrix4::<f32>::from(Matrix3::from_euler(pitch, yaw, Rad::zero()));
        }

        let mut target = display.draw();
        target.clear_color(0.3, 0.3, 0.3, 1.0);
        let (width, height) = target.get_dimensions();

        let mat_projection: Matrix4<f32> =  PerspectiveFov {
            fovy:   Deg::new(60f32).into(),
            aspect: height as f32 / width as f32,
            near:   0.1,
            far:    1024.,
        }.into();

        let uniforms = uniform! {
            model:      Into::<[[f32; 4]; 4]>::into(mat_model),
            view:       Into::<[[f32; 4]; 4]>::into(mat_view),
            projection: Into::<[[f32; 4]; 4]>::into(mat_projection),
            tex: lf_sampler,
        };

        target.draw(&vertex_buffer, &indices, &program, &uniforms,
                    &Default::default()).unwrap();

        target.finish().unwrap();
        /*
        println!("model: {:#?}", mat_model);
        println!("view: {:#?}", mat_view);
        println!("projection: {:#?}", mat_projection);
        println!("");
        */
    }
}
<commit_msg>mousewheel zoom<commit_after>#[macro_use]
extern crate glium;
extern crate image;
extern crate zip;
extern crate cgmath;
extern crate notify;

use cgmath::{Vector, Vector2, Vector3, Vector4};
use cgmath::{Basis3};
use cgmath::{Matrix, SquareMatrix, Matrix3, Matrix4};
use cgmath::{Angle, Rad, Deg};
use cgmath::{Rotation, Rotation3};
use cgmath::{PerspectiveFov};

use glium::glutin::{Event, MouseButton, ElementState, MouseScrollDelta};
use glium::debug::DebugCallbackBehavior;

//use glium::texture::{Texture2d, RawImage2d};
use glium::uniforms::Sampler;
//use glium::buffer::{Buffer, BufferMode, BufferSlice};

mod lightfield;
use lightfield::Lightfield;

mod reloading_program;
use reloading_program::ReloadingProgram;

fn main() {
    use glium::{DisplayBuild, Surface};
    let display = glium::glutin::WindowBuilder::new()
        .with_vsync()
        .build_glium_debug(DebugCallbackBehavior::PrintAll)
        .unwrap();

    #[derive(Copy, Clone)]
    struct Vertex {
        position: [f32; 2],
        tex_coords: [f32; 2],
    }

    implement_vertex!(Vertex, position, tex_coords);

    let vertex1 = Vertex { position: [-0.5, -0.5], tex_coords: [0.0, 0.0] };
    let vertex2 = Vertex { position: [ 0.0,  0.5], tex_coords: [0.0, 1.0] };
    let vertex3 = Vertex { position: [ 0.5, -0.25], tex_coords: [1.0, 0.0] };
    let shape = vec![vertex1, vertex2, vertex3];

    let vertex_buffer = glium::VertexBuffer::new(&display, &shape).unwrap();
    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);

    let mut reloading_program = ReloadingProgram::from_source(&display, "shaders/lightfield.vsh", "shaders/lightfield.fsh", None);

    let lf = Lightfield::new(&display, "chess.jpg.zip");
    let lf_sampler = Sampler::new(&lf.tex);

    let mut cursor_pos          = Vector2::new(0f32, 0f32);
    let mut cursor_startpos     = Vector2::new(0f32, 0f32);
    let mut cursor_totaloff     = Vector2::new(0f32, 0f32);
    let mut cursor_totaloff_old = Vector2::new(0f32, 0f32);
    let mut scale = 1f32;
    let mut mouse_pressed = false;
    let mut mouse_scrolled = false;
    let mut mat_model = Matrix4::<f32>::identity();
    let mut mat_view = Matrix4::<f32>::identity();
    mat_view[3][2] = -5.0;
    let mut window_size = display.get_window().unwrap().get_inner_size_pixels().unwrap();
    let mut shaders_broken = false;
    loop {
        if shaders_broken {
            println!("Shaders are broken, waiting for updated shader before resuming...");
            reloading_program.wait_for_change();
        }
        let program = match reloading_program.current() {
            &Err(ref err) => {
                println!("Error compiling shader: {:?}.", err);
                shaders_broken = true;
                continue
            }
            &Ok(ref prog) => {
                shaders_broken = false;
                prog
            }
        };

        for ev in display.poll_events() {
            match ev {
                Event::Closed => return,
                Event::Resized(w,h) => {
                    window_size = (w,h);
                },
                Event::MouseMoved(m) => {
                    cursor_pos.x = m.0 as f32 / window_size.0 as f32 - 0.5;
                    cursor_pos.y = m.1 as f32 / window_size.1 as f32 - 0.5;
                },
                Event::MouseInput(ElementState::Pressed,  MouseButton::Left) => {
                    cursor_startpos = cursor_pos;
                    mouse_pressed = true;
                },
                Event::MouseInput(ElementState::Released, MouseButton::Left) => {
                    cursor_totaloff_old = cursor_totaloff;
                    mouse_pressed = false;
                },
                Event::MouseWheel(MouseScrollDelta::LineDelta(_, lines)) => {
                    scale *= f32::powf(1.1, lines);
                    //println!("scroll: {}, scale {}", lines, scale);
                    mouse_scrolled = true;
                },
                _ => ()
            }
        }
        if mouse_pressed || mouse_scrolled {
            let offset = Vector2::from((cursor_startpos - cursor_pos));
            cursor_totaloff = cursor_totaloff_old + offset;
            //println!("{:?}", cursor_totaloff);
            let yaw   = Rad::<f32>::full_turn() * cursor_totaloff.x;
            let pitch   = Rad::<f32>::full_turn() * cursor_totaloff.y;
            let mat_rot = Matrix4::<f32>::from(Matrix3::from_euler(pitch, yaw, Rad::zero()));
            let mat_scale = Matrix4::<f32>::from_diagonal(Vector4::new(scale, scale, scale, 1.0));
            mat_model = mat_rot * mat_scale;
            mouse_scrolled = false; // only recompute once!
        }

        let mut target = display.draw();
        target.clear_color(0.3, 0.3, 0.3, 1.0);
        let (width, height) = target.get_dimensions();

        let mat_projection: Matrix4<f32> =  PerspectiveFov {
            fovy:   Deg::new(60f32).into(),
            aspect: height as f32 / width as f32,
            near:   0.1,
            far:    1024.,
        }.into();

        let uniforms = uniform! {
            model:      Into::<[[f32; 4]; 4]>::into(mat_model),
            view:       Into::<[[f32; 4]; 4]>::into(mat_view),
            projection: Into::<[[f32; 4]; 4]>::into(mat_projection),
            tex: lf_sampler,
        };

        target.draw(&vertex_buffer, &indices, &program, &uniforms,
                    &Default::default()).unwrap();

        target.finish().unwrap();
        /*
        println!("model: {:#?}", mat_model);
        println!("view: {:#?}", mat_view);
        println!("projection: {:#?}", mat_projection);
        println!("");
        */
    }
}
<|endoftext|>


<commit_before>use std::f32;

extern crate gnuplot;
use gnuplot::{AxesCommon, Figure, Color};
use gnuplot::LabelOption::TextColor;
use gnuplot::PlotOption::LineWidth;

mod genetic;
use genetic::helpers::Range;
use genetic::helpers::{hamming_distance, euclidean_distance_int, euclidean_distance_float};
use genetic::population::{Population};
use genetic::fitness::{max_alternating_bits,
                       max_alternating_even_odd,
                       pattern_recognition,
                       min_dejong,
                       n_queens,
                       path_fitness,
                       deceptive_f3,
                       deceptive_f3s,
                       deceptive_4};
use genetic::crossover::{one_point_crossover,
                         one_point_crossover_3,
                         uniform_average_crossover,
                         uniform_crossover,
                         uniform_crossover_3,
                         partially_matched_crossover};
use genetic::mutation::{bit_flip,
                        swap_position,
                        random_int,
                        delta_mutation,
                        gaussian_mutation};

fn main() {
    let total_generations = 2000;
    let population_size = 30;
    let genome_size = 30;

    let crossover_probability = 0.95;
    let mutation_probability = 0.05;

    let has_elitism = true;
    let has_scaling = true;
    let has_generation_gap = true;
    let has_fitness_sharing = true;
    let crowding_factor = 1.0;

    let distance_function = hamming_distance;

    let fitness_function = max_alternating_bits;
    let mutation_function = bit_flip;

    let mut population = Population::<u8>::new(population_size,
                                               genome_size,
                                               crossover_probability,
                                               mutation_probability,
                                               Range::new(0, 1),
                                               has_elitism,
                                               has_scaling,
                                               has_generation_gap,
                                               has_fitness_sharing,
                                               crowding_factor,
                                               distance_function,
                                               fitness_function,
                                               one_point_crossover,
                                               mutation_function);

    println!("Initial population");
    population.print();

    for current_generation in 0..total_generations {
        population.iterate_generation(current_generation, total_generations);
        //println!("\nGeneration: {}", current_generation);
        //population.print();
    }

    population.print_best_individual_diagnostic();

    show_convergence_plot(&population.average_fitness_in_generation,
                          &population.best_fitness_in_generation);

    show_diversity_plot(&population.diversity_in_generation);
}

fn show_convergence_plot(average_fitnesses: &Vec<f32>, best_fitnesses: &Vec<f32>) {
    let generations: Vec<usize> = (0..average_fitnesses.len()).collect();

    let mut fg = Figure::new();
    fg.set_terminal("wxt size 800, 400", "");
    {
        let axes = fg.axes2d()
            .lines(&generations,
                   average_fitnesses,
                   &[Color("#505050"), LineWidth(1.2)])
            .lines(&generations,
                   best_fitnesses,
                   &[Color("#0072bd"), LineWidth(1.2)]);

        let label_options = &[gnuplot::LabelOption::TextColor("black")];
        axes.set_x_label("Gerações", label_options);
        axes.set_y_label("Fitness", label_options);
    }
    fg.show();
}

fn show_diversity_plot(diversity_in_generations: &Vec<f32>) {
    let generations: Vec<usize> = (0..diversity_in_generations.len()).collect();

    let mut fg = Figure::new();
    fg.set_terminal("wxt size 800, 400", "");
    {
        let axes = fg.axes2d()
            .lines(&generations,
                   diversity_in_generations,
                   &[Color("#505050"), LineWidth(1.2)]);

        let label_options = &[gnuplot::LabelOption::TextColor("black")];
        axes.set_x_label("Gerações", label_options);
        axes.set_y_label("Diversidade", label_options);
    }
    fg.show();
}

<commit_msg>Debugging F3<commit_after>use std::f32;

extern crate gnuplot;
use gnuplot::{AxesCommon, Figure, Color};
use gnuplot::LabelOption::TextColor;
use gnuplot::PlotOption::LineWidth;

mod genetic;
use genetic::helpers::Range;
use genetic::helpers::{hamming_distance, euclidean_distance_int, euclidean_distance_float};
use genetic::population::{Population};
use genetic::fitness::{max_alternating_bits,
                       max_alternating_even_odd,
                       pattern_recognition,
                       min_dejong,
                       n_queens,
                       path_fitness,
                       deceptive_f3,
                       deceptive_f3s,
                       deceptive_4};
use genetic::crossover::{one_point_crossover,
                         one_point_crossover_3,
                         uniform_average_crossover,
                         uniform_crossover,
                         uniform_crossover_3,
                         partially_matched_crossover};
use genetic::mutation::{bit_flip,
                        swap_position,
                        random_int,
                        delta_mutation,
                        gaussian_mutation};

fn main() {
    let total_generations = 2000;
    let population_size = 30;
    let genome_size = 30;

    let crossover_probability = 0.60;
    let mutation_probability = 0.005;

    let has_elitism = true;
    let has_scaling = true;
    let has_generation_gap = true;
    let has_fitness_sharing = true;
    let crowding_factor = 1.0;

    let distance_function = hamming_distance;

    let fitness_function = deceptive_f3;
    let mutation_function = bit_flip;

    let mut population = Population::<u8>::new(population_size,
                                               genome_size,
                                               crossover_probability,
                                               mutation_probability,
                                               Range::new(0, 1),
                                               has_elitism,
                                               has_scaling,
                                               has_generation_gap,
                                               has_fitness_sharing,
                                               crowding_factor,
                                               distance_function,
                                               fitness_function,
                                               uniform_crossover_3,
                                               mutation_function);

    println!("Initial population");
    population.print();

    for current_generation in 0..total_generations {
        population.iterate_generation(current_generation, total_generations);
        //println!("\nGeneration: {}", current_generation);
        //population.print();
    }

    population.print_best_individual_diagnostic();

    show_convergence_plot(&population.average_fitness_in_generation,
                          &population.best_fitness_in_generation);

    show_diversity_plot(&population.diversity_in_generation);
}

fn show_convergence_plot(average_fitnesses: &Vec<f32>, best_fitnesses: &Vec<f32>) {
    let generations: Vec<usize> = (0..average_fitnesses.len()).collect();

    let mut fg = Figure::new();
    fg.set_terminal("wxt size 800, 400", "");
    {
        let axes = fg.axes2d()
            .lines(&generations,
                   average_fitnesses,
                   &[Color("#505050"), LineWidth(1.2)])
            .lines(&generations,
                   best_fitnesses,
                   &[Color("#0072bd"), LineWidth(1.2)]);

        let label_options = &[gnuplot::LabelOption::TextColor("black")];
        axes.set_x_label("Gerações", label_options);
        axes.set_y_label("Fitness", label_options);
    }
    fg.show();
}

fn show_diversity_plot(diversity_in_generations: &Vec<f32>) {
    let generations: Vec<usize> = (0..diversity_in_generations.len()).collect();

    let mut fg = Figure::new();
    fg.set_terminal("wxt size 800, 400", "");
    {
        let axes = fg.axes2d()
            .lines(&generations,
                   diversity_in_generations,
                   &[Color("#505050"), LineWidth(1.2)]);

        let label_options = &[gnuplot::LabelOption::TextColor("black")];
        axes.set_x_label("Gerações", label_options);
        axes.set_y_label("Diversidade", label_options);
    }
    fg.show();
}

<|endoftext|>


<commit_before>use std::cell::Cell;

struct Coordinates {
    x: Cell<i32>,
    y: Cell<i32>,
}

fn main() {
    let origin = Coordinates { x: Cell::new(0), y: Cell::new(0) };

    move_up(&origin.y); // borrow the value so that it can change (using the '&' symbol borrows the var)
    move_up(&origin.y);
    move_down(&origin.y);
    move_right(&origin.x);
    move_right(&origin.x);
    move_left(&origin.x);

    println!("X is {:?} and Y is {:?}", origin.x, origin.y);
}

fn move_up(y_cord: &Cell<i32>) -> &Cell<i32> {
    let new_val = y_cord.get(); // get the value and store it
    y_cord.set(new_val + 1); // modify the stored value and set the incoming param
    y_cord // no semicolon here because it is the return value
}

fn move_down(y_cord: &Cell<i32>) -> &Cell<i32> {
    let new_val = y_cord.get(); // get the value and store it
    y_cord.set(new_val - 1); // modify the stored value and set the incoming param
    y_cord // no semicolon here because it is the return value
}

fn move_right(x_cord: &Cell<i32>) -> &Cell<i32> {
    let new_val = x_cord.get(); // get the value and store it
    x_cord.set(new_val + 1); // modify the stored value and set the incoming param
    x_cord // no semicolon here because it is the return value
}

fn move_left(x_cord: &Cell<i32>) -> &Cell<i32> {
    let new_val = x_cord.get(); // get the value and store it
    x_cord.set(new_val - 1); // modify the stored value and set the incoming param
    x_cord // no semicolon here because it is the return value
}

#[test]
fn it_can_move() {
    let origin = Coordinates { x: Cell::new(0), y: Cell::new(0) };

    assert_eq!(0, origin.y.get());

    move_up(&origin.y);

    assert_eq!(1, origin.y.get());

    move_up(&origin.y);
    move_up(&origin.y);
    move_up(&origin.y);

    assert_eq!(4, origin.y.get());

    for _ in 0..19 { // _ instead of x so that rust does not complain about x not being used
        move_up(&origin.y); // moves up 19 times
    }

    assert_eq!(23, origin.y.get());

    // test it can move down

    for _ in 0..19 {
        move_down(&origin.y);
    }

    assert_eq!(4, origin.y.get());

    // test it can move right

    for _ in 0..19 {
        move_right(&origin.x);
    }

    assert_eq!(19, origin.x.get());

    // test it can move left

    for _ in 0..10 {
        move_left(&origin.x);
    }

    assert_eq!(9, origin.x.get());
}
<commit_msg>above the block of move calls<commit_after>use std::cell::Cell;

struct Coordinates {
    x: Cell<i32>,
    y: Cell<i32>,
}

fn main() {
    let origin = Coordinates { x: Cell::new(0), y: Cell::new(0) };

    // borrow the value so that it can change (using the '&' symbol borrows the var)
    move_up(&origin.y);
    move_up(&origin.y);
    move_down(&origin.y);
    move_right(&origin.x);
    move_right(&origin.x);
    move_left(&origin.x);

    println!("X is {:?} and Y is {:?}", origin.x, origin.y);
}

fn move_up(y_cord: &Cell<i32>) -> &Cell<i32> {
    let new_val = y_cord.get(); // get the value and store it
    y_cord.set(new_val + 1); // modify the stored value and set the incoming param
    y_cord // no semicolon here because it is the return value
}

fn move_down(y_cord: &Cell<i32>) -> &Cell<i32> {
    let new_val = y_cord.get(); // get the value and store it
    y_cord.set(new_val - 1); // modify the stored value and set the incoming param
    y_cord // no semicolon here because it is the return value
}

fn move_right(x_cord: &Cell<i32>) -> &Cell<i32> {
    let new_val = x_cord.get(); // get the value and store it
    x_cord.set(new_val + 1); // modify the stored value and set the incoming param
    x_cord // no semicolon here because it is the return value
}

fn move_left(x_cord: &Cell<i32>) -> &Cell<i32> {
    let new_val = x_cord.get(); // get the value and store it
    x_cord.set(new_val - 1); // modify the stored value and set the incoming param
    x_cord // no semicolon here because it is the return value
}

#[test]
fn it_can_move() {
    let origin = Coordinates { x: Cell::new(0), y: Cell::new(0) };

    assert_eq!(0, origin.y.get());

    move_up(&origin.y);

    assert_eq!(1, origin.y.get());

    move_up(&origin.y);
    move_up(&origin.y);
    move_up(&origin.y);

    assert_eq!(4, origin.y.get());

    for _ in 0..19 { // _ instead of x so that rust does not complain about x not being used
        move_up(&origin.y); // moves up 19 times
    }

    assert_eq!(23, origin.y.get());

    // test it can move down

    for _ in 0..19 {
        move_down(&origin.y);
    }

    assert_eq!(4, origin.y.get());

    // test it can move right

    for _ in 0..19 {
        move_right(&origin.x);
    }

    assert_eq!(19, origin.x.get());

    // test it can move left

    for _ in 0..10 {
        move_left(&origin.x);
    }

    assert_eq!(9, origin.x.get());
}
<|endoftext|>


<commit_before>//! Implementation of a simple uTP client and server.
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate getopts;
extern crate daemonize;
extern crate udt;

use daemonize::{Daemonize};
use std::process;
use std::process::Command;
use std::thread;
use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr};
use std::net;
use std::str;
use std::env;
use std::fs::File;
use std::str::FromStr;
use std::path::Path;
use getopts::Options;
use udt::*;

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} [options] REMOTE-LOCATION", program);
    print!("{}", opts.usage(&brief));
}

fn main() {
    use std::io::{stdin, stdout, stderr, Read, Write};

    // This example may run in either server or client mode.
    // Using an enum tends to make the code cleaner and easier to read.
    enum Mode {Server, Client}

    // Start logging
    env_logger::init().expect("Error starting logger");

    // Fetch arguments
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    opts.optopt("o", "", "set output file name", "NAME");
    opts.optflag("s", "server", "server mode");
    opts.optflag("p", "port-range", "server listening port range");
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { panic!(f.to_string()) }
    };

    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }

    let input = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        return;
    };

    // Parse the mode argument
    let mode: Mode = match matches.opt_present("s") {
        true => Mode::Server,
        false => Mode::Client
    };

    match mode {
        Mode::Server => {
            udt::init();
            let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
            sock.setsockopt(UdtOpts::UDP_RCVBUF, 5590000i32);
            sock.setsockopt(UdtOpts::UDP_SNDBUF, 5590000i32);
            sock.bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_str("0.0.0.0").unwrap(), 55000))).unwrap();
            let my_addr = sock.getsockname().unwrap();
            println!("Server bound to {:?}", my_addr);

            sock.listen(5).unwrap();

            let (mut stream, peer) = sock.accept().unwrap();
            println!("Received new connection from peer {:?}", peer);

            let mut f = File::open(input).unwrap();

            let daemonize = Daemonize::new();

            let mut writer = stdout();
            // let _ = writeln!(&mut stderr(), "Serving on {}", addr);

            let mut startmagic = vec![0; 1];
            let amount_read = stream.recv(&mut startmagic, 1).unwrap();
            println!("got {} magic byte(s).", amount_read);

            // match daemonize.start() {
            //     Ok(_) => { let _ = writeln!(&mut stderr(), "daemonized"); }
            //     Err(e) => { let _ = writeln!(&mut stderr(), "RWRWARWARARRR"); }
            // }

            let mut total = 0;
            // Create a reasonably sized buffer
            let mut payload = vec![0; 1300];
            loop {
                match stream.send(&payload) {
                    Ok(written) => { print!("."); }
                    Err(e) => { panic!("{:?}", e); }
                }
            }
            // loop {
            //     match f.read(&mut payload) {
            //         Ok(read) => {
            //             println!("file read {}", read);
            //             match stream.write(&payload[0..read]) {
            //                 Ok(written) => {
            //                     total += written;
            //                     println!("written {}", total);
            //                 },
            //                 Err(e) => {
            //                     stream.close().expect("Error closing stream");
            //                     panic!("{}", e);
            //                 }
            //             }
            //         },
            //         Err(e) => {
            //             stream.close().expect("Error closing stream");
            //             panic!("{}", e);
            //         }
            //     }
            // }
        }
        Mode::Client => {
            let sections: Vec<&str> = input.split(":").collect();
            let addr: String = sections[0].to_owned();
            let path: String = sections[1].to_owned();
            let cmd = format!("~/bin/shoop -s {}", path);
            println!("addr: {}, path: {}, cmd: {}", addr, path, cmd);

            // let output = Command::new("ssh")
            //                      .arg(addr.to_owned())
            //                      .arg(cmd)
            //                      .output()
            //                      .unwrap_or_else(|e| {
            //                          panic!("failed to execute process: {}", e);
            //                      });
            // let udp_addr = String::from_utf8_lossy(&output.stdout).trim().to_owned();
            //
            // // Create a stream and try to connect to the remote address
            // println!("shoop server told us to connect to {}", udp_addr);
            udt::init();
            let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
            sock.setsockopt(UdtOpts::UDP_RCVBUF, 5590000i32);
            sock.setsockopt(UdtOpts::UDP_SNDBUF, 5590000i32);
            let addr: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_str("144.76.81.4").unwrap(), 55000));
            sock.bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_str("0.0.0.0").unwrap(), 0)));
            match sock.connect(addr) {
                Ok(()) => {
                    println!("connected!");
                },
                Err(e) => {
                    panic!("errrrrrrr {:?}", e);
                }
            }

            // let mut f = File::create("outfile").unwrap();
            // println!("created file.");
            // Create a reasonably sized buffer
            let mut payload = vec![0; 1024 * 1024];
            sock.send(b"\x01");
            println!("write magic byte.");

            let mut total = 0;
            loop {
                match sock.recv(&mut payload, 1024 * 1024) {
                    Ok(0) => {
                        println!("EOF");
                        break
                    },
                    Ok(read) => {
                        total += read;
                        println!("read {}", total);
                        // f.write_all(&payload[0..read-1]);
                    },
                    Err(e) => {
                        panic!("{:?}", e);
                    }
                }
            }

            // Explicitly close the stream.
        }
    }
}

<commit_msg>file stuff<commit_after>//! Implementation of a simple uTP client and server.
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate getopts;
extern crate daemonize;
extern crate udt;

use daemonize::{Daemonize};
use std::process;
use std::process::Command;
use std::thread;
use std::net::{SocketAddr, SocketAddrV4, Ipv4Addr};
use std::net;
use std::str;
use std::env;
use std::fs::File;
use std::str::FromStr;
use std::path::Path;
use getopts::Options;
use udt::*;

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} [options] REMOTE-LOCATION", program);
    print!("{}", opts.usage(&brief));
}

fn main() {
    use std::io::{stdin, stdout, stderr, Read, Write};

    // This example may run in either server or client mode.
    // Using an enum tends to make the code cleaner and easier to read.
    enum Mode {Server, Client}

    // Start logging
    env_logger::init().expect("Error starting logger");

    // Fetch arguments
    let args: Vec<String> = env::args().collect();
    let program = args[0].clone();
    let mut opts = Options::new();
    opts.optopt("o", "output", "set output file name", "NAME");
    opts.optflag("s", "server", "server mode");
    opts.optflag("p", "port-range", "server listening port range");
    opts.optflag("h", "help", "print this help menu");

    let matches = match opts.parse(&args[1..]) {
        Ok(m) => { m }
        Err(f) => { panic!(f.to_string()) }
    };

    if matches.opt_present("h") {
        print_usage(&program, opts);
        return;
    }

    let input = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        print_usage(&program, opts);
        return;
    };

    // Parse the mode argument
    let mode: Mode = match matches.opt_present("s") {
        true => Mode::Server,
        false => Mode::Client
    };

    match mode {
        Mode::Server => {
            udt::init();
            let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
            sock.setsockopt(UdtOpts::UDP_RCVBUF, 5590000i32);
            sock.setsockopt(UdtOpts::UDP_SNDBUF, 5590000i32);
            sock.bind(SocketAddr::V4(SocketAddrV4::from_str("0.0.0.0:55000").unwrap())).unwrap();
            let my_addr = sock.getsockname().unwrap();
            println!("Server bound to {:?}", my_addr);

            sock.listen(5).unwrap();

            let (mut stream, peer) = sock.accept().unwrap();
            println!("Received new connection from peer {:?}", peer);

            let mut f = File::open(input).unwrap();

            let daemonize = Daemonize::new();

            let mut writer = stdout();
            // let _ = writeln!(&mut stderr(), "Serving on {}", addr);

            let mut startmagic = vec![0; 1];
            let amount_read = stream.recv(&mut startmagic, 1).unwrap();
            println!("got {} magic byte(s).", amount_read);

            // match daemonize.start() {
            //     Ok(_) => { let _ = writeln!(&mut stderr(), "daemonized"); }
            //     Err(e) => { let _ = writeln!(&mut stderr(), "RWRWARWARARRR"); }
            // }

            let mut total = 0;
            // Create a reasonably sized buffer
            let mut payload = vec![0; 1300];
            // loop {
            //     match stream.send(&payload) {
            //         Ok(written) => { print!("."); }
            //         Err(e) => { panic!("{:?}", e); }
            //     }
            // }
            loop {
                match f.read(&mut payload) {
                    Ok(read) => {
                        println!("file read {}", read);
                        match stream.send(&payload[0..read]) {
                            Ok(written) => {
                                total += written;
                                print!("\rwritten {}", total);
                            },
                            Err(e) => {
                                stream.close().expect("Error closing stream");
                                panic!("{:?}", e);
                            }
                        }
                    },
                    Err(e) => {
                        stream.close().expect("Error closing stream");
                        panic!("{}", e);
                    }
                }
            }
            println!("yay");
        }
        Mode::Client => {
            let sections: Vec<&str> = input.split(":").collect();
            let addr: String = sections[0].to_owned();
            let path: String = sections[1].to_owned();
            let cmd = format!("~/bin/shoop -s {}", path);
            println!("addr: {}, path: {}, cmd: {}", addr, path, cmd);

            // let output = Command::new("ssh")
            //                      .arg(addr.to_owned())
            //                      .arg(cmd)
            //                      .output()
            //                      .unwrap_or_else(|e| {
            //                          panic!("failed to execute process: {}", e);
            //                      });
            // let udp_addr = String::from_utf8_lossy(&output.stdout).trim().to_owned();
            //
            // // Create a stream and try to connect to the remote address
            // println!("shoop server told us to connect to {}", udp_addr);
            udt::init();
            let sock = UdtSocket::new(SocketFamily::AFInet, SocketType::Stream).unwrap();
            sock.setsockopt(UdtOpts::UDP_RCVBUF, 5590000i32);
            sock.setsockopt(UdtOpts::UDP_SNDBUF, 5590000i32);
            let addr: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_str(&addr).unwrap(), 55000));
            sock.bind(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::from_str("0.0.0.0").unwrap(), 0)));
            match sock.connect(addr) {
                Ok(()) => {
                    println!("connected!");
                },
                Err(e) => {
                    panic!("errrrrrrr {:?}", e);
                }
            }

            let mut f = File::create("outfile").unwrap();
            println!("created file.");
            let mut payload = vec![0; 1024 * 1024];
            sock.send(b"\x01");
            println!("write magic byte.");

            let mut total = 0;
            loop {
                match sock.recv(&mut payload, 1024 * 1024) {
                    Ok(0) => {
                        println!("EOF");
                        break
                    },
                    Ok(read) => {
                        total += read;
                        println!("read {}", total);
                        f.write_all(&payload[0..(read-1) as usize]);
                    },
                    Err(e) => {
                        panic!("{:?}", e);
                    }
                }
            }
            sock.close();
        }
    }
}

<|endoftext|>


<commit_before>extern crate xml;
extern crate rustc;

use std::os;

use std::io::{File, BufferedReader};
use std::fmt;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread::Thread;
use std::io::timer::sleep;
use std::time::duration::Duration;

use rustc::middle::graph::{NodeIndex, Graph};

use xml::reader::EventReader;
use xml::reader::events::XmlEvent;

fn main() {
	println!("XGConsole:");
	for arg in parse_command_line(os::args()).iter() {
		println!("  {}", arg);
	}
	xg_parse();

	let (tx_result, rx_result): (Sender<String>, Receiver<String>) = channel();
	let (tx_task, rx_task): (Sender<String>, Receiver<String>) = channel();
	let mutex_rx_task = Arc::new(Mutex::new(rx_task));

	for cpu_id in range(0, std::os::num_cpus()) {
		let local_rx_task = mutex_rx_task.clone();
		let local_tx_result = tx_result .clone();
				Thread::spawn(move || {
				loop {
					let message: String;
					{
						match local_rx_task.lock().recv_opt() {
								Ok(v) => {message = v;}
								Err(_) => {break;}
							}
					}
					println!("{}: {}", cpu_id, message);
					sleep(Duration::milliseconds(100));
					local_tx_result.send(format!("Done {}", message));
				}
				println!("{}: done", cpu_id);
			}).detach();
	}
	free(tx_result);

	for task_id in range (0i, 50i) {
			tx_task.send(format!("Task {}", task_id));
	}
	free(tx_task);

	for message in rx_result.iter() {
		println!("B: {}", message);
	}
	println!("done");
}

fn free<T>(_:T) {
}

fn parse_command_line(args: Vec<String>) -> Vec<String> {
	let mut result: Vec<String> = Vec::new();
	for arg in args.slice(1, args.len()).iter() {
			result.push(arg.clone());
	}
	result
}

struct BuildTask {
working_dir: String,
}

struct XgTask {
id: Option<String>,
title: Option<String>,
tool: String,
working_dir: String,
depends_on: Vec<String>,
}

impl fmt::Show for XgTask {
fn fmt(& self, f: &mut fmt::Formatter) -> fmt::Result {
	write!(f, "id={}, title={}, tool={}, working_dir={}, depends_on={}", self .id, self .title, self .tool, self .working_dir, self .depends_on)
}
}

struct XgTool {
id: String,
path: String,
params: String,
}

impl fmt::Show for XgTool {
fn fmt(& self, f: &mut fmt::Formatter) -> fmt::Result {
	write!(f, "id={}, path={}", self .id, self .path)
}
}

fn xg_parse() -> Graph<BuildTask, ()> {
	let file = File::open(&Path::new("tests/graph-parser.xml")).unwrap();
	let reader = BufferedReader::new(file);

	let mut parser = EventReader::new(reader);
	let mut tasks:Vec<XgTask> = vec![];
	let mut tools:HashMap<String, XgTool> = HashMap::new();
	for e in parser.events() {
		match e {
				XmlEvent::StartElement {name, attributes, ..} => {
				match name.local_name.as_slice() {
						"Task" =>
						{
							match xg_parse_task(&attributes) {
									Ok(task) =>
									{
											tasks.push(task);
									}
									Err(msg) =>
									{
										panic!(msg);
									}
								};
						}
						"Tool" =>
						{
							match xg_parse_tool(&attributes) {
									Ok(tool) =>
									{
											tools.insert(tool.id.to_string(), tool);
									}
									Err(msg) =>
									{
										panic!(msg);
									}
								};
						}
						_ => {}
					}
			}
				XmlEvent::EndElement{..} => {
			}
				_ => {
			}
			}
	}
	xg_parse_create_graph(&tasks)
}

fn xg_parse_create_graph(tasks:&Vec<XgTask>) -> Graph<BuildTask, ()> {
	let mut graph: Graph<BuildTask, ()> = Graph::new();
	let mut nodes: Vec<NodeIndex> = vec![];
	let mut task_refs: HashMap<&str, NodeIndex> = HashMap::new();
	for task in tasks.iter() {
		let node = graph.add_node(BuildTask {
		working_dir : task.working_dir.clone(),
		});
		match task.id {
				Some(ref v) => {
					task_refs.insert(v.as_slice(), node);
			}
				_ => {}
			}
		nodes.push(node);
	}
	for idx in range(0, nodes.len()) {
		let ref task = tasks[idx];
		let ref node = nodes[idx];
		for id in task.depends_on.iter() {
			let dep_node = task_refs.get(id.as_slice());
			graph.add_edge(*node, *dep_node.unwrap(), ());
		}
	}
	graph
}

fn map_attributes (attributes: &Vec<xml::attribute::OwnedAttribute>) -> HashMap< String, String> {
	let mut attrs: HashMap<String, String> = HashMap::new();
	for attr in attributes.iter() {
			attrs.insert(attr.name.local_name.clone(), attr.value.clone());
	}
	attrs
}

fn xg_parse_task (attributes: & Vec<xml::attribute::OwnedAttribute>)->Result<XgTask, String> {
	let mut attrs = map_attributes(attributes);
	// Tool
	let tool: String;
	match attrs.remove("Tool") {
			Some(v) => {tool = v;}
			_ => {return Err("Invalid task data: attribute @Tool not found.".to_string());}
		}
	// WorkingDir
	let working_dir: String;
	match attrs.remove("WorkingDir") {
			Some(v) => {working_dir = v;}
			_ => {return Err("Invalid task data: attribute @WorkingDir not found.".to_string());}
		}
	// DependsOn
	let mut depends_on : Vec<String> = vec![];
	match attrs.remove("DependsOn") {
			Some(v) =>
			{
				for item in v.split_str(";").collect::<Vec<&str>>().iter() {
						depends_on.push(item.to_string())
				}
			}
			_ =>
			{
			}
		};

		Ok(XgTask {
	id: attrs.remove("Name"),
	title: attrs.remove("Caption"),
	tool: tool,
	working_dir: working_dir,
	depends_on: depends_on,
	})
}
fn xg_parse_tool (attributes: &Vec<xml::attribute::OwnedAttribute>)->Result<XgTool, String> {
	let mut attrs = map_attributes(attributes);
	// Name
	let id: String;
	match attrs.remove("Name") {
			Some(v) => {id = v;}
			_ => {return Err("Invalid task data: attribute @Name not found.".to_string());}
		}
	// Path
	let path: String;
	match attrs.remove("Path") {
			Some(v) => {path = v;}
			_ => {return Err("Invalid task data: attribute @Name not found.".to_string());}
		}

	Ok(XgTool {
	id: id,
	path: path,
	params: match attrs.remove("Params") {
			Some(v) => {v}
			_ => {"".to_string()}
		},
	})
}
<commit_msg>Don't panic on missing dependency id.<commit_after>extern crate xml;
extern crate rustc;

use std::os;

use std::io::{File, BufferedReader};
use std::fmt;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread::Thread;
use std::io::timer::sleep;
use std::time::duration::Duration;

use rustc::middle::graph::{NodeIndex, Graph};

use xml::reader::EventReader;
use xml::reader::events::XmlEvent;

fn main() {
	println!("XGConsole:");
	for arg in parse_command_line(os::args()).iter() {
		println!("  {}", arg);
	}
	xg_parse();

	let (tx_result, rx_result): (Sender<String>, Receiver<String>) = channel();
	let (tx_task, rx_task): (Sender<String>, Receiver<String>) = channel();
	let mutex_rx_task = Arc::new(Mutex::new(rx_task));

	for cpu_id in range(0, std::os::num_cpus()) {
		let local_rx_task = mutex_rx_task.clone();
		let local_tx_result = tx_result .clone();
				Thread::spawn(move || {
				loop {
					let message: String;
					{
						match local_rx_task.lock().recv_opt() {
								Ok(v) => {message = v;}
								Err(_) => {break;}
							}
					}
					println!("{}: {}", cpu_id, message);
					sleep(Duration::milliseconds(100));
					local_tx_result.send(format!("Done {}", message));
				}
				println!("{}: done", cpu_id);
			}).detach();
	}
	free(tx_result);

	for task_id in range (0i, 50i) {
			tx_task.send(format!("Task {}", task_id));
	}
	free(tx_task);

	for message in rx_result.iter() {
		println!("B: {}", message);
	}
	println!("done");
}

fn free<T>(_:T) {
}

fn parse_command_line(args: Vec<String>) -> Vec<String> {
	let mut result: Vec<String> = Vec::new();
	for arg in args.slice(1, args.len()).iter() {
			result.push(arg.clone());
	}
	result
}

struct BuildTask {
working_dir: String,
}

struct XgTask {
id: Option<String>,
title: Option<String>,
tool: String,
working_dir: String,
depends_on: Vec<String>,
}

impl fmt::Show for XgTask {
fn fmt(& self, f: &mut fmt::Formatter) -> fmt::Result {
	write!(f, "id={}, title={}, tool={}, working_dir={}, depends_on={}", self .id, self .title, self .tool, self .working_dir, self .depends_on)
}
}

struct XgTool {
id: String,
path: String,
params: String,
}

impl fmt::Show for XgTool {
fn fmt(& self, f: &mut fmt::Formatter) -> fmt::Result {
	write!(f, "id={}, path={}", self .id, self .path)
}
}

fn xg_parse() -> Result<Graph<BuildTask, ()>, String> {
	let file = File::open(&Path::new("tests/graph-parser.xml")).unwrap();
	let reader = BufferedReader::new(file);

	let mut parser = EventReader::new(reader);
	let mut tasks:Vec<XgTask> = vec![];
	let mut tools:HashMap<String, XgTool> = HashMap::new();
	for e in parser.events() {
		match e {
				XmlEvent::StartElement {name, attributes, ..} => {
				match name.local_name.as_slice() {
						"Task" =>
						{
							match xg_parse_task(&attributes) {
									Ok(task) =>
									{
											tasks.push(task);
									}
									Err(msg) =>
									{
										panic!(msg);
									}
								};
						}
						"Tool" =>
						{
							match xg_parse_tool(&attributes) {
									Ok(tool) =>
									{
											tools.insert(tool.id.to_string(), tool);
									}
									Err(msg) =>
									{
										panic!(msg);
									}
								};
						}
						_ => {}
					}
			}
				XmlEvent::EndElement{..} => {
			}
				_ => {
			}
			}
	}
	xg_parse_create_graph(&tasks)
}

fn xg_parse_create_graph(tasks:&Vec<XgTask>) -> Result<Graph<BuildTask, ()>, String> {
	let mut graph: Graph<BuildTask, ()> = Graph::new();
	let mut nodes: Vec<NodeIndex> = vec![];
	let mut task_refs: HashMap<&str, NodeIndex> = HashMap::new();
	for task in tasks.iter() {
		let node = graph.add_node(BuildTask {
		working_dir : task.working_dir.clone(),
		});
		match task.id {
				Some(ref v) => {
					task_refs.insert(v.as_slice(), node);
			}
				_ => {}
			}
		nodes.push(node);
	}
	for idx in range(0, nodes.len()) {
		let ref task = tasks[idx];
		let ref node = nodes[idx];
		for id in task.depends_on.iter() {
			let dep_node = task_refs.get(id.as_slice());
			match dep_node {
					Some(v) => {
						graph.add_edge(*node, *v, ());
				}
					_ => {
					return Err(format!("Can't find task for dependency with id: {}", id));
				}
				}
			graph.add_edge(*node, *dep_node.unwrap(), ());
		}
	}
	Ok(graph)
}

fn map_attributes (attributes: &Vec<xml::attribute::OwnedAttribute>) -> HashMap< String, String> {
	let mut attrs: HashMap<String, String> = HashMap::new();
	for attr in attributes.iter() {
			attrs.insert(attr.name.local_name.clone(), attr.value.clone());
	}
	attrs
}

fn xg_parse_task (attributes: & Vec<xml::attribute::OwnedAttribute>)->Result<XgTask, String> {
	let mut attrs = map_attributes(attributes);
	// Tool
	let tool: String;
	match attrs.remove("Tool") {
			Some(v) => {tool = v;}
			_ => {return Err("Invalid task data: attribute @Tool not found.".to_string());}
		}
	// WorkingDir
	let working_dir: String;
	match attrs.remove("WorkingDir") {
			Some(v) => {working_dir = v;}
			_ => {return Err("Invalid task data: attribute @WorkingDir not found.".to_string());}
		}
	// DependsOn
	let mut depends_on : Vec<String> = vec![];
	match attrs.remove("DependsOn") {
			Some(v) =>
			{
				for item in v.split_str(";").collect::<Vec<&str>>().iter() {
						depends_on.push(item.to_string())
				}
			}
			_ =>
			{
			}
		};

		Ok(XgTask {
	id: attrs.remove("Name"),
	title: attrs.remove("Caption"),
	tool: tool,
	working_dir: working_dir,
	depends_on: depends_on,
	})
}
fn xg_parse_tool (attributes: &Vec<xml::attribute::OwnedAttribute>)->Result<XgTool, String> {
	let mut attrs = map_attributes(attributes);
	// Name
	let id: String;
	match attrs.remove("Name") {
			Some(v) => {id = v;}
			_ => {return Err("Invalid task data: attribute @Name not found.".to_string());}
		}
	// Path
	let path: String;
	match attrs.remove("Path") {
			Some(v) => {path = v;}
			_ => {return Err("Invalid task data: attribute @Name not found.".to_string());}
		}

	Ok(XgTool {
	id: id,
	path: path,
	params: match attrs.remove("Params") {
			Some(v) => {v}
			_ => {"".to_string()}
		},
	})
}
<|endoftext|>