<commit_before>use cartridge::Cartridge;

use bus::Bus;
use cpu::{Cpu, Interrupt};
use joypad::Button;
use lcd::{SCREEN_WIDTH, SCREEN_HEIGHT};
use minifb::{Key, Scale, WindowOptions, Window};
use std::time::{Instant, Duration};
use std::thread;

const CYCLES_PER_FRAME: usize = 69905;
const MS_PER_FRAME: u128 = 16;

pub struct Rustboy<'a> {
    options: RustboyOptions,
    bus: Bus<'a>,
    cpu: Cpu,
    screen_buffer: [u32; SCREEN_WIDTH * SCREEN_HEIGHT],
    window: Window
}

#[derive(Clone, Copy, Debug)]
pub struct RustboyOptions {
    pub scale: Scale,
    pub verbose: bool,
    pub unlock_fps: bool
}

impl<'a> Rustboy<'a> {
    pub fn new(cartridge: &'a mut Cartridge, options: RustboyOptions) -> Self {
        Self {
            options: options,
            bus: Bus::new(cartridge),
            cpu: Cpu::new(),
            screen_buffer: [0; SCREEN_WIDTH * SCREEN_HEIGHT],
            window: create_window(options.scale)
        }
    }

    pub fn run(&mut self) {
        // Clear the window
        for i in self.screen_buffer.iter_mut() {
            *i = 0xFFFFFF;
        }

        self.window.update_with_buffer(&self.screen_buffer).expect("Unable to render window");

        // Set the CPU to initial values
        self.cpu.reset();

        // FPS counter variables
        let mut fps_counter_time = Instant::now();
        let mut fps_counter_frames = 0;

        let mut cycles_since_last_frame = 0;
        let mut time_since_last_frame = Instant::now();

        let mut buttons = Button::empty();

        while self.window.is_open() && !self.window.is_key_down(Key::Escape) {
            // Execute the next CPU instruction. The number of cycles used is returned.
            let cycles = self.cpu.step(&mut self.bus);

            cycles_since_last_frame += cycles;

            // Step timer
            let timer_result = self.bus.timer.step(cycles);

            // Step serial port
            let serial_result = self.bus.serial.step(cycles);

            // Step LCD
            let lcd_result = self.bus.lcd.step(cycles, &mut self.screen_buffer);

            // Step joypad
            let joypad_result = self.bus.joypad.step(buttons);

            // The timer interrupts when the counter reaches its goal
            if timer_result.interrupt {
                self.cpu.interrupt(&mut self.bus, Interrupt::Timer);
            }

            // Serial interrupt happens after a byte is transferred
            if serial_result.interrupt {
                self.cpu.interrupt(&mut self.bus, Interrupt::Serial);
            }

            // LCD can generate a STAT interrupt when modes change or when the cursor reaches a specific line
            if lcd_result.int_stat {
                self.cpu.interrupt(&mut self.bus, Interrupt::Stat);
            }

            // Joypad interrupts when a button is pressed
            if joypad_result.interrupt {
                self.cpu.interrupt(&mut self.bus, Interrupt::Joypad);
            }

            // LCD interrupts when VLANK is reached
            // We'll use this time to update the framebuffer and FPS counter. Also we'll get the current pressed buttons
            if lcd_result.int_vblank {
                self.cpu.interrupt(&mut self.bus, Interrupt::VBlank);
                self.window.update_with_buffer(&self.screen_buffer).unwrap();

                if cycles_since_last_frame > CYCLES_PER_FRAME {
                    let elapsed = time_since_last_frame.elapsed();

                    if !self.options.unlock_fps && elapsed.as_millis() < MS_PER_FRAME {
                        // Sleep for the remaining time
                        thread::sleep(Duration::from_millis((MS_PER_FRAME - elapsed.as_millis()) as u64))
                    }
                }

                cycles_since_last_frame = 0;
                time_since_last_frame = Instant::now();

                fps_counter_frames += 1;

                // If a second has passed, update the FPS counter
                let elapsed = fps_counter_time.elapsed();

                if elapsed.as_secs() > 0 {
                    self.window.set_title(format!("Rustboy ({} FPS)", fps_counter_frames).as_str());
                    fps_counter_time = Instant::now();
                    fps_counter_frames = 0;
                }

                self.set_button_presses(&mut buttons);
            }
        }
    }

    fn set_button_presses(&self, buttons: &mut Button) {
        *buttons = Button::empty();

        if self.window.is_key_down(Key::Enter) {
            *buttons |= Button::START;
        }

        if self.window.is_key_down(Key::RightShift) || self.window.is_key_down(Key::LeftShift) {
            *buttons |= Button::SELECT;
        }

        if self.window.is_key_down(Key::Up) {
            *buttons |= Button::UP;
        }

        if self.window.is_key_down(Key::Right) {
            *buttons |= Button::RIGHT;
        }

        if self.window.is_key_down(Key::Down) {
            *buttons |= Button::DOWN;
        }

        if self.window.is_key_down(Key::Left) {
            *buttons |= Button::LEFT;
        }

        if self.window.is_key_down(Key::Z) {
            *buttons |= Button::B;
        }

        if self.window.is_key_down(Key::X) {
            *buttons |= Button::A;
        }
    }
}

fn create_window(scale: Scale) -> Window {
    Window::new(
        "Rustboy",
        SCREEN_WIDTH,
        SCREEN_HEIGHT,
        WindowOptions {
            scale: scale,
            ..WindowOptions::default()
        }).expect("Unable to create window")
}<commit_msg>D-pad restrictions<commit_after>use cartridge::Cartridge;

use bus::Bus;
use cpu::{Cpu, Interrupt};
use joypad::Button;
use lcd::{SCREEN_WIDTH, SCREEN_HEIGHT};
use minifb::{Key, Scale, WindowOptions, Window};
use std::time::{Instant, Duration};
use std::thread;

const CYCLES_PER_FRAME: usize = 69905;
const MS_PER_FRAME: u128 = 16;

pub struct Rustboy<'a> {
    options: RustboyOptions,
    bus: Bus<'a>,
    cpu: Cpu,
    screen_buffer: [u32; SCREEN_WIDTH * SCREEN_HEIGHT],
    window: Window
}

#[derive(Clone, Copy, Debug)]
pub struct RustboyOptions {
    pub scale: Scale,
    pub verbose: bool,
    pub unlock_fps: bool
}

impl<'a> Rustboy<'a> {
    pub fn new(cartridge: &'a mut Cartridge, options: RustboyOptions) -> Self {
        Self {
            options: options,
            bus: Bus::new(cartridge),
            cpu: Cpu::new(),
            screen_buffer: [0; SCREEN_WIDTH * SCREEN_HEIGHT],
            window: create_window(options.scale)
        }
    }

    pub fn run(&mut self) {
        // Clear the window
        for i in self.screen_buffer.iter_mut() {
            *i = 0xFFFFFF;
        }

        self.window.update_with_buffer(&self.screen_buffer).expect("Unable to render window");

        // Set the CPU to initial values
        self.cpu.reset();

        // FPS counter variables
        let mut fps_counter_time = Instant::now();
        let mut fps_counter_frames = 0;

        let mut cycles_since_last_frame = 0;
        let mut time_since_last_frame = Instant::now();

        let mut buttons = Button::empty();

        while self.window.is_open() && !self.window.is_key_down(Key::Escape) {
            // Execute the next CPU instruction. The number of cycles used is returned.
            let cycles = self.cpu.step(&mut self.bus);

            cycles_since_last_frame += cycles;

            // Step timer
            let timer_result = self.bus.timer.step(cycles);

            // Step serial port
            let serial_result = self.bus.serial.step(cycles);

            // Step LCD
            let lcd_result = self.bus.lcd.step(cycles, &mut self.screen_buffer);

            // Step joypad
            let joypad_result = self.bus.joypad.step(buttons);

            // The timer interrupts when the counter reaches its goal
            if timer_result.interrupt {
                self.cpu.interrupt(&mut self.bus, Interrupt::Timer);
            }

            // Serial interrupt happens after a byte is transferred
            if serial_result.interrupt {
                self.cpu.interrupt(&mut self.bus, Interrupt::Serial);
            }

            // LCD can generate a STAT interrupt when modes change or when the cursor reaches a specific line
            if lcd_result.int_stat {
                self.cpu.interrupt(&mut self.bus, Interrupt::Stat);
            }

            // Joypad interrupts when a button is pressed
            if joypad_result.interrupt {
                self.cpu.interrupt(&mut self.bus, Interrupt::Joypad);
            }

            // LCD interrupts when VLANK is reached
            // We'll use this time to update the framebuffer and FPS counter. Also we'll get the current pressed buttons
            if lcd_result.int_vblank {
                self.cpu.interrupt(&mut self.bus, Interrupt::VBlank);
                self.window.update_with_buffer(&self.screen_buffer).unwrap();

                if cycles_since_last_frame > CYCLES_PER_FRAME {
                    let elapsed = time_since_last_frame.elapsed();

                    if !self.options.unlock_fps && elapsed.as_millis() < MS_PER_FRAME {
                        // Sleep for the remaining time
                        thread::sleep(Duration::from_millis((MS_PER_FRAME - elapsed.as_millis()) as u64))
                    }
                }

                cycles_since_last_frame = 0;
                time_since_last_frame = Instant::now();

                fps_counter_frames += 1;

                // If a second has passed, update the FPS counter
                let elapsed = fps_counter_time.elapsed();

                if elapsed.as_secs() > 0 {
                    self.window.set_title(format!("Rustboy ({} FPS)", fps_counter_frames).as_str());
                    fps_counter_time = Instant::now();
                    fps_counter_frames = 0;
                }

                self.set_button_presses(&mut buttons);
            }
        }
    }

    fn set_button_presses(&self, buttons: &mut Button) {
        *buttons = Button::empty();

        if self.window.is_key_down(Key::Enter) {
            *buttons |= Button::START;
        }

        if self.window.is_key_down(Key::RightShift) || self.window.is_key_down(Key::LeftShift) {
            *buttons |= Button::SELECT;
        }

        if self.window.is_key_down(Key::Up) {
            *buttons |= Button::UP;
        } else if self.window.is_key_down(Key::Down) {
            *buttons |= Button::DOWN;
        }

        if self.window.is_key_down(Key::Right) {
            *buttons |= Button::RIGHT;
        } else if self.window.is_key_down(Key::Left) {
            *buttons |= Button::LEFT;
        }

        if self.window.is_key_down(Key::Z) {
            *buttons |= Button::B;
        }

        if self.window.is_key_down(Key::X) {
            *buttons |= Button::A;
        }
    }
}

fn create_window(scale: Scale) -> Window {
    Window::new(
        "Rustboy",
        SCREEN_WIDTH,
        SCREEN_HEIGHT,
        WindowOptions {
            scale: scale,
            ..WindowOptions::default()
        }).expect("Unable to create window")
}<|endoftext|>


<commit_before>
use token::{Token, TokenKind};
use error::{NcclError, ErrorKind};

use std::error::Error;

// ranked worst to best
enum Indent {
    Neither,
    Tabs,
    Spaces(u8),
}

pub struct Scanner {
    source: Vec<u8>,
    tokens: Vec<Token>,
    start: usize,
    current: usize,
    line: u64,
    indent: Indent,
}

impl Scanner {
    pub fn new(source: String) -> Self {
        Scanner {
            source: source.into_bytes(),
            tokens: Vec::new(),
            start: 0,
            current: 0,
            line: 1,
            indent: Indent::Neither,
        }
    }

