<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 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();
}
<commit_msg>Ball bounces against left paddle, but bounce angle is all wrong.<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>) -> Self {
        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) -> Self {
        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) -> Self {
        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) -> Self {
        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.check_for_ball_and_lpaddle_collision();
        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;
        let ui = &mut self.ui;

        // Left or right wall.
        if ball.x <= 0. && ball.vx < -0. {
            ball.x = 0.;
            ball.vx = -ball.vx;
        } else if ball.x + ball.width >= ui.width && ball.vx > 0. {
            ball.x = 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 >= ui.height && ball.vy > 0. {
            ball.y = ui.height - ball.height;
            ball.vy = -ball.vy;
        }
    }

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

        if ball.vx < 0. && ball.x <= lpaddle.width &&
            ball.y >= lpaddle.y && ball.y <= lpaddle.y + lpaddle.height {

            // Calculate the ball's position relative to the center of the paddle.
            let hit_loc = ball.y - lpaddle.y;

            // Calculate an angle multiplier as a percentage of half the paddle's height.
            let angle_multiplier = (hit_loc / (lpaddle.height / 2.)).abs();

            // Calculate the angle the ball should return at.
            let angle = (f32::consts::PI / 6.) * angle_multiplier;

            // Calculate new vertical and horizontal velocities.
            let vx = angle.cos() * ball.speed;
            let vy = angle.sin() * ball.speed * if hit_loc > 0. {1.} else {-1.};

            ball.x = ball.width;
            ball.vx = vx;
            ball.vy = 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() -> Self {
        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) -> Self {
        self.screen_width = width;
        self.screen_height = height;
        self
    }

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

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

    pub fn with_paddle_speed_per_sec(mut self, paddle_speed: f32) -> Self {
        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(1000.)
        .build();
    game.start();
}
<|endoftext|>


<commit_before>use std::path::Path;
use std::fs::File;
use std::error::Error;
use std::env;
use std::io::BufReader;
use std::io::BufRead;
use std::io::Lines;

use CommandType::{A_COMMAND, C_COMMAND, L_COMMAND};

enum CommandType {
	A_COMMAND,
	C_COMMAND,
	L_COMMAND,
}

struct Parser {
	input_lines: Lines<BufReader<File>>,
	current_command: String,
}

impl Parser {
	/// Opens the input file/stream and gets ready to parse it.
	fn new(filename: &str) -> Parser {
		let path = Path::new(filename);
		let file = match File::open(&path) {
			Err(why) => panic!("couldn't open {}: {}", path.display(), Error::description(&why)),
			Ok(file) => file,
		};

		let lines = BufReader::new(file).lines(); // iterator
		Parser { input_lines: lines, current_command: String::new()}
	}

	/// Encapsulates has_more_command and avance method from the proposed API.
	///
	///		Are there any more commands in the input?
	///			Reads the next command from the input and makes it the current command
	fn parse(mut self) {
		for line in self.input_lines { // has_more_commands + advance
			// println!("{0}", line.unwrap().trim());
			self.current_command = line.unwrap().trim().to_string();
			match self.command_type() {
				A_COMMAND 	=> {println!("A_COMMAND: {0}", self.current_command);},
				C_COMMAND 	=> {println!("C_COMMAND: {0}", self.current_command);},
				L_COMMAND 	=> {println!("L_COMMAND: {0}", self.current_command);},
			}
		}
	}

	/// Returns the type of the current command.
	///
	/// * A_COMMAND: For @xxx where xxx is either a symbol or a decimal number
	/// * C_COMMAND: For dest=comp;jump
	/// * L_COMMAND: Pseudo-Command. for (xxx) where xxx is a symbol
	fn command_type(&self) -> CommandType {
		A_COMMAND
	}
}

fn main() {
	let args: Vec<String> = env::args().collect();
	if args.len() != 2 {
		println!("Usage: assembler [PATH_TO_ASM_FILE]");
		return;
	}
	let path_to_asm = &args[1];
	let mut parser = Parser::new(path_to_asm);
	parser.parse();
}
<commit_msg>Finally got out of borrow checker fight about input_line. Using input_line.next() instead of for loop on input_lines. Works<commit_after>use std::path::Path;
use std::fs::File;
use std::error::Error;
use std::env;
use std::io::BufReader;
use std::io::BufRead;
use std::io::Lines;

use CommandType::{ACommand, CCommand, LCommand};

enum CommandType {
	ACommand,
	CCommand,
	LCommand,
}

struct Parser {
	input_lines: Lines<BufReader<File>>,
	current_command: String,
}

impl Parser {
	/// Opens the input file/stream and gets ready to parse it.
	fn new(filename: &str) -> Parser {
		let path = Path::new(filename);
		let file = match File::open(&path) {
			Err(why) => panic!("couldn't open {}: {}", path.display(), Error::description(&why)),
			Ok(file) => file,
		};

		let lines = BufReader::new(file).lines(); // iterator
		Parser {
			input_lines: lines,
			current_command: String::new(),
		}
	}

	/// Encapsulates has_more_command and avance method from the proposed API.
	///
	///		Are there any more commands in the input?
	///			Reads the next command from the input and makes it the current command
	fn parse(&mut self) {
		loop {
			match self.input_lines.next() {
				Some(line) => {
					self.current_command = line.unwrap().trim().to_string();
					match self.command_type() {
						ACommand => {println!("ACommand: {0}", self.current_command);},
						CCommand => {println!("CCommand: {0}", self.current_command);},
						LCommand => {println!("LCommand: {0}", self.current_command);},
					}
				},
				None => break,
			}
		}
	}

	/// Returns the type of the current command.
	///
	/// * ACommand: For @xxx where xxx is either a symbol or a decimal number
	/// * CCommand: For dest=comp;jump
	/// * LCommand: Pseudo-Command. for (xxx) where xxx is a symbol
	fn command_type(&self) -> CommandType {
		ACommand
	}
}

fn main() {
	let args: Vec<String> = env::args().collect();
	if args.len() != 2 {
		println!("HACK Assembler. Translates assembly (mnemonic) into binary machine code.\n\nUsage:\n\tassembler [PATH_TO_ASM_FILE]");
		return;
	}
	let path_to_asm = &args[1];
	let mut parser = Parser::new(path_to_asm);
	parser.parse();
}
<|endoftext|>


<commit_before>extern crate fuse;
extern crate libc;
extern crate time;
extern crate hyper;
extern crate rustc_serialize;
extern crate clap;

use std::collections::BTreeMap;
use std::path::Path;
use std::env;
use std::io::prelude::Read;
use libc::{ENOENT, ENOSYS};
use time::Timespec;
use fuse::{FileAttr, FileType, Filesystem, Request, ReplyAttr, ReplyData, ReplyEntry, ReplyDirectory, ReplyOpen};
use hyper::client::{Client, Response};
use rustc_serialize::json::Json;
use clap::{App, Arg};

struct TwitchFileSystem {
    attrs: BTreeMap<u64, FileAttr>,
    inodes: BTreeMap<String, u64>
}

impl TwitchFileSystem {
    fn new() -> TwitchFileSystem {
        let mut attrs = BTreeMap::new();
        let mut inodes = BTreeMap::new();
        let ts = time::now().to_timespec();
        let attr = FileAttr {
            ino: 1,
            size: 0,
            blocks: 0,
            atime: ts,
            mtime: ts,
            ctime: ts,
            crtime: ts,
            kind: FileType::Directory,
            perm: 0o755,
            nlink: 0,
            uid: 0,
            gid: 0,
            rdev: 0,
            flags: 0
        };
        attrs.insert(1, attr);
        inodes.insert("/".to_owned(), 1);
        let mut body = String::new();
        Client::new()
            .get("https://api.twitch.tv/kraken/games/top")
            .send()
            .expect("Couldn't load twitch")
            .read_to_string(&mut body);

        match Json::from_str(&body) {
            Ok(data) => {
                let games = data.find("top").unwrap().as_array().unwrap();
                for (i, game) in games.iter().enumerate() {
                    let attr = FileAttr {
                        ino: i as u64 + 2,
                        size: 0,
                        blocks: 0,
                        atime: ts,
                        mtime: ts,
                        ctime: ts,
                        crtime: ts,
                        kind: FileType::RegularFile,
                        perm: 0o644,
                        nlink: 0,
                        uid: 0,
                        gid: 0,
                        rdev: 0,
                        flags: 0
                    };
                    let name = game
                        .find_path(&["game", "name"])
                        .unwrap()
                        .as_string()
                        .unwrap();

                    attrs.insert(attr.ino, attr);
                    inodes.insert(name.to_owned(), attr.ino);
                }
            },
            Err(_) => println!("Twitch returned invalid json")
        }
        TwitchFileSystem {attrs: attrs, inodes: inodes}
    }
}

impl Filesystem for TwitchFileSystem {
    fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) {
        match self.attrs.get(&ino) {
            Some(attr) => {
                let ttl = Timespec::new(1, 0);
                reply.attr(&ttl, attr);
            },
            None => reply.error(ENOENT)
        }
    }

    fn lookup(&mut self, _req: &Request, parent: u64, name: &Path, reply: ReplyEntry) {
        let inode = match self.inodes.get(name.to_str().unwrap()) {
            Some(inode) => inode,
            None => {
                reply.error(ENOENT);
                return;
            }
        };
        match self.attrs.get(inode) {
            Some(attr) => {
                let ttl = Timespec::new(1, 0);
                reply.entry(&ttl, attr, 0);
            },
            None => reply.error(ENOENT),
        };
    }

    fn readdir(&mut self, _req: &Request, ino: u64, fh: u64, offset: u64, mut reply: ReplyDirectory) {
        if offset == 0 {
            for (game, &inode) in &self.inodes {
                if inode == 1 { continue; }
                let offset = inode;
                reply.add(inode, offset, FileType::RegularFile, &Path::new(game));
            }
            reply.add(1, 0, FileType::Directory, &Path::new("."));
            reply.add(1, 1, FileType::Directory, &Path::new(".."));
        }

        reply.ok();
    }
    fn read(&mut self, _req: &Request, ino: u64, fh: u64, offset: u64, size: u32, reply: ReplyData) {
        reply.data("test".as_bytes());
    }
}

fn main() {
    let matches = App::new("twitch-fs")
        .version(option_env!("CARGO_PKG_VERSION").unwrap_or("unknown version"))
        .arg(Arg::with_name("mountpoint")
             .index(1)
             .required(true))
        .get_matches();

    // unwrap() is safe here because the argument is set as required
    let mountpoint = matches.value_of_os("mountpoint").unwrap();
    let fs = TwitchFileSystem::new();

    fuse::mount(fs , &mountpoint, &[])
}
<commit_msg>Change file list to directories<commit_after>extern crate fuse;
extern crate libc;
extern crate time;
extern crate hyper;
extern crate rustc_serialize;
extern crate clap;

use std::collections::BTreeMap;
use std::path::Path;
use std::env;
use std::io::prelude::Read;
use libc::{ENOENT, ENOSYS};
use time::Timespec;
use fuse::{FileAttr, FileType, Filesystem, Request, ReplyAttr, ReplyData, ReplyEntry, ReplyDirectory, ReplyOpen};
use hyper::client::{Client, Response};
use rustc_serialize::json::Json;
use clap::{App, Arg};

struct TwitchFileSystem {
    attrs: BTreeMap<u64, FileAttr>,
    inodes: BTreeMap<String, u64>
}

impl TwitchFileSystem {
    fn new() -> TwitchFileSystem {
        let mut attrs = BTreeMap::new();
        let mut inodes = BTreeMap::new();
        let ts = time::now().to_timespec();
        let attr = FileAttr {
            ino: 1,
            size: 0,
            blocks: 0,
            atime: ts,
            mtime: ts,
            ctime: ts,
            crtime: ts,
            kind: FileType::Directory,
            perm: 0o755,
            nlink: 0,
            uid: 0,
            gid: 0,
            rdev: 0,
            flags: 0
        };
        attrs.insert(1, attr);
        inodes.insert("/".to_owned(), 1);
        let mut body = String::new();
        Client::new()
            .get("https://api.twitch.tv/kraken/games/top")
            .send()
            .expect("Couldn't load twitch")
            .read_to_string(&mut body);

        match Json::from_str(&body) {
            Ok(data) => {
                let games = data.find("top").unwrap().as_array().unwrap();
                for (i, game) in games.iter().enumerate() {
                    let attr = FileAttr {
                        ino: i as u64 + 2,
                        size: 0,
                        blocks: 0,
                        atime: ts,
                        mtime: ts,
                        ctime: ts,
                        crtime: ts,
                        kind: FileType::Directory,
                        perm: 0o644,
                        nlink: 0,
                        uid: 0,
                        gid: 0,
                        rdev: 0,
                        flags: 0
                    };
                    let name = game
                        .find_path(&["game", "name"])
                        .unwrap()
                        .as_string()
                        .unwrap();

                    attrs.insert(attr.ino, attr);
                    inodes.insert(name.to_owned(), attr.ino);
                }
            },
            Err(_) => println!("Twitch returned invalid json")
        }
        TwitchFileSystem {attrs: attrs, inodes: inodes}
    }
}

impl Filesystem for TwitchFileSystem {
    fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) {
        match self.attrs.get(&ino) {
            Some(attr) => {
                let ttl = Timespec::new(1, 0);
                reply.attr(&ttl, attr);
            },
            None => reply.error(ENOENT)
        }
    }

    fn lookup(&mut self, _req: &Request, parent: u64, name: &Path, reply: ReplyEntry) {
        let inode = match self.inodes.get(name.to_str().unwrap()) {
            Some(inode) => inode,
            None => {
                reply.error(ENOENT);
                return;
            }
        };
        match self.attrs.get(inode) {
            Some(attr) => {
                let ttl = Timespec::new(1, 0);
                reply.entry(&ttl, attr, 0);
            },
            None => reply.error(ENOENT),
        };
    }

    fn readdir(&mut self, _req: &Request, ino: u64, fh: u64, offset: u64, mut reply: ReplyDirectory) {
        if offset == 0 {
            for (game, &inode) in &self.inodes {
                if inode == 1 { continue; }
                let offset = inode;
                reply.add(inode, offset, FileType::RegularFile, &Path::new(game));
            }
            reply.add(1, 0, FileType::Directory, &Path::new("."));
            reply.add(1, 1, FileType::Directory, &Path::new(".."));
        } else if offset == 1 {
            reply.add(1, 0, FileType::Directory, &Path::new("u wot m8"));
        }

        reply.ok();
    }
    fn read(&mut self, _req: &Request, ino: u64, fh: u64, offset: u64, size: u32, reply: ReplyData) {
        reply.data("test".as_bytes());
    }
}

