<commit_before>use std::collections::HashSet;

struct WorldMap{
    map: HashSet<(i8, i8)>
}

impl WorldMap{

    fn empty() -> WorldMap {
        return WorldMap::new( HashSet::new() );
    }

    fn new(new_map: HashSet<(i8,i8)>) -> WorldMap {
        return WorldMap { map: new_map };
    }

    fn mark_cell_as_alive(&self, cell_coordinates: (i8, i8)) -> WorldMap {
        let mut new_map = self.map.clone();
        new_map.insert(cell_coordinates);
        let new_world = WorldMap::new(new_map);
        return new_world;
    }

    fn is_cell_alive(&self, cell_coordinates: (i8,i8)) -> bool {
        return self.map.contains(&cell_coordinates);
    }

    fn count_alive_neighbours(&self, cell_coordinates: (i8, i8)) -> usize {
        let mut neighbour_coordinates = HashSet::new();
        let (x, y) = cell_coordinates;
        neighbour_coordinates.insert((x-1, y-1));
        neighbour_coordinates.insert((x-1, y));
        neighbour_coordinates.insert((x-1, y+1));
        neighbour_coordinates.insert((x, y-1));
        neighbour_coordinates.insert((x, y+1));
        neighbour_coordinates.insert((x+1, y-1));
        neighbour_coordinates.insert((x+1, y));
        neighbour_coordinates.insert((x+1, y+1));
        let neighbours_alive = self.map.intersection(&neighbour_coordinates).collect::<Vec<&(i8,i8)>>();
        return neighbours_alive.len();
    }
}

#[test]
fn the_only_alive_cell_should_have_no_alive_neighbours() {
    let coords = (0,0);
    let world = WorldMap::empty();
    let new_world = world.mark_cell_as_alive(coords);
    let alive_neighbours_count = new_world.count_alive_neighbours(coords);
    assert_eq!(0, alive_neighbours_count);
}

#[test]
fn is_cell_alive_should_return_true_for_alive_cell() {
    let coords = (0,0);
    let world = WorldMap::empty();
    let new_world = world.mark_cell_as_alive(coords);
    let is_alive = new_world.is_cell_alive(coords);
    assert_eq!(true, is_alive);
}

#[test]
fn is_cell_alive_should_return_false_for_dead_cell() {
    let coords = (0,0);
    let world = WorldMap::empty();
    let is_alive = world.is_cell_alive(coords);
    assert_eq!(false, is_alive);
}
<commit_msg>one more test for the alive neighbour count<commit_after>use std::collections::HashSet;

struct WorldMap{
    map: HashSet<(i8, i8)>
}

impl WorldMap{

    fn empty() -> WorldMap {
        return WorldMap::new( HashSet::new() );
    }

    fn new(new_map: HashSet<(i8,i8)>) -> WorldMap {
        return WorldMap { map: new_map };
    }

    fn mark_cell_as_alive(&self, cell_coordinates: (i8, i8)) -> WorldMap {
        let mut new_map = self.map.clone();
        new_map.insert(cell_coordinates);
        let new_world = WorldMap::new(new_map);
        return new_world;
    }

    fn is_cell_alive(&self, cell_coordinates: (i8,i8)) -> bool {
        return self.map.contains(&cell_coordinates);
    }

    fn count_alive_neighbours(&self, cell_coordinates: (i8, i8)) -> usize {
        let mut neighbour_coordinates = HashSet::new();
        let (x, y) = cell_coordinates;
        neighbour_coordinates.insert((x-1, y-1));
        neighbour_coordinates.insert((x-1, y));
        neighbour_coordinates.insert((x-1, y+1));
        neighbour_coordinates.insert((x, y-1));
        neighbour_coordinates.insert((x, y+1));
        neighbour_coordinates.insert((x+1, y-1));
        neighbour_coordinates.insert((x+1, y));
        neighbour_coordinates.insert((x+1, y+1));
        let neighbours_alive = self.map.intersection(&neighbour_coordinates).collect::<Vec<&(i8,i8)>>();
        return neighbours_alive.len();
    }
}

#[test]
fn the_only_alive_cell_should_have_no_alive_neighbours() {
    let coords = (0,0);
    let world = WorldMap::empty();
    let new_world = world.mark_cell_as_alive(coords);
    let alive_neighbours_count = new_world.count_alive_neighbours(coords);
    assert_eq!(0, alive_neighbours_count);
}

#[test]
fn alive_neighbour_on_the_diagonal_should_count() {
    let (x, y) = (0,0);
    let coords = (x,y);
    let world = WorldMap::empty();
    let new_world1 = world.mark_cell_as_alive(coords);
    let new_world2 = new_world1.mark_cell_as_alive((x, y+1));
    let alive_neighbours_count = new_world2.count_alive_neighbours(coords);
    assert_eq!(1, alive_neighbours_count);
}

#[test]
fn is_cell_alive_should_return_true_for_alive_cell() {
    let coords = (0,0);
    let world = WorldMap::empty();
    let new_world = world.mark_cell_as_alive(coords);
    let is_alive = new_world.is_cell_alive(coords);
    assert_eq!(true, is_alive);
}

#[test]
fn is_cell_alive_should_return_false_for_dead_cell() {
    let coords = (0,0);
    let world = WorldMap::empty();
    let is_alive = world.is_cell_alive(coords);
    assert_eq!(false, is_alive);
}
<|endoftext|>


<commit_before>extern crate hmacsha1;

use std::fmt;

/// This implementation of HMAC-Based One Time Passwords proceeds in three
/// stages, as per [RFC 4226](https://www.ietf.org/rfc/rfc4226.txt):
///
/// 1. Generate an HMAC-SHA-1 value given a shared secret `key` and a
/// moving factor `counter` that *should* change on every use
/// 2. Extraction of a 4-byte value from the SHA-1 digest
/// 3. Deriving a final HOTP value between 0 and
/// 10^{`desired_code_length`}-1 from the 4-byte value extracted
/// in the last step.
///
/// Note that it is the responsibility of the caller to:
///
/// * Fulfill the precondition that `counter` is an 8-byte value
/// * Increment the counter accordingly per invocation
///
/// # Examples
///
/// To generate an HOTP value between 0 and 10^8 - 1, given the shared
/// secret ASCII key `"Hello world!"` and current counter `0`:
///
/// ```
/// rusthotp::hotp(8, "Hello world!".as_bytes(), &[0; 8]);
/// ```
pub fn hotp(desired_code_length: usize, key: &[u8], counter: &[u8]) -> HotpOutput {
    let hmac_value = hmacsha1::hmac_sha1(key, counter);
    let dbc = sbits(&hmac_value);
    HotpOutput{ code: dbc % 10u32.pow(desired_code_length as u32), length: desired_code_length }
}

fn offset(b: &[u8]) -> usize {
    (b.last().unwrap() & 0xf) as usize
}

fn sbits(bits: &[u8]) -> u32 {
    let offset = offset(bits);

    let mut val: u32 = 0;
    val += bits[offset + 3] as u32;
    val += (bits[offset + 2] as u32) << 8;
    val += (bits[offset + 1] as u32) << 16;
    val += ((bits[offset] as u32) & 0x7f) << 24;
    val
}

pub struct HotpOutput {
    pub code: u32,
    pub length: usize,
}

impl fmt::Display for HotpOutput {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:0length$}", self.code, length = self.length)
    }
}
<commit_msg>Improves hotp documentation by adding another sample and assertions<commit_after>extern crate hmacsha1;

use std::fmt;

/// This implementation of HMAC-Based One Time Passwords proceeds in three
/// stages, as per [RFC 4226](https://www.ietf.org/rfc/rfc4226.txt):
///
/// 1. Generate an HMAC-SHA-1 value given a shared secret `key` and a
/// moving factor `counter` that *should* change on every use
/// 2. Extraction of a 4-byte value from the SHA-1 digest
/// 3. Deriving a final HOTP value between 0 and
/// 10^{`desired_code_length`}-1 from the 4-byte value extracted
/// in the last step.
///
/// Note that it is the responsibility of the caller to:
///
/// * Fulfill the precondition that `counter` is an 8-byte value
/// * Increment the counter accordingly per invocation
///
/// # Examples
///
/// To generate an HOTP value between 0 and 10^6 - 1, given the shared
/// secret ASCII key `"Hello world!"` and current counter `0`:
///
/// ```
/// let six_digit_result = rusthotp::hotp(6, "Hello world!".as_bytes(), &[0; 8]);
/// assert_eq!(format!("{}", six_digit_result), "124111");
/// ```
///
/// To generate an HOTP value between 0 and 10^8 - 1, given the shared
/// secret ASCII key `"12345678901234567890"` and current counter `1`:
///
/// ```
/// let eight_digit_result = rusthotp::hotp(8, "12345678901234567890".as_bytes(), &[0, 0, 0, 0, 0, 0, 0, 1]);
/// assert_eq!(format!("{}", eight_digit_result), "94287082");
/// ```

pub fn hotp(desired_code_length: usize, key: &[u8], counter: &[u8]) -> HotpOutput {
    let hmac_value = hmacsha1::hmac_sha1(key, counter);
    let dbc = sbits(&hmac_value);
    HotpOutput{ code: dbc % 10u32.pow(desired_code_length as u32), length: desired_code_length }
}

fn offset(b: &[u8]) -> usize {
    (b.last().unwrap() & 0xf) as usize
}

fn sbits(bits: &[u8]) -> u32 {
    let offset = offset(bits);

    let mut val: u32 = 0;
    val += bits[offset + 3] as u32;
    val += (bits[offset + 2] as u32) << 8;
    val += (bits[offset + 1] as u32) << 16;
    val += ((bits[offset] as u32) & 0x7f) << 24;
    val
}

pub struct HotpOutput {
    pub code: u32,
    pub length: usize,
}

impl fmt::Display for HotpOutput {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:0length$}", self.code, length = self.length)
    }
}
<|endoftext|>


<commit_before>use filemap::{FileMap, Span, Loc};
use std::rc::Rc;
use term_painter::ToStyle;
use term_painter::Color::*;
use term_painter::Attr::*;

pub struct ErrorHandler {
    fmap: Rc<FileMap>,
}

// macro_rules! colored {
//     ($c:ident, $p:expr ) => ({
//         term::stdout().unwrap().fg(term::color::$c).unwrap();
//         $p;
//         term::stdout().unwrap().reset().unwrap();
//     })
// }

// macro_rules! attrib {
//     ($a:ident, $p:expr ) => ({
//         term::stdout().unwrap().attr(term::Attr::$a).unwrap();
//         $p;
//         term::stdout().unwrap().reset().unwrap();
//     })
// }