    pub fn scan_tokens(&mut self) -> Result<Vec<Token>, Vec<Box<Error>>> {
        let mut err: Vec<Box<Error>> = vec![];

        while !self.is_at_end() {
            self.start = self.current;
            let e = self.scan_token();
            if e.is_err() {
                err.push(Box::new(e.err().unwrap()));
            }
        }

        self.tokens.push(Token::new(TokenKind::EOF, "".into(), self.line));

        if !err.is_empty() {
            Err(err)
        } else {
            Ok(self.tokens.clone())
        }
    }

    fn scan_token(&mut self) -> Result<(), NcclError> {
        let mut error = Ok(());
        match self.advance() {
            b'#' => {
                while self.peek() != b'\n' && !self.is_at_end() {
                    self.advance();
                }
            },

            b' ' => {
                match self.indent {
                    Indent::Neither => {
                        let mut spaces = 0;
                        while self.peek() == b' ' && !self.is_at_end() {
                            self.advance();
                            spaces += 1;
                        }
                        if self.is_at_end() {
                            error = Err(NcclError::new(ErrorKind::ParseError, "Expected value, found EOF", self.line));
                        }
                        self.indent = Indent::Spaces(spaces);
                        self.add_token(TokenKind::Indent);
                    }
                    Indent::Spaces(s) => {
                        let mut spaces = 0;
                        while spaces < s  && !self.is_at_end() {
                            if self.peek() != b' ' {
                                error = Err(NcclError::new(ErrorKind::IndentationError, &format!("Incorrect number of spaces: found {}, expected {}", spaces, s), self.line));
                            }
                            self.advance();
                            spaces += 1;
                        }
                        if self.is_at_end() {
                            error = Err(NcclError::new(ErrorKind::ParseError, "Expected value, found EOF", self.line));
                        }
                        self.add_token(TokenKind::Indent);
                    },
                    Indent::Tabs => { error = Err(NcclError::new(ErrorKind::IndentationError, "Expected tabs, found spaces", self.line)); }
                }
            },

            b'\t' => {
                match self.indent {
                    Indent::Neither => {
                        self.add_token(TokenKind::Indent);
                        self.indent = Indent::Tabs;
                    },
                    Indent::Tabs => {
                        self.add_token(TokenKind::Indent);
                    },
                    Indent::Spaces(_) => { error = Err(NcclError::new(ErrorKind::IndentationError, "Expected spaces, found tabs", self.line)); }
                }
            },

            b'\n' => {
                self.add_token(TokenKind::Newline);
                self.line += 1;
                if self.peek() != b' ' && self.peek() != b'\t' && self.peek() != b'#' {
                    self.indent = Indent::Neither;
                }
            },

            b'\r' => {},

            b'"' => if let Err(e) = self.string() { error = Err(e); },

            _ => if let Err(e) = self.identifier() { error = Err(e); },
        }

        error
    }

    fn identifier(&mut self) -> Result<(), NcclError> {
        loop {
            if self.peek() == b'\n' || self.peek() == b'\r' || self.is_at_end() {
                break;
            } else if self.peek() == b'#' {
                while (self.reverse() as char).is_whitespace() {
                }
                self.advance();

                let value = String::from_utf8(self.source[self.start..self.current].to_vec()).unwrap();
                self.add_token_string(TokenKind::Value, value);

                //self.newline();
                while self.advance() != b'\n' {}

                return Ok(());
            } else {
                self.advance();
            }
        }

        let value = String::from_utf8(self.source[self.start..self.current].to_vec()).unwrap();
        self.add_token_string(TokenKind::Value, value);

        Ok(())
    }

    fn string(&mut self) -> Result<(), NcclError> {
        let mut value = String::new();
        while self.peek() != b'"' && !self.is_at_end() {
            if self.peek() == b'\n' {
                self.line += 1;
            }

            if self.peek() == b'\\' {
                self.advance();
                match self.peek() {
                    b'n' => {
                        value.push('\n');
                    },
                    b'r' => {
                        value.push('\r');
                    }
                    b'\\' => {
                        value.push('\\');
                    },
                    b'"' => {
                        value.push('"');
                    },
                    b'\n' => {
                        self.advance();
                        while self.peek() == b' ' || self.peek() == b'\t' {
                            self.advance();
                        }
                        self.reverse();
                    },
                    _ => return Err(NcclError::new(ErrorKind::ParseError, &format!("Unknown format code: {}", self.peek()), self.line))
                }
            } else {
                value.push(self.source[self.current] as char);
            }

            self.advance();
        }

        if self.is_at_end() {
            return Err(NcclError::new(ErrorKind::ParseError, "Unterminated string", self.line));
        }

        self.advance();

        self.add_token_string(TokenKind::Value, value);

        while self.peek() != b'\n' {
            self.advance();
        }

        Ok(())
    }

    fn add_token(&mut self, kind: TokenKind) {
        let text = String::from_utf8(self.source[self.start..self.current].to_vec()).unwrap();
        self.tokens.push(Token::new(kind, text, self.line));
    }

    fn add_token_string(&mut self, kind: TokenKind, value: String) {
        self.tokens.push(Token::new(kind, value, self.line));
    }

    fn is_at_end(&self) -> bool {
        self.current >= self.source.len()
    }

    fn advance(&mut self) -> u8 {
        self.current += 1;
        self.source[self.current - 1]
    }

    fn reverse(&mut self) -> u8 {
        self.current -= 1;
        self.source[self.current]
    }

    fn peek(&mut self) -> u8 {
        if self.current >= self.source.len() {
            b'\0'
        } else {
            self.source[self.current]
        }
    }
}

<commit_msg>clean up<commit_after>
use token::{Token, TokenKind};
use error::{NcclError, ErrorKind};

use std::error::Error;

// ranked worst to best
enum Indent {
    Neither,
    Tabs,
    Spaces(u8),
}

pub struct Scanner {
    source: Vec<u8>,
    tokens: Vec<Token>,
    start: usize,
    current: usize,
    line: u64,
    indent: Indent,
}

impl Scanner {
    pub fn new(source: String) -> Self {
        Scanner {
            source: source.into_bytes(),
            tokens: Vec::new(),
            start: 0,
            current: 0,
            line: 1,
            indent: Indent::Neither,
        }
    }

    pub fn scan_tokens(&mut self) -> Result<Vec<Token>, Vec<Box<Error>>> {
        let mut err: Vec<Box<Error>> = vec![];

        while !self.is_at_end() {
            self.start = self.current;
            let e = self.scan_token();
            if e.is_err() {
                err.push(Box::new(e.err().unwrap()));
            }
        }

        self.tokens.push(Token::new(TokenKind::EOF, "".into(), self.line));

        if !err.is_empty() {
            Err(err)
        } else {
            Ok(self.tokens.clone())
        }
    }

    fn scan_token(&mut self) -> Result<(), NcclError> {
        let mut error = Ok(());
        match self.advance() {
            b'#' => {
                while self.peek() != b'\n' && !self.is_at_end() {
                    self.advance();
                }
            },

            b' ' => {
                match self.indent {
                    Indent::Neither => {
                        let mut spaces = 0;
                        while self.peek() == b' ' && !self.is_at_end() {
                            self.advance();
                            spaces += 1;
                        }
                        if self.is_at_end() {
                            error = Err(NcclError::new(ErrorKind::ParseError, "Expected value, found EOF", self.line));
                        }
                        self.indent = Indent::Spaces(spaces);
                        self.add_token(TokenKind::Indent);
                    }
                    Indent::Spaces(s) => {
                        let mut spaces = 0;
                        while spaces < s  && !self.is_at_end() {
                            if self.peek() != b' ' {
                                error = Err(NcclError::new(ErrorKind::IndentationError, &format!("Incorrect number of spaces: found {}, expected {}", spaces, s), self.line));
                            }
                            self.advance();
                            spaces += 1;
                        }
                        if self.is_at_end() {
                            error = Err(NcclError::new(ErrorKind::ParseError, "Expected value, found EOF", self.line));
                        }
                        self.add_token(TokenKind::Indent);
                    },
                    Indent::Tabs => { error = Err(NcclError::new(ErrorKind::IndentationError, "Expected tabs, found spaces", self.line)); }
                }
            },

            b'\t' => {
                match self.indent {
                    Indent::Neither => {
                        self.add_token(TokenKind::Indent);
                        self.indent = Indent::Tabs;
                    },
                    Indent::Tabs => {
                        self.add_token(TokenKind::Indent);
                    },
                    Indent::Spaces(_) => { error = Err(NcclError::new(ErrorKind::IndentationError, "Expected spaces, found tabs", self.line)); }
                }
            },

            b'\n' => {
                self.add_token(TokenKind::Newline);
                self.line += 1;
                if self.peek() != b' ' && self.peek() != b'\t' && self.peek() != b'#' {
                    self.indent = Indent::Neither;
                }
            },

            b'\r' => {},

            b'"' => if let Err(e) = self.string() { error = Err(e); },

            _ => if let Err(e) = self.identifier() { error = Err(e); },
        }

        error
    }

    fn identifier(&mut self) -> Result<(), NcclError> {
        loop {
            if self.peek() == b'\n' || self.peek() == b'\r' || self.is_at_end() {
                break;
            } else if self.peek() == b'#' {
                while (self.reverse() as char).is_whitespace() {
                }
                self.advance();

                let value = String::from_utf8(self.source[self.start..self.current].to_vec()).unwrap();
                self.add_token_string(TokenKind::Value, value);

                while self.advance() != b'\n' {}

                return Ok(());
            } else {
                self.advance();
            }
        }

        let value = String::from_utf8(self.source[self.start..self.current].to_vec()).unwrap();
        self.add_token_string(TokenKind::Value, value);

        Ok(())
    }

    fn string(&mut self) -> Result<(), NcclError> {
        let mut value = String::new();
        while self.peek() != b'"' && !self.is_at_end() {
            if self.peek() == b'\n' {
                self.line += 1;
            }

            if self.peek() == b'\\' {
                self.advance();
                match self.peek() {
                    b'n' => {
                        value.push('\n');
                    },
                    b'r' => {
                        value.push('\r');
                    }
                    b'\\' => {
                        value.push('\\');
                    },
                    b'"' => {
                        value.push('"');
                    },
                    b'\n' => {
                        self.advance();
                        while self.peek() == b' ' || self.peek() == b'\t' {
                            self.advance();
                        }
                        self.reverse();
                    },
                    _ => return Err(NcclError::new(ErrorKind::ParseError, &format!("Unknown format code: {}", self.peek()), self.line))
                }
            } else {
                value.push(self.source[self.current] as char);
            }

            self.advance();
        }

        if self.is_at_end() {
            return Err(NcclError::new(ErrorKind::ParseError, "Unterminated string", self.line));
        }

        self.advance();

        self.add_token_string(TokenKind::Value, value);

        while self.peek() != b'\n' {
            self.advance();
        }

        Ok(())
    }

    fn add_token(&mut self, kind: TokenKind) {
        let text = String::from_utf8(self.source[self.start..self.current].to_vec()).unwrap();
        self.tokens.push(Token::new(kind, text, self.line));
    }

    fn add_token_string(&mut self, kind: TokenKind, value: String) {
        self.tokens.push(Token::new(kind, value, self.line));
    }

    fn is_at_end(&self) -> bool {
        self.current >= self.source.len()
    }

    fn advance(&mut self) -> u8 {
        self.current += 1;
        self.source[self.current - 1]
    }

    fn reverse(&mut self) -> u8 {
        self.current -= 1;
        self.source[self.current]
    }

