<commit_before>use std::fmt;
// use rand;
use rand::{Rand, Rng, random, thread_rng};

#[derive(Clone,Debug)]
pub enum Color {
    Empty,
    Red,
    Green,
    Blue,
    Yellow,
    Purple,
    Brown,
    Cyan,
}

const ALL_COLORS: [Color; 8] = [Color::Empty,
                                Color::Red,
                                Color::Green,
                                Color::Blue,
                                Color::Yellow,
                                Color::Purple,
                                Color::Brown,
                                Color::Cyan];

impl Color {
    fn get_string_representation(&self) -> &'static str {
        match *self {
            Color::Empty => "  ",
            Color::Red => "Re",
            Color::Green => "Gr",
            Color::Blue => "Bl",
            Color::Yellow => "Ye",
            Color::Purple => "Pu",
            Color::Brown => "Br",
            Color::Cyan => "Cy",
        }
    }
    fn random(extraColor: bool) -> Color {
        let maxcol = if extraColor == true {
            ALL_COLORS.len()
        } else {
            ALL_COLORS.len() - 1
        };
        ALL_COLORS[thread_rng().gen_range(1, maxcol)].clone()
    }
}

impl Default for Color {
    fn default() -> Color {
        Color::Empty
    }
}
// TODO: There must be a more elegant way to get a random enum
impl Rand for Color {
    fn rand<R: Rng>(rng: &mut R) -> Self {
        let a = rng.gen_range(1, 7);
        match a {
            1 => Color::Red,
            2 => Color::Green,
            3 => Color::Blue,
            4 => Color::Yellow,
            5 => Color::Purple,
            6 => Color::Brown,
            7 => Color::Cyan,
            _ => unreachable!(),
        }
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.get_string_representation())
    }
}

#[derive(Debug)]
pub struct HexaGrid<T> {
    width: usize,
    heigth: usize,
    data: Box<[T]>,
}

impl<T: Clone + Default + Rand> HexaGrid<T> {
    pub fn new(w: usize, h: usize) -> HexaGrid<T> {
        let flat_size = h * w + (h / 2);
        HexaGrid::<T> {
            width: w,
            heigth: h,
            data: vec![<T>::default(); flat_size].into_boxed_slice(),
        }
    }
    pub fn randomize(&mut self) {
        for i in 0..self.data.len() {
            self.data[i] = random::<T>();
        }
    }
}

impl<T: fmt::Display> fmt::Display for HexaGrid<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Approxiamte capacity : (4 * (w+1)*h
        let mut res: String = String::with_capacity("[  ]".len() * (self.width + 1) * self.heigth);
        let mut index = 0;
        for i in 0..self.heigth {
            let w = if (i & 1) == 0 {
                res.push_str("  ");
                self.width
            } else {
                self.width + 1
            };
            for _ in 0..w {
                res.push_str(format!("[{}]", self.data[index]).as_str());
                index += 1;
            }
            res.push_str("\n");
        }
        f.write_str(res.as_str())
    }
}
<commit_msg>Last color was never choosed randomly<commit_after>use std::fmt;
// use rand;
use rand::{Rand, Rng, random, thread_rng};

#[derive(Clone,Debug)]
pub enum Color {
    Empty,
    Red,
    Green,
    Blue,
    Yellow,
    Purple,
    Brown,
    Cyan,
}

const ALL_COLORS: [Color; 8] = [Color::Empty,
                                Color::Red,
                                Color::Green,
                                Color::Blue,
                                Color::Yellow,
                                Color::Purple,
                                Color::Brown,
                                Color::Cyan];

impl Color {
    fn get_string_representation(&self) -> &'static str {
        match *self {
            Color::Empty => "  ",
            Color::Red => "Re",
            Color::Green => "Gr",
            Color::Blue => "Bl",
            Color::Yellow => "Ye",
            Color::Purple => "Pu",
            Color::Brown => "Br",
            Color::Cyan => "Cy",
        }
    }
    fn random(extraColor: bool) -> Color {
        let maxcol = if extraColor == true {
            ALL_COLORS.len()
        } else {
            ALL_COLORS.len() - 1
        };
        ALL_COLORS[thread_rng().gen_range(1, maxcol)].clone()
    }
}

impl Default for Color {
    fn default() -> Color {
        Color::Empty
    }
}
// TODO: There must be a more elegant way to get a random enum
impl Rand for Color {
    fn rand<R: Rng>(rng: &mut R) -> Self {
        let a = rng.gen_range(1, 8);
        match a {
            1 => Color::Red,
            2 => Color::Green,
            3 => Color::Blue,
            4 => Color::Yellow,
            5 => Color::Purple,
            6 => Color::Brown,
            7 => Color::Cyan,
            _ => unreachable!(),
        }
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.get_string_representation())
    }
}

#[derive(Debug)]
pub struct HexaGrid<T> {
    width: usize,
    heigth: usize,
    data: Box<[T]>,
}

impl<T: Clone + Default + Rand> HexaGrid<T> {
    pub fn new(w: usize, h: usize) -> HexaGrid<T> {
        let flat_size = h * w + (h / 2);
        HexaGrid::<T> {
            width: w,
            heigth: h,
            data: vec![<T>::default(); flat_size].into_boxed_slice(),
        }
    }
    pub fn randomize(&mut self) {
        for i in 0..self.data.len() {
            self.data[i] = random::<T>();
        }
    }
}

impl<T: fmt::Display> fmt::Display for HexaGrid<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Approxiamte capacity : (4 * (w+1)*h
        let mut res: String = String::with_capacity("[  ]".len() * (self.width + 1) * self.heigth);
        let mut index = 0;
        for i in 0..self.heigth {
            let w = if (i & 1) == 0 {
                res.push_str("  ");
                self.width
            } else {
                self.width + 1
            };
            for _ in 0..w {
                res.push_str(format!("[{}]", self.data[index]).as_str());
                index += 1;
            }
            res.push_str("\n");
        }
        f.write_str(res.as_str())
    }
}
<|endoftext|>


<commit_before>use std;
pub fn prime_filter(iter_size: usize) -> std::vec::Vec<bool>{
    //Sieve of Atkin
    if iter_size < 100 {
        old_prime_filter(iter_size)
    }else{
        let mut prime_filter = vec![false; iter_size];
        prime_filter[2] = true;
        prime_filter[3] = true;
        prime_filter[5] = true;
        let mut y_sq = 1;
        let mut to_next_y_sq = 3;
        while y_sq<iter_size {
            if y_sq%2 == 1 {
                //n_1 = 4x^2 + y^2 === 1 (mod 4)
                let (mut n_1, mut to_next_n_1) = (y_sq, 4);
                loop{
                    n_1 += to_next_n_1;
                    to_next_n_1 += 8;
                    match n_1%60{
                        _ if n_1 >= iter_size => break,
                        1 | 13 | 17 | 29 | 37 | 41 | 49 | 53 => (),
                        _ => continue,
                    };

                    // println!("1: {}", n_1);
                    prime_filter[n_1] ^= true;
                };
            };
            if y_sq%3 == 1 {
                //n_2 = 3x^2 + y^2 === 1 (mod 6)
                let (mut n_2, mut to_next_n_2) = (y_sq, 3);
                loop {
                    n_2 += to_next_n_2;
                    to_next_n_2 += 6;
                    match n_2%60{
                        _ if n_2 >= iter_size => break,
                        7 | 19 | 31 | 43 => (),
                        _ => continue,
                    };
                    // println!("2: {}", n_2);
                    prime_filter[n_2] ^= true;
                };
                //n_3 = 3x^2 - y^2 === 11 (mod 12)
                let (mut n_3, mut to_next_n_3) = (2*y_sq, 3*to_next_y_sq);
                loop {
                    n_3 += to_next_n_3;
                    to_next_n_3 += 6;
                    match n_3%60{
                        _ if n_3 >= iter_size => break,
                        11 | 23 | 47 | 59 => (),
                        _ => continue,
                    };
                    // println!("3: {}", n_3);
                    prime_filter[n_3] ^= true;
                };
            };
            while{ //Do-while
                y_sq += to_next_y_sq;
                to_next_y_sq += 2;
                y_sq%6 == 0
            } {};
        };
        //Eliminate non-squarefree numbers
        let mut n_sq = 49; // 7^2
        let mut next_n_sq = 32; //9^2 - 7^2, skip even numbers.
        while n_sq < iter_size {
            let mut non_sq_free = n_sq;
            while non_sq_free < iter_size {
                prime_filter[non_sq_free] = false;
                while{ //Do-while
                    non_sq_free += n_sq + n_sq;
                    (non_sq_free%3==0) | (non_sq_free%5==0)
                } {};
            };
            while{ //Do-while
                n_sq += next_n_sq;
                next_n_sq += 8;
                (n_sq%3==0) | (n_sq%5 == 0)
            } {};
        }
        prime_filter
    }
}