#[allow(dead_code)]
impl ErrorHandler {
    pub fn new(fmap: Rc<FileMap>) -> ErrorHandler {
        ErrorHandler { fmap: fmap }
    }

    pub fn error(&self, m: &str) {
        println!("");
        print!("{}: {} {}",
            self.fmap.filename, Red.paint("error:"), Bold.paint(m));
    }

    fn print_snippet(&self, start: Loc, end: Loc) {
        if start.line == end.line {
            let pre = format!("{}:{}: ", self.fmap.filename, start.line);

            println!("{}:{}: {}",
                self.fmap.filename,
                Blue.paint(start.line),
                self.fmap.get_line(start.line));

            // Print spaces until the span start is reached
            print!("{0:>1$}", " ", pre.len() + start.col);

            print!("{}", Yellow.paint("^"));
            for _ in 0..(end.col-start.col+1) {
                print!("{}", Yellow.paint("-"));
            }
            println!("");
        } else {
            for line in start.line .. end.line + 1 {
                println!("{}:{}: {}",
                    self.fmap.filename,
                    Blue.paint(line),
                    self.fmap.get_line(line));
            }
        }
    }

    pub fn error_span(&self, span: Span, m: &str) {
        let start = self.fmap.get_loc(span.lo);
        let end = self.fmap.get_loc(span.hi - 1);

        println!("");
        println!("{file}:{sl}:{sc} .. {el}:{ec}: {error} {m}",
            file=self.fmap.filename,
            sl=Blue.paint(start.line), sc=start.col,
            el=Blue.paint(end.line), ec=end.col,
            error=Red.paint("error:"), m=Bold.paint(m));

        self.print_snippet(start, end);

    }
}
<commit_msg>Add small helper function for nicer formatting...<commit_after>use filemap::{FileMap, Span, Loc};
use std::rc::Rc;
use std::iter::repeat;
use term_painter::ToStyle;
use term_painter::Color::*;
use term_painter::Attr::*;

pub struct ErrorHandler {
    fmap: Rc<FileMap>,
}

fn times(s: &str, rhs: usize) -> String {
    repeat(s).take(rhs).collect()
}

// macro_rules! colored {
//     ($c:ident, $p:expr ) => ({
//         term::stdout().unwrap().fg(term::color::$c).unwrap();
//         $p;
//         term::stdout().unwrap().reset().unwrap();
//     })
// }

// macro_rules! attrib {
//     ($a:ident, $p:expr ) => ({
//         term::stdout().unwrap().attr(term::Attr::$a).unwrap();
//         $p;
//         term::stdout().unwrap().reset().unwrap();
//     })
// }

#[allow(dead_code)]
impl ErrorHandler {
    pub fn new(fmap: Rc<FileMap>) -> ErrorHandler {
        ErrorHandler { fmap: fmap }
    }

    pub fn error(&self, m: &str) {
        println!("");
        print!("{}: {} {}",
            self.fmap.filename, Red.paint("error:"), Bold.paint(m));
    }

    fn print_snippet(&self, start: Loc, end: Loc) {
        if start.line == end.line {
            let pre = format!("{}:{}: ", self.fmap.filename, start.line);

            println!("{}:{}: {}",
                self.fmap.filename,
                Blue.paint(start.line),
                self.fmap.get_line(start.line));

            // Print spaces until the span start is reached
            print!("{0:>1$}", " ", pre.len() + start.col);

            println!("{}{}", Yellow.paint("^"),
                Yellow.paint(times("-", end.col-start.col+1)));

        } else {
            for line in start.line .. end.line + 1 {
                println!("{}:{}: {}",
                    self.fmap.filename,
                    Blue.paint(line),
                    self.fmap.get_line(line));
            }
        }
    }

    pub fn error_span(&self, span: Span, m: &str) {
        let start = self.fmap.get_loc(span.lo);
        let end = self.fmap.get_loc(span.hi - 1);

        println!("");
        println!("{file}:{sl}:{sc} .. {el}:{ec}: {error} {m}",
            file=self.fmap.filename,
            sl=Blue.paint(start.line), sc=start.col,
            el=Blue.paint(end.line), ec=end.col,
            error=Red.paint("error:"), m=Bold.paint(m));

        self.print_snippet(start, end);

    }
}
<|endoftext|>


<commit_before>// Implements http://rosettacode.org/wiki/Echo_server
#![feature(io)]
#![feature(old_io)]
#![feature(std_misc)]
use std::old_io::{Acceptor, BufferedReader, IoError, IoResult, Listener, TimedOut,
    Writer, BufferPrelude};
use std::old_io::net::tcp::{TcpListener, TcpStream};
use std::time::Duration;
use std::thread::spawn;

// The actual echo server
fn echo_server(host: &'static str, port: u16, timeout: Option<Duration>) -> IoResult<()> {
    // Create a new TCP listener at host:port.
    let mut listener = try!(TcpListener::bind((host, port)));
    println!("Starting echo server on {:?}", listener.socket_name());

    let mut acceptor = try!(listener.listen());
    println!("Echo server started");

    // The server will cease to accept new connectinos after `timeout`.
    acceptor.set_timeout(timeout.map( |d| d.num_milliseconds() as u64));

    // Process each new connection to the server
    for stream in acceptor.incoming() {
        match stream {
            Err(e @ IoError { kind: TimedOut, .. } ) => {
                println!("No longer accepting new requests: {}", e);
                break
            }
            Err(e) => println!("Connection failed: {}", e),
            Ok(mut stream) => {
                let name = try!(stream.peer_name());
                println!("New connection: {}", name);
                // Launch a new thread to deal with the connection.
                spawn(move || -> () {
                    if let Err(e) = echo_session(stream.clone()) {
                        println!("I/O error: {} -- {}", name, e);
                    }
                    println!("Closing connection: {}", name);;
                    drop(stream);
                });
            }
        }
    }
    Ok(())
    // Server closes automatically at end of block
}

// Each connection gets its own session.
fn echo_session(mut stream: TcpStream) -> IoResult<()> {
    let name = try!(stream.peer_name());
    let ref mut writer = stream.clone();
    let mut reader = BufferedReader::new(stream);
    for line in reader.lines() {
        let l = try!(line);
        print!("Received line from {}: {}", name, l);
        try!(writer.write_str(&l[..]));
        print!("Wrote line to {}: {}", name, l);
    }
    Ok(())
}

const HOST: &'static str = "127.0.0.1";
const PORT: u16 = 12321;

pub fn run_server(duration: Option<Duration>) -> IoResult<()> {
    echo_server(HOST, PORT, duration)
}

#[cfg(not(test))]
pub fn main() {
    run_server(Some(Duration::minutes(1))).unwrap();
}
<commit_msg>Fix echo_server.rs warnings<commit_after>// Implements http://rosettacode.org/wiki/Echo_server

use std::io::{self, BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;

// The actual echo server
fn echo_server(host: &'static str, port: u16) -> io::Result<()> {
    // Create a new TCP listener at host:port.
    let listener = try!(TcpListener::bind((host, port)));
    println!("Starting echo server on {:?}", listener.local_addr());

    // Process each new connection to the server
    for stream in listener.incoming() {
        match stream {
            Err(e) => println!("Connection failed: {}", e),
            Ok(stream) => {
                let addr = try!(stream.peer_addr());
                println!("New connection: {}", addr);
                // Launch a new thread to deal with the connection.
                thread::spawn(move || {
                    if let Err(e) = echo_session(stream) {
                        println!("I/O error: {} -- {}", addr, e);
                    }
                    println!("Closing connection: {}", addr);
                });
            }
        }
    }
    Ok(())
    // Server closes automatically at end of block
}

// Each connection gets its own session.
fn echo_session(stream: TcpStream) -> io::Result<()> {
    let addr = try!(stream.peer_addr());
    let mut writer = stream.try_clone().unwrap();
    let reader = BufReader::new(stream);
    for line in reader.lines() {
        let line = try!(line);
        print!("Received line from {}: {}", addr, line);
        try!(writer.write_all(line.as_bytes()));
        print!("Wrote line to {}: {}", addr, line);
    }
    Ok(())
}

const HOST: &'static str = "127.0.0.1";
const PORT: u16 = 12321;

#[cfg(not(test))]
pub fn main() {
    echo_server(HOST, PORT).unwrap();
}
<|endoftext|>


<commit_before>extern crate zmq;
extern crate serde_json;

use std::error;
use std::io;
use std::fmt;
use std::error::Error;

use api::ErrorCode;
use errors::ToErrorCode;

#[derive(Debug)]
pub enum PoolError {
    NotCreated(String),
    InvalidData(String),
    InvalidConfiguration(String),
    InvalidHandle(String),
    Io(io::Error)
}

impl fmt::Display for PoolError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            PoolError::NotCreated(ref description) => write!(f, "Not created: {}", description),
            PoolError::InvalidHandle(ref description) => write!(f, "Invalid Handle: {}", description),
            PoolError::InvalidConfiguration(ref description) => write!(f, "Invalid configuration: {}", description),
            PoolError::InvalidData(ref description) => write!(f, "Invalid data: {}", description),
            PoolError::Io(ref err) => err.fmt(f)
        }
    }
}

impl error::Error for PoolError {
    fn description(&self) -> &str {
        match *self {
            PoolError::NotCreated(ref description) => description,
            PoolError::InvalidHandle(ref description) => description,
            PoolError::InvalidData(ref description) => description,
            PoolError::InvalidConfiguration(ref description) => description,
            PoolError::Io(ref err) => err.description()
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            PoolError::NotCreated(ref description) => None,
            PoolError::InvalidHandle(ref description) => None,
            PoolError::InvalidData(ref description) => None,
            PoolError::InvalidConfiguration(ref description) => None,
            PoolError::Io(ref err) => Some(err)
        }
    }
}

impl From<io::Error> for PoolError {
    fn from(err: io::Error) -> PoolError {
        PoolError::Io(err)
    }
}

impl From<zmq::Error> for PoolError {
    fn from(err: zmq::Error) -> PoolError {
        PoolError::Io(io::Error::from(err))
    }
}

impl From<serde_json::Error> for PoolError {
    fn from(err: serde_json::Error) -> PoolError {
        PoolError::InvalidConfiguration(err.description().to_string())
    }
}

impl ToErrorCode for PoolError {
    fn to_error_code(&self) -> ErrorCode {
        match *self {
            PoolError::NotCreated(ref description) => ErrorCode::PoolLedgerNotCreatedError,
            PoolError::InvalidConfiguration(ref description) => ErrorCode::PoolLedgerInvalidConfiguration,
            PoolError::InvalidHandle(ref description) => ErrorCode::PoolLedgerInvalidPoolHandle,
            PoolError::InvalidData(ref description) => ErrorCode::PoolLedgerInvalidDataFormat,
            PoolError::Io(ref err) => ErrorCode::PoolLedgerIOError
        }
    }
}