fn main() {
    let matches = App::new("twitch-fs")
        .version(option_env!("CARGO_PKG_VERSION").unwrap_or("unknown version"))
        .arg(Arg::with_name("mountpoint")
             .index(1)
             .required(true))
        .get_matches();

    // unwrap() is safe here because the argument is set as required
    let mountpoint = matches.value_of_os("mountpoint").unwrap();
    let fs = TwitchFileSystem::new();

    fuse::mount(fs , &mountpoint, &[])
}
<|endoftext|>


<commit_before>/*!
# ParView
*/
#![feature(phase)]

#![deny(non_camel_case_types)]
#![deny(unnecessary_parens)]
#![deny(non_uppercase_statics)]
#![deny(unnecessary_qualification)]
#![deny(missing_doc)]
#![deny(unused_result)]
#![deny(unnecessary_typecast)]

#[phase(plugin)]
extern crate docopt_macros;
extern crate docopt;

extern crate serialize;
extern crate flate2;

extern crate "nalgebra" as na;
extern crate kiss3d;
extern crate glfw;
extern crate parview;

use serialize::{json, Encodable, Decodable};
use flate2::reader::GzDecoder;
use std::rand::random;
use std::io::{File,BufferedWriter,BufferedReader};

use kiss3d::window::Window;

use parview::{Sphere,Frame,rand_vec};

/// Generate an example json file
pub fn generate_frame() {
    let f = Frame {
        spheres : Vec::from_fn(16, |_| {
            let loc : na::Vec3<f32> = rand_vec();
            let s : f32 = random();
            Sphere{loc:(loc.x, loc.y, loc.z), radius:s*0.2, color:None}
        }),
        text : None
    };

    let mut framevec : Vec<Frame> = vec!();

    for i in range(0u,40u){
        let mut f2 = Frame {
            spheres : f.spheres.iter().enumerate().map(|(n, &s)| {
					let mut newr = s.radius;
					let mut color = s.color;
					if n == 0 {
						newr = random::<f32>() * 0.2f32;
						color = Some((random::<u8>(), random::<u8>(), random::<u8>()));
					}
					Sphere::new(s.x() + (rand_vec() * 0.1f32), newr, color)
				}).collect(),
            text : Some(format!("Frame {} with {} spheres", i, f.spheres.len()))
        };

        if i > 10 && i < 20 {
			let l = f2.spheres.len();
			f2.spheres.truncate(l - 8);
		}
        framevec.push(f2);
    }

    let path = Path::new("test_frame.json");
    let mut file = BufferedWriter::new(File::create(&path));
    {
        let mut encoder = json::PrettyEncoder::new(&mut file);
        match framevec.encode(&mut encoder) {
            Ok(()) => (),
            Err(e) => fail!("json encoding error: {}", e)
        };
    }
}

fn draw_cube(window : &mut Window) -> kiss3d::scene::SceneNode {
    let rotations : Vec<Option<na::Vec3<f32>>> = vec!(
        None, Some(na::Vec3::x()), Some(na::Vec3::z()));
    let translations = vec!((-0.5f32, -0.5),
                            (-0.5,0.5),
                            (0.5, -0.5),
                            (0.5, 0.5));
    let translations : Vec<na::Vec3<f32>> = translations
        .iter()
        .map(|&(x,z)| na::Vec3::new(x,0.0,z))
        .collect();

    let mut cube = window.add_group();
    for rot in rotations.iter() {
        for t in translations.iter() {
            let mut caps = cube.add_capsule(0.01, 1.0);
            caps.append_translation(t);
            match rot {
                &Some(ref r) => {caps.append_rotation(&(r * std::f32::consts::FRAC_PI_2))},
                &None => {}
            }
            //caps.append_translation(&Vec3::new(-0.5, 0.0, -0.5));
        }
    }
    cube.set_color(1.0, 0.0, 0.0);

    cube
}