pub fn old_prime_filter(iter_size: usize) -> std::vec::Vec<bool>{
    if iter_size < 5 {
         let mut ret = vec![false, false, true, true];
         ret.truncate(iter_size);
         return ret
     }
    let mut prime_filter = vec![true; iter_size];
    prime_filter[0] = false;
    prime_filter[1] = false;
    let mut cur_num = 2;
    'outer: loop{
        for i in (cur_num+1)..iter_size{
            if 0 == i%cur_num { prime_filter[i] = false; }
        }
        cur_num += 1;
        while !prime_filter[cur_num]{
            if cur_num*cur_num > iter_size {
                break 'outer
            }
            cur_num += 1;
        }
    }
    prime_filter
}
<commit_msg>no country for old primes<commit_after>use std;
pub fn prime_filter(iter_size: usize) -> std::vec::Vec<bool>{
    //Sieve of Atkin
    if iter_size < 100 {
        old_prime_filter(iter_size)
    }else{
        let mut prime_filter = vec![false; iter_size];
        prime_filter[2] = true;
        prime_filter[3] = true;
        prime_filter[5] = true;
        let mut y_sq = 1;
        let mut to_next_y_sq = 3;
        while y_sq<iter_size {
            if y_sq%2 == 1 {
                //n_1 = 4x^2 + y^2 === 1 (mod 4)
                let (mut n_1, mut to_next_n_1) = (y_sq, 4);
                loop{
                    n_1 += to_next_n_1;
                    to_next_n_1 += 8;
                    match n_1%60{
                        _ if n_1 >= iter_size => break,
                        1 | 13 | 17 | 29 | 37 | 41 | 49 | 53 => (),
                        _ => continue,
                    };

                    // println!("1: {}", n_1);
                    prime_filter[n_1] ^= true;
                };
            };
            if y_sq%3 == 1 {
                //n_2 = 3x^2 + y^2 === 1 (mod 6)
                let (mut n_2, mut to_next_n_2) = (y_sq, 3);
                loop {
                    n_2 += to_next_n_2;
                    to_next_n_2 += 6;
                    match n_2%60{
                        _ if n_2 >= iter_size => break,
                        7 | 19 | 31 | 43 => (),
                        _ => continue,
                    };
                    // println!("2: {}", n_2);
                    prime_filter[n_2] ^= true;
                };
                //n_3 = 3x^2 - y^2 === 11 (mod 12)
                let (mut n_3, mut to_next_n_3) = (2*y_sq, 3*to_next_y_sq);
                loop {
                    n_3 += to_next_n_3;
                    to_next_n_3 += 6;
                    match n_3%60{
                        _ if n_3 >= iter_size => break,
                        11 | 23 | 47 | 59 => (),
                        _ => continue,
                    };
                    // println!("3: {}", n_3);
                    prime_filter[n_3] ^= true;
                };
            };
            while{ //Do-while
                y_sq += to_next_y_sq;
                to_next_y_sq += 2;
                y_sq%6 == 0
            } {};
        };
        //Eliminate non-squarefree numbers
        let mut n_sq = 49; // 7^2
        let mut next_n_sq = 32; //9^2 - 7^2, skip even numbers.
        while n_sq < iter_size {
            let mut non_sq_free = n_sq;
            while non_sq_free < iter_size {
                prime_filter[non_sq_free] = false;
                while{ //Do-while
                    non_sq_free += n_sq + n_sq;
                    (non_sq_free%3==0) | (non_sq_free%5==0)
                } {};
            };
            while{ //Do-while
                n_sq += next_n_sq;
                next_n_sq += 8;
                (n_sq%3==0) | (n_sq%5 == 0)
            } {};
        }
        prime_filter
    }
}

fn old_prime_filter(iter_size: usize) -> std::vec::Vec<bool>{
    if iter_size < 5 {
         let mut ret = vec![false, false, true, true];
         ret.truncate(iter_size);
         return ret
     }
    let mut prime_filter = vec![true; iter_size];
    prime_filter[0] = false;
    prime_filter[1] = false;
    let mut cur_num = 2;
    'outer: loop{
        for i in (cur_num+1)..iter_size{
            if 0 == i%cur_num { prime_filter[i] = false; }
        }
        cur_num += 1;
        while !prime_filter[cur_num]{
            if cur_num*cur_num > iter_size {
                break 'outer
            }
            cur_num += 1;
        }
    }
    prime_filter
}
<|endoftext|>


<commit_before>extern crate nom;

use std::str;
use nom::*;

fn is_ws(c: char) -> bool {
    let u = c as u32;
    u == 0x20 || u == 0x9 || u == 0xD || u == 0xA
}

fn is_anon(c: char) -> bool {
    c == '[' || c == ']' || is_ws(c)
}

fn is_exponent(c: char) -> bool {
    c == 'e' || c == 'E' || c == '+' || c == '-' || is_digit(c as u8)
}

named!(pub exponent<&str, &str>, verify!(
    take_while_s!(is_exponent),
    |val:&str| {
        let len = val.char_indices().count();
        val.char_indices().all(|(idx, c)| {
            if idx == 0 {
                c == 'e' || c == 'E'
            } else if idx == 1 {
                c == '+' || c == '-' || is_digit(c as u8)
            } else {
                is_digit(c as u8)
            }
        })
    }
));

/* [161s] WS */
named!(pub ws<&str, &str>, take_while_s!(is_ws));

/* [162s] ANON */
named!(pub anon<&str, &str>, verify!(
    take_while_s!(is_anon),
    |val:&str| {
        let len = val.char_indices().count();
        val.char_indices().all(|(idx, c)| {
            if idx == 0 {
                c == '['
            } else if idx == len - 1 {
                c == ']'
            } else {
                is_ws(c)
            }
        })
    }
));

/* [170s] PERCENT */
named!(pub percent<&str, &str>, verify!(
    take_s!(3),
    |val:&str| {
        let bytes = val.as_bytes();
        bytes[0] == 0x25 && is_hex_digit(bytes[1]) && is_hex_digit(bytes[2])
    }
));

#[cfg(test)]
mod test {
    use super::*;
    use nom::IResult;

    #[test]
    fn exponent_test() {
        assert_eq!(exponent("e-0001rest"), IResult::Done("rest", "e-0001"));
    }

    #[test]
    fn ws_test() {
        assert_eq!(ws("   a"), IResult::Done("a", "   "));
    }

    #[test]
    fn anon_test() {
        assert_eq!(anon("[ ]a"), IResult::Done("a", "[ ]"));
    }

    #[test]
    fn percent_test() {
        assert_eq!(percent("%2Abc"), IResult::Done("bc", "%2A"));
    }
}
<commit_msg>Add Exponent struct<commit_after>extern crate nom;

use std::str;
use nom::*;

fn is_ws(c: char) -> bool {
    let u = c as u32;
    u == 0x20 || u == 0x9 || u == 0xD || u == 0xA
}

fn is_anon(c: char) -> bool {
    c == '[' || c == ']' || is_ws(c)
}

fn is_digit_c(c: char) -> bool {
    is_digit(c as u8)
}

#[derive(PartialEq, Debug)]
pub struct Exponent<'a> {
    exponent_symbol: &'a str,
    sign: Option<&'a str>,
    exponent_number: &'a str,
}

/* [154s] EXPONENT */
named!(pub exponent<&str, Exponent>, do_parse!(
    exponent_symbol: alt!(tag!("e") | tag!("E")) >>
    sign:            opt!(alt!(tag!("+") | tag!("-"))) >>
    exponent_number: take_while1_s!(is_digit_c) >>
    (Exponent{
        exponent_symbol: exponent_symbol,
        sign:            sign,
        exponent_number: exponent_number,
    })
));

/* [161s] WS */
named!(pub ws<&str, &str>, take_while_s!(is_ws));

/* [162s] ANON */
named!(pub anon<&str, &str>, verify!(
    take_while_s!(is_anon),
    |val:&str| {
        let len = val.char_indices().count();
        val.char_indices().all(|(idx, c)| {
            if idx == 0 {
                c == '['
            } else if idx == len - 1 {
                c == ']'
            } else {
                is_ws(c)
            }
        })
    }
));

/* [170s] PERCENT */
named!(pub percent<&str, &str>, verify!(
    take_s!(3),
    |val:&str| {
        let bytes = val.as_bytes();
        bytes[0] == 0x25 && is_hex_digit(bytes[1]) && is_hex_digit(bytes[2])
    }
));

#[cfg(test)]
mod test {
    use super::*;
    use nom::IResult;

    #[test]
    fn exponent_normal_test() {
        let input = "e-0123456789rest";
        let expected = IResult::Done("rest", Exponent{
            exponent_symbol: "e",
            sign:            Some("-"),
            exponent_number: "0123456789",
        });
        assert_eq!(exponent(input), expected);

        let input = "E+0123456789rest";
        let expected = IResult::Done("rest", Exponent{
            exponent_symbol: "E",
            sign:            Some("+"),
            exponent_number: "0123456789",
        });
        assert_eq!(exponent(input), expected);

        let input = "e0123456789rest";
        let expected = IResult::Done("rest", Exponent{
            exponent_symbol: "e",
            sign:            None,
            exponent_number: "0123456789",
        });
        assert_eq!(exponent(input), expected);
    }

    #[test]
    fn ws_test() {
        assert_eq!(ws("   a"), IResult::Done("a", "   "));
    }

    #[test]
    fn anon_test() {
        assert_eq!(anon("[ ]a"), IResult::Done("a", "[ ]"));
    }

    #[test]
    fn percent_test() {
        assert_eq!(percent("%2Abc"), IResult::Done("bc", "%2A"));
    }
}
<|endoftext|>


<commit_before>extern crate mustache;

use std::io::net::ip::{SocketAddr, IpAddr, Port};
use std::sync::{Arc, RWLock};
use std::collections::HashMap;

use http::server::{Config, Request, ResponseWriter};
use http::server::Server as HttpServer;