#[cfg(test)]
mod tests {
    //use super::*;
    // TODO: FIXME: Provide tests!!!

    //    #[test]
    //    fn sovrin_error_can_be_created() {
    //        let not_created_error = PoolError::NotCreated("NotCreated".to_string());
    //        let invalid_handle_error = PoolError::InvalidHandle("InvalidHandle".to_string());
    //        let no_consensus_error = PoolError::NoConsensus("NoConsensus".to_string());
    //        let invalid_data_error = PoolError::InvalidData("InvalidData".to_string());
    //        let io_error = PoolError::Io(io::Error());
    //    }
    //
    //    #[test]
    //    fn sovrin_error_can_be_formatted() {
    //        let not_created_error_formatted = format!("{}", PoolError::NotCreated("NotCreated".to_string()));
    //        let invalid_handle_error_formatted = format!("{}", PoolError::InvalidHandle("InvalidHandle".to_string()));
    //        let no_consensus_error_formatted = format!("{}", PoolError::NoConsensus("NoConsensus".to_string()));
    //        let invalid_data_error_formatted = format!("{}", PoolError::InvalidData("InvalidData".to_string()));
    //        let io_error_formatted = format!("{}", PoolError::Io(io::Error()));
    //
    //        assert_eq!("No consensus: NotCreated", not_created_error_formatted);
    //        assert_eq!("No consensus: InvalidHandle", invalid_handle_error_formatted);
    //        assert_eq!("No consensus: NoConsensus", no_consensus_error_formatted);
    //        assert_eq!("Invalid data: InvalidData", invalid_data_error_formatted);
    //        assert_eq!("IO", io_error_formatted);
    //    }
}<commit_msg>Add PoolError::InvalidState.<commit_after>extern crate zmq;
extern crate serde_json;

use std::error;
use std::io;
use std::fmt;
use std::error::Error;

use api::ErrorCode;
use errors::ToErrorCode;

#[derive(Debug)]
pub enum PoolError {
    NotCreated(String),
    InvalidState(String),
    InvalidData(String),
    InvalidConfiguration(String),
    InvalidHandle(String),
    Io(io::Error)
}

impl fmt::Display for PoolError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            PoolError::NotCreated(ref description) => write!(f, "Not created: {}", description),
            PoolError::InvalidState(ref description) => write!(f, "Internal error: {}", description),
            PoolError::InvalidHandle(ref description) => write!(f, "Invalid Handle: {}", description),
            PoolError::InvalidConfiguration(ref description) => write!(f, "Invalid configuration: {}", description),
            PoolError::InvalidData(ref description) => write!(f, "Invalid data: {}", description),
            PoolError::Io(ref err) => err.fmt(f)
        }
    }
}

impl error::Error for PoolError {
    fn description(&self) -> &str {
        match *self {
            PoolError::NotCreated(ref description) |
            PoolError::InvalidState(ref description) |
            PoolError::InvalidHandle(ref description) |
            PoolError::InvalidData(ref description) |
            PoolError::InvalidConfiguration(ref description) => description,
            PoolError::Io(ref err) => err.description()
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            PoolError::NotCreated(ref description) |
            PoolError::InvalidState(ref description) |
            PoolError::InvalidHandle(ref description) |
            PoolError::InvalidData(ref description) |
            PoolError::InvalidConfiguration(ref description) => None,
            PoolError::Io(ref err) => Some(err)
        }
    }
}

impl From<io::Error> for PoolError {
    fn from(err: io::Error) -> PoolError {
        PoolError::Io(err)
    }
}

impl From<zmq::Error> for PoolError {
    fn from(err: zmq::Error) -> PoolError {
        PoolError::Io(io::Error::from(err))
    }
}

impl From<serde_json::Error> for PoolError {
    fn from(err: serde_json::Error) -> PoolError {
        PoolError::InvalidConfiguration(err.description().to_string())
    }
}

impl ToErrorCode for PoolError {
    fn to_error_code(&self) -> ErrorCode {
        match *self {
            PoolError::NotCreated(ref description) => ErrorCode::PoolLedgerNotCreatedError,
            PoolError::InvalidState(ref description) => ErrorCode::CommonInvalidState,
            PoolError::InvalidConfiguration(ref description) => ErrorCode::PoolLedgerInvalidConfiguration,
            PoolError::InvalidHandle(ref description) => ErrorCode::PoolLedgerInvalidPoolHandle,
            PoolError::InvalidData(ref description) => ErrorCode::PoolLedgerInvalidDataFormat,
            PoolError::Io(ref err) => ErrorCode::PoolLedgerIOError
        }
    }
}

#[cfg(test)]
mod tests {
    //use super::*;
    // TODO: FIXME: Provide tests!!!

    //    #[test]
    //    fn sovrin_error_can_be_created() {
    //        let not_created_error = PoolError::NotCreated("NotCreated".to_string());
    //        let invalid_handle_error = PoolError::InvalidHandle("InvalidHandle".to_string());
    //        let no_consensus_error = PoolError::NoConsensus("NoConsensus".to_string());
    //        let invalid_data_error = PoolError::InvalidData("InvalidData".to_string());
    //        let io_error = PoolError::Io(io::Error());
    //    }
    //
    //    #[test]
    //    fn sovrin_error_can_be_formatted() {
    //        let not_created_error_formatted = format!("{}", PoolError::NotCreated("NotCreated".to_string()));
    //        let invalid_handle_error_formatted = format!("{}", PoolError::InvalidHandle("InvalidHandle".to_string()));
    //        let no_consensus_error_formatted = format!("{}", PoolError::NoConsensus("NoConsensus".to_string()));
    //        let invalid_data_error_formatted = format!("{}", PoolError::InvalidData("InvalidData".to_string()));
    //        let io_error_formatted = format!("{}", PoolError::Io(io::Error()));
    //
    //        assert_eq!("No consensus: NotCreated", not_created_error_formatted);
    //        assert_eq!("No consensus: InvalidHandle", invalid_handle_error_formatted);
    //        assert_eq!("No consensus: NoConsensus", no_consensus_error_formatted);
    //        assert_eq!("Invalid data: InvalidData", invalid_data_error_formatted);
    //        assert_eq!("IO", io_error_formatted);
    //    }
}<|endoftext|>


<commit_before>/// A type for which the layout is determined by its C++ definition.
///
/// This trait serves the following two related purposes.
///
///

///
/// ## Safely unifying occurrences of the same extern type
///
/// `ExternType` makes it possible for CXX to safely share a consistent Rust
/// type across multiple #\[cxx::bridge\] invocations that refer to a common
/// extern C++ type.
///
/// In the following snippet, two #\[cxx::bridge\] invocations in different
/// files (possibly different crates) both contain function signatures involving
/// the same C++ type `example::Demo`. If both were written just containing
/// `type Demo;`, then both macro expansions would produce their own separate
/// Rust type called `Demo` and thus the compiler wouldn't allow us to take the
/// `Demo` returned by `file1::ffi::create_demo` and pass it as the `Demo`
/// argument accepted by `file2::ffi::take_ref_demo`. Instead, one of the two
/// `Demo`s has been defined as an extern type alias of the other, making them
/// the same type in Rust. The CXX code generator will use an automatically
/// generated `ExternType` impl emitted in file1 to statically verify that in
/// file2 `crate::file1::ffi::Demo` really does refer to the C++ type
/// `example::Demo` as expected in file2.
///
/// ```no_run
/// // file1.rs
/// # mod file1 {
/// #[cxx::bridge(namespace = example)]
/// pub mod ffi {
///     extern "C" {
///         type Demo;
///
///         fn create_demo() -> UniquePtr<Demo>;
///     }
/// }
/// # }
///
/// // file2.rs
/// #[cxx::bridge(namespace = example)]
/// pub mod ffi {
///     extern "C" {
///         type Demo = crate::file1::ffi::Demo;
///
///         fn take_ref_demo(demo: &Demo);
///     }
/// }
/// #
/// # fn main() {}
/// ```
///
///

///
/// ## Integrating with bindgen-generated types
///
/// Handwritten `ExternType` impls make it possible to plug in a data structure
/// emitted by bindgen as the definition of a C++ type emitted by CXX.
///
/// By writing the unsafe `ExternType` impl, the programmer asserts that the C++
/// namespace and type name given in the type id refers to a C++ type that is
/// equivalent to Rust type that is the `Self` type of the impl.
///
/// ```no_run
/// # const _: &str = stringify! {
/// mod folly_sys;  // the bindgen-generated bindings
/// # };
/// # mod folly_sys {
/// #     #[repr(transparent)]
/// #     pub struct StringPiece([usize; 2]);
/// # }
///
/// use cxx::{type_id, ExternType};
///
/// unsafe impl ExternType for folly_sys::StringPiece {
///     type Id = type_id!("folly::StringPiece");
///     type Kind = cxx::kind::Opaque;
/// }
///
/// #[cxx::bridge(namespace = folly)]
/// pub mod ffi {
///     extern "C" {
///         include!("rust_cxx_bindings.h");
///
///         type StringPiece = crate::folly_sys::StringPiece;
///
///         fn print_string_piece(s: &StringPiece);
///     }
/// }
///
/// // Now if we construct a StringPiece or obtain one through one
/// // of the bindgen-generated signatures, we are able to pass it
/// // along to ffi::print_string_piece.
/// #
/// # fn main() {}
/// ```
///
///

///
/// ## Opaque and Trivial types
///
/// Some C++ types are safe to hold and pass around in Rust, by value.
/// Those C++ types must have a trivial move constructor, and must
/// have no destructor.
///
/// If you believe your C++ type is indeed trivial, you can specify
/// ```
/// # struct TypeName;
/// # unsafe impl cxx::ExternType for TypeName {
/// type Id = cxx::type_id!("name::space::of::TypeName");
/// type Kind = cxx::kind::Trivial;
/// # }
/// ```
/// which will enable you to pass it into C++ functions by value,
/// return it by value from such functions, and include it in
/// `struct`s that you have declared to `cxx::bridge`. Your promises
/// about the triviality of the C++ type will be checked using
/// `static_assert`s in the generated C++.
///
/// Opaque types can't be passed by value, but can still be held
/// in `UniquePtr`.
pub unsafe trait ExternType {
    /// A type-level representation of the type's C++ namespace and type name.
    ///
    /// This will always be defined using `type_id!` in the following form:
    ///
    /// ```
    /// # struct TypeName;
    /// # unsafe impl cxx::ExternType for TypeName {
    /// type Id = cxx::type_id!("name::space::of::TypeName");
    /// type Kind = cxx::kind::Opaque;
    /// # }
    /// ```
    type Id;