fn open_file(path : &Path) -> std::io::IoResult<Vec<Frame>> {
	let mut buf = BufferedReader::new(File::open(path));
	//~ let coded = json::from_reader(&mut buf).unwrap();
    //~ let mut decoder =json::Decoder::new(coded);
    //~ let frames: Vec<Frame> = Decodable::decode(&mut decoder).unwrap();

	let coded_opt = match path.extension(){
		Some(b"gz") => match GzDecoder::new(buf) {
				Err(e) => {return Err(e);}
				Ok(mut gzbuf) => {json::from_reader(&mut gzbuf)}
		},
		_ => {
			json::from_reader(&mut buf)
			}
	};

	let json_result = match coded_opt {
		Err(e) => {
			return Err(std::io::IoError{
				kind: std::io::InvalidInput,
				desc: "Parser Error",
				detail: Some(format!("{}", e))
			});
		}
		Ok(coded) => {
			let mut decoder =json::Decoder::new(coded);
			Decodable::decode(&mut decoder)
		}
	};

	match json_result {
		Ok(frames) => Ok(frames),
		Err(e) =>  Err(
			std::io::IoError{
				kind: std::io::InvalidInput,
				desc: "Decoder Error",
				detail: Some(format!("{}", e))
			}
		)
	}
}

docopt!(Args, "
Usage: parview [-h | --help] [-g] [<file>]

Options:
	[-h | --help]   Help and usage
	-g

Arguments:
    <file>     	json file representing the frames. json.gz also accepted, if the extension is \".gz\".
",
	flag_g : bool,
	arg_file : Option<String>)

/// Main entry point, now using test_frame.json
pub fn main() {
	let args: Args = docopt::FlagParser::parse().unwrap_or_else(|e| e.exit());
    if args.flag_g {
		generate_frame()
	}

    let path = Path::new(args.arg_file.unwrap_or("test_frame.json".to_string()));
    let frames = open_file(&path).unwrap();

    let ref f : Frame = frames[0];

    let mut window = Window::new("Kiss3d: draw_sphere");
	let _ = draw_cube(&mut window);

	let eye              = na::Pnt3::new(0.0f32, 0.0, 2.0);
	let at               = na::orig();
	let mut arc_ball     = kiss3d::camera::ArcBall::new(eye, at);

	//window.set_background_color(1.0, 1.0, 1.0);
	window.set_light(kiss3d::light::StickToCamera);
	window.set_framerate_limit(Some(20));

	let mut nodes = parview::SphereNodes::new(f.spheres.iter(), &mut window);

	let mut lastframe = -1;
	let mut timer = parview::Timer::new(vec![1./16., 1./8., 1./4., 1./2.,1., 2., 5., 10.], Some(frames.len()));
	let mut text = None;

	let fontsize =48;
	let font = kiss3d::text::Font::new(&Path::new("/usr/share/fonts/OTF/Inconsolata.otf"), fontsize);

	while window.render_with_camera(&mut arc_ball) {
		for mut event in window.events().iter() {
            match event.value {
				glfw::KeyEvent(glfw::KeyQ, _, glfw::Release, _) => {
					return;
				},
				glfw::KeyEvent(glfw::KeyComma, _, glfw::Release, _) => {
					timer.slower();
					event.inhibited = true; // override the default keyboard handler
				},
				glfw::KeyEvent(glfw::KeyPeriod, _, glfw::Release, _) => {
					timer.faster();
					event.inhibited = true; // override the default keyboard handler
				},
				glfw::KeyEvent(glfw::KeyF, _, glfw::Release, _) => {
					timer.switch_direction();
					event.inhibited = true; // override the default keyboard handler
				}
				glfw::KeyEvent(code, _, glfw::Release, _) => {
                    println!("You released the key with code: {}", code);
                    //~ println!("Do not try to press escape: the event is inhibited!");
                    event.inhibited = true // override the default keyboard handler
                },
                _ => {}
			}
		}

		let i = timer.incr();

		if lastframe != i {
			let ref frame = frames[i];
			text = frame.text.clone();
			nodes.update(frame.spheres.iter(), &mut window);
			lastframe = i;
		}

		match text {
			Some(ref t) => {
				window.draw_text(t.as_slice(), &na::orig(), &font, &na::Pnt3::new(1.0, 1.0, 1.0));
			}
			None => {}
		}

		let text_loc = na::Pnt2::new(0.0, window.height() * 2. - (fontsize as f32));
		window.draw_text(format!("t:{:6}, dt:{:8.2f}", i, timer.get_dt()).as_slice(),
				&text_loc, &font, &na::Pnt3::new(1.0, 1.0, 1.0));
	};
}
<commit_msg>Added keys to reset view<commit_after>/*!
# ParView
*/
#![feature(phase)]

#![deny(non_camel_case_types)]
#![deny(unnecessary_parens)]
#![deny(non_uppercase_statics)]
#![deny(unnecessary_qualification)]
#![deny(missing_doc)]
#![deny(unused_result)]
#![deny(unnecessary_typecast)]

#[phase(plugin)]
extern crate docopt_macros;
extern crate docopt;

extern crate serialize;
extern crate flate2;

extern crate "nalgebra" as na;
extern crate kiss3d;
extern crate glfw;
extern crate parview;

use serialize::{json, Encodable, Decodable};
use flate2::reader::GzDecoder;
use std::rand::random;
use std::io::{File,BufferedWriter,BufferedReader};

use kiss3d::window::Window;

use parview::{Sphere,Frame,rand_vec};

/// Generate an example json file
pub fn generate_frame() {
    let f = Frame {
        spheres : Vec::from_fn(16, |_| {
            let loc : na::Vec3<f32> = rand_vec();
            let s : f32 = random();
            Sphere{loc:(loc.x, loc.y, loc.z), radius:s*0.2, color:None}
        }),
        text : None
    };

    let mut framevec : Vec<Frame> = vec!();

    for i in range(0u,40u){
        let mut f2 = Frame {
            spheres : f.spheres.iter().enumerate().map(|(n, &s)| {
					let mut newr = s.radius;
					let mut color = s.color;
					if n == 0 {
						newr = random::<f32>() * 0.2f32;
						color = Some((random::<u8>(), random::<u8>(), random::<u8>()));
					}
					Sphere::new(s.x() + (rand_vec() * 0.1f32), newr, color)
				}).collect(),
            text : Some(format!("Frame {} with {} spheres", i, f.spheres.len()))
        };

        if i > 10 && i < 20 {
			let l = f2.spheres.len();
			f2.spheres.truncate(l - 8);
		}
        framevec.push(f2);
    }

    let path = Path::new("test_frame.json");
    let mut file = BufferedWriter::new(File::create(&path));
    {
        let mut encoder = json::PrettyEncoder::new(&mut file);
        match framevec.encode(&mut encoder) {
            Ok(()) => (),
            Err(e) => fail!("json encoding error: {}", e)
        };
    }
}

fn draw_cube(window : &mut Window) -> kiss3d::scene::SceneNode {
    let rotations : Vec<Option<na::Vec3<f32>>> = vec!(
        None, Some(na::Vec3::x()), Some(na::Vec3::z()));
    let translations = vec!((-0.5f32, -0.5),
                            (-0.5,0.5),
                            (0.5, -0.5),
                            (0.5, 0.5));
    let translations : Vec<na::Vec3<f32>> = translations
        .iter()
        .map(|&(x,z)| na::Vec3::new(x,0.0,z))
        .collect();

    let mut cube = window.add_group();
    for rot in rotations.iter() {
        for t in translations.iter() {
            let mut caps = cube.add_capsule(0.01, 1.0);
            caps.append_translation(t);
            match rot {
                &Some(ref r) => {caps.append_rotation(&(r * std::f32::consts::FRAC_PI_2))},
                &None => {}
            }
            //caps.append_translation(&Vec3::new(-0.5, 0.0, -0.5));
        }
    }
    cube.set_color(1.0, 0.0, 0.0);

    cube
}

fn open_file(path : &Path) -> std::io::IoResult<Vec<Frame>> {
	let mut buf = BufferedReader::new(File::open(path));
	//~ let coded = json::from_reader(&mut buf).unwrap();
    //~ let mut decoder =json::Decoder::new(coded);
    //~ let frames: Vec<Frame> = Decodable::decode(&mut decoder).unwrap();

	let coded_opt = match path.extension(){
		Some(b"gz") => match GzDecoder::new(buf) {
				Err(e) => {return Err(e);}
				Ok(mut gzbuf) => {json::from_reader(&mut gzbuf)}
		},
		_ => {
			json::from_reader(&mut buf)
			}
	};

	let json_result = match coded_opt {
		Err(e) => {
			return Err(std::io::IoError{
				kind: std::io::InvalidInput,
				desc: "Parser Error",
				detail: Some(format!("{}", e))
			});
		}
		Ok(coded) => {
			let mut decoder =json::Decoder::new(coded);
			Decodable::decode(&mut decoder)
		}
	};

	match json_result {
		Ok(frames) => Ok(frames),
		Err(e) =>  Err(
			std::io::IoError{
				kind: std::io::InvalidInput,
				desc: "Decoder Error",
				detail: Some(format!("{}", e))
			}
		)
	}
}

docopt!(Args, "
Usage: parview [-h | --help] [-g] [<file>]

Options:
	[-h | --help]   Help and usage
	-g

Arguments:
    <file>     	json file representing the frames. json.gz also accepted, if the extension is \".gz\".
",
	flag_g : bool,
	arg_file : Option<String>)