    fn peek(&mut self) -> u8 {
        if self.current >= self.source.len() {
            b'\0'
        } else {
            self.source[self.current]
        }
    }
}

<|endoftext|>


<commit_before>extern crate csv;
mod common;

fn train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
                data: &Vec<(u32, u32)>) -> (f32, f32) {

    let m = data.len() as f32;

    let mut sum0 = 0.0_f32;
    let mut sum1 = 0.0_f32;

    for &(miles, price) in data {

        let d = (common::estimate_price(miles, theta0, theta1) as f32 - price as f32) as f32;
        sum0 += d;
        sum1 += d * miles as f32;
    }
    // println!("m: {}, sum0: {}, sum1: {}", m, sum0, sum1);
    (learn_rate * (1_f32 / m) * sum0, learn_rate * (1_f32 / m) * sum1)
}

fn loop_train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
                     data: &Vec<(u32, u32)>) -> (f32, f32) {

    let mut theta0 = theta0;
    let mut theta1 = theta1;

    // while error > 0.03_f32 {
    for _ in 0..10_000 {

        let (tmp_theta0, tmp_theta1) = train_thetas(learn_rate, theta0, theta1, &data);

        // println!("theta0: {}, theta1: {}", theta0, theta1);
        // println!("tmp_theta0: {}, tmp_theta1: {}", tmp_theta0, tmp_theta1);

        theta0 -= tmp_theta0;
        theta1 -= tmp_theta1;
    }
    (theta0, theta1)
}

fn save_thetas(file: &str, theta0: f32, theta1: f32) {

    let mut wtr = csv::Writer::from_file(file).unwrap();

    let result = wtr.encode(("theta0", "theta1"));
    assert!(result.is_ok());

    let result = wtr.encode((theta0, theta1));
    assert!(result.is_ok());
}

// https://github.com/SiegeLord/RustGnuplot
fn main() {

    if let Some(filename) = std::env::args().nth(1) {

        let mut rdr = csv::Reader::from_file(filename).unwrap();
        let data = rdr.decode().collect::<csv::Result<Vec<(u32, u32)>>>().unwrap();

        let learn_rate = 1_E-10_f32;
        let (theta0, theta1) = (0_f32, 0_f32);

        let (trained_theta0, trained_theta1) = loop_train_thetas(learn_rate, theta0, theta1, &data);
        println!("After computation: ({}, {})", trained_theta0, trained_theta1);

        save_thetas(common::TMP_FILE_THETAS, trained_theta0, trained_theta1);
    }
    else {
        panic!("You need to specify a `csv file`. format: (miles,price)");
    }
}
<commit_msg>working good<commit_after>extern crate csv;
mod common;

fn train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
                data: &Vec<(u32, u32)>) -> (f32, f32) {

    let m = data.len() as f32;

    let mut sum0 = 0.0_f32;
    let mut sum1 = 0.0_f32;

    for &(miles, price) in data {

        let d = (common::estimate_price(miles, theta0, theta1) as f32 - price as f32) as f32;
        sum0 += d;
        sum1 += d * miles as f32;
    }
    // println!("m: {}, sum0: {}, sum1: {}", m, sum0, sum1);
    (learn_rate * (1_f32 / m) * sum0, learn_rate * (1_f32 / m) * sum1)
}

fn loop_train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
                     data: &Vec<(u32, u32)>) -> (f32, f32) {

    let mut theta0 = theta0;
    let mut theta1 = theta1;

    // while error > 0.03_f32 {
    for _ in 0..50_000 {

        let (tmp_theta0, tmp_theta1) = train_thetas(learn_rate, theta0, theta1, &data);

        // println!("theta0: {}, theta1: {}", theta0, theta1);
        // println!("tmp_theta0: {}, tmp_theta1: {}", tmp_theta0, tmp_theta1);

        theta0 -= tmp_theta0;
        theta1 -= tmp_theta1;
    }
    (theta0, theta1)
}

fn save_thetas(file: &str, theta0: f32, theta1: f32) {

    let mut wtr = csv::Writer::from_file(file).unwrap();

    let result = wtr.encode(("theta0", "theta1"));
    assert!(result.is_ok());

    let result = wtr.encode((theta0, theta1));
    assert!(result.is_ok());
}

// https://github.com/SiegeLord/RustGnuplot
fn main() {

    if let Some(filename) = std::env::args().nth(1) {

        let mut rdr = csv::Reader::from_file(filename).unwrap();
        let data = rdr.decode().collect::<csv::Result<Vec<(u32, u32)>>>().unwrap();

        let learn_rate = 1_E-10_f32;
        let (theta0, theta1) = (0_f32, 0_f32);

        let (trained_theta0, trained_theta1) = loop_train_thetas(learn_rate, theta0, theta1, &data);
        println!("After computation: ({}, {})", trained_theta0, trained_theta1);

        save_thetas(common::TMP_FILE_THETAS, trained_theta0, trained_theta1);
    }
    else {
        panic!("You need to specify a `csv file`. format: (miles,price)");
    }
}
<|endoftext|>


<commit_before>/* Copyright 2016 Torbjørn Birch Moltu
 *
 * Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
 * http://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.
 */

//! Boilerplatey error enums

extern crate core;
use self::core::fmt::{self,Display,Formatter};
#[cfg(feature="std")]
use std::error::Error;

macro_rules! description {($err:ty, $desc:expr) => {
    #[cfg(not(feature="std"))]
    impl $err {
        #[allow(missing_docs)]
        pub fn description(&self) -> &'static str {
            ($desc)(self)
        }
    }
    #[cfg(feature="std")]
    impl Error for $err {
        fn description(&self) -> &'static str {
            ($desc)(self)
        }
    }
    impl Display for $err {
        fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
            write!(fmtr, "{}", self.description())
        }
    }
}}

/// Cannot tell whether an `u16` needs an extra unit,
/// because it's a trailing surrogate itself.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub struct InvalidUtf16FirstUnit;
description!{InvalidUtf16FirstUnit, |_| "Is a trailing surrogate" }

macro_rules! simple {(#[$tydoc:meta] $err:ident  {
                          $($(#[$vardoc:meta])* ::$variant:ident => $string:expr),+,
                      } ) => {
    #[$tydoc]
    #[derive(Clone,Copy, Debug, PartialEq,Eq)]
    pub enum $err {
        $($(#[$vardoc])* $variant),*
    }
    description!{$err, |e: &$err| match *e {$($err::$variant=>$string),*} }
}}

simple!{/// Reasons why an `u32` is not a valid UTF codepoint.
    InvalidCodepoint {
        /// It's reserved for UTF-16 surrogate pairs."
        ::Utf16Reserved => "is reserved for UTF-16 surrogate pairs",
        /// It's higher than the highest codepoint (which is 0x10ffff).
        ::TooHigh => "is higher than the highest codepoint",
    }}
use self::InvalidCodepoint::*;
impl InvalidCodepoint {
    /// Get the range of values for which this error would be given.
    pub fn error_range(self) -> (u32,u32) {match self {
        Utf16Reserved => (0xd8_00, 0xdf_ff),
        TooHigh => (0x00_10_ff_ff, 0xff_ff_ff_ff),
    }}
}

simple!{/// Reasons why one or two `u16`s are not valid UTF-16, in sinking precedence.
    InvalidUtf16Tuple {
        /// The first unit is a trailing/low surrogate, which is never valid.
        ///
        /// Note that the value of a low surrogate is actually higher than a high surrogate.
        ::FirstIsTrailingSurrogate => "the first unit is a trailing / low surrogate, which is never valid",
        /// You provided a second unit, but the first one stands on its own.
        ::SuperfluousSecond => "the second unit is superfluous",
        /// The first and only unit requires a second unit.
        ::MissingSecond => "the first unit requires a second unit",
        /// The first unit requires a second unit, but it's not a trailing/low surrogate.
        ///
        /// Note that the value of a low surrogate is actually higher than a high surrogate.
        ::InvalidSecond => "the required second unit is not a trailing / low surrogate",
    }}

simple!{/// Reasons why a slice of `u16`s doesn't start with valid UTF-16.
    InvalidUtf16Slice {
        /// The slice is empty.
        ::EmptySlice => "the slice is empty",
        /// The first unit is a low surrogate.
        ::FirstLowSurrogate => "the first unit is a trailing surrogate",
        /// The first and only unit requires a second unit.
        ::MissingSecond => "the first and only unit requires a second one",
        /// The first unit requires a second one, but it's not a trailing surrogate.
        ::SecondNotLowSurrogate => "the required second unit is not a trailing surrogate",
    }}

/// Cannot create an `Utf8Char` for the first codepoint of a str,
/// because there are none.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub struct EmptyStrError;
description!{EmptyStrError, |_| "Is empty" }

simple!{/// Reasons why `Utf8Char::from_str()` failed.
    FromStrError {
        /// `Utf8Char` cannot store more than a single codepoint.
        ::MultipleCodepoints => "has more than one codepoint",
        /// `Utf8Char` cannot be empty.
        ::Empty => "is empty",
    }}

simple!{/// Reasons why a byte is not the start of a UTF-8 codepoint.
    InvalidUtf8FirstByte {
        /// Sequences cannot be longer than 4 bytes. Is given for values >= 240.
        ::TooLongSeqence => "is greater than 247 (UTF-8 sequences cannot be longer than four bytes)",
        /// This byte belongs to a previous sequence. Is given for values between 128 and 192 (exclusive).
        ::ContinuationByte => "is a continuation of a previous sequence",
    }}
use self::InvalidUtf8FirstByte::*;

macro_rules! complex {
($err:ty
 {$($sub:ty => $to:expr,)*}
 {$($desc:pat => $string:expr),+,}
 => $use_cause:expr =>
 {$($cause:pat => $result:expr),+,} $(#[$causedoc:meta])*
) => {
    $(impl From<$sub> for $err {
          fn from(error: $sub) -> $err {
              $to(error)
          }
      })*
    #[cfg(not(feature="std"))]
    impl $err {
        #[allow(missing_docs)]
        pub fn description(&self) -> &'static str {
            match *self{ $($desc => $string,)* }
        }
        /// A hack to avoid two Display impls
        fn cause(&self) -> Option<&Display> {None}
    }
    #[cfg(feature="std")]
    impl Error for $err {
        fn description(&self) -> &'static str {
            match *self{ $($desc => $string,)* }
        }
        $(#[$causedoc])*
        fn cause(&self) -> Option<&Error> {
            match *self{ $($cause => $result,)* }
        }
    }
    impl Display for $err {
        fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
            match (self.cause(), $use_cause) {
                (Some(d),true) => write!(fmtr, "{}: {}", self.description(), d),
                        _      => write!(fmtr, "{}", self.description()),
            }
        }
    }
}}

/// Reasons why a byte sequence is not valid UTF-8, excluding invalid codepoint.
/// In sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8 {
    /// Something is wrong with the first byte.
    FirstByte(InvalidUtf8FirstByte),
    /// Thee byte at index 1...3 should be a continuation byte,
    /// but dosesn't fit the pattern 0b10xx_xxxx.
    NotAContinuationByte(usize),
    /// There are too many leading zeros: it could be a byte shorter.
    ///
    /// [Decoding this could allow someone to input otherwise prohibited
    /// characters and sequences, such as "../"](https://tools.ietf.org/html/rfc3629#section-10).
    OverLong,
}
use self::InvalidUtf8::*;
complex!{InvalidUtf8 {
        InvalidUtf8FirstByte => FirstByte,
    } {
        FirstByte(TooLongSeqence) => "the first byte is greater than 239 (UTF-8 sequences cannot be longer than four bytes)",
        FirstByte(ContinuationByte) => "the first byte is a continuation of a previous sequence",
        OverLong => "the sequence contains too many zeros and could be shorter",
        NotAContinuationByte(_) => "the sequence is too short",
    } => false => {
        FirstByte(ref cause) => Some(cause),
        _ => None,
    }/// Returns `Some` if the error is a `InvalidUtf8FirstByte`.
}

/// Reasons why a byte array is not valid UTF-8, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8Array {
    /// Not a valid UTF-8 sequence.
    Utf8(InvalidUtf8),
    /// Not a valid unicode codepoint.
    Codepoint(InvalidCodepoint),
}
complex!{InvalidUtf8Array {
        InvalidUtf8 => InvalidUtf8Array::Utf8,
        InvalidCodepoint => InvalidUtf8Array::Codepoint,
    } {
        InvalidUtf8Array::Utf8(_) => "the sequence is invalid UTF-8",
        InvalidUtf8Array::Codepoint(_) => "the encoded codepoint is invalid",
    } => true => {
        InvalidUtf8Array::Utf8(ref u) => Some(u),
        InvalidUtf8Array::Codepoint(ref c) => Some(c),
    }/// Always returns `Some`.
}