    /// Either `cxx::kind::Opaque` or `cxx::kind::Trivial`. If in doubt, use
    /// `cxx::kind::Opaque`.
    type Kind;
}

/// Marker types identifying Rust's knowledge about an extern C++ type.
///
/// These markers are used in the `Kind` associated type in impls of the
/// [`ExternType`] trait. Refer to the discussion of [Opaque and Trivial
/// types][trait] for an overview of their purpose.
///
/// [trait]: ExternType#opaque-and-trivial-types
pub mod kind {
    /// An opaque type which can't be passed or held by value within Rust.
    /// For example, a C++ type with a destructor, or a non-trivial move
    /// constructor. Rust's strict move semantics mean that we can't own
    /// these by value in Rust, but they can still be owned by a
    /// `UniquePtr`...
    pub struct Opaque;

    /// A type with trivial move constructors and no destructor, which
    /// can therefore be owned and moved around in Rust code directly.
    pub struct Trivial;
}

#[doc(hidden)]
pub fn verify_extern_type<T: ExternType<Id = Id>, Id>() {}

#[doc(hidden)]
pub fn verify_extern_kind<T: ExternType<Kind = Kind>, Kind>() {}
<commit_msg>Update documentation of Opaque and Trivial markers<commit_after>/// A type for which the layout is determined by its C++ definition.
///
/// This trait serves the following two related purposes.
///
///

///
/// ## Safely unifying occurrences of the same extern type
///
/// `ExternType` makes it possible for CXX to safely share a consistent Rust
/// type across multiple #\[cxx::bridge\] invocations that refer to a common
/// extern C++ type.
///
/// In the following snippet, two #\[cxx::bridge\] invocations in different
/// files (possibly different crates) both contain function signatures involving
/// the same C++ type `example::Demo`. If both were written just containing
/// `type Demo;`, then both macro expansions would produce their own separate
/// Rust type called `Demo` and thus the compiler wouldn't allow us to take the
/// `Demo` returned by `file1::ffi::create_demo` and pass it as the `Demo`
/// argument accepted by `file2::ffi::take_ref_demo`. Instead, one of the two
/// `Demo`s has been defined as an extern type alias of the other, making them
/// the same type in Rust. The CXX code generator will use an automatically
/// generated `ExternType` impl emitted in file1 to statically verify that in
/// file2 `crate::file1::ffi::Demo` really does refer to the C++ type
/// `example::Demo` as expected in file2.
///
/// ```no_run
/// // file1.rs
/// # mod file1 {
/// #[cxx::bridge(namespace = example)]
/// pub mod ffi {
///     extern "C" {
///         type Demo;
///
///         fn create_demo() -> UniquePtr<Demo>;
///     }
/// }
/// # }
///
/// // file2.rs
/// #[cxx::bridge(namespace = example)]
/// pub mod ffi {
///     extern "C" {
///         type Demo = crate::file1::ffi::Demo;
///
///         fn take_ref_demo(demo: &Demo);
///     }
/// }
/// #
/// # fn main() {}
/// ```
///
///

///
/// ## Integrating with bindgen-generated types
///
/// Handwritten `ExternType` impls make it possible to plug in a data structure
/// emitted by bindgen as the definition of a C++ type emitted by CXX.
///
/// By writing the unsafe `ExternType` impl, the programmer asserts that the C++
/// namespace and type name given in the type id refers to a C++ type that is
/// equivalent to Rust type that is the `Self` type of the impl.
///
/// ```no_run
/// # const _: &str = stringify! {
/// mod folly_sys;  // the bindgen-generated bindings
/// # };
/// # mod folly_sys {
/// #     #[repr(transparent)]
/// #     pub struct StringPiece([usize; 2]);
/// # }
///
/// use cxx::{type_id, ExternType};
///
/// unsafe impl ExternType for folly_sys::StringPiece {
///     type Id = type_id!("folly::StringPiece");
///     type Kind = cxx::kind::Opaque;
/// }
///
/// #[cxx::bridge(namespace = folly)]
/// pub mod ffi {
///     extern "C" {
///         include!("rust_cxx_bindings.h");
///
///         type StringPiece = crate::folly_sys::StringPiece;
///
///         fn print_string_piece(s: &StringPiece);
///     }
/// }
///
/// // Now if we construct a StringPiece or obtain one through one
/// // of the bindgen-generated signatures, we are able to pass it
/// // along to ffi::print_string_piece.
/// #
/// # fn main() {}
/// ```
///
///

///
/// ## Opaque and Trivial types
///
/// Some C++ types are safe to hold and pass around in Rust, by value.
/// Those C++ types must have a trivial move constructor, and must
/// have no destructor.
///
/// If you believe your C++ type is indeed trivial, you can specify
/// ```
/// # struct TypeName;
/// # unsafe impl cxx::ExternType for TypeName {
/// type Id = cxx::type_id!("name::space::of::TypeName");
/// type Kind = cxx::kind::Trivial;
/// # }
/// ```
/// which will enable you to pass it into C++ functions by value,
/// return it by value from such functions, and include it in
/// `struct`s that you have declared to `cxx::bridge`. Your promises
/// about the triviality of the C++ type will be checked using
/// `static_assert`s in the generated C++.
///
/// Opaque types can't be passed by value, but can still be held
/// in `UniquePtr`.
pub unsafe trait ExternType {
    /// A type-level representation of the type's C++ namespace and type name.
    ///
    /// This will always be defined using `type_id!` in the following form:
    ///
    /// ```
    /// # struct TypeName;
    /// # unsafe impl cxx::ExternType for TypeName {
    /// type Id = cxx::type_id!("name::space::of::TypeName");
    /// type Kind = cxx::kind::Opaque;
    /// # }
    /// ```
    type Id;

    /// Either `cxx::kind::Opaque` or `cxx::kind::Trivial`. If in doubt, use
    /// `cxx::kind::Opaque`.
    type Kind;
}

/// Marker types identifying Rust's knowledge about an extern C++ type.
///
/// These markers are used in the `Kind` associated type in impls of the
/// [`ExternType`] trait. Refer to the discussion of [Opaque and Trivial
/// types][trait] for an overview of their purpose.
///
/// [trait]: ExternType#opaque-and-trivial-types
pub mod kind {
    /// An opaque type which cannot be passed or held by value within Rust.
    ///
    /// Rust's move semantics are such that every move is equivalent to a
    /// memcpy. This is incompatible in general with C++'s constructor-based
    /// move semantics, so a C++ type which has a destructor or nontrivial move
    /// constructor must never exist by value in Rust. In CXX, such types are
    /// called opaque C++ types.
    ///
    /// When passed across an FFI boundary, an opaque C++ type must be behind an
    /// indirection such as a reference or UniquePtr.
    pub struct Opaque;

    /// A type with trivial move constructor and no destructor, which can
    /// therefore be owned and moved around in Rust code without requiring
    /// indirection.
    pub struct Trivial;
}

#[doc(hidden)]
pub fn verify_extern_type<T: ExternType<Id = Id>, Id>() {}

#[doc(hidden)]
pub fn verify_extern_kind<T: ExternType<Kind = Kind>, Kind>() {}
<|endoftext|>


<commit_before>//! TODO Fill in

use super::class::{Class, ClassBuilder};
use super::object::{self, Object, Objectable};
use cairo_sys::cairo_pattern_t;
use rlua::{self, LightUserData, Lua, Table, ToLua, UserData, UserDataMethods, Value};
use std::default::Default;
use std::fmt::{self, Display, Formatter};

/// Handle to the list of global key bindings
pub const ROOT_KEYS_HANDLE: &'static str = "__ROOT_KEYS";

#[derive(Clone, Debug)]
pub struct RootState {
    // TODO Fill in
    dummy: i32
}

pub struct Root<'lua>(Object<'lua>);

impl Default for RootState {
    fn default() -> Self {
        RootState { dummy: 0 }
    }
}

impl Display for RootState {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Root: {:p}", self)
    }
}

impl<'lua> ToLua<'lua> for Root<'lua> {
    fn to_lua(self, lua: &'lua Lua) -> rlua::Result<Value<'lua>> {
        self.0.to_lua(lua)
    }
}

impl UserData for RootState {
    fn add_methods(methods: &mut UserDataMethods<Self>) {
        object::default_add_methods(methods);
    }
}

pub fn init(lua: &Lua) -> rlua::Result<Class> {
    // FIXME: In awesome there is no root class
    method_setup(lua, Class::builder(lua, "FIXME", None)?)?.save_class("root")?
                                                           .build()
}

fn method_setup<'lua>(lua: &'lua Lua,
                      builder: ClassBuilder<'lua>)
                      -> rlua::Result<ClassBuilder<'lua>> {
    // TODO Do properly
    use super::dummy;
    builder.method("connect_signal".into(), lua.create_function(dummy)?)?
           .method("buttons".into(), lua.create_function(dummy)?)?
           .method("wallpaper".into(), lua.create_function(wallpaper)?)?
           .method("tags".into(), lua.create_function(tags)?)?
           .method("keys".into(), lua.create_function(root_keys)?)?
           .method("size".into(), lua.create_function(dummy_double)?)?
           .method("size_mm".into(), lua.create_function(dummy_double)?)?
           .method("cursor".into(), lua.create_function(dummy)?)
}

impl_objectable!(Root, RootState);

fn dummy_double<'lua>(_: &'lua Lua, _: rlua::Value) -> rlua::Result<(i32, i32)> {
    Ok((0, 0))
}

/// Gets the wallpaper as a cairo surface or set it as a cairo pattern
fn wallpaper<'lua>(lua: &'lua Lua, pattern: Option<LightUserData>) -> rlua::Result<Value<'lua>> {
    // TODO FIXME Implement for realz
    if let Some(pattern) = pattern {
        // TODO Wrap before giving it to set_wallpaper
        let pattern = pattern.0 as *mut cairo_pattern_t;
        return set_wallpaper(lua, pattern)?.to_lua(lua)
    }
    // TODO Look it up in global conf (e.g probably super secret lua value)
    return Ok(Value::Nil)
}

fn set_wallpaper<'lua>(_: &'lua Lua, _pattern: *mut cairo_pattern_t) -> rlua::Result<bool> {
    warn!("Fake setting the wallpaper");
    Ok(true)
}