use middleware::MiddlewareStack;
use request;
use response;

pub struct Server {
    middleware_stack: MiddlewareStack,
    ip: IpAddr,
    port: Port,
    templates: response::TemplateCache
}

impl HttpServer for Arc<Server> {
    fn get_config(&self) -> Config {
        Config { bind_address: SocketAddr { ip: self.ip, port: self.port } }
    }

    fn handle_request(&self, req: Request, res: &mut ResponseWriter) {

        let nickel_req = &mut request::Request::from_internal(&req);
        let nickel_res = &mut response::Response::from_internal(res, &self.templates);

        self.middleware_stack.invoke(nickel_req, nickel_res);
    }
}

impl Server {
    pub fn new(middleware_stack: MiddlewareStack, ip: IpAddr, port: Port) -> Server {
        Server {
            middleware_stack: middleware_stack,
            ip: ip,
            port: port,
            templates: RWLock::new(HashMap::<&'static str, mustache::Template>::new())
        }
    }

    // why do we need this? Is the http::Server.serve_forever method protected in C# terms?
    pub fn serve(self) {
        let arc = Arc::new(self);
        arc.serve_forever();
    }
}
<commit_msg>refactor(server): don't use extern crate in module, reimport outer mustache into server module<commit_after>use std::io::net::ip::{SocketAddr, IpAddr, Port};
use std::sync::{Arc, RWLock};
use std::collections::HashMap;

use http::server::{Config, Request, ResponseWriter};
use http::server::Server as HttpServer;

use middleware::MiddlewareStack;
use request;
use response;
use mustache;

pub struct Server {
    middleware_stack: MiddlewareStack,
    ip: IpAddr,
    port: Port,
    templates: response::TemplateCache
}

impl HttpServer for Arc<Server> {
    fn get_config(&self) -> Config {
        Config { bind_address: SocketAddr { ip: self.ip, port: self.port } }
    }

    fn handle_request(&self, req: Request, res: &mut ResponseWriter) {

        let nickel_req = &mut request::Request::from_internal(&req);
        let nickel_res = &mut response::Response::from_internal(res, &self.templates);

        self.middleware_stack.invoke(nickel_req, nickel_res);
    }
}

impl Server {
    pub fn new(middleware_stack: MiddlewareStack, ip: IpAddr, port: Port) -> Server {
        Server {
            middleware_stack: middleware_stack,
            ip: ip,
            port: port,
            templates: RWLock::new(HashMap::<&'static str, mustache::Template>::new())
        }
    }

    // why do we need this? Is the http::Server.serve_forever method protected in C# terms?
    pub fn serve(self) {
        let arc = Arc::new(self);
        arc.serve_forever();
    }
}
<|endoftext|>


<commit_before>use std::fmt;
use std::from_str::FromStr;
use buf::{Buf, MutBuf};
use io;
use io::{IoAcceptor, IoReader, IoWriter, IoHandle, NonBlock, Ready, WouldBlock};
use error::MioResult;
use os;

pub use std::io::net::ip::{IpAddr, Port};
pub use std::io::net::ip::Ipv4Addr as IpV4Addr;

pub trait Socket : IoHandle {
    // Various sock opt fns
    fn is_acceptor(&self) -> bool {
        unimplemented!();
    }

    fn linger(&self) -> MioResult<uint> {
        os::linger(self.desc())
    }

    fn set_linger(&self, dur_s: uint) -> MioResult<()> {
        os::set_linger(self.desc(), dur_s)
    }

    fn set_reuseaddr(&self, val: bool) -> MioResult<()> {
        os::set_reuseaddr(self.desc(), val)
    }
}

#[deriving(Show)]
pub struct TcpSocket {
    desc: os::IoDesc
}

impl TcpSocket {
    pub fn v4() -> MioResult<TcpSocket> {
        TcpSocket::new(Inet)
    }

    pub fn v6() -> MioResult<TcpSocket> {
        TcpSocket::new(Inet6)
    }

    fn new(family: AddressFamily) -> MioResult<TcpSocket> {
        Ok(TcpSocket { desc: try!(os::socket(family)) })
    }

    pub fn bind(self, addr: &SockAddr) -> MioResult<TcpAcceptor> {
        try!(os::bind(&self.desc, addr))
        Ok(TcpAcceptor { desc: self.desc })
    }
}

impl IoHandle for TcpSocket {
    fn desc(&self) -> &os::IoDesc {
        &self.desc
    }
}

impl IoReader for TcpSocket {
    fn read(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<()>> {
        io::read(self, buf)
    }
}

impl IoWriter for TcpSocket {
    fn write(&mut self, buf: &mut Buf) -> MioResult<NonBlock<()>> {
        io::write(self, buf)
    }
}

impl Socket for TcpSocket {
}

#[deriving(Show)]
pub struct TcpAcceptor {
    desc: os::IoDesc
}

impl IoHandle for TcpAcceptor {
    fn desc(&self) -> &os::IoDesc {
        &self.desc
    }
}

impl Socket for TcpAcceptor {
}

impl IoAcceptor<TcpSocket> for TcpAcceptor {
    fn accept(&mut self) -> MioResult<NonBlock<TcpSocket>> {
        match os::accept(self.desc()) {
            Ok(sock) => Ok(Ready(TcpSocket { desc: sock })),
            Err(e) => {
                if e.is_would_block() {
                    return Ok(WouldBlock);
                }

                return Err(e);
            }
        }
    }
}

#[deriving(Show)]
pub struct UnixSocket {
    desc: os::IoDesc
}

impl IoHandle for UnixSocket {
    fn desc(&self) -> &os::IoDesc {
        &self.desc
    }
}

impl Socket for UnixSocket {
}

// Types of sockets
pub enum AddressFamily {
    Inet,
    Inet6,
    Unix,
}

pub enum SockAddr {
    UnixAddr(Path),
    InetAddr(IpAddr, Port)
}

impl SockAddr {
    pub fn parse(s: &str) -> Option<SockAddr> {
        use std::io::net::ip;

        let addr: Option<ip::SocketAddr> = FromStr::from_str(s);
        addr.map(|a| InetAddr(a.ip, a.port))
    }
}

impl FromStr for SockAddr {
    fn from_str(s: &str) -> Option<SockAddr> {
        SockAddr::parse(s)
    }
}

impl fmt::Show for SockAddr {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            InetAddr(ip, port) => write!(fmt, "{}:{}", ip, port),
            _ => write!(fmt, "not implemented")
        }
    }
}
<commit_msg>Remove unused fn Socket::is_acceptor<commit_after>use std::fmt;
use std::from_str::FromStr;
use buf::{Buf, MutBuf};
use io;
use io::{IoAcceptor, IoReader, IoWriter, IoHandle, NonBlock, Ready, WouldBlock};
use error::MioResult;
use os;

pub use std::io::net::ip::{IpAddr, Port};
pub use std::io::net::ip::Ipv4Addr as IpV4Addr;

pub trait Socket : IoHandle {
    fn linger(&self) -> MioResult<uint> {
        os::linger(self.desc())
    }

    fn set_linger(&self, dur_s: uint) -> MioResult<()> {
        os::set_linger(self.desc(), dur_s)
    }

    fn set_reuseaddr(&self, val: bool) -> MioResult<()> {
        os::set_reuseaddr(self.desc(), val)
    }
}

#[deriving(Show)]
pub struct TcpSocket {
    desc: os::IoDesc
}

impl TcpSocket {
    pub fn v4() -> MioResult<TcpSocket> {
        TcpSocket::new(Inet)
    }

    pub fn v6() -> MioResult<TcpSocket> {
        TcpSocket::new(Inet6)
    }

    fn new(family: AddressFamily) -> MioResult<TcpSocket> {
        Ok(TcpSocket { desc: try!(os::socket(family)) })
    }

    pub fn bind(self, addr: &SockAddr) -> MioResult<TcpAcceptor> {
        try!(os::bind(&self.desc, addr))
        Ok(TcpAcceptor { desc: self.desc })
    }
}

impl IoHandle for TcpSocket {
    fn desc(&self) -> &os::IoDesc {
        &self.desc
    }
}

impl IoReader for TcpSocket {
    fn read(&mut self, buf: &mut MutBuf) -> MioResult<NonBlock<()>> {
        io::read(self, buf)
    }
}

impl IoWriter for TcpSocket {
    fn write(&mut self, buf: &mut Buf) -> MioResult<NonBlock<()>> {
        io::write(self, buf)
    }
}

impl Socket for TcpSocket {
}

#[deriving(Show)]
pub struct TcpAcceptor {
    desc: os::IoDesc
}

impl IoHandle for TcpAcceptor {
    fn desc(&self) -> &os::IoDesc {
        &self.desc
    }
}

impl Socket for TcpAcceptor {
}

impl IoAcceptor<TcpSocket> for TcpAcceptor {
    fn accept(&mut self) -> MioResult<NonBlock<TcpSocket>> {
        match os::accept(self.desc()) {
            Ok(sock) => Ok(Ready(TcpSocket { desc: sock })),
            Err(e) => {
                if e.is_would_block() {
                    return Ok(WouldBlock);
                }

                return Err(e);
            }
        }
    }
}

#[deriving(Show)]
pub struct UnixSocket {
    desc: os::IoDesc
}

impl IoHandle for UnixSocket {
    fn desc(&self) -> &os::IoDesc {
        &self.desc
    }
}

impl Socket for UnixSocket {
}

// Types of sockets
pub enum AddressFamily {
    Inet,
    Inet6,
    Unix,
}

pub enum SockAddr {
    UnixAddr(Path),
    InetAddr(IpAddr, Port)
}

impl SockAddr {
    pub fn parse(s: &str) -> Option<SockAddr> {
        use std::io::net::ip;

        let addr: Option<ip::SocketAddr> = FromStr::from_str(s);
        addr.map(|a| InetAddr(a.ip, a.port))
    }
}

impl FromStr for SockAddr {
    fn from_str(s: &str) -> Option<SockAddr> {
        SockAddr::parse(s)
    }
}

impl fmt::Show for SockAddr {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            InetAddr(ip, port) => write!(fmt, "{}:{}", ip, port),
            _ => write!(fmt, "not implemented")
        }
    }
}
<|endoftext|>


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