/// Main entry point, now using test_frame.json
pub fn main() {
	let args: Args = docopt::FlagParser::parse().unwrap_or_else(|e| e.exit());
    if args.flag_g {
		generate_frame()
	}

    let path = Path::new(args.arg_file.unwrap_or("test_frame.json".to_string()));
    let frames = open_file(&path).unwrap();

    let ref f : Frame = frames[0];

    let mut window = Window::new(format!("Parviewer: {}", path.as_str()).as_slice());
	let _ = draw_cube(&mut window);

	let eye              = na::Pnt3::new(0.0f32, 0.0, 2.0);
	let at               = na::orig();
	let mut arc_ball     = kiss3d::camera::ArcBall::new(eye, at);

	//window.set_background_color(1.0, 1.0, 1.0);
	window.set_light(kiss3d::light::StickToCamera);
	window.set_framerate_limit(Some(20));

	let mut nodes = parview::SphereNodes::new(f.spheres.iter(), &mut window);

	let mut lastframe = -1;
	let mut timer = parview::Timer::new(vec![1./16., 1./8., 1./4., 1./2.,1., 2., 5., 10.], Some(frames.len()));
	let mut text = None;

	let fontsize =48;
	let font = kiss3d::text::Font::new(&Path::new("/usr/share/fonts/OTF/Inconsolata.otf"), fontsize);

	while window.render_with_camera(&mut arc_ball) {
		for mut event in window.events().iter() {
            match event.value {
				glfw::KeyEvent(glfw::KeyQ, _, glfw::Release, _) => {
					return;
				},
				glfw::KeyEvent(glfw::KeyComma, _, glfw::Release, _) => {
					timer.slower();
					event.inhibited = true; // override the default keyboard handler
				},
				glfw::KeyEvent(glfw::KeyPeriod, _, glfw::Release, _) => {
					timer.faster();
					event.inhibited = true; // override the default keyboard handler
				},
				glfw::KeyEvent(glfw::KeyF, _, glfw::Release, _) => {
					timer.switch_direction();
					event.inhibited = true; // override the default keyboard handler
				}
				glfw::KeyEvent(glfw::KeyUp, _, glfw::Release, _) => {
                    arc_ball.set_pitch(3.14159/3.);
                    arc_ball.set_yaw(3.14159/4.);
                    event.inhibited = true // override the default keyboard handler
                },
				glfw::KeyEvent(glfw::KeyDown, _, glfw::Release, _) => {
                    arc_ball.set_pitch(3.14159/2.);
                    arc_ball.set_yaw(3.14159/2.);
                    event.inhibited = true // override the default keyboard handler
                },
                glfw::KeyEvent(glfw::KeyW, _, glfw::Release, _) => {
                    println!("yaw: {:6.2f}, pitch: {:6.2f}", arc_ball.yaw(), arc_ball.pitch());
                    //~ println!("Do not try to press escape: the event is inhibited!");
                    event.inhibited = true // override the default keyboard handler
                },
                glfw::KeyEvent(code, _, glfw::Release, _) => {
                    println!("You released the key with code: {}", code);
                    //~ println!("Do not try to press escape: the event is inhibited!");
                    event.inhibited = true // override the default keyboard handler
                },
				_ => {}
			}
		}

		let i = timer.incr();

		if lastframe != i {
			let ref frame = frames[i];
			text = frame.text.clone();
			nodes.update(frame.spheres.iter(), &mut window);
			lastframe = i;
		}

		match text {
			Some(ref t) => {
				window.draw_text(t.as_slice(), &na::orig(), &font, &na::Pnt3::new(1.0, 1.0, 1.0));
			}
			None => {}
		}

		let text_loc = na::Pnt2::new(0.0, window.height() * 2. - (fontsize as f32));
		window.draw_text(format!("t:{:6}, dt:{:8.2f}", i, timer.get_dt()).as_slice(),
				&text_loc, &font, &na::Pnt3::new(1.0, 1.0, 1.0));
	};
}
<|endoftext|>


<commit_before>//extern crate rand;
extern crate clap;
extern crate image;

//use std::io;
//use std::cmp::Ordering;
//use std::fs::File;
use std::path::Path;
//use rand::Rng;
use clap::{Arg, App};
use image::{DynamicImage, GenericImage, RgbaImage};

/*fn foo() {

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

    let mut guess = String::new();

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

    let guess: i32 = guess.trim().parse()
        .expect("please type a number");

    match guess.cmp(&secret_number) {
        Ordering::Equal => println!("same"),
        Ordering::Greater => println!("too big"),
        Ordering::Less => println!("too small"),
    }
}*/

fn main() {
    let matches = App::new("asami")
        //.version("1.0")
        .author("Sebastian Schulz <mail@sesc.me>")
        .about("pixel sorter")
        .arg(Arg::with_name("input")
            .short("i")
            .long("input")
            .value_name("PATH")
            .help("path to input file")
            .takes_value(true)
            .required(true))
        .arg(Arg::with_name("output")
            .short("o")
            .long("output")
            .value_name("PATH")
            .help("path to output file")
            .takes_value(true)
            .required(true))
        /*.arg(Arg::with_name("v")
            .short("v")
            .multiple(true)
            .help("Sets the level of verbosity"))*/
        .get_matches();

    let input = matches.value_of("input").unwrap();
    let output = matches.value_of("output").unwrap();

    handle_request(input, output);

    // Vary the output based on how many times the user used the "verbose" flag
    // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
    /*match matches.occurrences_of("v") {
        0 => println!("No verbose info"),
        1 => println!("Some verbose info"),
        2 => println!("Tons of verbose info"),
        3 | _ => println!("Don't be crazy"),
    }*/
}

fn handle_request(input: &str, output: &str) {
    println!("input: {}, output: {}", input, output);

    let ref in_img = image::open(&Path::new(input)).unwrap();

    // The dimensions method returns the images width and height
    println!("dimensions {:?}", in_img.dimensions());

    // The color method returns the image's ColorType
    println!("{:?}", in_img.color());

    let ref mut out_img = RgbaImage::new(in_img.width(), in_img.height());

    sort_them_pixels(in_img, out_img);

    // Write the contents of this image to the Writer in PNG format.
    let _ = out_img.save(output).unwrap();
}

fn sort_them_pixels(input: &DynamicImage, output: &mut RgbaImage){
    for (x, y, pixel) in input.pixels() {
        output.put_pixel(x, y, pixel);
    }
}
<commit_msg>basic sorting<commit_after>//extern crate rand;
extern crate clap;
extern crate image;

//use std::io;
//use std::cmp::Ordering;
//use std::fs::File;
use std::path::Path;
//use rand::Rng;
use clap::{Arg, App};
use image::{DynamicImage, GenericImage, RgbaImage};

/*fn foo() {

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

    let mut guess = String::new();

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

    let guess: i32 = guess.trim().parse()
        .expect("please type a number");

    match guess.cmp(&secret_number) {
        Ordering::Equal => println!("same"),
        Ordering::Greater => println!("too big"),
        Ordering::Less => println!("too small"),
    }
}*/

fn main() {
    let matches = App::new("asami")
        //.version("1.0")
        .author("Sebastian Schulz <mail@sesc.me>")
        .about("pixel sorter")
        .arg(Arg::with_name("input")
            .short("i")
            .long("input")
            .value_name("PATH")
            .help("path to input file")
            .takes_value(true)
            .required(true))
        .arg(Arg::with_name("output")
            .short("o")
            .long("output")
            .value_name("PATH")
            .help("path to output file")
            .takes_value(true)
            .required(true))
        /*.arg(Arg::with_name("v")
            .short("v")
            .multiple(true)
            .help("Sets the level of verbosity"))*/
        .get_matches();

    let input = matches.value_of("input").unwrap();
    let output = matches.value_of("output").unwrap();

    handle_request(input, output);

    // Vary the output based on how many times the user used the "verbose" flag
    // (i.e. 'myprog -v -v -v' or 'myprog -vvv' vs 'myprog -v'
    /*match matches.occurrences_of("v") {
        0 => println!("No verbose info"),
        1 => println!("Some verbose info"),
        2 => println!("Tons of verbose info"),
        3 | _ => println!("Don't be crazy"),
    }*/
}

fn handle_request(input: &str, output: &str) {
    println!("input: {}, output: {}", input, output);

    let ref in_img = image::open(&Path::new(input)).unwrap();

    // The dimensions method returns the images width and height
    println!("dimensions {:?}", in_img.dimensions());

    // The color method returns the image's ColorType
    println!("{:?}", in_img.color());

    let ref mut out_img = RgbaImage::new(in_img.width(), in_img.height());

    sort_them_pixels(in_img, out_img);

    // Write the contents of this image to the Writer in PNG format.
    let _ = out_img.save(output).unwrap();
}