fn tags<'lua>(lua: &'lua Lua, _: ()) -> rlua::Result<Table<'lua>> {
    let table = lua.create_table()?;
    let activated_tags = lua.named_registry_value::<Table>(super::tag::TAG_LIST)?;
    for pair in activated_tags.pairs::<Value, Value>() {
        let (key, value) = pair?;
        table.set(key, value)?;
    }
    Ok(table)
}

/// Get or set global key bindings.
///
/// These bindings will be available when you press keys on the root window.
fn root_keys<'lua>(lua: &'lua Lua, key_array: rlua::Value<'lua>) -> rlua::Result<rlua::Value<'lua>> {
    match key_array {
        // Set the global keys
        Value::Table(key_array) => {
            lua.set_named_registry_value(ROOT_KEYS_HANDLE, key_array.clone())?;
            Ok(Value::Table(key_array))
        }
        // Get the global keys
        Value::Nil => {
            // NOTE We make a deep clone so they can't modify references.
            let res = lua.create_table()?;
            for entry in lua.globals().get::<_, Table>(ROOT_KEYS_HANDLE).or(lua.create_table())?.pairs() {
                let (key, value) = entry?;
                res.set::<Value, Value>(key, value)?;
            }
            Ok(Value::Table(res))
        }
        v => {
            Err(rlua::Error::RuntimeError(format!("Expected nil or array \
                                                   of keys, got {:?}",
                                                  v)))
        }
    }
}

#[cfg(test)]
mod test {
    use super::super::root;
    use super::super::tag;
    use rlua::Lua;

    #[test]
    fn tags_none() {
        let lua = Lua::new();
        tag::init(&lua).unwrap();
        root::init(&lua).unwrap();
        lua.eval(
                 r#"
local t = root.tags()
assert(type(t) == "table")
assert(type(next(t)) == "nil")
"#,
                 None
        ).unwrap()
    }

    #[test]
    fn tags_does_not_copy() {
        let lua = Lua::new();
        tag::init(&lua).unwrap();
        root::init(&lua).unwrap();
        lua.eval(
                 r#"
local t = tag{ activated = true }
local t2 = root.tags()[1]
assert(t == t2)
t2.name = "Foo"
assert(t.name == "Foo")
"#,
                 None
        ).unwrap()
    }

    #[test]
    fn tags_some() {
        let lua = Lua::new();
        tag::init(&lua).unwrap();
        root::init(&lua).unwrap();
        lua.eval(
                 r#"
local first = tag{ activated = true }
local second = tag{ activated = true }
local t = root.tags()
assert(t[1] == first)
assert(t[2] == second)
"#,
                 None
        ).unwrap()
    }

    #[test]
    fn tags_removal() {
        let lua = Lua::new();
        tag::init(&lua).unwrap();
        root::init(&lua).unwrap();
        lua.eval(
                 r#"
local first = tag{ activated = true }
local second = tag{ activated = true }
first.activated = false
local t = root.tags()
assert(t[1] == second)
assert(type(t[2]) == "nil")
"#,
                 None
        ).unwrap()
    }
}
<commit_msg>root.keys(): Make a copy when setting keys<commit_after>//! TODO Fill in

use super::class::{Class, ClassBuilder};
use super::object::{self, Object, Objectable};
use cairo_sys::cairo_pattern_t;
use rlua::{self, LightUserData, Lua, Table, ToLua, UserData, UserDataMethods, Value};
use std::default::Default;
use std::fmt::{self, Display, Formatter};

/// Handle to the list of global key bindings
pub const ROOT_KEYS_HANDLE: &'static str = "__ROOT_KEYS";

#[derive(Clone, Debug)]
pub struct RootState {
    // TODO Fill in
    dummy: i32
}

pub struct Root<'lua>(Object<'lua>);

impl Default for RootState {
    fn default() -> Self {
        RootState { dummy: 0 }
    }
}

impl Display for RootState {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "Root: {:p}", self)
    }
}

impl<'lua> ToLua<'lua> for Root<'lua> {
    fn to_lua(self, lua: &'lua Lua) -> rlua::Result<Value<'lua>> {
        self.0.to_lua(lua)
    }
}

impl UserData for RootState {
    fn add_methods(methods: &mut UserDataMethods<Self>) {
        object::default_add_methods(methods);
    }
}

pub fn init(lua: &Lua) -> rlua::Result<Class> {
    // FIXME: In awesome there is no root class
    method_setup(lua, Class::builder(lua, "FIXME", None)?)?.save_class("root")?
                                                           .build()
}

fn method_setup<'lua>(lua: &'lua Lua,
                      builder: ClassBuilder<'lua>)
                      -> rlua::Result<ClassBuilder<'lua>> {
    // TODO Do properly
    use super::dummy;
    builder.method("connect_signal".into(), lua.create_function(dummy)?)?
           .method("buttons".into(), lua.create_function(dummy)?)?
           .method("wallpaper".into(), lua.create_function(wallpaper)?)?
           .method("tags".into(), lua.create_function(tags)?)?
           .method("keys".into(), lua.create_function(root_keys)?)?
           .method("size".into(), lua.create_function(dummy_double)?)?
           .method("size_mm".into(), lua.create_function(dummy_double)?)?
           .method("cursor".into(), lua.create_function(dummy)?)
}

impl_objectable!(Root, RootState);

fn dummy_double<'lua>(_: &'lua Lua, _: rlua::Value) -> rlua::Result<(i32, i32)> {
    Ok((0, 0))
}

/// Gets the wallpaper as a cairo surface or set it as a cairo pattern
fn wallpaper<'lua>(lua: &'lua Lua, pattern: Option<LightUserData>) -> rlua::Result<Value<'lua>> {
    // TODO FIXME Implement for realz
    if let Some(pattern) = pattern {
        // TODO Wrap before giving it to set_wallpaper
        let pattern = pattern.0 as *mut cairo_pattern_t;
        return set_wallpaper(lua, pattern)?.to_lua(lua)
    }
    // TODO Look it up in global conf (e.g probably super secret lua value)
    return Ok(Value::Nil)
}

fn set_wallpaper<'lua>(_: &'lua Lua, _pattern: *mut cairo_pattern_t) -> rlua::Result<bool> {
    warn!("Fake setting the wallpaper");
    Ok(true)
}

fn tags<'lua>(lua: &'lua Lua, _: ()) -> rlua::Result<Table<'lua>> {
    let table = lua.create_table()?;
    let activated_tags = lua.named_registry_value::<Table>(super::tag::TAG_LIST)?;
    for pair in activated_tags.pairs::<Value, Value>() {
        let (key, value) = pair?;
        table.set(key, value)?;
    }
    Ok(table)
}

/// Get or set global key bindings.
///
/// These bindings will be available when you press keys on the root window.
fn root_keys<'lua>(lua: &'lua Lua, key_array: rlua::Value<'lua>) -> rlua::Result<rlua::Value<'lua>> {
    match key_array {
        // Set the global keys
        Value::Table(key_array) => {
            let copy = lua.create_table()?;
            // NOTE We make a deep clone so they can't modify references.
            for entry in key_array.clone().pairs() {
                let (key, value) = entry?;
                copy.set::<Value, Value>(key, value)?;
            }
            lua.set_named_registry_value(ROOT_KEYS_HANDLE, copy)?;
            Ok(Value::Table(key_array))
        }
        // Get the global keys
        Value::Nil => {
            let res = lua.create_table()?;
            for entry in lua.globals().get::<_, Table>(ROOT_KEYS_HANDLE).or(lua.create_table())?.pairs() {
                let (key, value) = entry?;
                res.set::<Value, Value>(key, value)?;
            }
            Ok(Value::Table(res))
        }
        v => {
            Err(rlua::Error::RuntimeError(format!("Expected nil or array \
                                                   of keys, got {:?}",
                                                  v)))
        }
    }
}

#[cfg(test)]
mod test {
    use super::super::root;
    use super::super::tag;
    use rlua::Lua;

    #[test]
    fn tags_none() {
        let lua = Lua::new();
        tag::init(&lua).unwrap();
        root::init(&lua).unwrap();
        lua.eval(
                 r#"
local t = root.tags()
assert(type(t) == "table")
assert(type(next(t)) == "nil")
"#,
                 None
        ).unwrap()
    }

    #[test]
    fn tags_does_not_copy() {
        let lua = Lua::new();
        tag::init(&lua).unwrap();
        root::init(&lua).unwrap();
        lua.eval(
                 r#"
local t = tag{ activated = true }
local t2 = root.tags()[1]
assert(t == t2)
t2.name = "Foo"
assert(t.name == "Foo")
"#,
                 None
        ).unwrap()
    }

    #[test]
    fn tags_some() {
        let lua = Lua::new();
        tag::init(&lua).unwrap();
        root::init(&lua).unwrap();
        lua.eval(
                 r#"
local first = tag{ activated = true }
local second = tag{ activated = true }
local t = root.tags()
assert(t[1] == first)
assert(t[2] == second)
"#,
                 None
        ).unwrap()
    }

    #[test]
    fn tags_removal() {
        let lua = Lua::new();
        tag::init(&lua).unwrap();
        root::init(&lua).unwrap();
        lua.eval(
                 r#"
local first = tag{ activated = true }
local second = tag{ activated = true }
first.activated = false
local t = root.tags()
assert(t[1] == second)
assert(type(t[2]) == "nil")
"#,
                 None
        ).unwrap()
    }
}
<|endoftext|>


<commit_before>use futures::{Async, Poll, Stream};

/// Implementor for greedy folding in streams.
pub struct GreedyFold<S, F, A> {
    stream: S,
    fold_fn: F,
    acc: A,
    exhausted: bool,
}

/// Stream that folds all immediately available items from the underlying stream, yielding a single
/// resulting value. If there is no currently ready values in the stream, returns the initial value
/// of the accumulator. Once the stream is exhausted, greedy folding also stops yielding values.
///
/// # Example
///
/// ```
/// # extern crate futures;
/// # extern crate exonum_testkit;
/// use futures::{stream, Stream};
/// use exonum_testkit::GreedilyFoldable;
/// # fn main() {
/// let stream = stream::iter_ok::<_, ()>(vec![1, 2, 3, 4])
///     .greedy_fold(0, |acc, item| acc + item);
/// let values: Vec<_> = stream.wait().into_iter().collect();
/// assert_eq!(values, vec![Ok(10)]);
/// # }
/// ```
pub trait GreedilyFoldable: Stream {
    /// Performs greedy folding.
    fn greedy_fold<F, A>(self, acc: A, fold_fn: F) -> GreedyFold<Self, F, A>
    where
        F: FnMut(A, Self::Item) -> A,
        A: Clone,
        Self: Sized;
}