use std::ops::{Add, Div, Mul, Sub};

/// Vector with three f32 components
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vec3f {
    pub x: f32,
    pub y: f32,
    pub z: f32
}

impl Vec3f {
    fn new(x: f32, y: f32, z: f32) -> Vec3f {
        Vec3f { x: x,
                y: y,
                z: z }
    }
}

/// Vec3f(0.0, 0.0, 0.0)
pub const ZERO_3F: Vec3f = Vec3f { x: 0.0, y: 0.0, z: 0.0 };

pub trait CastF32 { fn as_f32(&self) -> f32; }

impl CastF32 for f32 { fn as_f32(&self) -> f32 { *self } }
impl CastF32 for f64 { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for i8  { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for i16 { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for i32 { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for u8  { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for u16 { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for u32 { fn as_f32(&self) -> f32 { *self as f32 } }

/// Create a Vec3f from x, y, and z inputs
///
/// This is a convenience function that provides a little more
/// flexibility than Vec3f::new in that it will happily take numbers
/// that aren't f32 (including a mix of different types for each
/// component). Vec3f is such a common type that it seems reasonable
/// to provide a little extra ease of use.
pub fn vec3f<X: CastF32, Y: CastF32, Z: CastF32>(x: X, y: Y, z: Z) -> Vec3f {
    Vec3f { x: x.as_f32(), y: y.as_f32(), z: z.as_f32() }
}

/// Inner product of two Vec3f inputs
pub fn dot3(a: Vec3f, b: Vec3f) -> f32 {
    let v = a * b;
    v.x + v.y + v.z
}

/// Cross product of two Vec3f inputs
pub fn cross(a: Vec3f, b: Vec3f) -> Vec3f {
    Vec3f::new(a.y * b.z - a.z * b.y,
               a.z * b.x - a.x * b.z,
               a.x * b.y - a.y * b.x)
}

impl Add for Vec3f {
    type Output = Vec3f;
    fn add(self, v: Vec3f) -> Vec3f {
        Vec3f::new(self.x + v.x, self.y + v.y, self.z + v.z)
    }
}

impl Div for Vec3f {
    type Output = Vec3f;
    fn div(self, v: Vec3f) -> Vec3f {
        Vec3f::new(self.x / v.x, self.y / v.y, self.z / v.z)
    }
}

impl Mul for Vec3f {
    type Output = Vec3f;
    fn mul(self, v: Vec3f) -> Vec3f {
        Vec3f::new(self.x * v.x, self.y * v.y, self.z * v.z)
    }
}

impl Sub for Vec3f {
    type Output = Vec3f;
    fn sub(self, v: Vec3f) -> Vec3f {
        Vec3f::new(self.x - v.x, self.y - v.y, self.z - v.z)
    }
}

#[test]
fn test_vec3f_create() {
    vec3f(1.0f32, 2, 3i32);
}

#[test]
fn test_vec3f_arithmetic() {
    let a = vec3f(1, 2, 3);
    let b = vec3f(4, 5, 6);
    assert!(a + b == vec3f(5, 7, 9));
    assert!(a - b == vec3f(-3, -3, -3));
    assert!(a * b == vec3f(4, 10, 18));
    assert!(a / b == vec3f(0.25, 2.0 / 5.0, 0.5));
}

#[test]
fn test_vec3f_dot() {
    assert!(dot3(vec3f(1, 2, 3), vec3f(4, 5, 6)) == 32.0);
}

#[test]
fn test_vec3f_cross() {
    assert!(cross(vec3f(1, 0, 0), vec3f(0, 1, 0)) == vec3f(0, 0, 1));
}
<commit_msg>Add multiplication between Vec3f and scalar f32<commit_after>// Copyright 2015 Nicholas Bishop
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::ops::{Add, Div, Mul, Sub};

/// Vector with three f32 components
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Vec3f {
    pub x: f32,
    pub y: f32,
    pub z: f32
}

impl Vec3f {
    fn new(x: f32, y: f32, z: f32) -> Vec3f {
        Vec3f { x: x,
                y: y,
                z: z }
    }
}

/// Vec3f(0.0, 0.0, 0.0)
pub const ZERO_3F: Vec3f = Vec3f { x: 0.0, y: 0.0, z: 0.0 };

pub trait CastF32 { fn as_f32(&self) -> f32; }

impl CastF32 for f32 { fn as_f32(&self) -> f32 { *self } }
impl CastF32 for f64 { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for i8  { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for i16 { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for i32 { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for u8  { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for u16 { fn as_f32(&self) -> f32 { *self as f32 } }
impl CastF32 for u32 { fn as_f32(&self) -> f32 { *self as f32 } }

/// Create a Vec3f from x, y, and z inputs
///
/// This is a convenience function that provides a little more
/// flexibility than Vec3f::new in that it will happily take numbers
/// that aren't f32 (including a mix of different types for each
/// component). Vec3f is such a common type that it seems reasonable
/// to provide a little extra ease of use.
pub fn vec3f<X: CastF32, Y: CastF32, Z: CastF32>(x: X, y: Y, z: Z) -> Vec3f {
    Vec3f { x: x.as_f32(), y: y.as_f32(), z: z.as_f32() }
}

/// Inner product of two Vec3f inputs
pub fn dot3(a: Vec3f, b: Vec3f) -> f32 {
    let v = a * b;
    v.x + v.y + v.z
}

/// Cross product of two Vec3f inputs
pub fn cross(a: Vec3f, b: Vec3f) -> Vec3f {
    Vec3f::new(a.y * b.z - a.z * b.y,
               a.z * b.x - a.x * b.z,
               a.x * b.y - a.y * b.x)
}

impl Add for Vec3f {
    type Output = Vec3f;
    fn add(self, v: Vec3f) -> Vec3f {
        Vec3f::new(self.x + v.x, self.y + v.y, self.z + v.z)
    }
}

impl Div for Vec3f {
    type Output = Vec3f;
    fn div(self, v: Vec3f) -> Vec3f {
        Vec3f::new(self.x / v.x, self.y / v.y, self.z / v.z)
    }
}

impl Mul<Vec3f> for Vec3f {
    type Output = Vec3f;
    fn mul(self, v: Vec3f) -> Vec3f {
        Vec3f::new(self.x * v.x, self.y * v.y, self.z * v.z)
    }
}

impl Mul<f32> for Vec3f {
    type Output = Vec3f;
    fn mul(self, f: f32) -> Vec3f {
        Vec3f::new(self.x * f, self.y * f, self.z * f)
    }
}

impl Sub for Vec3f {
    type Output = Vec3f;
    fn sub(self, v: Vec3f) -> Vec3f {
        Vec3f::new(self.x - v.x, self.y - v.y, self.z - v.z)
    }
}

#[test]
fn test_vec3f_create() {
    vec3f(1.0f32, 2, 3i32);
}

#[test]
fn test_vec3f_arithmetic() {
    let a = vec3f(1, 2, 3);
    let b = vec3f(4, 5, 6);
    assert!(a + b == vec3f(5, 7, 9));
    assert!(a - b == vec3f(-3, -3, -3));
    assert!(a * b == vec3f(4, 10, 18));
    assert!(a / b == vec3f(0.25, 2.0 / 5.0, 0.5));
}

#[test]
fn test_vec3f_dot() {
    assert!(dot3(vec3f(1, 2, 3), vec3f(4, 5, 6)) == 32.0);
}

#[test]
fn test_vec3f_cross() {
    assert!(cross(vec3f(1, 0, 0), vec3f(0, 1, 0)) == vec3f(0, 0, 1));
}
<|endoftext|>


<commit_before>use std::io::{Read, Write};
use common::*;

mod memory;
mod registers;
mod opcodes;
mod modes;

use self::memory::*;

pub struct VM<'a, R: Read, W: Write> {
    input: R,
    output: W,

    registers: Registers,
    memory: Memory<'a>,
}

impl<'a, R: Read, W: Write> VM<'a, R, W> {
    pub fn new(input: R, output: W) -> Self {
        unimplemented!()
    }

    pub fn run(&mut self, executable: Data) {
        unimplemented!()
    }

    fn parse_executable(executable: Data) -> Memory<'a> {
        unimplemented!()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{BufReader, BufWriter};
    use self::registers::*;
    use self::opcodes::*;
    use self::modes::*;