fn sort_them_pixels(input: &DynamicImage, output: &mut RgbaImage){
    let mut tmp_x = 0;
    let mut tmp_y = 0;

    let mut tmp = Vec::new();

    for (x, y, pixel) in input.pixels() {
        tmp.push(pixel);
        if tmp.len() > 20 {
            tmp.sort_by(|a, b| a[0].cmp(&b[0]));
            //tmp = Vec::new();
            while !tmp.is_empty() {
                output.put_pixel(tmp_x, tmp_y, tmp.pop().unwrap());
                tmp_y = tmp_y + (tmp_x + 1) / input.width();
                tmp_x = (tmp_x + 1) % input.width();
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![deny(missing_docs)]
#![deny(non_camel_case_types)]
#![cfg_attr(feature = "nightly", feature(proc_macro))]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![warn(missing_copy_implementations,
        missing_debug_implementations,
        missing_docs,
        trivial_numeric_casts,
        unsafe_code,
        unused_extern_crates,
        unused_import_braces,
        unused_qualifications)]
#![cfg_attr(feature="clippy", warn(cast_possible_truncation))]
#![cfg_attr(feature="clippy", warn(cast_possible_wrap))]
#![cfg_attr(feature="clippy", warn(cast_precision_loss))]
#![cfg_attr(feature="clippy", warn(cast_sign_loss))]
#![cfg_attr(feature="clippy", warn(mut_mut))]
// This allows us to use `unwrap` on `Option` values when compiling in test mode
// (because using it in tests is idiomatic).
#![cfg_attr(all(not(test), feature="clippy"), warn(result_unwrap_used))]
#![cfg_attr(feature="clippy", warn(wrong_pub_self_convention))]

//! Smexybot is a general-purpose [Discord](https://discordapp.com/) bot written
//! in [Rust](https://www.rust-lang.org/). It is built upon the
//! [serenity.rs](https://github.com/zeyla/serenity.rs) Discord API.

extern crate chrono;
extern crate env_logger;
extern crate hyper;
#[cfg(any(feature = "roll", feature = "wolfram", feature = "xkcd"))]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate rand;
extern crate serde;
#[cfg(feature = "nightly")]
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serenity;
extern crate url;

mod command;
mod config;
mod error;
mod util;

use std::env;

use chrono::{DateTime, UTC};
use serenity::Client;
use serenity::client::LoginType;
use serenity::ext::framework::Framework;

use config::Config;
use util::{check_msg, timestamp_to_string};

lazy_static! {
    static ref CONFIG: Config = Config::new(Some("config.json"));
    static ref UPTIME: DateTime<UTC> = UTC::now();
}

fn main() {
    // Initialize the `env_logger` to provide logging output.
    env_logger::init().expect("Failed to initialize env_logger");

    // Initialize the `UPTIME` variable.
    debug!("Initialized at: {}", timestamp_to_string(&*UPTIME));

    // Create a client for a user.
    let (_, mut client) = login();

    client.on_ready(|_context, ready| {
        println!(
            "[Ready] {} is serving {} guilds!",
            ready.user.name,
            ready.guilds.len(),
        );
    });

    client.with_framework(build_framework);

    if let Err(err) = client.start() {
        error!("Client error: {:?}", err);
    }
}

// Configures the `Framework` used by serenity, and registers the handlers for
// any enabled commands.
fn build_framework(framework: Framework) -> Framework {
    let mut framework = framework.configure(|c| c
        .prefix(&CONFIG.command_prefix))
    .before(|_context, message, command_name| {
        debug!(
            "Got command '{}' from user '{}'",
            command_name,
            message.author.name,
        );

        true
    })
    .after(|context, _message, command_name, error| {
        if let Err(err) = error {
            check_msg(context.say(&err));
        } else {
            debug!("Processed command '{}'", command_name);
        }
    });

    #[cfg(feature = "fuyu")]
    {
        framework = framework.on("fuyu", command::fuyu::handler);
    }
    #[cfg(feature = "help")]
    {
        use serenity::ext::framework::help_commands;
        framework = framework.command("help", |c| c
          .exec_help(help_commands::plain));
    }
    #[cfg(feature = "ping")]
    {
        framework = framework.on("ping", command::ping::handler);
    }
    #[cfg(feature = "roll")]
    {
        framework = framework.on("roll", command::roll::handler);
    }
    #[cfg(feature = "stats")]
    {
        framework = framework.on("stats", command::stats::handler);
    }
    #[cfg(feature = "tag")]
    {
        framework = framework.on("tag", command::tag::handler);
    }
    #[cfg(feature = "wolfram")]
    {
        framework = framework.on("wolfram", command::wolfram_alpha::handler);
    }
    #[cfg(feature = "xkcd")]
    {
        framework = framework.on("xkcd", command::xkcd::handler);
    }

    framework
}

// Creates a `Client`.
fn login() -> (LoginType, Client) {
    debug!("Attempting to login");

    if let Ok(bot_token) = env::var("DISCORD_BOT_TOKEN") {
        debug!("Performing bot token login");
        return (
            LoginType::Bot,
            Client::login_bot(&bot_token),
        )
    }
    debug!("Skipping bot token login");

    if let Ok(user_token) = env::var("DISCORD_USER_TOKEN") {
        debug!("Performing user token login");
        return (
            LoginType::User,
            Client::login_user(&user_token),
        )
    }
    debug!("Skipping user token login");

    panic!("No suitable authentication method found");
}
<commit_msg>impr: more verbose on_ready message<commit_after>// Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![deny(missing_docs)]
#![deny(non_camel_case_types)]
#![cfg_attr(feature = "nightly", feature(proc_macro))]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![warn(missing_copy_implementations,
        missing_debug_implementations,
        missing_docs,
        trivial_numeric_casts,
        unsafe_code,
        unused_extern_crates,
        unused_import_braces,
        unused_qualifications)]
#![cfg_attr(feature="clippy", warn(cast_possible_truncation))]
#![cfg_attr(feature="clippy", warn(cast_possible_wrap))]
#![cfg_attr(feature="clippy", warn(cast_precision_loss))]
#![cfg_attr(feature="clippy", warn(cast_sign_loss))]
#![cfg_attr(feature="clippy", warn(mut_mut))]
// This allows us to use `unwrap` on `Option` values when compiling in test mode
// (because using it in tests is idiomatic).
#![cfg_attr(all(not(test), feature="clippy"), warn(result_unwrap_used))]
#![cfg_attr(feature="clippy", warn(wrong_pub_self_convention))]

//! Smexybot is a general-purpose [Discord](https://discordapp.com/) bot written
//! in [Rust](https://www.rust-lang.org/). It is built upon the
//! [serenity.rs](https://github.com/zeyla/serenity.rs) Discord API.

extern crate chrono;
extern crate env_logger;
extern crate hyper;
#[cfg(any(feature = "roll", feature = "wolfram", feature = "xkcd"))]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate rand;
extern crate serde;
#[cfg(feature = "nightly")]
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate serenity;
extern crate url;

mod command;
mod config;
mod error;
mod util;

use std::env;

use chrono::{DateTime, UTC};
use serenity::Client;
use serenity::client::LoginType;
use serenity::ext::framework::Framework;

use config::Config;
use util::{check_msg, timestamp_to_string};

lazy_static! {
    static ref CONFIG: Config = Config::new(Some("config.json"));
    static ref UPTIME: DateTime<UTC> = UTC::now();
}

fn main() {
    // Initialize the `env_logger` to provide logging output.
    env_logger::init().expect("Failed to initialize env_logger");

    // Initialize the `UPTIME` variable.
    debug!("Initialized at: {}", timestamp_to_string(&*UPTIME));

    // Create a client for a user.
    let (_, mut client) = login();

    client.on_ready(|_context, ready| {
        let shard_info = if let Some(s) = ready.shard {
            Some(format!("shard {}/{} ", s[0] + 1, s[1]))
        } else {
            None
        };
        println!(
            "Started {}as {}#{}, serving {} guilds",
            shard_info.unwrap_or_else(|| "".to_owned()),
            ready.user.name,
            ready.user.discriminator,
            ready.guilds.len(),
        );
    });

    client.with_framework(build_framework);

    if let Err(err) = client.start_autosharded() {
        error!("Client error: {:?}", err);
    }
}

// Configures the `Framework` used by serenity, and registers the handlers for
// any enabled commands.
fn build_framework(framework: Framework) -> Framework {
    let mut framework = framework.configure(|c| c
        .prefix(&CONFIG.command_prefix))
    .before(|_context, message, command_name| {
        debug!(
            "Got command '{}' from user '{}'",
            command_name,
            message.author.name,
        );

        true
    })
    .after(|context, _message, command_name, error| {
        if let Err(err) = error {
            check_msg(context.say(&err));
        } else {
            debug!("Processed command '{}'", command_name);
        }
    });

    #[cfg(feature = "fuyu")]
    {
        framework = framework.on("fuyu", command::fuyu::handler);
    }
    #[cfg(feature = "help")]
    {
        use serenity::ext::framework::help_commands;
        framework = framework.command("help", |c| c
          .exec_help(help_commands::plain));
    }
    #[cfg(feature = "ping")]
    {
        framework = framework.on("ping", command::ping::handler);
    }
    #[cfg(feature = "roll")]
    {
        framework = framework.on("roll", command::roll::handler);
    }
    #[cfg(feature = "stats")]
    {
        framework = framework.on("stats", command::stats::handler);
    }
    #[cfg(feature = "tag")]
    {
        framework = framework.on("tag", command::tag::handler);
    }
    #[cfg(feature = "wolfram")]
    {
        framework = framework.on("wolfram", command::wolfram_alpha::handler);
    }
    #[cfg(feature = "xkcd")]
    {
        framework = framework.on("xkcd", command::xkcd::handler);
    }

    framework
}

// Creates a `Client`.
fn login() -> (LoginType, Client) {
    debug!("Attempting to login");

    if let Ok(bot_token) = env::var("DISCORD_BOT_TOKEN") {
        debug!("Performing bot token login");
        return (
            LoginType::Bot,
            Client::login_bot(&bot_token),
        )
    }
    debug!("Skipping bot token login");

    if let Ok(user_token) = env::var("DISCORD_USER_TOKEN") {
        debug!("Performing user token login");
        return (
            LoginType::User,
            Client::login_user(&user_token),
        )
    }
    debug!("Skipping user token login");

    panic!("No suitable authentication method found");
}
<|endoftext|>