/// Reasons why a byte slice is not valid UTF-8, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8Slice {
    /// Something is certainly wrong with the first byte.
    Utf8(InvalidUtf8),
    /// The encoded codepoint is invalid:
    Codepoint(InvalidCodepoint),
    /// The slice is too short; n bytes was required.
    TooShort(usize),
}
complex!{InvalidUtf8Slice {
        InvalidUtf8 => InvalidUtf8Slice::Utf8,
        InvalidCodepoint => InvalidUtf8Slice::Codepoint,
    } {
        InvalidUtf8Slice::Utf8(_) => "the sequence is invalid UTF-8",
        InvalidUtf8Slice::Codepoint(_) => "the encoded codepoint is invalid",
        InvalidUtf8Slice::TooShort(0) => "the slice is empty",
        InvalidUtf8Slice::TooShort(_) => "the slice is shorter than the sequence",
    } => true => {
        InvalidUtf8Slice::Utf8(ref u) => Some(u),
        InvalidUtf8Slice::Codepoint(ref c) => Some(c),
        InvalidUtf8Slice::TooShort(_) => None,
    }
}
<commit_msg>Fix another typo in error docs<commit_after>/* Copyright 2016 Torbjørn Birch Moltu
 *
 * Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
 * http://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.
 */

//! Boilerplatey error enums

extern crate core;
use self::core::fmt::{self,Display,Formatter};
#[cfg(feature="std")]
use std::error::Error;

macro_rules! description {($err:ty, $desc:expr) => {
    #[cfg(not(feature="std"))]
    impl $err {
        #[allow(missing_docs)]
        pub fn description(&self) -> &'static str {
            ($desc)(self)
        }
    }
    #[cfg(feature="std")]
    impl Error for $err {
        fn description(&self) -> &'static str {
            ($desc)(self)
        }
    }
    impl Display for $err {
        fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
            write!(fmtr, "{}", self.description())
        }
    }
}}

/// Cannot tell whether an `u16` needs an extra unit,
/// because it's a trailing surrogate itself.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub struct InvalidUtf16FirstUnit;
description!{InvalidUtf16FirstUnit, |_| "Is a trailing surrogate" }