    #[cfg_attr(rustfmt, rustfmt_skip)]
    #[test]
    fn simple() {
        assert!(run(&[], vec![]).0.is_empty());

        {
            let mut executable = vec![0,
                MOV, REG, A, VALUE, 123, 0,
                ADD, REG, B, REG, A, REG, A];
            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[], executable);

            assert_eq!(123, registers[A as usize]);
            assert_eq!(246, registers[B as usize]);
            assert!(output.is_empty());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                SUB, REG, SP, 4, 0,  // stack allocation for 2 words
                PUSH, VALUE, 5, 0,
                PUSH, VALUE, 6, 0,
                ADD,   REG, A,   PTR, REG, SP,   PTR_WITH_OFFSET, REG, SP, 2, 0,
                // add a, [sp], [sp+2]
                POP, B,
                POP, C,
                ADD, 4, 0];
            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory)  = run(&[], executable);

            assert_eq!(11, registers[A as usize]);
            assert_eq!(6, registers[B as usize]);
            assert_eq!(5, registers[C as usize]);
            assert!(output.is_empty());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                MOV, REG, A, VALUE, 10, 0,
                DEC, REG, A,
                WRITE, REG, A,
                JNZ, 0];
            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[], executable);

            assert_eq!(0, registers[A as usize]);
            assert_eq!(&[10, 0, 9, 0, 8, 0, 7, 0, 6, 0, 5, 0,
                         4, 0, 3, 0, 2, 0, 1, 0, 0, 0], output.as_slice());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                MOV, REG, B, VALUE, 20, 0,       // data address
                MOV, REG, A, PTR, REG, B,        // dereference B
                WRITE, REG, A,
                INC, REG, B,
                INC, REG, B,
                JNZ, 0,

                3, 0,                            // data with address 23
                2, 0,                            // data with address 25
                1, 0,
                0, 0];
            let data_length = 8;
            let code_length = executable.len() as u8 - data_length;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[], executable);

            assert_eq!(8, memory.data.len());
            assert_eq!(0, registers[A as usize]);
            assert_eq!(&[3, 0, 2, 0, 1, 0, 0, 0], output.as_slice());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                READ, REG, A,
                WRITE, REG, A,
                JNZ, 0];
            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[3, 0, 2, 0, 1, 0, 0, 0], executable);
            assert_eq!(0, registers[A as usize]);
            assert_eq!(&[3, 0, 2, 0, 1, 0, 0, 0], output.as_slice());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                                                   // do
                READ, REG, A,                      //   a = read
                SUB, REG, SP, 2, 0,                //   (stack allocation)
                PUSH, REG, A,
                CALL, VALUE, 28, 0,                //   a = f(a)
                WRITE, REG, A,                     //   print a
                ADD,  REG, SP,  VALUE,  2, 0,      //   (stack deallocation)
                JNZ, 0,                            // while a != 0 goto addr 0
                JMP, 39,                           // exit

                // label f
                PUSH, REG, BP,
                MOV, REG, BP, REG, SP,

                POP, REG, A,
                MUL, REG, A, REG, A, VALUE, 2, 0,  // a = a * 2

                MOV, REG, SP, REG, BP,
                POP, REG, BP,
                RET,

                NOP                                // optional
            ];

            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[3, 0, 2, 0, 1, 0, 0, 0],
                                                  executable);

            assert_eq!(0, registers[A as usize]);
            assert_eq!(&[6, 0, 4, 0, 1, 0, 0, 0], output.as_slice());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }
    }

    fn run<'a>(input: &[u8], executable: Data) -> (Data, Registers, Memory<'a>) {
        let input = BufReader::new(input);

        let output: Data = vec![];
        let output = BufWriter::new(output);

        let mut vm = VM::new(input, output);
        vm.run(executable);

        let output = vm.output
            .get_mut()
            .by_ref()
            .iter()
            .map(|x| *x)
            .collect::<Data>();

        (output, vm.registers, vm.memory)
    }
}
<commit_msg>using rustfmt<commit_after>use common::*;
use std::io::{Read, Write};

mod memory;
mod registers;
mod opcodes;
mod modes;

use self::memory::*;

pub struct VM<'a, R: Read, W: Write> {
    input: R,
    output: W,

    registers: Registers,
    memory: Memory<'a>,
}

impl<'a, R: Read, W: Write> VM<'a, R, W> {
    pub fn new(input: R, output: W) -> Self {
        unimplemented!()
    }

    pub fn run(&mut self, executable: Data) {
        unimplemented!()
    }

    fn parse_executable(executable: Data) -> Memory<'a> {
        unimplemented!()
    }
}

#[cfg(test)]
mod tests {
    use self::modes::*;
    use self::opcodes::*;
    use self::registers::*;
    use std::io::{BufReader, BufWriter};
    use super::*;

    #[cfg_attr(rustfmt, rustfmt_skip)]
    #[test]
    fn simple() {
        assert!(run(&[], vec![]).0.is_empty());

        {
            let mut executable = vec![0,
                MOV, REG, A, VALUE, 123, 0,
                ADD, REG, B, REG, A, REG, A];
            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[], executable);

            assert_eq!(123, registers[A as usize]);
            assert_eq!(246, registers[B as usize]);
            assert!(output.is_empty());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                SUB, REG, SP, 4, 0,  // stack allocation for 2 words
                PUSH, VALUE, 5, 0,
                PUSH, VALUE, 6, 0,
                ADD,   REG, A,   PTR, REG, SP,   PTR_WITH_OFFSET, REG, SP, 2, 0,
                // add a, [sp], [sp+2]
                POP, B,
                POP, C,
                ADD, 4, 0];
            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory)  = run(&[], executable);

            assert_eq!(11, registers[A as usize]);
            assert_eq!(6, registers[B as usize]);
            assert_eq!(5, registers[C as usize]);
            assert!(output.is_empty());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                MOV, REG, A, VALUE, 10, 0,
                DEC, REG, A,
                WRITE, REG, A,
                JNZ, 0];
            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[], executable);

            assert_eq!(0, registers[A as usize]);
            assert_eq!(&[10, 0, 9, 0, 8, 0, 7, 0, 6, 0, 5, 0,
                         4, 0, 3, 0, 2, 0, 1, 0, 0, 0], output.as_slice());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                MOV, REG, B, VALUE, 20, 0,       // data address
                MOV, REG, A, PTR, REG, B,        // dereference B
                WRITE, REG, A,
                INC, REG, B,
                INC, REG, B,
                JNZ, 0,

                3, 0,                            // data with address 23
                2, 0,                            // data with address 25
                1, 0,
                0, 0];
            let data_length = 8;
            let code_length = executable.len() as u8 - data_length;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[], executable);

            assert_eq!(8, memory.data.len());
            assert_eq!(0, registers[A as usize]);
            assert_eq!(&[3, 0, 2, 0, 1, 0, 0, 0], output.as_slice());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                READ, REG, A,
                WRITE, REG, A,
                JNZ, 0];
            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[3, 0, 2, 0, 1, 0, 0, 0], executable);
            assert_eq!(0, registers[A as usize]);
            assert_eq!(&[3, 0, 2, 0, 1, 0, 0, 0], output.as_slice());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }

        {
            let mut executable = vec![0,
                                                   // do
                READ, REG, A,                      //   a = read
                SUB, REG, SP, 2, 0,                //   (stack allocation)
                PUSH, REG, A,
                CALL, VALUE, 28, 0,                //   a = f(a)
                WRITE, REG, A,                     //   print a
                ADD,  REG, SP,  VALUE,  2, 0,      //   (stack deallocation)
                JNZ, 0,                            // while a != 0 goto addr 0
                JMP, 39,                           // exit

                // label f
                PUSH, REG, BP,
                MOV, REG, BP, REG, SP,

                POP, REG, A,
                MUL, REG, A, REG, A, VALUE, 2, 0,  // a = a * 2

                MOV, REG, SP, REG, BP,
                POP, REG, BP,
                RET,

                NOP                                // optional
            ];

            let code_length = executable.len() as u8;
            executable[0] = code_length;

            let (output, registers, memory) = run(&[3, 0, 2, 0, 1, 0, 0, 0],
                                                  executable);

            assert_eq!(0, registers[A as usize]);
            assert_eq!(&[6, 0, 4, 0, 1, 0, 0, 0], output.as_slice());
            assert!(memory.stack_is_empty(registers[SP as usize]));
        }
    }

    fn run<'a>(input: &[u8], executable: Data) -> (Data, Registers, Memory<'a>) {
        let input = BufReader::new(input);

        let output: Data = vec![];
        let output = BufWriter::new(output);

        let mut vm = VM::new(input, output);
        vm.run(executable);

        let output = vm.output
            .get_mut()
            .by_ref()
            .iter()
            .map(|x| *x)
            .collect::<Data>();

        (output, vm.registers, vm.memory)
    }
}
<|endoftext|>


<commit_before>//
// Sysinfo
//
// Copyright (c) 2018 Guillaume Gomez
//

use ComponentExt;

/// Struct containing a component information (temperature and name for the moment).
pub struct Component {
    temperature: f32,
    max: f32,
    critical: Option<f32>,
    label: String,
}

impl Component {
    /// Creates a new `Component` with the given information.
    pub fn new(label: String, max: Option<f32>, critical: Option<f32>) -> Component {
        Component {
            temperature: 0f32,
            label: label,
            max: max.unwrap_or(0.0),
            critical: critical,
        }
    }
}

impl ComponentExt for Component {
    fn get_temperature(&self) -> f32 {
        self.temperature
    }

    fn get_max(&self) -> f32 {
        self.max
    }