<commit_before>extern crate regex;
use regex::Regex;

fn main() {
    let re1 = Regex::new(r"\(").unwrap();
    let re2 = Regex::new(r"\)").unwrap();

    let test = "(abc)";

    let mut after = re1.replace_all(test,"( ");
    after = re2.replace_all(after.as_slice(), " )");

    println!("{}",after)
}

/*
fn tokenize<'s>(chars: &'s String) -> Vec<&'s str> {
    let with_space: &'s String = chars.replace("(", "( ");
    let vected: Vec<&'s str>  = with_space.as_slice().split(' ').collect();
    return vected
}
*/
<commit_msg>Tokenizes add spaces.<commit_after>extern crate regex;
use regex::Regex;

fn main() {

    let test = "(abc)".to_string();
    let tokened: String = tokenize(&test);

    println!("{}",tokened)
}

fn tokenize(input: &String) -> String{

    let re1 = Regex::new(r"\(").unwrap();
    let re2 = Regex::new(r"\)").unwrap();
    let after = re1.replace_all(input,"( ");
    re2.replace_all(after.as_slice(), " )")
}
<|endoftext|>


<commit_before>use libc::{c_char, c_int, c_ulong, c_long, c_float, c_double, c_void};
use gmp::mpz::mpz_srcptr;
use gmp::mpq::mpq_srcptr;
use gmp::mpf::mpf_srcptr;
use std::mem::uninitialized;

type mpfr_prec_t = c_int;
type mpfr_sign_t = c_int;
type mpfr_exp_t = c_int;

#[repr(C)]
pub enum mpfr_rnd_t {
	MPFR_RNDN=0,  /* round to nearest, with ties to even */
	MPFR_RNDZ,    /* round toward zero */
	MPFR_RNDU,    /* round toward +Inf */
	MPFR_RNDD,    /* round toward -Inf */
	MPFR_RNDA,    /* round away from zero */
	MPFR_RNDF,    /* faithful rounding (not implemented yet) */
	MPFR_RNDNA=-1 /* round to nearest, with ties away from zero (mpfr_rouund) */
}

#[repr(C)]
pub struct mpfr_struct {
    _mpfr_prec: mpfr_prec_t,
    _mpfr_sign: mpfr_sign_t,
    _mpfr_exp: mpfr_exp_t,
    _mpfr_d: *mut c_void
}

pub type mpfr_srcptr = *const mpfr_struct;
pub type mpfr_ptr = *mut mpfr_struct;