macro_rules! simple {(#[$tydoc:meta] $err:ident  {
                          $($(#[$vardoc:meta])* ::$variant:ident => $string:expr),+,
                      } ) => {
    #[$tydoc]
    #[derive(Clone,Copy, Debug, PartialEq,Eq)]
    pub enum $err {
        $($(#[$vardoc])* $variant),*
    }
    description!{$err, |e: &$err| match *e {$($err::$variant=>$string),*} }
}}

simple!{/// Reasons why an `u32` is not a valid UTF codepoint.
    InvalidCodepoint {
        /// It's reserved for UTF-16 surrogate pairs."
        ::Utf16Reserved => "is reserved for UTF-16 surrogate pairs",
        /// It's higher than the highest codepoint (which is 0x10ffff).
        ::TooHigh => "is higher than the highest codepoint",
    }}
use self::InvalidCodepoint::*;
impl InvalidCodepoint {
    /// Get the range of values for which this error would be given.
    pub fn error_range(self) -> (u32,u32) {match self {
        Utf16Reserved => (0xd8_00, 0xdf_ff),
        TooHigh => (0x00_10_ff_ff, 0xff_ff_ff_ff),
    }}
}

simple!{/// Reasons why one or two `u16`s are not valid UTF-16, in sinking precedence.
    InvalidUtf16Tuple {
        /// The first unit is a trailing/low surrogate, which is never valid.
        ///
        /// Note that the value of a low surrogate is actually higher than a high surrogate.
        ::FirstIsTrailingSurrogate => "the first unit is a trailing / low surrogate, which is never valid",
        /// You provided a second unit, but the first one stands on its own.
        ::SuperfluousSecond => "the second unit is superfluous",
        /// The first and only unit requires a second unit.
        ::MissingSecond => "the first unit requires a second unit",
        /// The first unit requires a second unit, but it's not a trailing/low surrogate.
        ///
        /// Note that the value of a low surrogate is actually higher than a high surrogate.
        ::InvalidSecond => "the required second unit is not a trailing / low surrogate",
    }}

simple!{/// Reasons why a slice of `u16`s doesn't start with valid UTF-16.
    InvalidUtf16Slice {
        /// The slice is empty.
        ::EmptySlice => "the slice is empty",
        /// The first unit is a low surrogate.
        ::FirstLowSurrogate => "the first unit is a trailing surrogate",
        /// The first and only unit requires a second unit.
        ::MissingSecond => "the first and only unit requires a second one",
        /// The first unit requires a second one, but it's not a trailing surrogate.
        ::SecondNotLowSurrogate => "the required second unit is not a trailing surrogate",
    }}

/// Cannot create an `Utf8Char` for the first codepoint of a str,
/// because there are none.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub struct EmptyStrError;
description!{EmptyStrError, |_| "Is empty" }

simple!{/// Reasons why `Utf8Char::from_str()` failed.
    FromStrError {
        /// `Utf8Char` cannot store more than a single codepoint.
        ::MultipleCodepoints => "has more than one codepoint",
        /// `Utf8Char` cannot be empty.
        ::Empty => "is empty",
    }}

simple!{/// Reasons why a byte is not the start of a UTF-8 codepoint.
    InvalidUtf8FirstByte {
        /// Sequences cannot be longer than 4 bytes. Is given for values >= 240.
        ::TooLongSeqence => "is greater than 247 (UTF-8 sequences cannot be longer than four bytes)",
        /// This byte belongs to a previous sequence. Is given for values between 128 and 192 (exclusive).
        ::ContinuationByte => "is a continuation of a previous sequence",
    }}
use self::InvalidUtf8FirstByte::*;

macro_rules! complex {
($err:ty
 {$($sub:ty => $to:expr,)*}
 {$($desc:pat => $string:expr),+,}
 => $use_cause:expr =>
 {$($cause:pat => $result:expr),+,} $(#[$causedoc:meta])*
) => {
    $(impl From<$sub> for $err {
          fn from(error: $sub) -> $err {
              $to(error)
          }
      })*
    #[cfg(not(feature="std"))]
    impl $err {
        #[allow(missing_docs)]
        pub fn description(&self) -> &'static str {
            match *self{ $($desc => $string,)* }
        }
        /// A hack to avoid two Display impls
        fn cause(&self) -> Option<&Display> {None}
    }
    #[cfg(feature="std")]
    impl Error for $err {
        fn description(&self) -> &'static str {
            match *self{ $($desc => $string,)* }
        }
        $(#[$causedoc])*
        fn cause(&self) -> Option<&Error> {
            match *self{ $($cause => $result,)* }
        }
    }
    impl Display for $err {
        fn fmt(&self,  fmtr: &mut Formatter) -> fmt::Result {
            match (self.cause(), $use_cause) {
                (Some(d),true) => write!(fmtr, "{}: {}", self.description(), d),
                        _      => write!(fmtr, "{}", self.description()),
            }
        }
    }
}}

/// Reasons why a byte sequence is not valid UTF-8, excluding invalid codepoint.
/// In sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8 {
    /// Something is wrong with the first byte.
    FirstByte(InvalidUtf8FirstByte),
    /// The byte at index 1...3 should be a continuation byte,
    /// but dosesn't fit the pattern 0b10xx_xxxx.
    NotAContinuationByte(usize),
    /// There are too many leading zeros: it could be a byte shorter.
    ///
    /// [Decoding this could allow someone to input otherwise prohibited
    /// characters and sequences, such as "../"](https://tools.ietf.org/html/rfc3629#section-10).
    OverLong,
}
use self::InvalidUtf8::*;
complex!{InvalidUtf8 {
        InvalidUtf8FirstByte => FirstByte,
    } {
        FirstByte(TooLongSeqence) => "the first byte is greater than 239 (UTF-8 sequences cannot be longer than four bytes)",
        FirstByte(ContinuationByte) => "the first byte is a continuation of a previous sequence",
        OverLong => "the sequence contains too many zeros and could be shorter",
        NotAContinuationByte(_) => "the sequence is too short",
    } => false => {
        FirstByte(ref cause) => Some(cause),
        _ => None,
    }/// Returns `Some` if the error is a `InvalidUtf8FirstByte`.
}

/// Reasons why a byte array is not valid UTF-8, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8Array {
    /// Not a valid UTF-8 sequence.
    Utf8(InvalidUtf8),
    /// Not a valid unicode codepoint.
    Codepoint(InvalidCodepoint),
}
complex!{InvalidUtf8Array {
        InvalidUtf8 => InvalidUtf8Array::Utf8,
        InvalidCodepoint => InvalidUtf8Array::Codepoint,
    } {
        InvalidUtf8Array::Utf8(_) => "the sequence is invalid UTF-8",
        InvalidUtf8Array::Codepoint(_) => "the encoded codepoint is invalid",
    } => true => {
        InvalidUtf8Array::Utf8(ref u) => Some(u),
        InvalidUtf8Array::Codepoint(ref c) => Some(c),
    }/// Always returns `Some`.
}

/// Reasons why a byte slice is not valid UTF-8, in sinking precedence.
#[derive(Clone,Copy, Debug, PartialEq,Eq)]
pub enum InvalidUtf8Slice {
    /// Something is certainly wrong with the first byte.
    Utf8(InvalidUtf8),
    /// The encoded codepoint is invalid:
    Codepoint(InvalidCodepoint),
    /// The slice is too short; n bytes was required.
    TooShort(usize),
}
complex!{InvalidUtf8Slice {
        InvalidUtf8 => InvalidUtf8Slice::Utf8,
        InvalidCodepoint => InvalidUtf8Slice::Codepoint,
    } {
        InvalidUtf8Slice::Utf8(_) => "the sequence is invalid UTF-8",
        InvalidUtf8Slice::Codepoint(_) => "the encoded codepoint is invalid",
        InvalidUtf8Slice::TooShort(0) => "the slice is empty",
        InvalidUtf8Slice::TooShort(_) => "the slice is shorter than the sequence",
    } => true => {
        InvalidUtf8Slice::Utf8(ref u) => Some(u),
        InvalidUtf8Slice::Codepoint(ref c) => Some(c),
        InvalidUtf8Slice::TooShort(_) => None,
    }
}
<|endoftext|>


<commit_before>//! Common filesystem errors.
//!
//! This module provides convenience functions for generating [`io::Error`]s from OS error codes.
//! Notably, these errors are the only errors returned in the [`mem`] module if using implemented
//! behavior (unimplemented behavior returns `Error::new::ErrorKind::Other`).
//!
//! [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
//! [`mem`]: ../mem/index.html

use std::io::Error;

/// Used when a file or directory does not exist.
#[allow(non_snake_case)]
pub fn ENOENT() -> Error {
    Error::from_raw_os_error(2)
}

/// Used when performing an operation with a file that was not opened in a way to allow that
/// operation (read on a write only open, etc).
#[allow(non_snake_case)]
pub fn EBADF() -> Error {
    Error::from_raw_os_error(9)
}

/// Used when a user does not have requisite permissions.
#[allow(non_snake_case)]
pub fn EACCES() -> Error {
    Error::from_raw_os_error(13)
}

/// Used when a file or directory does not exist.
#[allow(non_snake_case)]
pub fn EEXIST() -> Error {
    Error::from_raw_os_error(17)
}

/// Used when attempting to perform a directory operation on a file.
#[allow(non_snake_case)]
pub fn ENOTDIR() -> Error {
    Error::from_raw_os_error(20)
}

/// Used when attempting to perform a file operation on a directory.
#[allow(non_snake_case)]
pub fn EISDIR() -> Error {
    Error::from_raw_os_error(21)
}

/// Used when performing an invalid operation (aka, a bad `OpenOptions` combination).
#[allow(non_snake_case)]
pub fn EINVAL() -> Error {
    Error::from_raw_os_error(22)
}

/// Used when an operation needs an empty directory and is performed on a non-empty directory.
#[allow(non_snake_case)]
pub fn ENOTEMPTY() -> Error {
    // TODO Windows is 41, other Unix / BSD distros differ from 39.
    Error::from_raw_os_error(39)
}
<commit_msg>errors: add ELOOP and EBUSY<commit_after>//! Common filesystem errors.
//!
//! This module provides convenience functions for generating [`io::Error`]s from OS error codes.
//! Notably, these errors are the only errors returned in the [`mem`] module if using implemented
//! behavior (unimplemented behavior returns `Error::new::ErrorKind::Other`).
//!
//! [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html
//! [`mem`]: ../mem/index.html

use std::io::Error;

/// Used when a file or directory does not exist.
#[allow(non_snake_case)]
pub fn ENOENT() -> Error {
    Error::from_raw_os_error(2)
}

/// Used when performing an operation with a file that was not opened in a way to allow that
/// operation (read on a write only open, etc).
#[allow(non_snake_case)]
pub fn EBADF() -> Error {
    Error::from_raw_os_error(9)
}

/// Used when a user does not have requisite permissions.
#[allow(non_snake_case)]
pub fn EACCES() -> Error {
    Error::from_raw_os_error(13)
}

/// Used when trying to modify something that is actively performing an operation.
#[allow(non_snake_case)]
pub fn EBUSY() -> Error {
    Error::from_raw_os_error(16)
}

/// Used when a file or directory does not exist.
#[allow(non_snake_case)]
pub fn EEXIST() -> Error {
    Error::from_raw_os_error(17)
}

/// Used when attempting to perform a directory operation on a file.
#[allow(non_snake_case)]
pub fn ENOTDIR() -> Error {
    Error::from_raw_os_error(20)
}

/// Used when attempting to perform a file operation on a directory.
#[allow(non_snake_case)]
pub fn EISDIR() -> Error {
    Error::from_raw_os_error(21)
}

/// Used when performing an invalid operation (aka, a bad `OpenOptions` combination).
#[allow(non_snake_case)]
pub fn EINVAL() -> Error {
    Error::from_raw_os_error(22)
}

/// Used when an operation needs an empty directory and is performed on a non-empty directory.
#[allow(non_snake_case)]
pub fn ENOTEMPTY() -> Error {
    // TODO Windows is 41, other Unix / BSD distros differ from 39.
    Error::from_raw_os_error(39)
}

/// Used when traversing too many symlinks.
#[allow(non_snake_case)]
pub fn ELOOP() -> Error {
    Error::from_raw_os_error(40)
}
<|endoftext|>


<commit_before>/*!
 * Bounded package merge algorithm, based on the paper
 * "A Fast and Space-Economical Algorithm for Length-Limited Coding
 * Jyrki Katajainen, Alistair Moffat, Andrew Turpin".
 */

use std::mem;
use std::ptr::{null, null_mut};

use libc::{c_void, size_t};
use libc::funcs::c95::stdlib::{free, malloc};

/// Nodes forming chains. Also used to represent leaves.
struct Node {
    /// Total weight (symbol count) of this chain.
    weight: usize,
    /// Previous node(s) of this chain, or 0 if none.
    tail: *mut Node,
    /// Leaf symbol index, or number of leaves before this chain.
    count: i32,
    /// Tracking for garbage collection.
    in_use: bool,
}

/// Memory pool for nodes.
struct NodePool {
    /// The pool.
    nodes: *mut Node,
    /// Pointer to a possibly free node in the pool.
    next: *mut Node,
    /// Size of the memory pool.
    size: u32,
}

/// Initializes a chain node with the given values and marks it as in use.
unsafe fn init_node(weight: usize, count: i32, tail: *mut Node, node: *mut Node) {
    (*node).weight = weight;
    (*node).count = count;
    (*node).tail = tail;
    (*node).in_use = true;
}

/**
 * Finds a free location in the memory pool. Performs garbage collection if needed.
 * lists: If given, used to mark in-use nodes during garbage collection.
 * maxbits: Size of lists.
 * pool: Memory pool to get free node from.
 */
unsafe fn get_free_node(lists: *const *mut *mut Node, maxbits: i32, pool: *mut NodePool) -> *mut Node {
    loop {
        if (*pool).next >= (*pool).nodes.offset((*pool).size as isize) {
            // Garbage collection
            for i in 0..(*pool).size {
                (*(*pool).nodes.offset(i as isize)).in_use = false;
            }
            if !lists.is_null() {
                for i in 0..maxbits*2 {
                    let mut node = *(*lists.offset((i / 2) as isize)).offset((i % 2) as isize);
                    while !node.is_null() {
                        (*node).in_use = true;
                        node = (*node).tail;
                    }
                }
            }
            (*pool).next = (*pool).nodes;
        }
        if !(*(*pool).next).in_use {
            break;
        }
        (*pool).next = (*pool).next.offset(1);
    }
    let free_node = (*pool).next;
    (*pool).next = (*pool).next.offset(1);
    free_node
}

/**
 * Performs a Boundary Package-Merge step. Puts a new chain in the given list. The
 * new chain is, depending on the weights, a leaf or a combination of two chains
 * from the previous list.
 * lists: The lists of chains.
 * maxbits: Number of lists.
 * leaves: The leaves, one per symbol.
 * numsymbols: Number of leaves.
 * pool: the node memory pool.
 * index: The index of the list in which a new chain or leaf is required.
 * final: Whether this is the last time this function is called. If it is then it
 *   is no more needed to recursively call self.
 */
unsafe fn boundary_pm(lists: *const *mut *mut Node, maxbits: i32, leaves: *const Node, numsymbols: i32, pool: *mut NodePool,
                      index: i32, is_final: bool) {
    let lastcount = (**(*lists.offset(index as isize)).offset(1)).count; // Count of last chain of list.

    if index == 0 && lastcount >= numsymbols {
        return;
    }

    let newchain = get_free_node(lists, maxbits, pool);
    let oldchain = *(*lists.offset(index as isize)).offset(1);

    // These are set up before the recursive calls below, so that there is a list
    // pointing to the new node, to let the garbage collection know it's in use.
    *(*lists.offset(index as isize)).offset(0) = oldchain;
    *(*lists.offset(index as isize)).offset(1) = newchain;

    if index == 0 {
        //New leaf node in list 0.
        init_node((*leaves.offset(lastcount as isize)).weight, lastcount + 1, null_mut(), newchain);
    } else {
        let sum = (**(*lists.offset((index - 1) as isize)).offset(0)).weight + (**(*lists.offset((index - 1) as isize)).offset(0)).weight;
        if lastcount < numsymbols && sum > (*leaves.offset(lastcount as isize)).weight {
            // New leaf inserted in list, so count is incremented.
            init_node((*leaves.offset(lastcount as isize)).weight, lastcount + 1, (*oldchain).tail, newchain);
        } else {
            init_node(sum, lastcount, *(*lists.offset((index - 1) as isize)).offset(1), newchain);
            if !is_final {
                // Two lookahead chains of previous list used up, create new ones.
                boundary_pm(lists, maxbits, leaves, numsymbols, pool, index - 1, false);
                boundary_pm(lists, maxbits, leaves, numsymbols, pool, index - 1, false);
            }
        }
    }
}

/// Initializes each list with as lookahead chains the two leaves with lowest weights.
unsafe fn init_lists(pool: *mut NodePool, leaves: *const Node, maxbits: i32, lists: *const *mut *mut Node) {
    let node0 = get_free_node(null(), maxbits, pool);
    let node1 = get_free_node(null(), maxbits, pool);
    init_node((*leaves.offset(0)).weight, 1, null_mut(), node0);
    init_node((*leaves.offset(1)).weight, 2, null_mut(), node1);
    for i in 0..maxbits {
        *(*lists.offset(i as isize)).offset(0) = node0;
        *(*lists.offset(i as isize)).offset(1) = node1;
    }
}

/**
 * Converts result of boundary package-merge to the bitlengths. The result in the
 * last chain of the last list contains the amount of active leaves in each list.
 * chain: Chain to extract the bit length from (last chain from last list).
 */
unsafe fn extract_bit_lengths(chain: *const Node, leaves: *const Node, bitlengths: *mut u32) {
    let mut node = chain;
    while node != null() {
        for i in 0..(*node).count {
            *bitlengths.offset((*leaves.offset(i as isize)).count as isize) = *bitlengths.offset((*leaves.offset(i as isize)).count as isize) + 1;
        }
        node = (*node).tail;
    }
}

/// Comparator for sorting the leaves. Has the function signature for qsort.
extern fn leaf_comparator(a: *const c_void, b: *const c_void) -> i32 {
    unsafe {
        let node_a: *const Node = a as *const Node;
        let node_b: *const Node = b as *const Node;
        (*node_a).weight as i32 - (*node_b).weight as i32
    }
}

#[link(name="c")]
extern {
    fn qsort(base: *mut c_void, nmemb: size_t, size: size_t, compar: extern fn(*const c_void, *const c_void) -> i32);
}

pub unsafe fn length_limited_code_lengths(frequencies: *const usize, n: i32, maxbits: i32, bitlengths: *mut u32) -> bool {
    // Amount of symbols with frequency > 0.
    let mut numsymbols = 0;

    // One leaf per symbol. Only numsymbols leaves will be used.
    let leaves: *mut Node = malloc((n as usize * mem::size_of::<Node>()) as size_t) as *mut Node;

    // Initialize all bitlengths at 0.
    for i in 0..n {
        *bitlengths.offset(i as isize) = 0;
    }

    // Count used symbols and place them in the leaves.
    for i in 0..n {
        if *frequencies.offset(i as isize) != 0 {
            (*leaves.offset(numsymbols)).weight = *frequencies.offset(i as isize);
            (*leaves.offset(numsymbols)).count = i; // Index of symbol this leaf represents.
            numsymbols += 1;
        }
    }

    // Check special cases and error conditions.
    if (1 << maxbits) < numsymbols {
        free(leaves as *mut c_void);
        return true; // Error, too few maxbits to represent symbols.
    }
    if numsymbols == 0 {
        free(leaves as *mut c_void);
        return false; // No symbols at all. OK.
    }
    if numsymbols == 1 {
        *bitlengths.offset((*leaves.offset(0)).count as isize) = 1;
        free(leaves as *mut c_void);
        return false; // Only one symbol, give it bitlength 1, not 0. OK.
    }

    // Sort the leaves from lightest to heaviest.
    qsort(leaves as *mut c_void, numsymbols as size_t, mem::size_of::<Node>() as size_t, leaf_comparator);

    // Initialize node memory pool.
    let pool_size = 2 * maxbits * (maxbits + 1);
    let pool_nodes = malloc((pool_size as usize * mem::size_of::<Node>()) as size_t) as *mut Node;
    let mut pool = NodePool { size: pool_size as u32, nodes: pool_nodes, next: pool_nodes };
    for i in 0..pool.size {
        (*pool.nodes.offset(i as isize)).in_use = false;
    }

    // Array of lists of chains. Each list requires only two lookahead chains at
    // a time, so each list is a array of two Node*'s.
    let lists: *const *mut *mut Node = malloc((maxbits as usize * mem::size_of::<*const *const Node>()) as size_t) as *const *mut *mut Node;
    init_lists(&mut pool, leaves, maxbits, lists);

    // In the last list, 2 * numsymbols - 2 active chains need to be created. Two
    // are already created in the initialization. Each BoundaryPM run creates one.
    let num_boundary_pm_runs = 2 * numsymbols - 4;
    for i in 0..num_boundary_pm_runs {
        let is_final = i == num_boundary_pm_runs - 1;
        boundary_pm(lists, maxbits, leaves, numsymbols as i32, &mut pool, maxbits - 1, is_final);
    }

    extract_bit_lengths(*(*lists.offset(maxbits as isize - 1)).offset(1), leaves, bitlengths);

    free(lists as *mut c_void);
    free(leaves as *mut c_void);
    free(pool.nodes as *mut c_void);
    false
}

#[cfg(test)]
mod tests {
    use std::mem::size_of;
    use libc::{c_void, size_t};

    use super::qsort;

    extern fn comparator(a: *const c_void, b: *const c_void) -> i32 {
        unsafe {
            *(a as *const i32) - *(b as *const i32)
        }
    }

    #[test]
    fn test_qsort() {
        unsafe {
            let mut a: [i32; 5] = [3, 2, 4, 1, 5];
            qsort(a.as_mut_ptr() as *mut c_void, a.len() as size_t, size_of::<i32>() as size_t, comparator);
            assert_eq!(a, [1, 2, 3, 4, 5]);
        }
    }
}
<commit_msg>Fix allocation of "lists"<commit_after>/*!
 * Bounded package merge algorithm, based on the paper
 * "A Fast and Space-Economical Algorithm for Length-Limited Coding
 * Jyrki Katajainen, Alistair Moffat, Andrew Turpin".
 */

use std::mem;
use std::ptr::{null, null_mut};

use libc::{c_void, size_t};
use libc::funcs::c95::stdlib::{free, malloc};

/// Nodes forming chains. Also used to represent leaves.
struct Node {
    /// Total weight (symbol count) of this chain.
    weight: usize,
    /// Previous node(s) of this chain, or 0 if none.
    tail: *mut Node,
    /// Leaf symbol index, or number of leaves before this chain.
    count: i32,
    /// Tracking for garbage collection.
    in_use: bool,
}

/// Memory pool for nodes.
struct NodePool {
    /// The pool.
    nodes: *mut Node,
    /// Pointer to a possibly free node in the pool.
    next: *mut Node,
    /// Size of the memory pool.
    size: u32,
}

/// Initializes a chain node with the given values and marks it as in use.
unsafe fn init_node(weight: usize, count: i32, tail: *mut Node, node: *mut Node) {
    (*node).weight = weight;
    (*node).count = count;
    (*node).tail = tail;
    (*node).in_use = true;
}

/**
 * Finds a free location in the memory pool. Performs garbage collection if needed.
 * lists: If given, used to mark in-use nodes during garbage collection.
 * maxbits: Size of lists.
 * pool: Memory pool to get free node from.
 */
unsafe fn get_free_node(lists: *const [*mut Node; 2], maxbits: i32, pool: *mut NodePool) -> *mut Node {
    loop {
        if (*pool).next >= (*pool).nodes.offset((*pool).size as isize) {
            // Garbage collection
            for i in 0..(*pool).size {
                (*(*pool).nodes.offset(i as isize)).in_use = false;
            }
            if !lists.is_null() {
                for i in 0..maxbits*2 {
                    let mut node = (*lists.offset((i / 2) as isize))[(i % 2) as usize];
                    while !node.is_null() {
                        (*node).in_use = true;
                        node = (*node).tail;
                    }
                }
            }
            (*pool).next = (*pool).nodes;
        }
        if !(*(*pool).next).in_use {
            break;
        }
        (*pool).next = (*pool).next.offset(1);
    }
    let free_node = (*pool).next;
    (*pool).next = (*pool).next.offset(1);
    free_node
}

/**
 * Performs a Boundary Package-Merge step. Puts a new chain in the given list. The
 * new chain is, depending on the weights, a leaf or a combination of two chains
 * from the previous list.
 * lists: The lists of chains.
 * maxbits: Number of lists.
 * leaves: The leaves, one per symbol.
 * numsymbols: Number of leaves.
 * pool: the node memory pool.
 * index: The index of the list in which a new chain or leaf is required.
 * final: Whether this is the last time this function is called. If it is then it
 *   is no more needed to recursively call self.
 */
unsafe fn boundary_pm(lists: *mut [*mut Node; 2], maxbits: i32, leaves: *const Node, numsymbols: i32, pool: *mut NodePool,
                      index: i32, is_final: bool) {
    let lastcount = (*(*lists.offset(index as isize))[1]).count; // Count of last chain of list.

    if index == 0 && lastcount >= numsymbols {
        return;
    }

    let newchain = get_free_node(lists, maxbits, pool);
    let oldchain = (*lists.offset(index as isize))[1];

    // These are set up before the recursive calls below, so that there is a list
    // pointing to the new node, to let the garbage collection know it's in use.
    (*lists.offset(index as isize))[0] = oldchain;
    (*lists.offset(index as isize))[1] = newchain;

    if index == 0 {
        //New leaf node in list 0.
        init_node((*leaves.offset(lastcount as isize)).weight, lastcount + 1, null_mut(), newchain);
    } else {
        let sum = (*(*lists.offset((index - 1) as isize))[0]).weight + (*(*lists.offset((index - 1) as isize))[0]).weight;
        if lastcount < numsymbols && sum > (*leaves.offset(lastcount as isize)).weight {
            // New leaf inserted in list, so count is incremented.
            init_node((*leaves.offset(lastcount as isize)).weight, lastcount + 1, (*oldchain).tail, newchain);
        } else {
            init_node(sum, lastcount, (*lists.offset((index - 1) as isize))[1], newchain);
            if !is_final {
                // Two lookahead chains of previous list used up, create new ones.
                boundary_pm(lists, maxbits, leaves, numsymbols, pool, index - 1, false);
                boundary_pm(lists, maxbits, leaves, numsymbols, pool, index - 1, false);
            }
        }
    }
}

/// Initializes each list with as lookahead chains the two leaves with lowest weights.
unsafe fn init_lists(pool: *mut NodePool, leaves: *const Node, maxbits: i32, lists: *mut [*mut Node; 2]) {
    let node0 = get_free_node(null(), maxbits, pool);
    let node1 = get_free_node(null(), maxbits, pool);
    init_node((*leaves.offset(0)).weight, 1, null_mut(), node0);
    init_node((*leaves.offset(1)).weight, 2, null_mut(), node1);
    for i in 0..maxbits {
        (*lists.offset(i as isize))[0] = node0;
        (*lists.offset(i as isize))[1] = node1;
    }
}

/**
 * Converts result of boundary package-merge to the bitlengths. The result in the
 * last chain of the last list contains the amount of active leaves in each list.
 * chain: Chain to extract the bit length from (last chain from last list).
 */
unsafe fn extract_bit_lengths(chain: *const Node, leaves: *const Node, bitlengths: *mut u32) {
    let mut node = chain;
    while node != null() {
        for i in 0..(*node).count {
            *bitlengths.offset((*leaves.offset(i as isize)).count as isize) = *bitlengths.offset((*leaves.offset(i as isize)).count as isize) + 1;
        }
        node = (*node).tail;
    }
}

/// Comparator for sorting the leaves. Has the function signature for qsort.
extern fn leaf_comparator(a: *const c_void, b: *const c_void) -> i32 {
    unsafe {
        let node_a: *const Node = a as *const Node;
        let node_b: *const Node = b as *const Node;
        (*node_a).weight as i32 - (*node_b).weight as i32
    }
}

#[link(name="c")]
extern {
    fn qsort(base: *mut c_void, nmemb: size_t, size: size_t, compar: extern fn(*const c_void, *const c_void) -> i32);
}

pub unsafe fn length_limited_code_lengths(frequencies: *const usize, n: i32, maxbits: i32, bitlengths: *mut u32) -> bool {
    // Amount of symbols with frequency > 0.
    let mut numsymbols = 0;

    // One leaf per symbol. Only numsymbols leaves will be used.
    let leaves: *mut Node = malloc((n as usize * mem::size_of::<Node>()) as size_t) as *mut Node;

    // Initialize all bitlengths at 0.
    for i in 0..n {
        *bitlengths.offset(i as isize) = 0;
    }

    // Count used symbols and place them in the leaves.
    for i in 0..n {
        if *frequencies.offset(i as isize) != 0 {
            (*leaves.offset(numsymbols)).weight = *frequencies.offset(i as isize);
            (*leaves.offset(numsymbols)).count = i; // Index of symbol this leaf represents.
            numsymbols += 1;
        }
    }

    // Check special cases and error conditions.
    if (1 << maxbits) < numsymbols {
        free(leaves as *mut c_void);
        return true; // Error, too few maxbits to represent symbols.
    }
    if numsymbols == 0 {
        free(leaves as *mut c_void);
        return false; // No symbols at all. OK.
    }
    if numsymbols == 1 {
        *bitlengths.offset((*leaves.offset(0)).count as isize) = 1;
        free(leaves as *mut c_void);
        return false; // Only one symbol, give it bitlength 1, not 0. OK.
    }

    // Sort the leaves from lightest to heaviest.
    qsort(leaves as *mut c_void, numsymbols as size_t, mem::size_of::<Node>() as size_t, leaf_comparator);

    // Initialize node memory pool.
    let pool_size = 2 * maxbits * (maxbits + 1);
    let pool_nodes = malloc((pool_size as usize * mem::size_of::<Node>()) as size_t) as *mut Node;
    let mut pool = NodePool { size: pool_size as u32, nodes: pool_nodes, next: pool_nodes };
    for i in 0..pool.size {
        (*pool.nodes.offset(i as isize)).in_use = false;
    }

    // Array of lists of chains. Each list requires only two lookahead chains at
    // a time, so each list is a array of two Node*'s.
    let mut lists: *mut [*mut Node; 2] = mem::uninitialized();
    lists = malloc((maxbits as usize * mem::size_of_val(&*lists)) as size_t) as *mut [*mut Node; 2];
    init_lists(&mut pool, leaves, maxbits, lists);

    // In the last list, 2 * numsymbols - 2 active chains need to be created. Two
    // are already created in the initialization. Each BoundaryPM run creates one.
    let num_boundary_pm_runs = 2 * numsymbols - 4;
    for i in 0..num_boundary_pm_runs {
        let is_final = i == num_boundary_pm_runs - 1;
        boundary_pm(lists, maxbits, leaves, numsymbols as i32, &mut pool, maxbits - 1, is_final);
    }

    extract_bit_lengths((*lists.offset(maxbits as isize - 1))[1], leaves, bitlengths);

    free(lists as *mut c_void);
    free(leaves as *mut c_void);
    free(pool.nodes as *mut c_void);
    false
}

#[cfg(test)]
mod tests {
    use std::mem::size_of;
    use libc::{c_void, size_t};

    use super::qsort;

    extern fn comparator(a: *const c_void, b: *const c_void) -> i32 {
        unsafe {
            *(a as *const i32) - *(b as *const i32)
        }
    }

    #[test]
    fn test_qsort() {
        unsafe {
            let mut a: [i32; 5] = [3, 2, 4, 1, 5];
            qsort(a.as_mut_ptr() as *mut c_void, a.len() as size_t, size_of::<i32>() as size_t, comparator);
            assert_eq!(a, [1, 2, 3, 4, 5]);
        }
    }
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use input::Key;

enum KeyState {
    Press,
    Release
}

pub struct KeyHandler {
    incoming: Vec<(KeyState, Key)>,
    last_press: Option<Key>,
    keys: HashMap<Key, u64>
}

impl KeyHandler {
    pub fn new() -> KeyHandler {
        KeyHandler {
            incoming: vec![],
            last_press: None,
            keys: HashMap::new()
        }
    }

    pub fn press(&mut self, key: Key) {
        self.incoming.push((KeyState::Press, key));
    }

    pub fn release(&mut self, key: Key) {
        self.incoming.push((KeyState::Release, key));
    }

    pub fn think(&mut self, tick: u64) {
        // Digest each of the incoming items;
        for &(ref state, ref key) in self.incoming.iter() {
            match *state {
                KeyState::Press => {
                    self.last_press = Some(*key);
                    self.keys.insert(*key, tick);
                },
                KeyState::Release => {
                    match self.last_press {
                        Some(last_key) if last_key == *key => {
                            self.last_press = None
                        },
                        _ => ()
                    };
                    self.keys.remove(key);
                }
            }
        };
        self.incoming.clear();
    }

    pub fn last_key(&self) -> Option<(Key, u64)> {
        match self.last_press {
            Some(key) => {
                match self.keys.get(&key) {
                    Some(timestamp) => {
                        Some((key, *timestamp))
                    },
                    None => None
                }
            },
            None => None
        }
    }
}
<commit_msg>Trying more input patterns<commit_after>use std::collections::HashMap;
use input::Key;

enum KeyState {
    Press,
    Release
}

pub struct KeyHandler {
    incoming: Vec<(KeyState, Key)>,
    last_press: Option<Key>,
    keys: HashMap<Key, u64>
}

impl KeyHandler {
    pub fn new() -> KeyHandler {
        KeyHandler {
            incoming: vec![],
            last_press: None,
            keys: HashMap::new()
        }
    }

    pub fn press(&mut self, key: Key) {
        self.incoming.push((KeyState::Press, key));
    }

    pub fn release(&mut self, key: Key) {
        self.incoming.push((KeyState::Release, key));
    }

    pub fn think(&mut self, tick: u64) {
        // Digest each of the incoming items;
        for &(ref state, ref key) in self.incoming.iter() {
            match *state {
                KeyState::Press => {
                    self.last_press = Some(*key);
                    self.keys.insert(*key, tick);
                },
                KeyState::Release => {
                    self.keys.remove(key);
                }
            }
        };
        self.incoming.clear();
    }

    pub fn last_key(&mut self) -> Option<(Key, u64)> {
        match self.last_press {
            Some(key) => {
                match self.keys.get(&key) {
                    Some(timestamp) => {
                        Some((key, *timestamp))
                    },
                    None => {
                        // Clear ourself out if we're not currently pressed
                        self.last_press = None;
                        Some((key, 0)) //FIXME: Should use a meaningful value
                    }
                }
            },
            None => None
        }
    }
}
<|endoftext|>


<commit_before>#[deriving(Clone,Show)]
pub enum Event {
    /// The size of the window has changed.
    Resized(uint, uint),

    /// The position of the window has changed.
    Moved(int, int),

    /// The window has been closed.
    Closed,

    /// The window received a unicode character.
    ReceivedCharacter(char),

    /// The window gained or lost focus.
    ///
    /// The parameter is true if the window has gained focus, and false if it has lost focus.
    Focused(bool),

    /// An event from the keyboard has been received.
    KeyboardInput(ElementState, ScanCode, Option<VirtualKeyCode>, KeyModifiers),

    /// The cursor has moved on the window.
    ///
    /// The parameter are the (x,y) coords in pixels relative to the top-left corner of the window.
    MouseMoved((int, int)),

    /// A positive value indicates that the wheel was rotated forward, away from the user;
    ///  a negative value indicates that the wheel was rotated backward, toward the user.
    MouseWheel(i32),

    /// An event from the mouse has been received.
    MouseInput(ElementState, MouseButton),
}

pub type ScanCode = u8;

bitflags!(
    #[deriving(Show)]
    flags KeyModifiers: u8 {
        const LeftControlModifier = 1,
        const RightControlModifier = 2,
        const LeftShitModifier = 4,
        const RightShitModifier = 8,
        const LeftAltModifier = 16,
        const RightRightModifier = 32,
        const NumLockModifier = 64,
        const CapsLockModifier = 128
    }
)

#[deriving(Show, Hash, PartialEq, Eq, Clone)]
pub enum ElementState {
    Pressed,
    Released,
}

#[deriving(Show, Hash, PartialEq, Eq, Clone)]
pub enum MouseButton {
    LeftMouseButton,
    RightMouseButton,
    MiddleMouseButton,
    OtherMouseButton(u8),
}

#[deriving(Show, Hash, PartialEq, Eq, Clone)]
pub enum VirtualKeyCode {
    Key0,
    Key1,
    Key2,
    Key3,
    Key4,
    Key5,
    Key6,
    Key7,
    Key8,
    Key9,
    A,
    AbntC1,
    AbntC2,
    Add,
    Apostrophe,
    Apps,
    At,
    Ax,
    B,
    Back,
    Backslash,
    C,
    Calculator,
    Capital,
    Colon,
    Comma,
    Convert,
    D,
    Decimal,
    Delete,
    Divide,
    Down,
    E,
    End,
    Equals,
    Escape,
    F,
    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F12,
    F13,
    F14,
    F15,
    G,
    Grave,
    H,
    Home,
    I,
    Insert,
    J,
    K,
    Kana,
    Kanji,
    L,
    LCracket,
    LControl,
    Left,
    LMenu,
    LShift,
    LWin,
    M,
    Mail,
    MediaSelect,
    MediaStop,
    Minus,
    Multiply,
    Mute,
    MyComputer,
    N,
    NextTrack,
    NoConvert,
    Numlock,
    Numpad0,
    Numpad1,
    Numpad2,
    Numpad3,
    Numpad4,
    Numpad5,
    Numpad6,
    Numpad7,
    Numpad8,
    Numpad9,
    NumpadComma,
    NumpadEnter,
    NumpadEquals,
    O,
    OEM102,
    P,
    PageDown,
    PageUp,
    Pause,
    Period,
    Playpause,
    Power,
    Prevtrack,
    Q,
    R,
    RBracket,
    RControl,
    Return,
    Right,
    RMenu,
    RShift,
    RWin,
    S,
    Scroll,
    Semicolon,
    Slash,
    Sleep,
    Snapshot,
    Space,
    Stop,
    Subtract,
    Sysrq,
    T,
    Tab,
    U,
    Underline,
    Unlabeled,
    Up,
    V,
    VolumeDown,
    VolumeUp,
    W,
    Wake,
    Webback,
    WebFavorites,
    WebForward,
    WebHome,
    WebRefresh,
    WebSearch,
    WebStop,
    X,
    Y,
    Yen,
    Z
}
<commit_msg>Fixed static uppercase warning<commit_after>#![allow(non_uppercase_statics)]

#[deriving(Clone,Show)]
pub enum Event {
    /// The size of the window has changed.
    Resized(uint, uint),

    /// The position of the window has changed.
    Moved(int, int),

    /// The window has been closed.
    Closed,

    /// The window received a unicode character.
    ReceivedCharacter(char),

    /// The window gained or lost focus.
    ///
    /// The parameter is true if the window has gained focus, and false if it has lost focus.
    Focused(bool),

    /// An event from the keyboard has been received.
    KeyboardInput(ElementState, ScanCode, Option<VirtualKeyCode>, KeyModifiers),

    /// The cursor has moved on the window.
    ///
    /// The parameter are the (x,y) coords in pixels relative to the top-left corner of the window.
    MouseMoved((int, int)),

    /// A positive value indicates that the wheel was rotated forward, away from the user;
    ///  a negative value indicates that the wheel was rotated backward, toward the user.
    MouseWheel(i32),

    /// An event from the mouse has been received.
    MouseInput(ElementState, MouseButton),
}

pub type ScanCode = u8;

bitflags!(
    #[deriving(Show)]
    flags KeyModifiers: u8 {
        const LeftControlModifier = 1,
        const RightControlModifier = 2,
        const LeftShitModifier = 4,
        const RightShitModifier = 8,
        const LeftAltModifier = 16,
        const RightRightModifier = 32,
        const NumLockModifier = 64,
        const CapsLockModifier = 128
    }
)

#[deriving(Show, Hash, PartialEq, Eq, Clone)]
pub enum ElementState {
    Pressed,
    Released,
}

#[deriving(Show, Hash, PartialEq, Eq, Clone)]
pub enum MouseButton {
    LeftMouseButton,
    RightMouseButton,
    MiddleMouseButton,
    OtherMouseButton(u8),
}

#[deriving(Show, Hash, PartialEq, Eq, Clone)]
pub enum VirtualKeyCode {
    Key0,
    Key1,
    Key2,
    Key3,
    Key4,
    Key5,
    Key6,
    Key7,
    Key8,
    Key9,
    A,
    AbntC1,
    AbntC2,
    Add,
    Apostrophe,
    Apps,
    At,
    Ax,
    B,
    Back,
    Backslash,
    C,
    Calculator,
    Capital,
    Colon,
    Comma,
    Convert,
    D,
    Decimal,
    Delete,
    Divide,
    Down,
    E,
    End,
    Equals,
    Escape,
    F,
    F1,
    F2,
    F3,
    F4,
    F5,
    F6,
    F7,
    F8,
    F9,
    F10,
    F11,
    F12,
    F13,
    F14,
    F15,
    G,
    Grave,
    H,
    Home,
    I,
    Insert,
    J,
    K,
    Kana,
    Kanji,
    L,
    LCracket,
    LControl,
    Left,
    LMenu,
    LShift,
    LWin,
    M,
    Mail,
    MediaSelect,
    MediaStop,
    Minus,
    Multiply,
    Mute,
    MyComputer,
    N,
    NextTrack,
    NoConvert,
    Numlock,
    Numpad0,
    Numpad1,
    Numpad2,
    Numpad3,
    Numpad4,
    Numpad5,
    Numpad6,
    Numpad7,
    Numpad8,
    Numpad9,
    NumpadComma,
    NumpadEnter,
    NumpadEquals,
    O,
    OEM102,
    P,
    PageDown,
    PageUp,
    Pause,
    Period,
    Playpause,
    Power,
    Prevtrack,
    Q,
    R,
    RBracket,
    RControl,
    Return,
    Right,
    RMenu,
    RShift,
    RWin,
    S,
    Scroll,
    Semicolon,
    Slash,
    Sleep,
    Snapshot,
    Space,
    Stop,
    Subtract,
    Sysrq,
    T,
    Tab,
    U,
    Underline,
    Unlabeled,
    Up,
    V,
    VolumeDown,
    VolumeUp,
    W,
    Wake,
    Webback,
    WebFavorites,
    WebForward,
    WebHome,
    WebRefresh,
    WebSearch,
    WebStop,
    X,
    Y,
    Yen,
    Z
}
<|endoftext|>


<commit_before>use luminance::{Dim2, Flat, Sampler};
use luminance_gl::gl33::Texture;
use image::{self, ImageResult};
use std::path::Path;

pub use luminance::RGBA32F;

/// Load an RGBA texture from an image at a path.
pub fn load_rgba_texture<P>(path: P, sampler: &Sampler, linear: bool) -> ImageResult<Texture<Flat, Dim2, RGBA32F>> where P: AsRef<Path> {
  let image = try!(image::open(path)).to_rgba();
  let dim = image.dimensions();
  let raw: Vec<f32> = image.into_raw().into_iter().map(|x| {
    let y = x as f32 / 255.;

    if linear {
      y
    } else {
      y.powf(1. / 2.2)
    }
  }).collect();

  let tex = Texture::new(dim, 0, sampler);
  tex.upload_raw(false, &raw);

  Ok(tex)
}

/// Save an RGBA image on disk.
pub fn save_rgba_texture<P>(texture: &Texture<Flat, Dim2, RGBA32F>, path: P) where P: AsRef<Path> {
  let texels = texture.get_raw_texels();
  let (w, h) = texture.size;
  let mut output = Vec::with_capacity((w * h) as usize);

  for texel in &texels {
    output.push((texel * 255.) as u8);
  }

  let _ = image::save_buffer(path, &output, w, h, image::ColorType::RGBA(8));
}

#[derive(Clone, Debug)]
pub enum TextureError {
  LoadingFailed(String)
}

#[cfg(feature = "hot-resource")]
mod hot {
  use super::*;

  use luminance::{Dim2, Flat, Sampler};
  use luminance_gl::gl33::Texture;
  use resource::ResourceManager;
  use std::ops::Deref;
  use std::path::{Path, PathBuf};
  use std::sync::mpsc;

  pub struct TextureImage {
    rx: mpsc::Receiver<()>,
    texture: Texture<Flat, Dim2, RGBA32F>,
    sampler: Sampler,
    linear: bool,
    path: PathBuf
  }

  impl TextureImage {
    pub fn load<P>(manager: &mut ResourceManager, path: P, sampler: &Sampler, linear: bool) -> Result<Self, TextureError> where P: AsRef<Path> {
      let path = path.as_ref();

      let tex = load_rgba_texture(path, sampler, linear);

      match tex {
        Ok(tex) => {
          // monitor that texture
          let (sx, rx) = mpsc::channel();

          manager.monitor(path, sx);

          Ok(TextureImage {
            rx: rx,
            texture: tex,
            sampler: *sampler,
            linear: linear,
            path: path.to_path_buf()
          })
        },
        Err(e) => {
          Err(TextureError::LoadingFailed(format!("{:?}", e)))
        }
      }
    }

    fn reload(&mut self) {
      let path = self.path.as_path();
      let tex = load_rgba_texture(path, &self.sampler, self.linear);

      match tex {
        Ok(tex) => {
          self.texture = tex;
          info!("reloaded texture {:?}", path);
        },
        Err(e) => {
          err!("reloading texture {:?} has failed: {:?}", path, e);
        }
      }
    }

    pub fn sync(&mut self) {
      if self.rx.try_recv().is_ok() {
        self.reload()
      }
    }
  }

  impl Deref for TextureImage {
    type Target = Texture<Flat, Dim2, RGBA32F>;

    fn deref(&self) -> &Self::Target {
      &self.texture
    }
  }
}

#[cfg(not(feature = "hot-resource"))]
mod cold {
  pub struct TextureImage(Texture<Flat, Dim2, RGBA32F>);

  impl TextureImage {
    pub fn load<P>(manager: &mut ResourceManager, path: P, sampler: &Sampler, linear: bool) -> Result<Self, TextureError> where P: AsRef<Path> {
      let tex = load_rgba_texture(path, sampler, linear);

      match tex {
        Ok(tex) => {
          Ok(TextureImage(tex))
        },
        Err(e) => {
          Err(TextureError::LoadingFailed(format!("{:?}", e)))
        }
      }
    }

    pub fn sync(&mut self) {}
  }

  impl Deref for TextureImage {
    type Target = Texture<Flat, Dim2, RGBA32F>;

    fn deref(&self) -> &Self::Target {
      &self.0
    }
  }
}

#[cfg(feature = "hot-resource")]
pub use self::hot::*;
#[cfg(not(feature = "hot-resource"))]
pub use self::cold::*;
<commit_msg>Hot textures are supported. (#3)<commit_after>use luminance::{Dim2, Flat, Sampler};
use luminance_gl::gl33::Texture;
use image::{self, ImageResult};
use std::path::Path;

pub use luminance::RGBA32F;

/// Load an RGBA texture from an image at a path.
pub fn load_rgba_texture<P>(path: P, sampler: &Sampler, linear: bool) -> ImageResult<Texture<Flat, Dim2, RGBA32F>> where P: AsRef<Path> {
  info!("loading texture image: \x1b[35m{:?}", path.as_ref());

  let image = try!(image::open(path)).to_rgba();
  let dim = image.dimensions();
  let raw: Vec<f32> = image.into_raw().into_iter().map(|x| {
    let y = x as f32 / 255.;

    if linear {
      y
    } else {
      y.powf(1. / 2.2)
    }
  }).collect();

  let tex = Texture::new(dim, 0, sampler);
  tex.upload_raw(false, &raw);

  Ok(tex)
}

/// Save an RGBA image on disk.
pub fn save_rgba_texture<P>(texture: &Texture<Flat, Dim2, RGBA32F>, path: P) where P: AsRef<Path> {
  info!("saving texture image to: \x1b[35m{:?}", path.as_ref());

  let texels = texture.get_raw_texels();
  let (w, h) = texture.size;
  let mut output = Vec::with_capacity((w * h) as usize);

  for texel in &texels {
    output.push((texel * 255.) as u8);
  }

  let _ = image::save_buffer(path, &output, w, h, image::ColorType::RGBA(8));
}

#[derive(Clone, Debug)]
pub enum TextureError {
  LoadingFailed(String)
}

#[cfg(feature = "hot-resource")]
mod hot {
  use super::*;

  use luminance::{Dim2, Flat, Sampler};
  use luminance_gl::gl33::Texture;
  use resource::ResourceManager;
  use std::ops::Deref;
  use std::path::{Path, PathBuf};
  use std::sync::mpsc;

  pub struct TextureImage {
    rx: mpsc::Receiver<()>,
    texture: Texture<Flat, Dim2, RGBA32F>,
    sampler: Sampler,
    linear: bool,
    path: PathBuf
  }

  impl TextureImage {
    pub fn load<P>(manager: &mut ResourceManager, path: P, sampler: &Sampler, linear: bool) -> Result<Self, TextureError> where P: AsRef<Path> {
      let path = path.as_ref();

      let tex = load_rgba_texture(path, sampler, linear);

      match tex {
        Ok(tex) => {
          // monitor that texture
          let (sx, rx) = mpsc::channel();

          manager.monitor(path, sx);

          Ok(TextureImage {
            rx: rx,
            texture: tex,
            sampler: *sampler,
            linear: linear,
            path: path.to_path_buf()
          })
        },
        Err(e) => {
          Err(TextureError::LoadingFailed(format!("{:?}", e)))
        }
      }
    }

    fn reload(&mut self) {
      let path = self.path.as_path();
      let tex = load_rgba_texture(path, &self.sampler, self.linear);

      match tex {
        Ok(tex) => {
          self.texture = tex;
          info!("reloaded texture {:?}", path);
        },
        Err(e) => {
          err!("reloading texture {:?} has failed: {:?}", path, e);
        }
      }
    }

    pub fn sync(&mut self) {
      if self.rx.try_recv().is_ok() {
        self.reload()
      }
    }
  }

  impl Deref for TextureImage {
    type Target = Texture<Flat, Dim2, RGBA32F>;

    fn deref(&self) -> &Self::Target {
      &self.texture
    }
  }
}

#[cfg(not(feature = "hot-resource"))]
mod cold {
  pub struct TextureImage(Texture<Flat, Dim2, RGBA32F>);

  impl TextureImage {
    pub fn load<P>(manager: &mut ResourceManager, path: P, sampler: &Sampler, linear: bool) -> Result<Self, TextureError> where P: AsRef<Path> {
      let tex = load_rgba_texture(path, sampler, linear);

      match tex {
        Ok(tex) => {
          Ok(TextureImage(tex))
        },
        Err(e) => {
          Err(TextureError::LoadingFailed(format!("{:?}", e)))
        }
      }
    }

    pub fn sync(&mut self) {}
  }

  impl Deref for TextureImage {
    type Target = Texture<Flat, Dim2, RGBA32F>;

    fn deref(&self) -> &Self::Target {
      &self.0
    }
  }
}

#[cfg(feature = "hot-resource")]
pub use self::hot::*;
#[cfg(not(feature = "hot-resource"))]
pub use self::cold::*;
<|endoftext|>


<commit_before>extern crate gauc;
extern crate env_logger;

use gauc::client::*;
use std::{thread, time};

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

    let mut client = Client::new("couchbase://korczis.com/default");

    for i in 0..100 {
        println!("Iteration #{}", i);

        // Store some data
        client.upsert(&format!("foo{}", i), &format!("This is test No. {}!", i), |res| {
            if let Ok(response) = res {
                println!("Created new document, CAS: {}", response.cas)
            }
        });
    }
    for i in 0..100 {
        // Get data
        client.get(&format!("foo{}", i), |res| {
            if let Ok(response) = res {
                println!("Got response: {} - {}", response.key.unwrap(), response.value.unwrap())
            }
        });
    }

    let sleep_interval = time::Duration::from_millis(1000);
    thread::sleep(sleep_interval);
}
<commit_msg>Set properly formated json<commit_after>extern crate gauc;
extern crate env_logger;

use gauc::client::*;
use std::{thread, time};

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

    let mut client = Client::new("couchbase://korczis.com/default");

    for i in 0..100 {
        println!("Iteration #{}", i);

        // Store some data
        client.upsert(&format!("foo{}", i), &format!("{{\"msg\": \"This is test No. {}!\"}}", i), |res| {
            if let Ok(response) = res {
                println!("Created new document, CAS: {}", response.cas)
            }
        });
    }
    for i in 0..100 {
        // Get data
        client.get(&format!("foo{}", i), |res| {
            if let Ok(response) = res {
                println!("Got response: {} - {}", response.key.unwrap(), response.value.unwrap())
            }
        });
    }

    let sleep_interval = time::Duration::from_millis(1000);
    thread::sleep(sleep_interval);
}
<|endoftext|>