    fn get_critical(&self) -> Option<f32> {
        self.critical
    }

    fn get_label(&self) -> &str {
        &self.label
    }
}

pub fn get_components() -> Vec<Component> {
    Connection::new()
        .and_then(|x| x.initialize_security())
        .and_then(|x| x.create_instance())
        .and_then(|x| x.connect_server())
        .and_then(|x| x.set_proxy_blanket())
        .and_then(|x| x.exec_query())
        .and_then(|x| {
            x.iterate();
            Some(())
        });
    Vec::new()
}

use std::ptr::null_mut;

use winapi::shared::rpcdce::{RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, RPC_C_AUTHN_LEVEL_CALL};
use winapi::shared::winerror::FAILED;
use winapi::shared::wtypesbase::CLSCTX_INPROC_SERVER;
use winapi::um::combaseapi::{CoCreateInstance, CoInitializeEx, CoUninitialize, CoInitializeSecurity, CoSetProxyBlanket};
use winapi::um::objbase::COINIT_MULTITHREADED;
use winapi::um::objidl::EOAC_NONE;
use winapi::um::oleauto::SysAllocString;
use winapi::um::oleauto::VariantClear;
use winapi::um::wbemcli::{CLSID_WbemLocator, IEnumWbemClassObject, IID_IWbemLocator, IWbemLocator, IWbemServices, WBEM_S_NO_ERROR, WBEM_FLAG_NONSYSTEM_ONLY, WBEM_FLAG_RETURN_IMMEDIATELY, WBEM_FLAG_FORWARD_ONLY};
use winapi::shared::wtypes::BSTR;
use winapi::um::oleauto::SysFreeString;
use winapi::um::wbemcli::IWbemClassObject;
 use winapi::um::oaidl::VARIANT_n3;

struct Instance(*mut IWbemLocator);

impl Drop for Instance {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { (*self.0).Release(); }
        }
    }
}

struct ServerConnection(*mut IWbemServices);

impl Drop for ServerConnection {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { (*self.0).Release(); }
        }
    }
}

struct Enumerator(*mut IEnumWbemClassObject);

impl Drop for Enumerator {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { (*self.0).Release(); }
        }
    }
}

macro_rules! bstr {
    ($($x:expr),*) => {{
        let x: &[u16] = &[$($x as u16),*];
        SysAllocString(x.as_ptr())
    }}
}

struct Connection {
    instance: Option<Instance>,
    server_connection: Option<ServerConnection>,
    enumerator: Option<Enumerator>,
}

impl Connection {
    fn new() -> Option<Connection> {
        let x = unsafe { CoInitializeEx(null_mut(), 0) };
        if FAILED(x) {
            eprintln!("1 => {}", x);
            None
        } else {
            Some(Connection {
                instance: None,
                server_connection: None,
                enumerator: None,
            })
        }
    }

    fn initialize_security(self) -> Option<Connection> {
        if FAILED(unsafe {
            CoInitializeSecurity(
                null_mut(),
                -1,
                null_mut(),
                null_mut(),
                RPC_C_AUTHN_LEVEL_DEFAULT,
                RPC_C_IMP_LEVEL_IMPERSONATE,
                null_mut(),
                EOAC_NONE,
                null_mut(),
            )
        }) {
            eprintln!("2");
            None
        } else {
            Some(self)
        }
    }

    fn create_instance(mut self) -> Option<Connection> {
        let mut pLoc = null_mut();

        if FAILED(unsafe {
            CoCreateInstance(
                *(&CLSID_WbemLocator as *const _ as *const usize) as *mut _,
                null_mut(),
                CLSCTX_INPROC_SERVER,
                *(&IID_IWbemLocator as *const _ as *const usize) as *mut _,
                &mut pLoc as *mut _ as *mut _,
            )
        }) {
            eprintln!("3");
            None
        } else {
            self.instance = Some(Instance(pLoc));
            Some(self)
        }
    }

    fn connect_server(mut self) -> Option<Connection> {
        let mut pSvc = null_mut();

        if let Some(ref instance) = self.instance {
            unsafe {
                let s = bstr!('R', 'O', 'O', 'T', '\\', 'W', 'M', 'I');
                let res = (*instance.0).ConnectServer(
                    s,
                    null_mut(),
                    null_mut(),
                    null_mut(),
                    0,
                    null_mut(),
                    null_mut(),
                    &mut pSvc as *mut _,
                );
                SysFreeString(s);
                if FAILED(res) {
                    eprintln!("4");
                    return None;
                }
            }
        } else {
            eprintln!("5");
            return None;
        }
        self.server_connection = Some(ServerConnection(pSvc));
        Some(self)
    }

    fn set_proxy_blanket(self) -> Option<Connection> {
        if let Some(ref server_connection) = self.server_connection {
            unsafe {
                if FAILED(CoSetProxyBlanket(
                   server_connection.0 as *mut _,
                   RPC_C_AUTHN_WINNT,
                   RPC_C_AUTHZ_NONE,
                   null_mut(),
                   RPC_C_AUTHN_LEVEL_CALL,
                   RPC_C_IMP_LEVEL_IMPERSONATE,
                   null_mut(),
                   EOAC_NONE,
                )) {
                    eprintln!("6");
                    return None;
                }
            }
        } else {
            eprintln!("7");
            return None;
        }
        Some(self)
    }

    fn exec_query(mut self) -> Option<Connection> {
        let mut pEnumerator = null_mut();

        if let Some(ref server_connection) = self.server_connection {
            unsafe {
                let s = bstr!('W', 'Q', 'L'); // query kind
                let query = bstr!('S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','M','S','A','c','p','i','_','T','h','e','r','m','a','l','Z','o','n','e','T','e','m','p','e','r','a','t','u','r','e');
                let hres = (*server_connection.0).ExecQuery(
                    s,
                    query,
                    (WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY) as _,
                    null_mut(),
                    &mut pEnumerator as *mut _,
                );
                SysFreeString(s);
                SysFreeString(query);
                if FAILED(hres) {
                    eprintln!("8");
                    return None;
                }
            }
        } else {
            eprintln!("9");
            return None;
        }
        self.enumerator = Some(Enumerator(pEnumerator));
        Some(self)
    }

    fn iterate(mut self) {
        let pEnum = match self.enumerator.take() {
            Some(x) => x,
            None => {
                eprintln!("10");
                return;
            }
        };
        loop {
            let mut pObj: *mut IWbemClassObject = null_mut();
            let mut uReturned = 0;

            let hRes = unsafe {
                (*pEnum.0).Next(
                    0,                  // Time out
                    1,                  // One object
                    &mut pObj as *mut _,
                    &mut uReturned,
                )
            };

            if uReturned == 0 {
                eprintln!("and done!");
                break;
            }

            unsafe {
                (*pObj).BeginEnumeration(WBEM_FLAG_NONSYSTEM_ONLY as _);

                let mut pVal: VARIANT_n3 = ::std::mem::uninitialized();
                let mut pstrName: BSTR = null_mut();

                while (*pObj).Next(0, &mut pstrName, &mut pVal as *mut _ as *mut _, null_mut(), null_mut()) == WBEM_S_NO_ERROR as _ {
                    {
                        let mut i = 0;
                        while (*pstrName.offset(i)) != 0 {
                            i += 1;
                        }
                        let bytes = ::std::slice::from_raw_parts(pstrName as *const u16, i as usize + 1);
                        i = 0;
                        while (*pVal.bstrVal().offset(i)) != 0 {
                            i += 1;
                        }
                        let bytes2 = ::std::slice::from_raw_parts(*pVal.bstrVal() as *const u16, i as usize + 1);
                        println!("==> {}::{}", String::from_utf16_lossy(bytes), String::from_utf16_lossy(bytes2));
                    }
                    SysFreeString(pstrName);
                    VariantClear(&mut pVal as *mut _ as *mut _);
                }
            }

            unsafe { (*pObj).Release(); }
        }
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        unsafe { CoUninitialize(); }
    }
}
<commit_msg>Working version<commit_after>//
// Sysinfo
//
// Copyright (c) 2018 Guillaume Gomez
//

use ComponentExt;

/// Struct containing a component information (temperature and name for the moment).
pub struct Component {
    temperature: f32,
    max: f32,
    critical: Option<f32>,
    label: String,
}

impl Component {
    /// Creates a new `Component` with the given information.
    pub fn new(label: String, max: Option<f32>, critical: Option<f32>) -> Component {
        Component {
            temperature: 0f32,
            label: label,
            max: max.unwrap_or(0.0),
            critical: critical,
        }
    }
}

impl ComponentExt for Component {
    fn get_temperature(&self) -> f32 {
        self.temperature
    }

    fn get_max(&self) -> f32 {
        self.max
    }

    fn get_critical(&self) -> Option<f32> {
        self.critical
    }

    fn get_label(&self) -> &str {
        &self.label
    }
}

pub fn get_components() -> Vec<Component> {
    Connection::new()
        .and_then(|x| x.initialize_security())
        .and_then(|x| x.create_instance())
        .and_then(|x| x.connect_server())
        .and_then(|x| x.set_proxy_blanket())
        .and_then(|x| x.exec_query())
        .and_then(|x| {
            x.iterate();
            Some(())
        });
    Vec::new()
}

use std::ptr::null_mut;