#[link(name = "mpfr")]
extern "C" {
	// Initialization
	fn mpfr_init2(x: mpfr_ptr, prec: mpfr_prec_t);
	fn mpfr_clear(x: mpfr_ptr);
	fn mpfr_set_default_prec(prec: mpfr_prec_t);
	fn mpfr_get_default_prec() -> mpfr_prec_t;
	fn mpfr_set_prec(x: mpfr_ptr, prec: mpfr_prec_t);
	fn mpfr_get_prec(x: mpfr_srcptr) -> mpfr_prec_t;

	// Assignment
	fn mpfr_set(rop: mpfr_ptr, op: mpfr_ptr, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_ui(rop: mpfr_ptr, op: c_ulong, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_si(rop: mpfr_ptr, op: c_long, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_flt(rop: mpfr_ptr, op: c_float, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_d(rop: mpfr_ptr, op: c_double, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_z(rop: mpfr_ptr, op: mpz_srcptr, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_q(rop: mpfr_ptr, op: mpq_srcptr, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_f(rop: mpfr_ptr, op: mpf_srcptr, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_ui_2exp(rop: mpfr_ptr, op: c_ulong, e: mpfr_exp_t, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_si_2exp(rop: mpfr_ptr, op: c_long, e: mpfr_exp_t, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_z_2exp(rop: mpfr_ptr, op: mpz_srcptr, e: mpfr_exp_t, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_str(rop: mpfr_ptr, s: *const c_char, base: c_int, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_strtofr(rop: mpfr_ptr, nptr: *const c_char, endptr: *mut c_void, base: c_int, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_nan(x: mpfr_ptr);
	fn mpfr_set_inf(x: mpfr_ptr, sign: c_int);
	fn mpfr_set_zero(x: mpfr_ptr, sign: c_int);
	fn mpfr_swap(x: mpfr_ptr, y: mpfr_ptr);

	// Initialization and assignment
	fn mpfr_init_set(rop: mpfr_ptr, op: mpfr_srcptr, rnd: mpfr_rnd_t) -> c_int;
}

pub struct Mpfr {
    pub mpfr: mpfr_struct,
}

unsafe impl Send for Mpfr { }

impl Drop for Mpfr {
    fn drop(&mut self) { unsafe { mpfr_clear(&mut self.mpfr) } }
}

impl Clone for Mpfr {
    fn clone(&self) -> Mpfr {
        unsafe {
            let mut mpfr = uninitialized();
            mpfr_init_set(&mut mpfr, &self.mpfr, mpfr_rnd_t::MPFR_RNDN);
            Mpfr { mpfr: mpfr }
        }
    }
}

impl Mpfr {
    pub fn new(precision: c_int) -> Mpfr {
        unsafe {
            let mut mpfr = uninitialized();
            mpfr_init2(&mut mpfr, precision);
            Mpfr { mpfr: mpfr }
        }
    }

    pub fn get_default_prec() -> i64 {
    	unsafe {
    		mpfr_get_default_prec() as i64
    	}
    }

    pub fn set_default_prec(precision: i64) {
    	unsafe {
    		mpfr_set_default_prec(precision as c_int);
    	}
    }

    pub fn get_prec(&self) -> i64 {
    	unsafe {
    		mpfr_get_prec(&self.mpfr) as i64
    	}
    }

    pub fn set_prec(&mut self, precision: i64) {
    	unsafe {
    		mpfr_set_prec(&mut self.mpfr, precision as c_int);
    	}
    }
}
<commit_msg>Implemented comparisons<commit_after>use libc::{c_char, c_int, c_ulong, c_long, c_float, c_double, c_void};
use gmp::mpz::mpz_srcptr;
use gmp::mpq::mpq_srcptr;
use gmp::mpf::mpf_srcptr;
use std::mem::uninitialized;
use std::cmp::{Eq, PartialEq, Ord, PartialOrd, Ordering};

type mpfr_prec_t = c_int;
type mpfr_sign_t = c_int;
type mpfr_exp_t = c_int;

#[repr(C)]
pub enum mpfr_rnd_t {
	MPFR_RNDN=0,  /* round to nearest, with ties to even */
	MPFR_RNDZ,    /* round toward zero */
	MPFR_RNDU,    /* round toward +Inf */
	MPFR_RNDD,    /* round toward -Inf */
	MPFR_RNDA,    /* round away from zero */
	MPFR_RNDF,    /* faithful rounding (not implemented yet) */
	MPFR_RNDNA=-1 /* round to nearest, with ties away from zero (mpfr_rouund) */
}

#[repr(C)]
pub struct mpfr_struct {
    _mpfr_prec: mpfr_prec_t,
    _mpfr_sign: mpfr_sign_t,
    _mpfr_exp: mpfr_exp_t,
    _mpfr_d: *mut c_void
}

pub type mpfr_srcptr = *const mpfr_struct;
pub type mpfr_ptr = *mut mpfr_struct;

#[link(name = "mpfr")]
extern "C" {
	// Initialization
	fn mpfr_init2(x: mpfr_ptr, prec: mpfr_prec_t);
	fn mpfr_clear(x: mpfr_ptr);
	fn mpfr_set_default_prec(prec: mpfr_prec_t);
	fn mpfr_get_default_prec() -> mpfr_prec_t;
	fn mpfr_set_prec(x: mpfr_ptr, prec: mpfr_prec_t);
	fn mpfr_get_prec(x: mpfr_srcptr) -> mpfr_prec_t;

	// Assignment
	fn mpfr_set(rop: mpfr_ptr, op: mpfr_ptr, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_ui(rop: mpfr_ptr, op: c_ulong, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_si(rop: mpfr_ptr, op: c_long, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_flt(rop: mpfr_ptr, op: c_float, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_d(rop: mpfr_ptr, op: c_double, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_z(rop: mpfr_ptr, op: mpz_srcptr, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_q(rop: mpfr_ptr, op: mpq_srcptr, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_f(rop: mpfr_ptr, op: mpf_srcptr, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_ui_2exp(rop: mpfr_ptr, op: c_ulong, e: mpfr_exp_t, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_si_2exp(rop: mpfr_ptr, op: c_long, e: mpfr_exp_t, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_z_2exp(rop: mpfr_ptr, op: mpz_srcptr, e: mpfr_exp_t, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_str(rop: mpfr_ptr, s: *const c_char, base: c_int, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_strtofr(rop: mpfr_ptr, nptr: *const c_char, endptr: *mut c_void, base: c_int, rnd: mpfr_rnd_t) -> c_int;
	fn mpfr_set_nan(x: mpfr_ptr);
	fn mpfr_set_inf(x: mpfr_ptr, sign: c_int);
	fn mpfr_set_zero(x: mpfr_ptr, sign: c_int);
	fn mpfr_swap(x: mpfr_ptr, y: mpfr_ptr);

	// Initialization and assignment
	fn mpfr_init_set(rop: mpfr_ptr, op: mpfr_srcptr, rnd: mpfr_rnd_t) -> c_int;

	// Comparison
	fn mpfr_cmp(op1: mpfr_srcptr, op2: mpfr_srcptr) -> c_int;
}

pub struct Mpfr {
    pub mpfr: mpfr_struct,
}

unsafe impl Send for Mpfr { }

impl Drop for Mpfr {
    fn drop(&mut self) { unsafe { mpfr_clear(&mut self.mpfr) } }
}

impl Clone for Mpfr {
    fn clone(&self) -> Mpfr {
        unsafe {
            let mut mpfr = uninitialized();
            mpfr_init_set(&mut mpfr, &self.mpfr, mpfr_rnd_t::MPFR_RNDN);
            Mpfr { mpfr: mpfr }
        }
    }
}

impl Mpfr {
    pub fn new(precision: c_int) -> Mpfr {
        unsafe {
            let mut mpfr = uninitialized();
            mpfr_init2(&mut mpfr, precision);
            Mpfr { mpfr: mpfr }
        }
    }

    pub fn get_default_prec() -> i64 {
    	unsafe {
    		mpfr_get_default_prec() as i64
    	}
    }

    pub fn set_default_prec(precision: i64) {
    	unsafe {
    		mpfr_set_default_prec(precision as c_int);
    	}
    }

    pub fn get_prec(&self) -> i64 {
    	unsafe {
    		mpfr_get_prec(&self.mpfr) as i64
    	}
    }

    pub fn set_prec(&mut self, precision: i64) {
    	unsafe {
    		mpfr_set_prec(&mut self.mpfr, precision as c_int);
    	}
    }
}

impl Eq for Mpfr { }
impl PartialEq for Mpfr {
	fn eq(&self, other: &Mpfr) -> bool {
		unsafe {
			mpfr_cmp(&self.mpfr, &other.mpfr) == 0
		}
	}
}

impl Ord for Mpfr {
    fn cmp(&self, other: &Mpfr) -> Ordering {
        let cmp = unsafe { mpfr_cmp(&self.mpfr, &other.mpfr) };
        if cmp == 0 {
            Ordering::Equal
        } else if cmp > 0 {
            Ordering::Greater
        } else {
            Ordering::Less
        }
    }
}

impl PartialOrd for Mpfr {
    fn partial_cmp(&self, other: &Mpfr) -> Option<Ordering> {
    	Some(self.cmp(other))
    }
}
<|endoftext|>


<commit_before>

use sound_stream_settings::SoundStreamSettings;
use std::fmt::Show;

/// The DSP Node contains a vector of children
/// nodes (within the `MixerInput`s), from which
/// audio can be requested as well as the current
/// SoundStream settings.
#[deriving(Show, Clone, Encodable, Decodable)]
pub struct Data {
    /// SoundStreamSettings for buffer calculations.
    pub settings: SoundStreamSettings,
    /// Master volume for DSP node.
    pub vol: f32,
    /// Panning for DSP node.
    pub pan: f32
}

impl Data {
    /// Default constructor for a Data struct.
    pub fn new(settings: SoundStreamSettings) -> Data {
        Data {
            settings: settings,
            vol: 1f32,
            pan: 0f32,
        }
    }
}

/// DSP Node trait. Implement this for any audio
/// instrument or effects types. Be sure to add
/// the `Node` struct to a field as well, and
/// override the `get_node` and `get_node_mut`
/// methods by returning a ref (/mut) to it.
pub trait Node: Clone + Show {

    /// Return a reference a Data struct owned by the Node.
    fn get_node_data<'a>(&'a mut self) -> &'a mut Data;
    /// Return a reference to the inputs for the Node.
    fn get_inputs<'a>(&'a self) -> Vec<&'a Node> { Vec::new() }
    /// Return a mutable reference to the inputs for the Node.
    fn get_inputs_mut<'a>(&'a mut self) -> Vec<&'a mut Node> { Vec::new() }

    /// Apply settings to self and all inputs.
    fn apply_settings(&mut self, settings: SoundStreamSettings) {
        for input in self.get_inputs_mut().mut_iter() {
            input.apply_settings(settings);
        }
        self.get_node_data().settings = settings;
    }

    /// Remove all inputs from the `inputs` vector.
    fn remove_all_inputs(&mut self) {
        self.get_inputs_mut().clear();
    }

    /// Receive incoming audio (override this
    /// to do something with the input).
    fn audio_received(&mut self, _input: &Vec<f32>) {}

    /// Request audio from inputs, process and
    /// pass back to the output! Override this
    /// method for any synthesis or generative
    /// types.
    fn audio_requested<'a>(&'a mut self, output: &mut Vec<f32>) {
        let frames = self.get_node_data().settings.frames as uint;
        let channels = self.get_node_data().settings.channels as uint;
        {
            let mut inputs = self.get_inputs_mut();
            let mut vol_per_channel: Vec<f32> = Vec::from_elem(channels, 1f32);
            for i in range(0, inputs.len()) {
                let input = inputs.get_mut(i);
                let input_vol = input.get_node_data().vol;
                let input_pan = input.get_node_data().pan;
                let mut working: Vec<f32> = Vec::from_elem((frames * channels) as uint, 0f32);
                // Call audio_requested for each input.
                input.audio_requested(&mut working);
                // Construct precalculated volume and
                // pan array (for efficiency).
                let vol_l: f32 = input_vol * (1f32 - input_pan);
                let vol_r: f32 = input_vol * input_pan;
                for j in range(0, vol_per_channel.len()) {
                    *vol_per_channel.get_mut(j) = if j == 0 { vol_l } else { vol_r };
                }
                // Sum all input nodes to output (considering
                // pan, vol and interleaving).
                for j in range(0, frames) {
                    for k in range(0, channels) {
                        *output.get_mut(j * channels + k) +=
                            *working.get(j * channels + k) * *vol_per_channel.get(k);
                    }
                }
            }
        }
        // Custom buffer processing.
        self.process_buffer(output);
    }

    /// Override for custom processing of audio per
    /// buffer. This is mainly for audio effects. Get's
    /// called at the end of audio_requested.
    fn process_buffer(&mut self, _output: &mut Vec<f32>) {}

}

<commit_msg>Fix deprecated get in favour of indexing<commit_after>

use sound_stream_settings::SoundStreamSettings;
use std::fmt::Show;

/// The DSP Node contains a vector of children
/// nodes (within the `MixerInput`s), from which
/// audio can be requested as well as the current
/// SoundStream settings.
#[deriving(Show, Clone, Encodable, Decodable)]
pub struct Data {
    /// SoundStreamSettings for buffer calculations.
    pub settings: SoundStreamSettings,
    /// Master volume for DSP node.
    pub vol: f32,
    /// Panning for DSP node.
    pub pan: f32
}

impl Data {
    /// Default constructor for a Data struct.
    pub fn new(settings: SoundStreamSettings) -> Data {
        Data {
            settings: settings,
            vol: 1f32,
            pan: 0f32,
        }
    }
}

/// DSP Node trait. Implement this for any audio
/// instrument or effects types. Be sure to add
/// the `Node` struct to a field as well, and
/// override the `get_node` and `get_node_mut`
/// methods by returning a ref (/mut) to it.
pub trait Node: Clone + Show {

    /// Return a reference a Data struct owned by the Node.
    fn get_node_data<'a>(&'a mut self) -> &'a mut Data;
    /// Return a reference to the inputs for the Node.
    fn get_inputs<'a>(&'a self) -> Vec<&'a Node> { Vec::new() }
    /// Return a mutable reference to the inputs for the Node.
    fn get_inputs_mut<'a>(&'a mut self) -> Vec<&'a mut Node> { Vec::new() }

    /// Apply settings to self and all inputs.
    fn apply_settings(&mut self, settings: SoundStreamSettings) {
        for input in self.get_inputs_mut().mut_iter() {
            input.apply_settings(settings);
        }
        self.get_node_data().settings = settings;
    }

    /// Remove all inputs from the `inputs` vector.
    fn remove_all_inputs(&mut self) {
        self.get_inputs_mut().clear();
    }

    /// Receive incoming audio (override this
    /// to do something with the input).
    fn audio_received(&mut self, _input: &Vec<f32>) {}

    /// Request audio from inputs, process and
    /// pass back to the output! Override this
    /// method for any synthesis or generative
    /// types.
    fn audio_requested<'a>(&'a mut self, output: &mut Vec<f32>) {
        let frames = self.get_node_data().settings.frames as uint;
        let channels = self.get_node_data().settings.channels as uint;
        {
            let mut inputs = self.get_inputs_mut();
            let mut vol_per_channel: Vec<f32> = Vec::from_elem(channels, 1f32);
            for i in range(0, inputs.len()) {
                let input = inputs.get_mut(i);
                let input_vol = input.get_node_data().vol;
                let input_pan = input.get_node_data().pan;
                let mut working: Vec<f32> = Vec::from_elem((frames * channels) as uint, 0f32);
                // Call audio_requested for each input.
                input.audio_requested(&mut working);
                // Construct precalculated volume and
                // pan array (for efficiency).
                let vol_l: f32 = input_vol * (1f32 - input_pan);
                let vol_r: f32 = input_vol * input_pan;
                for j in range(0, vol_per_channel.len()) {
                    *vol_per_channel.get_mut(j) = if j == 0 { vol_l } else { vol_r };
                }
                // Sum all input nodes to output (considering
                // pan, vol and interleaving).
                for j in range(0, frames) {
                    for k in range(0, channels) {
                        *output.get_mut(j * channels + k) +=
                            working[j * channels + k] * vol_per_channel[k];
                    }
                }
            }
        }
        // Custom buffer processing.
        self.process_buffer(output);
    }

    /// Override for custom processing of audio per
    /// buffer. This is mainly for audio effects. Get's
    /// called at the end of audio_requested.
    fn process_buffer(&mut self, _output: &mut Vec<f32>) {}

}

<|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.

//! Structured specification of command-line arguments.
//!
//! This module specifies all command-line arguments that RRG offers and exposes
//! functions for parsing them into a high-level structure.
//!
//! Ideally, only one instance of this high-level structure should ever be
//! created (using the [`from_args`] function). Then this instance should be
//! shared through the entire lifetime of a program and explicitly passed to
//! functions that care about it.
//!
//! [`from_args`]: fn.from_args.html

use std::time::Duration;
use std::path::PathBuf;

use structopt::StructOpt;

#[derive(StructOpt)]
#[structopt(name = "RRG", about = "A GRR agent rewritten in Rust.")]
pub struct Opts {
    /// A level of log verbosity.
    #[structopt(long="log-verbosity", name="LEVEL", default_value="info",
                help="Specifies the level of log verbosity")]
    pub log_verbosity: Verbosity,

    /// A standard stream to log into.
    #[structopt(long="log-stream", name="STREAM",
                help="Enables logging to the specified standard stream")]
    pub log_stream: Option<Stream>,

    /// A path to the file to log into.
    #[structopt(long="log-file", name="FILE",
                help="Enables logging to the specified file")]
    pub log_file: Option<PathBuf>,

    /// A frequency of heartbeat messages to send to the Fleetspeak client.
    #[structopt(long="heartbeat-rate", name="DURATION", default_value="5s",
                parse(try_from_str = humantime::parse_duration),
                help="Specifies the frequency of heartbeat messages")]
    pub heartbeat_rate: Duration,
}

/// Parses command-line arguments.
///
/// This is a just a convenience function intended to be used as a shortcut for
/// creating instances of [`Opts`]. Ideally, it should be called only once in
/// the entire lifetime of the agent.
///
/// [`Opts`]: struct.Opts.html
pub fn from_args() -> Opts {
    Opts::from_args()
}

/// A type representing level of log verbosity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Verbosity {
    level: log::LevelFilter,
}

impl Verbosity {

    /// Yields a corresponding log filter.
    pub fn level(&self) -> log::LevelFilter {
        self.level
    }
}

impl std::str::FromStr for Verbosity {

    type Err = ParseVerbosityError;

    fn from_str(string: &str) -> std::result::Result<Verbosity, ParseVerbosityError> {
        use log::LevelFilter::*;

        let level = match string {
            "quiet" => Off,
            "error" => Error,
            "warn" => Warn,
            "info" => Info,
            "debug" => Debug,
            "trace" => Trace,
            _ => return Err(ParseVerbosityError::new(string)),
        };

        Ok(Verbosity {
            level: level,
        })
    }
}

/// A type listing different options for logging to standard streams.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Stream {
    mode: simplelog::TerminalMode,
}

impl Stream {

    /// Yields a corresponding terminal mode.
    pub fn mode(&self) -> simplelog::TerminalMode {
        self.mode
    }
}

impl std::str::FromStr for Stream {

    type Err = ParseStreamError;

    fn from_str(string: &str) -> std::result::Result<Stream, ParseStreamError> {
        use simplelog::TerminalMode::*;

        let mode = match string {
            "stdout" => Stdout,
            "stderr" => Stderr,
            "mixed" => Mixed,
            _ => return Err(ParseStreamError::new(string)),
        };

        Ok(Stream {
            mode: mode,
        })
    }
}

/// An error type for failures related to parsing of verbosity levels.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParseVerbosityError {
    string: String,
}

impl ParseVerbosityError {

    /// Constructs a new error indicating failure of parsing given string.
    fn new<S: Into<String>>(string: S) -> ParseVerbosityError {
        ParseVerbosityError {
            string: string.into(),
        }
    }
}

impl std::fmt::Display for ParseVerbosityError {

    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "invalid verbosity level: '{}'", self.string)
    }
}

impl std::error::Error for ParseVerbosityError {

    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

/// An error type for failures related to parsing names of standard streams.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParseStreamError {
    string: String,
}

impl ParseStreamError {

    /// Constructs a new error indicating failure of parsing given string.
    fn new<S: Into<String>>(string: S) -> ParseStreamError {
        ParseStreamError {
            string: string.into(),
        }
    }
}

impl std::fmt::Display for ParseStreamError {

    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "invalid stream name: '{}'", self.string)
    }
}

impl std::error::Error for ParseStreamError {

    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}
<commit_msg>Remove redundant prefixes in type signatures.<commit_after>// Copyright 2020 Google LLC
//
// Use of this source code is governed by an MIT-style license that can be found
// in the LICENSE file or at https://opensource.org/licenses/MIT.

//! Structured specification of command-line arguments.
//!
//! This module specifies all command-line arguments that RRG offers and exposes
//! functions for parsing them into a high-level structure.
//!
//! Ideally, only one instance of this high-level structure should ever be
//! created (using the [`from_args`] function). Then this instance should be
//! shared through the entire lifetime of a program and explicitly passed to
//! functions that care about it.
//!
//! [`from_args`]: fn.from_args.html

use std::time::Duration;
use std::path::PathBuf;

use structopt::StructOpt;

#[derive(StructOpt)]
#[structopt(name = "RRG", about = "A GRR agent rewritten in Rust.")]
pub struct Opts {
    /// A level of log verbosity.
    #[structopt(long="log-verbosity", name="LEVEL", default_value="info",
                help="Specifies the level of log verbosity")]
    pub log_verbosity: Verbosity,

    /// A standard stream to log into.
    #[structopt(long="log-stream", name="STREAM",
                help="Enables logging to the specified standard stream")]
    pub log_stream: Option<Stream>,

    /// A path to the file to log into.
    #[structopt(long="log-file", name="FILE",
                help="Enables logging to the specified file")]
    pub log_file: Option<PathBuf>,

    /// A frequency of heartbeat messages to send to the Fleetspeak client.
    #[structopt(long="heartbeat-rate", name="DURATION", default_value="5s",
                parse(try_from_str = humantime::parse_duration),
                help="Specifies the frequency of heartbeat messages")]
    pub heartbeat_rate: Duration,
}