impl<T: Stream> GreedilyFoldable for T {
    fn greedy_fold<F, A>(self, acc: A, fold_fn: F) -> GreedyFold<Self, F, A>
    where
        F: FnMut(A, Self::Item) -> A,
        A: Clone,
        Self: Sized,
    {
        GreedyFold::new(self, acc, fold_fn)
    }
}

impl<S, F, A> GreedyFold<S, F, A>
where
    S: Stream,
    F: FnMut(A, S::Item) -> A,
    A: Clone,
{
    fn new(stream: S, acc: A, fold_fn: F) -> Self {
        GreedyFold {
            stream,
            fold_fn,
            acc,
            exhausted: false,
        }
    }
}

impl<S, F, A> Stream for GreedyFold<S, F, A>
where
    S: Stream,
    F: FnMut(A, S::Item) -> A,
    A: Clone,
{
    type Item = A;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<Option<A>, S::Error> {
        if self.exhausted {
            // Do not poll the underlying stream, as it may lead to unexpected behavior
            return Ok(Async::Ready(None));
        }

        let mut acc = self.acc.clone();
        let mut some_items = false;
        loop {
            match self.stream.poll()? {
                Async::Ready(None) => {
                    self.exhausted = true;
                    return Ok(if some_items {
                        Async::Ready(Some(acc))
                    } else {
                        Async::Ready(None)
                    });
                }
                Async::NotReady => {
                    // Waiting for the next polling
                    return Ok(Async::Ready(Some(acc)));
                }
                Async::Ready(Some(item)) => {
                    some_items = true;
                    acc = (self.fold_fn)(acc, item);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::executor;
    use futures::sync::mpsc;

    #[test]
    fn test_fold_empty_stream() {
        //! Check that the stream continues to return the initial value of the accumulator
        let (mut sender, receiver) = mpsc::channel(1_024);
        let stream = GreedyFold::new(receiver, 0, |acc, i| acc + i);
        sender.try_send(1).unwrap();
        sender.try_send(2).unwrap();
        sender.try_send(3).unwrap();
        sender.try_send(4).unwrap();

        let folded: Vec<_> = stream.take(4).wait().into_iter().collect();
        assert_eq!(
            folded,
            vec![
                Ok(10), Ok(0), Ok(0), Ok(0)
            ]
        );
    }

    #[test]
    fn test_iterative_fold() {
        let (mut sender, receiver) = mpsc::channel(1_024);
        let stream = GreedyFold::new(receiver, 0, |acc, i| acc + i);
        let mut exec = executor::spawn(stream);

        sender.try_send(1).unwrap();
        sender.try_send(2).unwrap();
        let result = exec.wait_stream();
        assert_eq!(result, Some(Ok(3)));

        sender.try_send(3).unwrap();
        sender.try_send(4).unwrap();
        sender.try_send(5).unwrap();
        let result = exec.wait_stream();
        assert_eq!(result, Some(Ok(12)));
    }

    #[test]
    fn test_iterative_fold_side_effects() {
        use std::cell::RefCell;

        let (mut sender, receiver) = mpsc::channel(1_024);
        let values = RefCell::new(Vec::new());
        let stream = {
            let stream = GreedyFold::new(receiver, (), |_, i| {
                values.borrow_mut().push(i);
            });
            stream
        };
        let mut exec = executor::spawn(stream);

        sender.try_send(1).unwrap();
        sender.try_send(2).unwrap();
        let result = exec.wait_stream();
        assert_eq!(result, Some(Ok(())));
        assert_eq!(
            *values.borrow(),
            vec![
                1, 2
            ]
        );

        sender.try_send(3).unwrap();
        sender.try_send(4).unwrap();
        sender.try_send(5).unwrap();
        let result = exec.wait_stream();
        assert_eq!(result, Some(Ok(())));
        assert_eq!(
            *values.borrow(),
            vec![
                1, 2, 3, 4, 5
            ]
        );
    }
}
<commit_msg>Fix code formating.<commit_after>use futures::{Async, Poll, Stream};

/// Implementor for greedy folding in streams.
pub struct GreedyFold<S, F, A> {
    stream: S,
    fold_fn: F,
    acc: A,
    exhausted: bool,
}

/// Stream that folds all immediately available items from the underlying stream, yielding a single
/// resulting value. If there is no currently ready values in the stream, returns the initial value
/// of the accumulator. Once the stream is exhausted, greedy folding also stops yielding values.
///
/// # Example
///
/// ```
/// # extern crate futures;
/// # extern crate exonum_testkit;
/// use futures::{stream, Stream};
/// use exonum_testkit::GreedilyFoldable;
/// # fn main() {
/// let stream = stream::iter_ok::<_, ()>(vec![1, 2, 3, 4])
///     .greedy_fold(0, |acc, item| acc + item);
/// let values: Vec<_> = stream.wait().into_iter().collect();
/// assert_eq!(values, vec![Ok(10)]);
/// # }
/// ```
pub trait GreedilyFoldable: Stream {
    /// Performs greedy folding.
    fn greedy_fold<F, A>(self, acc: A, fold_fn: F) -> GreedyFold<Self, F, A>
    where
        F: FnMut(A, Self::Item) -> A,
        A: Clone,
        Self: Sized;
}

impl<T: Stream> GreedilyFoldable for T {
    fn greedy_fold<F, A>(self, acc: A, fold_fn: F) -> GreedyFold<Self, F, A>
    where
        F: FnMut(A, Self::Item) -> A,
        A: Clone,
        Self: Sized,
    {
        GreedyFold::new(self, acc, fold_fn)
    }
}

impl<S, F, A> GreedyFold<S, F, A>
where
    S: Stream,
    F: FnMut(A, S::Item) -> A,
    A: Clone,
{
    fn new(stream: S, acc: A, fold_fn: F) -> Self {
        GreedyFold {
            stream,
            fold_fn,
            acc,
            exhausted: false,
        }
    }
}

impl<S, F, A> Stream for GreedyFold<S, F, A>
where
    S: Stream,
    F: FnMut(A, S::Item) -> A,
    A: Clone,
{
    type Item = A;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<Option<A>, S::Error> {
        if self.exhausted {
            // Do not poll the underlying stream, as it may lead to unexpected behavior
            return Ok(Async::Ready(None));
        }

        let mut acc = self.acc.clone();
        let mut some_items = false;
        loop {
            match self.stream.poll()? {
                Async::Ready(None) => {
                    self.exhausted = true;
                    return Ok(if some_items {
                        Async::Ready(Some(acc))
                    } else {
                        Async::Ready(None)
                    });
                }
                Async::NotReady => {
                    // Waiting for the next polling
                    return Ok(Async::Ready(Some(acc)));
                }
                Async::Ready(Some(item)) => {
                    some_items = true;
                    acc = (self.fold_fn)(acc, item);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use futures::executor;
    use futures::sync::mpsc;

    #[test]
    fn test_fold_empty_stream() {
        //! Check that the stream continues to return the initial value of the accumulator
        let (mut sender, receiver) = mpsc::channel(1_024);
        let stream = GreedyFold::new(receiver, 0, |acc, i| acc + i);
        sender.try_send(1).unwrap();
        sender.try_send(2).unwrap();
        sender.try_send(3).unwrap();
        sender.try_send(4).unwrap();

        let folded: Vec<_> = stream.take(4).wait().into_iter().collect();
        assert_eq!(folded, vec![Ok(10), Ok(0), Ok(0), Ok(0)]);
    }

    #[test]
    fn test_iterative_fold() {
        let (mut sender, receiver) = mpsc::channel(1_024);
        let stream = GreedyFold::new(receiver, 0, |acc, i| acc + i);
        let mut exec = executor::spawn(stream);

        sender.try_send(1).unwrap();
        sender.try_send(2).unwrap();
        let result = exec.wait_stream();
        assert_eq!(result, Some(Ok(3)));

        sender.try_send(3).unwrap();
        sender.try_send(4).unwrap();
        sender.try_send(5).unwrap();
        let result = exec.wait_stream();
        assert_eq!(result, Some(Ok(12)));
    }

    #[test]
    fn test_iterative_fold_side_effects() {
        use std::cell::RefCell;

        let (mut sender, receiver) = mpsc::channel(1_024);
        let values = RefCell::new(Vec::new());
        let stream = {
            let stream = GreedyFold::new(receiver, (), |_, i| { values.borrow_mut().push(i); });
            stream
        };
        let mut exec = executor::spawn(stream);

        sender.try_send(1).unwrap();
        sender.try_send(2).unwrap();
        let result = exec.wait_stream();
        assert_eq!(result, Some(Ok(())));
        assert_eq!(*values.borrow(), vec![1, 2]);

        sender.try_send(3).unwrap();
        sender.try_send(4).unwrap();
        sender.try_send(5).unwrap();
        let result = exec.wait_stream();
        assert_eq!(result, Some(Ok(())));
        assert_eq!(*values.borrow(), vec![1, 2, 3, 4, 5]);
    }
}
<|endoftext|>


<commit_before>#![allow(non_snake_case)]

use macos::cocoa::appkit::*;
use macos::cocoa::foundation::*;
use macos::cocoa::base::{nil};
use objc::declare::*;
use objc::runtime::*;
use std::panic;
use window::Message;

pub struct Window {
    app: *mut Object,
    window: *mut Object,
}

unsafe fn finish_launching(app: &mut Object) {
    let NSApplication = Class::get("NSApplication").unwrap();
    let method = NSApplication.instance_method(sel!(finishLaunching)).unwrap();
    let imp: unsafe extern fn (*mut Object, Sel) = ::std::mem::transmute(method.implementation());
    imp(app, sel!(finishLaunching));
}

impl Window {
    pub fn new(_name: &str) -> Window {
        extern fn run(
            _self: &mut Object,
            _sel: Sel
        ) {
            // TODO: Create autorelease blocks?

            println!("run({:?}, {:?})", _self, _sel);

            unsafe {
                //println!("getting NSRunLoop and ensuring there's a default run loop");
                //let NSRunLoop = Class::get("NSRunLoop").unwrap();
                //let current_run_loop: *mut Object = msg_send![NSRunLoop, currentRunLoop];
                //println!("Current run loop: {:?}", current_run_loop);
                //println!("NSDefaultRunLoopMode: {:?}", NSDefaultRunLoopMode);

                println!("finishing launching");
                //msg_send![_super, finishLaunching];
                finish_launching(_self);
            }

            println!("Done with run()");
        }

        extern fn send_event(
            _self: &mut Object,
            _sel: Sel,
            event: *mut Object, // NSEvent
        ) {
            println!("send_event({:?})", event);

            unsafe {
                let _super: *mut Object = msg_send![_self, super];
                msg_send![_super, sendEvent: event];
            }
        }

        // Grab Objective C types.
        let NSApplication = Class::get("NSApplication").unwrap();
        let NSAutoreleasePool = Class::get("NSAutoreleasePool").unwrap();

        let pool: *mut Object = unsafe { msg_send![NSAutoreleasePool, new] };

        // Create custom NSApplication subclass.
        let MyApplication = {
            let mut class_decl = ClassDecl::new("MyApplication", NSApplication).unwrap();
            unsafe {
                class_decl.add_method(
                    sel!(run),
                    run as extern fn (&mut Object, Sel));
                //class_decl.add_method(
                //    sel!(sendEvent:),
                //    send_event as extern fn (&mut Object, Sel, *mut Object),
                //);
            }
            class_decl.register()
        };

        // Initialize and run the application.
        // ===================================

        // Create and retrieve the application instance.
        let app: *mut Object = unsafe { msg_send![MyApplication, sharedApplication] };

        // Assign the app delegate to the application instance and run the appliction.
        unsafe {
            //msg_send![app, run];
            msg_send![app,
                performSelectorOnMainThread: sel!(run)
                withObject: nil
                waitUntilDone: YES];

            let window = open_window();

            msg_send![pool, release];

            Window {
                app: app,
                window: window,
            }
        }
    }

    pub fn close(&self) {
        // unsafe { self.window.performClose_(nil); }
    }

    pub fn next_message(&mut self) -> Option<Message> {
        println!("getting message");

        unsafe {
            // TODO: Create autorelease blocks?

            let NSDate = Class::get("NSDate").unwrap();
            let distant_future = msg_send![NSDate, distantFuture];

            //let event = msg_send![
            //    self.app,
            //    nextEventMatchingMask: NSAnyEventMask
            //    untilDate: distant_future
            //    inMode: 0
            //    dequeue: YES];
            let imp = get_next_message_imp();

            let event = imp(
                self.app,
                sel!(nextEventMatchingMask:untilDate:inMode:dequeue:),
                0xffffffff, //NSAnyEventMask,
                distant_future,
                NSDefaultRunLoopMode,
                YES,
            );

            let type_ptr: NSEventType = msg_send![event, type];
            println!("event: {:?}", type_ptr);

            msg_send![self.app, sendEvent:event];
            msg_send![self.app, updateWindows];
        }

        None
    }

    pub fn get_rect(&self) -> (i32, i32, i32, i32) {
        (0, 0, 1, 1)
    }
}

unsafe fn get_next_message_imp() -> extern fn (*mut Object, Sel, i64, *mut Object, *mut Object, BOOL) -> *mut Object {
    let NSApplication = Class::get("NSApplication").unwrap();
    let method = NSApplication.instance_method(sel!(nextEventMatchingMask:untilDate:inMode:dequeue:)).unwrap();
    ::std::mem::transmute(method.implementation())
}

/// Creates a window for the active application.
///
/// # Unsafety
///
/// - The `NSApplication` must fully initialized before attempting to open a window.
unsafe fn open_window() -> *mut Object {
    println!("Opening an NSWindow");

    let NSWindow = Class::get("NSWindow").unwrap();

    let point = NSPoint { x: 0.0, y: 0.0 };
    let size = NSSize { width: 500.0, height: 500.0 };
    let frame = NSRect { origin: point, size: size };

    let style_mask =
        NSWindowMask::NSTitledWindowMask as NSUInteger |
        NSWindowMask::NSClosableWindowMask as NSUInteger |
        NSWindowMask::NSMiniaturizableWindowMask as NSUInteger |
        NSWindowMask::NSResizableWindowMask as NSUInteger;

    // Create and initialize the window instance.
    let window: *mut Object = msg_send![NSWindow, alloc];
    let window: *mut Object = msg_send![
        window,
        initWithContentRect:frame
        styleMask:style_mask
        backing:NSBackingStoreType::NSBackingStoreRetained
        defer:NO
    ];

    // Create a view for the window.
    let frame = window.contentRectForFrameRect_(frame);
    let content = NSView::alloc(nil).initWithFrame_(frame);
    window.setContentView_(content);

    // Show the window.
    msg_send![
        window,
        makeKeyAndOrderFront:nil
    ];
    msg_send![window, orderFrontRegardless];

    // window.makeKeyAndOrderFront_(nil);
    // window.orderFrontRegardless();

    println!("Done opening NSWindow");

    window
}
<commit_msg>Capture window close event<commit_after>#![allow(non_snake_case)]

use macos::cocoa::appkit::*;
use macos::cocoa::foundation::*;
use macos::cocoa::base::{nil};
use objc::declare::*;
use objc::runtime::*;
use std::os::raw::c_void;
use window::Message;
use self::window_map::WindowInner;

mod window_map {
    use std::collections::{ HashMap, VecDeque };
    use std::sync::{Mutex, Once, ONCE_INIT};
    use objc::runtime::*;
    use window::Message;

    static mut WINDOW_MAP: Option<*const Mutex<WindowMap>> = None;
    static WINDOW_MAP_INIT: Once = ONCE_INIT;

    pub type WindowMap = HashMap<*mut Object, WindowInner>;

    pub fn with<F, T>(func: F) -> T
        where F: FnOnce(&mut WindowMap) -> T
    {
        unsafe {
            // Initialize the map once.
            WINDOW_MAP_INIT.call_once(|| {
                let boxed = Box::new(Mutex::new(HashMap::new()));
                WINDOW_MAP = Some(Box::into_raw(boxed));
            });

            // Lock the mutex and invoke `func` with the `WindowMap`.
            let mutex = WINDOW_MAP.expect("Window map was `None`, initialization must have failed");
            let mut guard = (&*mutex).lock().expect("Window mutex was poisoned");
            func(&mut *guard)
        }
    }

    #[derive(Debug, Default)]
    pub struct WindowInner {
        pub messages: VecDeque<Message>
    }
}

pub struct Window {
    app: *mut Object,
    window: *mut Object,
}

impl Window {
    pub fn new(_name: &str) -> Window {
        // Grab Objective C types.
        let NSApplication = Class::get("NSApplication").unwrap();
        let NSAutoreleasePool = Class::get("NSAutoreleasePool").unwrap();

        let pool: *mut Object = unsafe { msg_send![NSAutoreleasePool, new] };

        // Create custom NSApplication subclass.
        let MyApplication = {
            let mut class_decl = ClassDecl::new("MyApplication", NSApplication).unwrap();
            unsafe {
                class_decl.add_method(
                    sel!(run),
                    run as extern fn (&mut Object, Sel)
                );
                class_decl.add_method(
                    sel!(windowWillClose:),
                    window_will_close as extern fn (&mut Object, Sel, *mut Object),
                );
                class_decl.add_ivar::<*mut c_void>("bootstrapWindow");
                //class_decl.add_method(
                //    sel!(sendEvent:),
                //    send_event as extern fn (&mut Object, Sel, *mut Object),
                //);
            }
            class_decl.register()
        };

        // Initialize and run the application.
        // ===================================

        // Create and retrieve the application instance.
        let app: *mut Object = unsafe { msg_send![MyApplication, sharedApplication] };

        // Assign the app delegate to the application instance and run the appliction.
        let window = unsafe {
            //msg_send![app, run];
            msg_send![app,
                performSelectorOnMainThread: sel!(run)
                withObject: nil
                waitUntilDone: YES];

            let window = open_window(app);

            msg_send![pool, release];

            Window {
                app: app,
                window: window,
            }
        };

        // Initialize the window map if necessary and add the window to it.
        window_map::with(|window_map| {
            window_map.insert(window.app, WindowInner::default())
        });

        window
    }

    pub fn close(&self) {
        // unsafe { self.window.performClose_(nil); }
    }

    pub fn next_message(&mut self) -> Option<Message> {
        unsafe {
            // TODO: Create autorelease blocks?

            let NSDate = Class::get("NSDate").unwrap();
            let distant_future = msg_send![NSDate, distantFuture];

            //let NSApplication = Class::get("NSApplication").unwrap();
            //let event: *mut Object = msg_send![
            //    super(self.app, NSApplication),
            //    nextEventMatchingMask: 0xffffffff //NSAnyEventMask,
            //    untilDate: distant_future
            //    inMode: NSDefaultRunLoopMode
            //    dequeue: YES
            //];

            // HACK: For some reason the above doesn't work. I don't know why, but we should fix it.
            let imp = get_next_message_imp();

            let event = imp(
                self.app,
                sel!(nextEventMatchingMask:untilDate:inMode:dequeue:),
                0xffffffff, //NSAnyEventMask,
                distant_future,
                NSDefaultRunLoopMode,
                YES,
            );

            let type_ptr: NSEventType = msg_send![event, type];
            println!("event: {:?}", type_ptr);

            msg_send![self.app, sendEvent:event];
            msg_send![self.app, updateWindows];
        }

        None
    }

    pub fn get_rect(&self) -> (i32, i32, i32, i32) {
        (0, 0, 1, 1)
    }
}

extern fn run(
    app: &mut Object,
    _sel: Sel
) {
    // TODO: Create autorelease blocks?

    let NSApplication = Class::get("NSApplication").unwrap();
    unsafe {
        msg_send![super(app, NSApplication), finishLaunching];
    }
}

extern fn window_will_close(app: &mut Object, _sel: Sel, notification: *mut Object) {
    println!("window will close! :D");
    window_map::with(|window_map| {
        let message_queue = window_map.get_mut(&(app as *mut _)).expect("No window existed in window map");
        message_queue.messages.push_back(Message::Close);
    });
}

unsafe fn get_next_message_imp() -> extern fn (*mut Object, Sel, i64, *mut Object, *mut Object, BOOL) -> *mut Object {
    let NSApplication = Class::get("NSApplication").unwrap();
    let method = NSApplication.instance_method(sel!(nextEventMatchingMask:untilDate:inMode:dequeue:)).unwrap();
    ::std::mem::transmute(method.implementation())
}

/// Creates a window for the active application.
///
/// # Unsafety
///
/// - The `NSApplication` must fully initialized before attempting to open a window.
unsafe fn open_window(app: *mut Object) -> *mut Object {
    let NSWindow = Class::get("NSWindow").unwrap();

    let point = NSPoint { x: 0.0, y: 0.0 };
    let size = NSSize { width: 500.0, height: 500.0 };
    let frame = NSRect { origin: point, size: size };

    let style_mask =
        NSWindowMask::NSTitledWindowMask as NSUInteger |
        NSWindowMask::NSClosableWindowMask as NSUInteger |
        NSWindowMask::NSMiniaturizableWindowMask as NSUInteger |
        NSWindowMask::NSResizableWindowMask as NSUInteger;

    // Create and initialize the window instance.
    let window: *mut Object = msg_send![NSWindow, alloc];
    let window: *mut Object = msg_send![
        window,
        initWithContentRect:frame
        styleMask:style_mask
        backing:NSBackingStoreType::NSBackingStoreRetained
        defer:NO
    ];

    // Create a view for the window.
    let frame = window.contentRectForFrameRect_(frame);
    let content = NSView::alloc(nil).initWithFrame_(frame);
    window.setContentView_(content);

    // Configure the window delegate.
    msg_send![window, setDelegate: app];

    // Show the window.
    msg_send![
        window,
        makeKeyAndOrderFront:nil
    ];
    msg_send![window, orderFrontRegardless];

    window
}
<|endoftext|>


<commit_before>use graphics::modular_index::{offset, previous, next};

// Local crate.
use Vector2d = vector2d::Vector2d;

static EPSILON: f64 = 0.0000000001;

pub fn area(contour: &[Vector2d]) -> f64 {
    let n = contour.len();
    let mut sum = 0.0_f64;

    for i in range(0, n) {
        let q = i;
        let p = previous(n, i);
        sum += contour.get(p).unwrap().get_x() * contour.get(q).unwrap().get_y()
            - contour.get(q).unwrap().get_x() * contour.get(p).unwrap().get_y();
    }

    sum * 0.5_f64
}

/// InsideTriangle decides if a point P is Inside of the triangle
/// defined by A, B, C.
pub fn inside_triangle(
    a_x: f64, a_y: f64,
    b_x: f64, b_y: f64,
    c_x: f64, c_y: f64,
    p_x: f64, p_y: f64
) -> bool {

    let (bcx, bcy) = (c_x - b_x, c_y - b_y);
    let (cax, cay) = (a_x - c_x, a_y - c_y);
    let (abx, aby) = (b_x - a_x, b_y - a_y);
    let (apx, apy) = (p_x - a_x, p_y - a_y);
    let (bpx, bpy) = (p_x - b_x, p_y - b_y);
    let (cpx, cpy) = (p_x - c_x, p_y - c_y);

    let aCROSSbp = bcx*bpy - bcy*bpx;
    let cCROSSap = abx*apy - aby*apx;
    let bCROSScp = cax*cpy - cay*cpx;

    (
        (aCROSSbp >= 0.0_f64)
        && (bCROSScp >= 0.0_f64)
        && (cCROSSap >= 0.0_f64)
    )
}

pub fn snip(
    contour: &[Vector2d],
    triangle: [uint, ..3],
    n: uint,
    vertex_indices: &Vec<uint>
) -> bool {
    let (u, v, w) = (triangle[0], triangle[1], triangle[2]);

    let a_pos = contour.get(*vertex_indices.get(u)).unwrap();
    let b_pos = contour.get(*vertex_indices.get(v)).unwrap();
    let c_pos = contour.get(*vertex_indices.get(w)).unwrap();

    let (ax, ay) = (a_pos.get_x(), a_pos.get_y());
    let (bx, by) = (b_pos.get_x(), b_pos.get_y());
    let (cx, cy) = (c_pos.get_x(), c_pos.get_y());

    if EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) {
        return false;
    }

    for p in range(0, n) {
        // Do not check for any of the vertices in the triangle.
        if (p == u) || (p == v) || (p == w) { continue; }

        let p_pos = contour.get(*vertex_indices.get(p)).unwrap();
        if inside_triangle(ax,ay,bx,by,cx,cy,p_pos.get_x(),p_pos.get_y()) { return false; }
    }

    true
}

pub fn process(
    contour: &[Vector2d]
) -> Option<Vec<Vector2d>> {
    /* allocate and initialize list of Vertices in polygon */

    let n = contour.len();
    if n < 3 { return None; }

    let mut result: Vec<Vector2d> = Vec::new();
    let mut vertex_indices: Vec<uint> = Vec::with_capacity(n);

    /* we want a counter-clockwise polygon in V */

    // Computes the area which has opposite signs
    // whether the polygon is clock-wise or counter-clockwise.
    if 0.0_f64 < area(contour) {
        for v in range(0, n) { vertex_indices.push(v); }
    } else {
        // Add indices in reverse order.
        for v in range(0, n) { vertex_indices.push((n-1)-v); }
    }

    // Stores the number of vertices.
    // Used instead of `vertex_indices.len()` to emulate removing of vertices.
    let mut number_of_vertices = n;

    /*  remove nv-2 Vertices, creating 1 triangle every time */

    // Used for error detection.
    let mut count = 2 * number_of_vertices;

    let mut v = number_of_vertices - 1;
    while number_of_vertices > 2 {
        /* if we loop, it is probably a non-simple polygon */
        if count <= 0 {
            //** Triangulate: ERROR - probable bad polygon!
            return None;
        }

        count -= 1;

        /* three consecutive vertices in current polygon, <u,v,w> */
        let triangle = [
            v,
            next(number_of_vertices, v),
            offset(number_of_vertices, v, 2)
        ];
        v = triangle[1];

        if snip(contour, triangle, number_of_vertices, &mut vertex_indices) {
            for &i in triangle.iter() {
                result.push(*contour.get(*vertex_indices.get(i)).unwrap());
            }

            /* remove v from remaining polygon */
            for i in range(0, number_of_vertices - 3) {
                let s = v + i;
                let t = v + i + 1;

                *vertex_indices.get_mut(s) = *vertex_indices.get(t);
            }

            // "Removed" a vertex.
            number_of_vertices -= 1;

            /* resest error detection counter */
            count = 2 * number_of_vertices;
        }
    }

    Some(result)
}

<commit_msg>Simplified code<commit_after>use graphics::modular_index::{offset, previous, next};

// Local crate.
use Vector2d = vector2d::Vector2d;

static EPSILON: f64 = 0.0000000001;

pub fn area(contour: &[Vector2d]) -> f64 {
    let n = contour.len();
    let mut sum = 0.0_f64;

    for i in range(0, n) {
        let q = i;
        let p = previous(n, i);
        sum += contour.get(p).unwrap().get_x() * contour.get(q).unwrap().get_y()
            - contour.get(q).unwrap().get_x() * contour.get(p).unwrap().get_y();
    }

    sum * 0.5_f64
}

/// InsideTriangle decides if a point P is Inside of the triangle
/// defined by A, B, C.
pub fn inside_triangle(
    a_x: f64, a_y: f64,
    b_x: f64, b_y: f64,
    c_x: f64, c_y: f64,
    p_x: f64, p_y: f64
) -> bool {

    let (bcx, bcy) = (c_x - b_x, c_y - b_y);
    let (cax, cay) = (a_x - c_x, a_y - c_y);
    let (abx, aby) = (b_x - a_x, b_y - a_y);
    let (apx, apy) = (p_x - a_x, p_y - a_y);
    let (bpx, bpy) = (p_x - b_x, p_y - b_y);
    let (cpx, cpy) = (p_x - c_x, p_y - c_y);

    let bc_cross_bp = bcx * bpy - bcy * bpx;
    let ab_cross_ap = abx * apy - aby * apx;
    let ca_cross_cp = cax * cpy - cay * cpx;

    bc_cross_bp >= 0.0_f64
    && ca_cross_cp >= 0.0_f64
    && ab_cross_ap >= 0.0_f64
}

pub fn snip(
    contour: &[Vector2d],
    triangle: [uint, ..3],
    n: uint,
    vertex_indices: &Vec<uint>
) -> bool {
    let (u, v, w) = (triangle[0], triangle[1], triangle[2]);

    let a_pos = contour.get(*vertex_indices.get(u)).unwrap();
    let b_pos = contour.get(*vertex_indices.get(v)).unwrap();
    let c_pos = contour.get(*vertex_indices.get(w)).unwrap();

    let (ax, ay) = (a_pos.get_x(), a_pos.get_y());
    let (bx, by) = (b_pos.get_x(), b_pos.get_y());
    let (cx, cy) = (c_pos.get_x(), c_pos.get_y());

    if EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) {
        return false;
    }

    for p in range(0, n) {
        // Do not check for any of the vertices in the triangle.
        if (p == u) || (p == v) || (p == w) { continue; }

        let p_pos = contour.get(*vertex_indices.get(p)).unwrap();
        if inside_triangle(ax,ay,bx,by,cx,cy,p_pos.get_x(),p_pos.get_y()) { return false; }
    }

    true
}

pub fn process(
    contour: &[Vector2d]
) -> Option<Vec<Vector2d>> {
    /* allocate and initialize list of Vertices in polygon */

    let n = contour.len();
    if n < 3 { return None; }

    let mut result: Vec<Vector2d> = Vec::new();
    let mut vertex_indices: Vec<uint> = Vec::with_capacity(n);

    /* we want a counter-clockwise polygon in V */

    // Computes the area which has opposite signs
    // whether the polygon is clock-wise or counter-clockwise.
    if 0.0_f64 < area(contour) {
        for v in range(0, n) { vertex_indices.push(v); }
    } else {
        // Add indices in reverse order.
        for v in range(0, n) { vertex_indices.push((n-1)-v); }
    }

    // Stores the number of vertices.
    // Used instead of `vertex_indices.len()` to emulate removing of vertices.
    let mut number_of_vertices = n;

    /*  remove nv-2 Vertices, creating 1 triangle every time */

    // Used for error detection.
    let mut count = 2 * number_of_vertices;

    let mut v = number_of_vertices - 1;
    while number_of_vertices > 2 {
        /* if we loop, it is probably a non-simple polygon */
        if count <= 0 {
            //** Triangulate: ERROR - probable bad polygon!
            return None;
        }

        count -= 1;

        /* three consecutive vertices in current polygon, <u,v,w> */
        let triangle = [
            v,
            next(number_of_vertices, v),
            offset(number_of_vertices, v, 2)
        ];
        v = triangle[1];

        if snip(contour, triangle, number_of_vertices, &mut vertex_indices) {
            for &i in triangle.iter() {
                result.push(*contour.get(*vertex_indices.get(i)).unwrap());
            }

            /* remove v from remaining polygon */
            for i in range(0, number_of_vertices - 3) {
                let s = v + i;
                let t = v + i + 1;

                *vertex_indices.get_mut(s) = *vertex_indices.get(t);
            }

            // "Removed" a vertex.
            number_of_vertices -= 1;

            /* resest error detection counter */
            count = 2 * number_of_vertices;
        }
    }

    Some(result)
}

<|endoftext|>