use winapi::shared::rpcdce::{RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, RPC_C_AUTHN_LEVEL_CALL};
use winapi::shared::winerror::FAILED;
use winapi::shared::wtypesbase::CLSCTX_INPROC_SERVER;
use winapi::um::combaseapi::{CoCreateInstance, CoInitializeEx, CoUninitialize, CoInitializeSecurity, CoSetProxyBlanket};
use winapi::um::objbase::COINIT_MULTITHREADED;
use winapi::um::objidl::EOAC_NONE;
use winapi::um::oleauto::SysAllocString;
use winapi::um::oleauto::{VariantClear, VariantInit};
use winapi::um::wbemcli::{CLSID_WbemLocator, IEnumWbemClassObject, IID_IWbemLocator, IWbemLocator, IWbemServices, WBEM_S_NO_ERROR, WBEM_FLAG_NONSYSTEM_ONLY, WBEM_FLAG_RETURN_IMMEDIATELY, WBEM_FLAG_FORWARD_ONLY};
use winapi::shared::wtypes::BSTR;
use winapi::um::oleauto::SysFreeString;
use winapi::um::wbemcli::IWbemClassObject;
 use winapi::um::oaidl::{VARIANT, VARIANT_n3};

struct Instance(*mut IWbemLocator);

impl Drop for Instance {
    fn drop(&mut self) {
        println!("Instance::drop");
        if !self.0.is_null() {
            unsafe { (*self.0).Release(); }
        }
    }
}

struct ServerConnection(*mut IWbemServices);

impl Drop for ServerConnection {
    fn drop(&mut self) {
        println!("ServerConnection::drop");
        if !self.0.is_null() {
            unsafe { (*self.0).Release(); }
        }
    }
}

struct Enumerator(*mut IEnumWbemClassObject);

impl Drop for Enumerator {
    fn drop(&mut self) {
        println!("Enumerator::drop");
        if !self.0.is_null() {
            unsafe { (*self.0).Release(); }
        }
    }
}

macro_rules! bstr {
    ($($x:expr),*) => {{
        let x: &[u16] = &[$($x as u16),*, 0];
        SysAllocString(x.as_ptr())
    }}
}

struct Connection {
    instance: Option<Instance>,
    server_connection: Option<ServerConnection>,
    enumerator: Option<Enumerator>,
}

impl Connection {
    fn new() -> Option<Connection> {
        // "Funnily", this function returns ok, false or "this function has already been called".
        // So whatever, let's just ignore whatever it might return then!
        unsafe { CoInitializeEx(null_mut(), 0) };
         Some(Connection {
            instance: None,
            server_connection: None,
            enumerator: None,
        })
    }

    fn initialize_security(self) -> Option<Connection> {
        println!("initialize_security");
        if FAILED(unsafe {
            CoInitializeSecurity(
                null_mut(),
                -1,
                null_mut(),
                null_mut(),
                RPC_C_AUTHN_LEVEL_DEFAULT,
                RPC_C_IMP_LEVEL_IMPERSONATE,
                null_mut(),
                EOAC_NONE,
                null_mut(),
            )
        }) {
            eprintln!("2");
            None
        } else {
            Some(self)
        }
    }

    fn create_instance(mut self) -> Option<Connection> {
        println!("create_instance");
        let mut pLoc = null_mut();

        if FAILED(unsafe {
            CoCreateInstance(
                &CLSID_WbemLocator as *const _,
                null_mut(),
                CLSCTX_INPROC_SERVER,
                &IID_IWbemLocator as *const _,
                &mut pLoc as *mut _ as *mut _,
            )
        }) {
            eprintln!("3");
            None
        } else {
            self.instance = Some(Instance(pLoc));
            Some(self)
        }
    }

    fn connect_server(mut self) -> Option<Connection> {
        println!("connect_server");
        let mut pSvc = null_mut();

        if let Some(ref instance) = self.instance {
            unsafe {
                let s = bstr!('r', 'o', 'o', 't', '\\', 'W', 'M', 'I');
                let res = (*instance.0).ConnectServer(
                    s,
                    null_mut(),
                    null_mut(),
                    null_mut(),
                    0,
                    null_mut(),
                    null_mut(),
                    &mut pSvc as *mut _,
                );
                SysFreeString(s);
                if FAILED(res) {
                    eprintln!("4 => {}", res);
                    return None;
                }
            }
        } else {
            eprintln!("5");
            return None;
        }
        self.server_connection = Some(ServerConnection(pSvc));
        Some(self)
    }

    fn set_proxy_blanket(self) -> Option<Connection> {
        println!("set_proxy_blanket");
        if let Some(ref server_connection) = self.server_connection {
            unsafe {
                if FAILED(CoSetProxyBlanket(
                   server_connection.0 as *mut _,
                   RPC_C_AUTHN_WINNT,
                   RPC_C_AUTHZ_NONE,
                   null_mut(),
                   RPC_C_AUTHN_LEVEL_CALL,
                   RPC_C_IMP_LEVEL_IMPERSONATE,
                   null_mut(),
                   EOAC_NONE,
                )) {
                    eprintln!("6");
                    return None;
                }
            }
        } else {
            eprintln!("7");
            return None;
        }
        Some(self)
    }

    fn exec_query(mut self) -> Option<Connection> {
        let mut pEnumerator = null_mut();

        if let Some(ref server_connection) = self.server_connection {
            unsafe {
                let s = bstr!('W', 'Q', 'L'); // query kind
                // SELECT * FROM MSAcpi_ThermalZoneTemperature
                let query = bstr!('S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ','M','S','A','c','p','i','_','T','h','e','r','m','a','l','Z','o','n','e','T','e','m','p','e','r','a','t','u','r','e');
                let hres = (*server_connection.0).ExecQuery(
                    s,
                    query,
                    (WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY) as _,
                    null_mut(),
                    &mut pEnumerator as *mut _,
                );
                println!("xa");
                SysFreeString(s);
                SysFreeString(query);
                if FAILED(hres) {
                    eprintln!("8");
                    return None;
                }
            }
        } else {
            eprintln!("9");
            return None;
        }
        self.enumerator = Some(Enumerator(pEnumerator));
        Some(self)
    }

    fn iterate(mut self) {
        let pEnum = match self.enumerator.take() {
            Some(x) => x,
            None => {
                eprintln!("10");
                return;
            }
        };
        loop {
            let mut pObj: *mut IWbemClassObject = null_mut();
            let mut uReturned = 0;

            let hRes = unsafe {
                println!("foo {:?}", (*pEnum.0).lpVtbl as *const _ as usize);
                use winapi::um::wbemcli::WBEM_INFINITE;
                let x = (*(*pEnum.0).lpVtbl).Next;
                x(
                    pEnum.0,
                    WBEM_INFINITE as _, // Time out
                    1,                  // One object
                    &mut pObj as *mut _,
                    &mut uReturned,
                )
            };

            println!("-> {:?}", hRes);

            if uReturned == 0 {
                eprintln!("and done!");
                break;
            }

            unsafe {
                (*pObj).BeginEnumeration(WBEM_FLAG_NONSYSTEM_ONLY as _);

                let mut pVal: VARIANT = ::std::mem::uninitialized();
                let mut pstrName: BSTR = null_mut();

                //VariantInit(&mut pVal as *mut _ as *mut _);
                while (*pObj).Next(0, &mut pstrName, &mut pVal as *mut _ as *mut _, null_mut(), null_mut()) == WBEM_S_NO_ERROR as _ {
                    {
                        println!("c");
                        let mut i = 0;
                        while (*pstrName.offset(i)) != 0 {
                            i += 1;
                        }
                        let bytes = ::std::slice::from_raw_parts(pstrName as *const u16, i as usize);
                        println!("a");
                        i = 0;
                        let pVal = &pVal.n1;
                        let x = pVal.decVal();
                        println!("x {:?} {}", x.Hi32, x.Lo64);
                        /*while *x.offset(i) != 0 {
                            println!("a");
                            i += 1;
                        }
                        println!("b {:?}", x);
                        let bytes2 = ::std::slice::from_raw_parts(*x as *const u16, i as usize);
                        println!("==> {}::{}", String::from_utf16_lossy(bytes), String::from_utf16_lossy(bytes2));*/
                        println!("==> {}::{}", String::from_utf16_lossy(bytes), x.Hi32);
                    }
                    SysFreeString(pstrName);
                    VariantClear(&mut pVal as *mut _ as *mut _);
                }
            }

            unsafe { (*pObj).Release(); }
        }
    }
}

impl Drop for Connection {
    fn drop(&mut self) {
        // Those three calls are here to enforce that they get dropped in the good order.
        self.enumerator.take();
        self.server_connection.take();
        self.instance.take();
        println!("Connection::drop");
        unsafe { CoUninitialize(); }
    }
}
<|endoftext|>


<commit_before><commit_msg>Improve code structure<commit_after><|endoftext|>


<commit_before><commit_msg>Add some multi-byte character tests<commit_after><|endoftext|>


<commit_before><commit_msg>Add more data members to `Stream` struct<commit_after><|endoftext|>


<commit_before><commit_msg>Eval errors are Formulas<commit_after><|endoftext|>


<commit_before><commit_msg>add print formating for the terminal output<commit_after><|endoftext|>


<commit_before><commit_msg>Fix build breakage: ns module doesn't exist yet<commit_after><|endoftext|>


<commit_before><commit_msg>connect stdout/stderr directly to a file<commit_after><|endoftext|>


<commit_before><commit_msg>Add some trivial implementations<commit_after><|endoftext|>