/// Parses command-line arguments.
///
/// This is a just a convenience function intended to be used as a shortcut for
/// creating instances of [`Opts`]. Ideally, it should be called only once in
/// the entire lifetime of the agent.
///
/// [`Opts`]: struct.Opts.html
pub fn from_args() -> Opts {
    Opts::from_args()
}

/// A type representing level of log verbosity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Verbosity {
    level: log::LevelFilter,
}

impl Verbosity {

    /// Yields a corresponding log filter.
    pub fn level(&self) -> log::LevelFilter {
        self.level
    }
}

impl std::str::FromStr for Verbosity {

    type Err = ParseVerbosityError;

    fn from_str(string: &str) -> Result<Verbosity, ParseVerbosityError> {
        use log::LevelFilter::*;

        let level = match string {
            "quiet" => Off,
            "error" => Error,
            "warn" => Warn,
            "info" => Info,
            "debug" => Debug,
            "trace" => Trace,
            _ => return Err(ParseVerbosityError::new(string)),
        };

        Ok(Verbosity {
            level: level,
        })
    }
}

/// A type listing different options for logging to standard streams.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Stream {
    mode: simplelog::TerminalMode,
}

impl Stream {

    /// Yields a corresponding terminal mode.
    pub fn mode(&self) -> simplelog::TerminalMode {
        self.mode
    }
}

impl std::str::FromStr for Stream {

    type Err = ParseStreamError;

    fn from_str(string: &str) -> Result<Stream, ParseStreamError> {
        use simplelog::TerminalMode::*;

        let mode = match string {
            "stdout" => Stdout,
            "stderr" => Stderr,
            "mixed" => Mixed,
            _ => return Err(ParseStreamError::new(string)),
        };

        Ok(Stream {
            mode: mode,
        })
    }
}

/// An error type for failures related to parsing of verbosity levels.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParseVerbosityError {
    string: String,
}

impl ParseVerbosityError {

    /// Constructs a new error indicating failure of parsing given string.
    fn new<S: Into<String>>(string: S) -> ParseVerbosityError {
        ParseVerbosityError {
            string: string.into(),
        }
    }
}

impl std::fmt::Display for ParseVerbosityError {

    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "invalid verbosity level: '{}'", self.string)
    }
}

impl std::error::Error for ParseVerbosityError {

    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

/// An error type for failures related to parsing names of standard streams.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ParseStreamError {
    string: String,
}

impl ParseStreamError {

    /// Constructs a new error indicating failure of parsing given string.
    fn new<S: Into<String>>(string: S) -> ParseStreamError {
        ParseStreamError {
            string: string.into(),
        }
    }
}

impl std::fmt::Display for ParseStreamError {

    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "invalid stream name: '{}'", self.string)
    }
}

impl std::error::Error for ParseStreamError {

    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}
<|endoftext|>