<commit_before>use {
    Matrix2d,
};
use vecmath::{
    multiply,
    rotate_radians,
    scale,
    shear,
    translate,
};
use internal::{
    CanTransform,
    HasTransform,
};

/// Implemented by contexts that can transform.
pub trait RelativeTransform2d<'a> {
    /// Translate x and y.
    fn trans(&'a self, x: f64, y: f64) -> Self;

    /// Translate x an y in local coordinates.
    fn trans_local(&'a self, x: f64, y: f64) -> Self;

    /// Rotates degrees.
    #[inline(always)]
    fn rot_deg(&'a self, angle: f64) -> Self {
        let pi: f64 = Float::pi();
        self.rot_rad(angle * pi / 180.0)
    }

    /// Rotates degrees in local coordinates.
    #[inline(always)]
    fn rot_deg_local(&'a self, angle: f64) -> Self {
        let pi: f64 = Float::pi();
        self.rot_rad_local(angle * pi / 180.0)
    }

    /// Rotate radians.
    fn rot_rad(&'a self, angle: f64) -> Self;

    /// Rotate radians in local coordinates.
    fn rot_rad_local(&'a self, angle: f64) -> Self;

    /// Scale.
    fn scale(&'a self, sx: f64, sy: f64) -> Self;

    /// Scales in local coordinates.
    fn scale_local(&'a self, sx: f64, sy: f64) -> Self;

    /// Scales in both directions.
    #[inline(always)]
    fn zoom(&'a self, s: f64) -> Self {
        self.scale(s, s)
    }

    /// Scales in both directions in local coordinates.
    #[inline(always)]
    fn zoom_local(&'a self, s: f64) -> Self {
        self.scale_local(s, s)
    }

    /// Flips vertically.
    #[inline(always)]
    fn flip_v(&'a self) -> Self {
        self.scale(1.0, -1.0)
    }

    /// Flips vertically in local coordinates.
    #[inline(always)]
    fn flip_v_local(&'a self) -> Self {
        self.scale_local(1.0, -1.0)
    }

    /// Flips horizontally.
    #[inline(always)]
    fn flip_h(&'a self) -> Self {
        self.scale(-1.0, 0.0)
    }

    /// Flips horizontally in local coordinates.
    #[inline(always)]
    fn flip_h_local(&'a self) -> Self {
        self.scale_local(-1.0, 0.0)
    }

    /// Shear.
    fn shear(&'a self, sx: f64, sy: f64) -> Self;

    /// Shears in local coordinates.
    fn shear_local(&'a self, sx: f64, sy: f64) -> Self;
}

impl<
    'a,
    T: HasTransform<'a, Matrix2d> + CanTransform<'a, T, Matrix2d>
> RelativeTransform2d<'a> for T {
    #[inline(always)]
    fn trans(&'a self, x: f64, y: f64) -> T {
        let trans = translate(x, y);
        self.transform(multiply(&trans, self.get_transform()))
    }

    #[inline(always)]
    fn trans_local(&'a self, x: f64, y: f64) -> T {
        let trans = translate(x, y);
        self.transform(multiply(self.get_transform(), &trans))
    }

    #[inline(always)]
    fn rot_rad(&'a self, angle: f64) -> T {
        let rot = rotate_radians(angle);
        self.transform(multiply(&rot, self.get_transform()))
    }

    #[inline(always)]
    fn rot_rad_local(&'a self, angle: f64) -> T {
        let rot = rotate_radians(angle);
        self.transform(multiply(self.get_transform(), &rot))
    }

    #[inline(always)]
    fn scale(&'a self, sx: f64, sy: f64) -> T {
        let scale = scale(sx, sy);
        self.transform(multiply(&scale, self.get_transform()))
    }

    #[inline(always)]
    fn scale_local(&'a self, sx: f64, sy: f64) -> T {
        let scale = scale(sx, sy);
        self.transform(multiply(self.get_transform(), &scale))
    }

    #[inline(always)]
    fn shear(&'a self, sx: f64, sy: f64) -> T {
        let shear = shear(sx, sy);
        self.transform(multiply(&shear, self.get_transform()))
    }

    #[inline(always)]
    fn shear_local(&'a self, sx: f64, sy: f64) -> T {
        let shear = shear(sx, sy);
        self.transform(multiply(self.get_transform(), &shear))
    }
}

<commit_msg>Added `orient` and `orient_local`<commit_after>use {
    Matrix2d,
};
use vecmath::{
    multiply,
    orient,
    rotate_radians,
    scale,
    shear,
    translate,
};
use internal::{
    CanTransform,
    HasTransform,
};

/// Implemented by contexts that can transform.
pub trait RelativeTransform2d<'a> {
    /// Translate x and y.
    fn trans(&'a self, x: f64, y: f64) -> Self;

    /// Translate x an y in local coordinates.
    fn trans_local(&'a self, x: f64, y: f64) -> Self;

    /// Rotates degrees.
    #[inline(always)]
    fn rot_deg(&'a self, angle: f64) -> Self {
        let pi: f64 = Float::pi();
        self.rot_rad(angle * pi / 180.0)
    }

    /// Rotates degrees in local coordinates.
    #[inline(always)]
    fn rot_deg_local(&'a self, angle: f64) -> Self {
        let pi: f64 = Float::pi();
        self.rot_rad_local(angle * pi / 180.0)
    }

    /// Rotate radians.
    fn rot_rad(&'a self, angle: f64) -> Self;

    /// Rotate radians in local coordinates.
    fn rot_rad_local(&'a self, angle: f64) -> Self;

    /// Orients x axis to look at point.
    ///
    /// Leaves x axis unchanged if the point to look at is the origin.
    fn orient(&'a self, x: f64, y: f64) -> Self;

    /// Orients x axis to look at point locally.
    ///
    /// Leaves x axis unchanged if the point to look at is the origin.
    fn orient_local(&'a self, x: f64, y: f64) -> Self;

    /// Scale.
    fn scale(&'a self, sx: f64, sy: f64) -> Self;

    /// Scales in local coordinates.
    fn scale_local(&'a self, sx: f64, sy: f64) -> Self;

    /// Scales in both directions.
    #[inline(always)]
    fn zoom(&'a self, s: f64) -> Self {
        self.scale(s, s)
    }

    /// Scales in both directions in local coordinates.
    #[inline(always)]
    fn zoom_local(&'a self, s: f64) -> Self {
        self.scale_local(s, s)
    }

    /// Flips vertically.
    #[inline(always)]
    fn flip_v(&'a self) -> Self {
        self.scale(1.0, -1.0)
    }

    /// Flips vertically in local coordinates.
    #[inline(always)]
    fn flip_v_local(&'a self) -> Self {
        self.scale_local(1.0, -1.0)
    }

    /// Flips horizontally.
    #[inline(always)]
    fn flip_h(&'a self) -> Self {
        self.scale(-1.0, 0.0)
    }

    /// Flips horizontally in local coordinates.
    #[inline(always)]
    fn flip_h_local(&'a self) -> Self {
        self.scale_local(-1.0, 0.0)
    }

    /// Shear.
    fn shear(&'a self, sx: f64, sy: f64) -> Self;

    /// Shears in local coordinates.
    fn shear_local(&'a self, sx: f64, sy: f64) -> Self;
}

impl<
    'a,
    T: HasTransform<'a, Matrix2d> + CanTransform<'a, T, Matrix2d>
> RelativeTransform2d<'a> for T {
    #[inline(always)]
    fn trans(&'a self, x: f64, y: f64) -> T {
        let trans = translate(x, y);
        self.transform(multiply(&trans, self.get_transform()))
    }

    #[inline(always)]
    fn trans_local(&'a self, x: f64, y: f64) -> T {
        let trans = translate(x, y);
        self.transform(multiply(self.get_transform(), &trans))
    }

    #[inline(always)]
    fn rot_rad(&'a self, angle: f64) -> T {
        let rot = rotate_radians(angle);
        self.transform(multiply(&rot, self.get_transform()))
    }

    #[inline(always)]
    fn rot_rad_local(&'a self, angle: f64) -> T {
        let rot = rotate_radians(angle);
        self.transform(multiply(self.get_transform(), &rot))
    }

    #[inline(always)]
    fn orient(&'a self, x: f64, y: f64) -> T {
        let orient = orient(x, y);
        self.transform(multiply(&orient, self.get_transform()))
    }

    #[inline(always)]
    fn orient_local(&'a self, x: f64, y: f64) -> T {
        let orient = orient(x, y);
        self.transform(multiply(self.get_transform(), &orient))
    }

    #[inline(always)]
    fn scale(&'a self, sx: f64, sy: f64) -> T {
        let scale = scale(sx, sy);
        self.transform(multiply(&scale, self.get_transform()))
    }

    #[inline(always)]
    fn scale_local(&'a self, sx: f64, sy: f64) -> T {
        let scale = scale(sx, sy);
        self.transform(multiply(self.get_transform(), &scale))
    }

    #[inline(always)]
    fn shear(&'a self, sx: f64, sy: f64) -> T {
        let shear = shear(sx, sy);
        self.transform(multiply(&shear, self.get_transform()))
    }

    #[inline(always)]
    fn shear_local(&'a self, sx: f64, sy: f64) -> T {
        let shear = shear(sx, sy);
        self.transform(multiply(self.get_transform(), &shear))
    }
}

<|endoftext|>