<commit_before>use std::fmt;
use std::error::Error;
use std::collections::HashMap;
use std::collections::LinkedList;
use std::str::from_utf8;
use std::str::Utf8Error;
use std::num::ParseIntError;

pub enum Value {
    Nil,
    Integer(i64),
    Data(Vec<u8>),
    List(LinkedList<Vec<u8>>),
}

#[derive(Debug)]
pub enum OperationError {
    OverflowError,
    ValueError,
    WrongTypeError,
}

impl fmt::Display for OperationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.description().fmt(f)
    }
}

impl Error for OperationError {
    fn description(&self) -> &str {
        return "oops";
    }
}

impl From<Utf8Error> for OperationError {
    fn from(_: Utf8Error) -> OperationError { OperationError::ValueError }
}

impl From<ParseIntError> for OperationError {
    fn from(_: ParseIntError) -> OperationError { OperationError::ValueError }
}

impl Value {
    pub fn set(&mut self, value: Vec<u8>) -> Result<(), OperationError> {
        if value.len() < 32 { // ought to be enough!
            let try_utf8 = from_utf8(&*value);
            if try_utf8.is_ok() {
                let try_parse = try_utf8.unwrap().parse::<i64>();
                if try_parse.is_ok() {
                    *self = Value::Integer(try_parse.unwrap());
                    return Ok(());
                }
            }
        }
        *self = Value::Data(value);
        return Ok(());
    }

    pub fn append(&mut self, value: Vec<u8>) -> Result<usize, OperationError> {
        match self {
            &mut Value::Nil => {
                let len = value.len();
                *self = Value::Data(value);
                return Ok(len);
            },
            &mut Value::Data(ref mut data) => { data.extend(value); return Ok(data.len()); },
            &mut Value::Integer(i) => {
                let oldstr = format!("{}", i);
                let len = oldstr.len() + value.len();
                *self = Value::Data([oldstr.into_bytes(), value].concat());
                return Ok(len);
            },
            _ => return Err(OperationError::WrongTypeError),
        }
    }

    pub fn incr(&mut self, incr: i64) -> Result<i64, OperationError> {
        let mut newval:i64;
        match self {
            &mut Value::Nil => {
                newval = incr;
            },
            &mut Value::Integer(i) => {
                let tmp_newval = i.checked_add(incr);
                match tmp_newval {
                    Some(v) => newval = v,
                    None => return Err(OperationError::OverflowError),
                }
            },
            &mut Value::Data(ref data) => {
                if data.len() > 32 {
                    return Err(OperationError::OverflowError);
                }
                let res = try!(from_utf8(&data));
                let ival = try!(res.parse::<i64>());
                let tmp_newval = ival.checked_add(incr);
                match tmp_newval {
                    Some(v) => newval = v,
                    None => return Err(OperationError::OverflowError),
                }
            },
            _ => return Err(OperationError::WrongTypeError),
        }
        *self = Value::Integer(newval);
        return Ok(newval);
    }

    pub fn push(&mut self, el: Vec<u8>, right: bool) -> Result<usize, OperationError> {
        let listsize;
        match self {
            &mut Value::Nil => {
                let mut list = LinkedList::new();
                list.push_back(el);
                *self = Value::List(list);
                listsize = 1;
            },
            &mut Value::List(ref mut list) => {
                if right {
                    list.push_back(el);
                } else {
                    list.push_front(el);
                }
                listsize = list.len();
            }
            _ => return Err(OperationError::WrongTypeError),
        }
        return Ok(listsize);
    }

    pub fn pop(&mut self, right: bool) -> Result<Option<Vec<u8>>, OperationError> {
        let el;
        let mut clear;
        match self {
            &mut Value::Nil => {
                return Ok(None);
            },
            &mut Value::List(ref mut list) => {
                if right {
                    el = list.pop_back();
                } else {
                    el = list.pop_front();
                }
                clear = list.len() == 0;
            }
            _ => return Err(OperationError::WrongTypeError),
        }
        if clear {
            *self = Value::Nil;
        }
        return Ok(el);
    }

    pub fn lindex(&self, _index: i64) -> Result<Option<&Vec<u8>>, OperationError> {
        return match self {
            &Value::List(ref list) => {
                let index;
                let len = list.len() as i64;
                if _index < 0 {
                    index = len + _index;
                } else {
                    index = _index;
                }
                if index < 0 || index >= len {
                    return Ok(None);
                }
                return Ok(list.iter().nth(index as usize));
            },
            _ => Err(OperationError::WrongTypeError),
        }
    }

    pub fn linsert(&mut self, before: bool, pivot: Vec<u8>, value: Vec<u8>) -> Result<Option<usize>, OperationError> {
        match self {
            &mut Value::List(ref mut list) => {
                let pos;
                match list.iter().position(|x| x == &pivot) {
                    Some(_pos) => {
                        if before {
                            pos = _pos;
                        } else {
                            pos = _pos + 1;
                        }
                    },
                    None => return Ok(None),
                }
                println!("pos {}", pos);
                let mut right = list.split_off(pos);
                list.push_back(value);
                list.append(&mut right);
                return Ok(Some(list.len()));
            },
            _ => return Err(OperationError::WrongTypeError),
        };
    }

    pub fn llen(&self) -> Result<usize, OperationError> {
        match self {
            &Value::List(ref list) => {
                return Ok(list.len());
            },
            _ => return Err(OperationError::WrongTypeError),
        };
    }
}

pub struct Database {
    data: HashMap<Vec<u8>, Value>,
}

impl Database {
    pub fn new() -> Database {
        return Database {
            data: HashMap::new(),
        };
    }

    pub fn get(&self, key: &Vec<u8>) -> Option<&Value> {
        return self.data.get(key);
    }

    pub fn get_mut(&mut self, key: &Vec<u8>) -> Option<&mut Value> {
        return self.data.get_mut(key);
    }

    pub fn remove(&mut self, key: &Vec<u8>) -> Option<Value> {
        return self.data.remove(key);
    }

    pub fn clear(&mut self) {
        return self.data.clear();
    }

    pub fn get_or_create(&mut self, key: &Vec<u8>) -> &mut Value {
        if self.data.contains_key(key) {
            return self.data.get_mut(key).unwrap();
        }
        let val = Value::Nil;
        self.data.insert(Vec::clone(key), val);
        return self.data.get_mut(key).unwrap();
    }
}
<commit_msg>Remove debug println<commit_after>use std::fmt;
use std::error::Error;
use std::collections::HashMap;
use std::collections::LinkedList;
use std::str::from_utf8;
use std::str::Utf8Error;
use std::num::ParseIntError;

pub enum Value {
    Nil,
    Integer(i64),
    Data(Vec<u8>),
    List(LinkedList<Vec<u8>>),
}

#[derive(Debug)]
pub enum OperationError {
    OverflowError,
    ValueError,
    WrongTypeError,
}

impl fmt::Display for OperationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.description().fmt(f)
    }
}

impl Error for OperationError {
    fn description(&self) -> &str {
        return "oops";
    }
}

impl From<Utf8Error> for OperationError {
    fn from(_: Utf8Error) -> OperationError { OperationError::ValueError }
}

impl From<ParseIntError> for OperationError {
    fn from(_: ParseIntError) -> OperationError { OperationError::ValueError }
}

impl Value {
    pub fn set(&mut self, value: Vec<u8>) -> Result<(), OperationError> {
        if value.len() < 32 { // ought to be enough!
            let try_utf8 = from_utf8(&*value);
            if try_utf8.is_ok() {
                let try_parse = try_utf8.unwrap().parse::<i64>();
                if try_parse.is_ok() {
                    *self = Value::Integer(try_parse.unwrap());
                    return Ok(());
                }
            }
        }
        *self = Value::Data(value);
        return Ok(());
    }

    pub fn append(&mut self, value: Vec<u8>) -> Result<usize, OperationError> {
        match self {
            &mut Value::Nil => {
                let len = value.len();
                *self = Value::Data(value);
                return Ok(len);
            },
            &mut Value::Data(ref mut data) => { data.extend(value); return Ok(data.len()); },
            &mut Value::Integer(i) => {
                let oldstr = format!("{}", i);
                let len = oldstr.len() + value.len();
                *self = Value::Data([oldstr.into_bytes(), value].concat());
                return Ok(len);
            },
            _ => return Err(OperationError::WrongTypeError),
        }
    }

    pub fn incr(&mut self, incr: i64) -> Result<i64, OperationError> {
        let mut newval:i64;
        match self {
            &mut Value::Nil => {
                newval = incr;
            },
            &mut Value::Integer(i) => {
                let tmp_newval = i.checked_add(incr);
                match tmp_newval {
                    Some(v) => newval = v,
                    None => return Err(OperationError::OverflowError),
                }
            },
            &mut Value::Data(ref data) => {
                if data.len() > 32 {
                    return Err(OperationError::OverflowError);
                }
                let res = try!(from_utf8(&data));
                let ival = try!(res.parse::<i64>());
                let tmp_newval = ival.checked_add(incr);
                match tmp_newval {
                    Some(v) => newval = v,
                    None => return Err(OperationError::OverflowError),
                }
            },
            _ => return Err(OperationError::WrongTypeError),
        }
        *self = Value::Integer(newval);
        return Ok(newval);
    }

    pub fn push(&mut self, el: Vec<u8>, right: bool) -> Result<usize, OperationError> {
        let listsize;
        match self {
            &mut Value::Nil => {
                let mut list = LinkedList::new();
                list.push_back(el);
                *self = Value::List(list);
                listsize = 1;
            },
            &mut Value::List(ref mut list) => {
                if right {
                    list.push_back(el);
                } else {
                    list.push_front(el);
                }
                listsize = list.len();
            }
            _ => return Err(OperationError::WrongTypeError),
        }
        return Ok(listsize);
    }

    pub fn pop(&mut self, right: bool) -> Result<Option<Vec<u8>>, OperationError> {
        let el;
        let mut clear;
        match self {
            &mut Value::Nil => {
                return Ok(None);
            },
            &mut Value::List(ref mut list) => {
                if right {
                    el = list.pop_back();
                } else {
                    el = list.pop_front();
                }
                clear = list.len() == 0;
            }
            _ => return Err(OperationError::WrongTypeError),
        }
        if clear {
            *self = Value::Nil;
        }
        return Ok(el);
    }

    pub fn lindex(&self, _index: i64) -> Result<Option<&Vec<u8>>, OperationError> {
        return match self {
            &Value::List(ref list) => {
                let index;
                let len = list.len() as i64;
                if _index < 0 {
                    index = len + _index;
                } else {
                    index = _index;
                }
                if index < 0 || index >= len {
                    return Ok(None);
                }
                return Ok(list.iter().nth(index as usize));
            },
            _ => Err(OperationError::WrongTypeError),
        }
    }

    pub fn linsert(&mut self, before: bool, pivot: Vec<u8>, value: Vec<u8>) -> Result<Option<usize>, OperationError> {
        match self {
            &mut Value::List(ref mut list) => {
                let pos;
                match list.iter().position(|x| x == &pivot) {
                    Some(_pos) => {
                        if before {
                            pos = _pos;
                        } else {
                            pos = _pos + 1;
                        }
                    },
                    None => return Ok(None),
                }
                let mut right = list.split_off(pos);
                list.push_back(value);
                list.append(&mut right);
                return Ok(Some(list.len()));
            },
            _ => return Err(OperationError::WrongTypeError),
        };
    }

    pub fn llen(&self) -> Result<usize, OperationError> {
        match self {
            &Value::List(ref list) => {
                return Ok(list.len());
            },
            _ => return Err(OperationError::WrongTypeError),
        };
    }
}

pub struct Database {
    data: HashMap<Vec<u8>, Value>,
}

impl Database {
    pub fn new() -> Database {
        return Database {
            data: HashMap::new(),
        };
    }

    pub fn get(&self, key: &Vec<u8>) -> Option<&Value> {
        return self.data.get(key);
    }

    pub fn get_mut(&mut self, key: &Vec<u8>) -> Option<&mut Value> {
        return self.data.get_mut(key);
    }

    pub fn remove(&mut self, key: &Vec<u8>) -> Option<Value> {
        return self.data.remove(key);
    }

    pub fn clear(&mut self) {
        return self.data.clear();
    }

    pub fn get_or_create(&mut self, key: &Vec<u8>) -> &mut Value {
        if self.data.contains_key(key) {
            return self.data.get_mut(key).unwrap();
        }
        let val = Value::Nil;
        self.data.insert(Vec::clone(key), val);
        return self.data.get_mut(key).unwrap();
    }
}
<|endoftext|>


<commit_before><commit_msg>Hacking up a simple "console<commit_after>// Tifflin OS - simple_console
// - By John Hodge (thePowersGang)
//
// Simplistic console, used as a quick test case (fullscreen window)

extern crate tifflin_syscalls;

fn main() {
	let window = ::tifflin_syscalls::gui::new_window("Console").unwrap();
	window.maximise();
	window.fill_rect(0,0, !0,!0, 0x0);
	window.show();

	loop {
		// Bind to receive events relating to the window
		window.bind_event(1);
		match ::tifflin_syscalls::wait_event()
		{
		0 => {
			// Kernel event
			},
		1 => {
			// Main window event
			},
		}
	}
}

<|endoftext|>


<commit_before><commit_msg>Test(basic_dedup): add dedup test<commit_after><|endoftext|>


<commit_before>#![cfg_attr(all(feature="serde_type"), feature(proc_macro))]

extern crate iron;
extern crate router;
extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;

use iron::prelude::*;
use iron::{AfterMiddleware, status};
use iron::headers::{ContentEncoding, Encoding};
use router::Router;
use hbs::{Template, HandlebarsEngine, DirectorySource, MemorySource};
use hbs::handlebars::{Handlebars, RenderContext, RenderError, Helper};

use flate2::Compression;
use flate2::write::GzEncoder;

mod data {
    use hbs::handlebars::to_json;
    use serde_json::value::{Value, Map};

    #[derive(Serialize, Debug)]
    pub struct Team {
        name: String,
        pts: u16,
    }

    pub fn make_data() -> Map<String, Value> {
        let mut data = Map::new();

        data.insert("year".to_string(), to_json(&"2015".to_owned()));

        let teams = vec![Team {
                             name: "Jiangsu Sainty".to_string(),
                             pts: 43u16,
                         },
                         Team {
                             name: "Beijing Guoan".to_string(),
                             pts: 27u16,
                         },
                         Team {
                             name: "Guangzhou Evergrand".to_string(),
                             pts: 22u16,
                         },
                         Team {
                             name: "Shandong Luneng".to_string(),
                             pts: 12u16,
                         }];

        data.insert("teams".to_string(), to_json(&teams));
        data.insert("engine".to_string(), to_json(&"serde_json".to_owned()));
        data
    }
}

use data::*;

/// the handlers
fn index(_: &mut Request) -> IronResult<Response> {
    let mut resp = Response::new();
    let data = make_data();
    resp.set_mut(Template::new("some/path/hello", data)).set_mut(status::Ok);
    Ok(resp)
}

fn memory(_: &mut Request) -> IronResult<Response> {
    let mut resp = Response::new();
    let data = make_data();
    resp.set_mut(Template::new("memory", data)).set_mut(status::Ok);
    Ok(resp)
}

fn temp(_: &mut Request) -> IronResult<Response> {
    let mut resp = Response::new();
    let data = make_data();
    resp.set_mut(Template::with(include_str!("templates/some/path/hello.hbs"), data))
        .set_mut(status::Ok);
    Ok(resp)
}

fn plain(_: &mut Request) -> IronResult<Response> {
    Ok(Response::with((status::Ok, "It works")))
}

// an example compression middleware
pub struct GzMiddleware;

impl AfterMiddleware for GzMiddleware {
    fn after(&self, _: &mut Request, mut resp: Response) -> IronResult<Response> {

        let compressed_bytes = resp.body.as_mut().map(|mut b| {
            let mut encoder = GzEncoder::new(Vec::new(), Compression::Best);
            {
                let _ = b.write_body(&mut encoder);
            }
            encoder.finish().unwrap()
        });

        if let Some(b) = compressed_bytes {
            resp.headers.set(ContentEncoding(vec![Encoding::Gzip]));
            resp.set_mut(b);
        }

        Ok(resp)
    }
}

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

    let mut hbse = HandlebarsEngine::new();

    // add a directory source, all files with .hbs suffix will be loaded as template
    hbse.add(Box::new(DirectorySource::new("./examples/templates/", ".hbs")));

    let mem_templates = btreemap! {
        "memory".to_owned() => include_str!("templates/some/path/hello.hbs").to_owned()
    };
    // add a memory based source
    hbse.add(Box::new(MemorySource(mem_templates)));

    // load templates from all registered sources
    if let Err(r) = hbse.reload() {
        panic!("{}", r);
    }

    hbse.handlebars_mut().register_helper("some_helper",
                                          Box::new(|_: &Helper,
                                                    _: &Handlebars,
                                                    _: &mut RenderContext|
                                                    -> Result<(), RenderError> {
                                                       Ok(())
                                                   }));

    let mut router = Router::new();
    router.get("/", index, "index")
        .get("/mem", memory, "memory")
        .get("/temp", temp, "temp")
        .get("/plain", plain, "plain");
    let mut chain = Chain::new(router);
    chain.link_after(hbse);
    chain.link_after(GzMiddleware);
    println!("Server running at http://localhost:3000/");
    Iron::new(chain).http("localhost:3000").unwrap();
}
<commit_msg>(fix) remove unneed mut in example<commit_after>#![cfg_attr(all(feature="serde_type"), feature(proc_macro))]

extern crate iron;
extern crate router;
extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;

use iron::prelude::*;
use iron::{AfterMiddleware, status};
use iron::headers::{ContentEncoding, Encoding};
use router::Router;
use hbs::{Template, HandlebarsEngine, DirectorySource, MemorySource};
use hbs::handlebars::{Handlebars, RenderContext, RenderError, Helper};

use flate2::Compression;
use flate2::write::GzEncoder;

mod data {
    use hbs::handlebars::to_json;
    use serde_json::value::{Value, Map};

    #[derive(Serialize, Debug)]
    pub struct Team {
        name: String,
        pts: u16,
    }

    pub fn make_data() -> Map<String, Value> {
        let mut data = Map::new();

        data.insert("year".to_string(), to_json(&"2015".to_owned()));

        let teams = vec![Team {
                             name: "Jiangsu Sainty".to_string(),
                             pts: 43u16,
                         },
                         Team {
                             name: "Beijing Guoan".to_string(),
                             pts: 27u16,
                         },
                         Team {
                             name: "Guangzhou Evergrand".to_string(),
                             pts: 22u16,
                         },
                         Team {
                             name: "Shandong Luneng".to_string(),
                             pts: 12u16,
                         }];

        data.insert("teams".to_string(), to_json(&teams));
        data.insert("engine".to_string(), to_json(&"serde_json".to_owned()));
        data
    }
}

use data::*;

/// the handlers
fn index(_: &mut Request) -> IronResult<Response> {
    let mut resp = Response::new();
    let data = make_data();
    resp.set_mut(Template::new("some/path/hello", data)).set_mut(status::Ok);
    Ok(resp)
}

fn memory(_: &mut Request) -> IronResult<Response> {
    let mut resp = Response::new();
    let data = make_data();
    resp.set_mut(Template::new("memory", data)).set_mut(status::Ok);
    Ok(resp)
}

fn temp(_: &mut Request) -> IronResult<Response> {
    let mut resp = Response::new();
    let data = make_data();
    resp.set_mut(Template::with(include_str!("templates/some/path/hello.hbs"), data))
        .set_mut(status::Ok);
    Ok(resp)
}

fn plain(_: &mut Request) -> IronResult<Response> {
    Ok(Response::with((status::Ok, "It works")))
}

// an example compression middleware
pub struct GzMiddleware;

impl AfterMiddleware for GzMiddleware {
    fn after(&self, _: &mut Request, mut resp: Response) -> IronResult<Response> {

        let compressed_bytes = resp.body.as_mut().map(|b| {
            let mut encoder = GzEncoder::new(Vec::new(), Compression::Best);
            {
                let _ = b.write_body(&mut encoder);
            }
            encoder.finish().unwrap()
        });

        if let Some(b) = compressed_bytes {
            resp.headers.set(ContentEncoding(vec![Encoding::Gzip]));
            resp.set_mut(b);
        }

        Ok(resp)
    }
}

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

    let mut hbse = HandlebarsEngine::new();

    // add a directory source, all files with .hbs suffix will be loaded as template
    hbse.add(Box::new(DirectorySource::new("./examples/templates/", ".hbs")));

    let mem_templates = btreemap! {
        "memory".to_owned() => include_str!("templates/some/path/hello.hbs").to_owned()
    };
    // add a memory based source
    hbse.add(Box::new(MemorySource(mem_templates)));

    // load templates from all registered sources
    if let Err(r) = hbse.reload() {
        panic!("{}", r);
    }

    hbse.handlebars_mut().register_helper("some_helper",
                                          Box::new(|_: &Helper,
                                                    _: &Handlebars,
                                                    _: &mut RenderContext|
                                                    -> Result<(), RenderError> {
                                                       Ok(())
                                                   }));

    let mut router = Router::new();
    router.get("/", index, "index")
        .get("/mem", memory, "memory")
        .get("/temp", temp, "temp")
        .get("/plain", plain, "plain");
    let mut chain = Chain::new(router);
    chain.link_after(hbse);
    chain.link_after(GzMiddleware);
    println!("Server running at http://localhost:3000/");
    Iron::new(chain).http("localhost:3000").unwrap();
}
<|endoftext|>


<commit_before><commit_msg>add examples<commit_after>extern crate coroutine;

use coroutine::coroutine::Environment;

fn main() {
    // Initialize a new environment
    let mut env = Environment::new();

    // Spawn a new coroutine
    let mut coro = env.spawn(move|env| {
        // env is the environment that spawn this coroutine

        println!("Hello in coroutine!");

        // Yield back to it's parent
        env.yield_now();

        println!("We are back!!");

        let subcoro = env.spawn(move|_| {
            println!("Hello inside");
        });

        // Destroy the coroutine and try to resue its stack
        // It is optional but recommended
        env.recycle(subcoro);

        println!("Good bye");
    });

    println!("We are here!");

    // Resume the coroutine
    env.resume(&mut coro);

    println!("Back to main.");
    env.recycle(coro);
}
<|endoftext|>


<commit_before><commit_msg>added date and time to post<commit_after><|endoftext|>


<commit_before><commit_msg>[add] test code<commit_after>use std::io::fs::File;

pub const NAME: i8 = 0;
pub const STATUS: i8 = 1;
pub const CURRENT: i8 = 3;
pub const MAXIMUM: i8 = 4;
pub const SCORE: i8 = 6;

struct Database {
    name: String,
    status: String,
    current: i32,
    maximum: i32,
    score: i8
}

fn tokenize( data: & str, delimeters: & str ) -> Vec< String >  {
    let mut token: Vec< String > = Vec::new();
    let mut prev = 0us;
    let mut next = 0us;
    let mut comma = false;

    for i in data.chars() {
        comma = match i {
            '"' => !comma,
            _ => comma
        };
        if !comma {
            for j in delimeters.chars() {
                if i == j {
                    if next - prev >= 1us {
                        token.push( data.slice_chars( prev, next ).to_string() );
                        prev = next + 1us;
                        break;
                    }
                    prev = next + 1us;
                }
            }
        }
        next += 1us;
    }
    // add last token
    if next - prev >= 1us {
        token.push( data.slice_chars( prev, next ).to_string() );
    }
    return token;
}

fn print_item( item: & Database ) {
    println!( "<add>: '{}', status: {}, progress: {} / {}, score: {}",
              item.name, item.status, item.current, item.maximum, item.score );
}

fn main() {
    let path = Path::new( "anime-list" );
    let display = path.display();
    let mut file = match File::open( &path ) {
        Ok( file ) => file,
        Err( io_error ) => {
            panic!( io_error.desc );
        }
    };
    let mut anime: Vec< Database > = Vec::new();
    match file.read_to_string() {
        Ok( string ) => {
            let token = tokenize( string.as_slice(), " /\n" );
            let mut item = Database {
                name: "".to_string(),
                status: "plan".to_string(),
                current: 0,
                maximum: 0,
                score: 0
            };
            let mut counter = NAME;
            for element in token.iter() {
                match element.slice_chars( 0, 1 ) {
                    "\"" => {
                        counter = NAME;
                        if item.name.len() > 0 {
                            print_item( &item );
                            anime.push( Database {
                                name: item.name.to_string(),
                                status: item.status.to_string(),
                                current: item.current,
                                maximum: item.maximum,
                                score: item.score
                            });
                        }
                    },
                    _ => {
                        counter += 1;
                    }
                }
                match counter {
                    NAME => item.name  = element.slice_chars( 1, element.len() - 1 ).to_string(),
                    STATUS => item.status = element.to_string(),
                    CURRENT => item.current = element.parse::<i32>().unwrap(),
                    MAXIMUM => item.maximum = element.parse::<i32>().unwrap(),
                    SCORE => item.score = element.parse::<i8>().unwrap(),
                    _ => {}
                };
            }
        },
        Err( why ) => panic!( "couldn't read '{}': {}", display, why.desc )
    };
}<|endoftext|>


<commit_before><commit_msg>Added /version<commit_after><|endoftext|>


<commit_before>// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk.  If not, see <http://www.gnu.org/licenses/>.

/*!

Bindings and wrappers for __GTK+__, __GLib__ and __Cairo__.

The various parts of __rgtk__ can be found in the submodules __gtk__, __gdk__, __glib__ and __cairo__.

Trait reexports
===============

For your conveniance the various traits of `rgtk` are reexported in the `rgtk::*`
namespace as `{Gtk/Gdk/Glib/Cairo}{trait_name}Trait` so you can just use...

```Rust
extern mod rgtk;
use rgtk::*;
```

...to easily access all the traits methods:

```Rust
let button = gtk::Button:new(); // trait gtk::Button reexported as GtkButtonTrait,
                                // its trait methods can be accessed here.
```
*/

#![crate_name = "rgtk"]
#![crate_type = "lib"]
#![crate_type = "rlib"]
#![allow(dead_code)] // TODO: drop this
#![allow(raw_pointer_derive)]

#![feature(unsafe_destructor)]
#![feature(core)]
#![feature(collections)]
#![feature(std_misc)]
#![feature(hash)]
#![feature(libc)]
#![feature(rustc_private)]

extern crate libc;
#[macro_use] extern crate rustc_bitflags;

pub use glib::traits::Connect;
pub use gtk::widgets::GValuePublic;

pub use gtk::BoxTrait as GtkBoxTrait;
pub use gtk::ActionableTrait as GtkActionableTrait;
pub use gtk::AppChooserTrait as GtkAppChooserTrait;
pub use gtk::BinTrait as GtkBinTrait;
pub use gtk::ButtonTrait as GtkButtonTrait;
pub use gtk::CellEditableTrait as GtkCellEditableTrait;
pub use gtk::CellLayoutTrait as GtkCellLayoutTrait;
pub use gtk::CellRendererTrait as GtkCellRendererTrait;
pub use gtk::CheckMenuItemTrait as GtkCheckMenuItemTrait;
pub use gtk::ColorChooserTrait as GtkColorChooserTrait;
pub use gtk::ComboBoxTrait as GtkComboBoxTrait;
pub use gtk::ContainerTrait as GtkContainerTrait;
pub use gtk::DialogTrait as GtkDialogTrait;
pub use gtk::EditableTrait as GtkEditableTrait;
pub use gtk::EntryTrait as GtkEntryTrait;
pub use gtk::FileChooserTrait as GtkFileChooserTrait;
pub use gtk::FontChooserTrait as GtkFontChooserTrait;
pub use gtk::FrameTrait as GtkFrameTrait;
pub use gtk::GObjectTrait as GObjectTrait;
pub use gtk::LabelTrait as GtkLabelTrait;
pub use gtk::MenuItemTrait as GtkMenuItemTrait;
pub use gtk::MenuShellTrait as GtkMenuShellTrait;
pub use gtk::MiscTrait as GtkMiscTrait;
pub use gtk::OrientableTrait as GtkOrientableTrait;
pub use gtk::RangeTrait as GtkRangeTrait;
pub use gtk::RecentChooserTrait as GtkRecentChooserTrait;
pub use gtk::ScaleButtonTrait as GtkScaleButtonTrait;
pub use gtk::ScrollableTrait as GtkScrollableTrait;
pub use gtk::ScrolledWindowTrait as GtkScrolledWindowTrait;
pub use gtk::TextBufferTrait as GtkTextBufferTrait;
pub use gtk::ToggleButtonTrait as GtkToggleButtonTrait;
pub use gtk::ToggleToolButtonTrait as GtkToggleToolButtonTrait;
pub use gtk::ToolButtonTrait as GtkToolButtonTrait;
pub use gtk::ToolItemTrait as GtkToolItemTrait;
pub use gtk::ToolShellTrait as GtkToolShellTrait;
pub use gtk::WidgetTrait as GtkWidgetTrait;
pub use gtk::WindowTrait as GtkWindowTrait;

#[doc(hidden)]
#[cfg(target_os="macos")]
mod platform {
    #[link(name = "glib-2.0")]
    #[link(name = "gtk-3.0")]
    #[link(name = "gio-2.0")]
    #[link(name = "gobject-2.0")]
    #[link(name = "gdk-3.0")]
    #[link(name = "rgtk_glue", kind = "static")]
    extern{}
}

#[doc(hidden)]
#[cfg(target_os="linux")]
mod platform {
    #[link(name = "glib-2.0")]
    #[link(name = "gtk-3")]
    #[link(name = "gio-2.0")]
    #[link(name = "gobject-2.0")]
    #[link(name = "gdk-3")]
    #[link(name = "rgtk_glue", kind = "static")]
    extern{}
}

#[doc(hidden)]
#[cfg(target_os="windows")]
mod platform {
    #[link(name = "glib-2.0")]
    #[link(name = "gtk-3")]
    #[link(name = "gio-2.0")]
    #[link(name = "gobject-2.0")]
    #[link(name = "gdk-3")]
    #[link(name = "rgtk_glue", kind = "static")]
    extern{}
}

pub mod gtk;
pub mod cairo;
pub mod gdk;
pub mod glib;
<commit_msg>Remove obsolete linking instructions<commit_after>// This file is part of rgtk.
//
// rgtk is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with rgtk.  If not, see <http://www.gnu.org/licenses/>.

/*!

Bindings and wrappers for __GTK+__, __GLib__ and __Cairo__.

The various parts of __rgtk__ can be found in the submodules __gtk__, __gdk__, __glib__ and __cairo__.

Trait reexports
===============

For your conveniance the various traits of `rgtk` are reexported in the `rgtk::*`
namespace as `{Gtk/Gdk/Glib/Cairo}{trait_name}Trait` so you can just use...

```Rust
extern mod rgtk;
use rgtk::*;
```

...to easily access all the traits methods:

```Rust
let button = gtk::Button:new(); // trait gtk::Button reexported as GtkButtonTrait,
                                // its trait methods can be accessed here.
```
*/

#![crate_name = "rgtk"]
#![crate_type = "lib"]
#![crate_type = "rlib"]
#![allow(dead_code)] // TODO: drop this
#![allow(raw_pointer_derive)]

#![feature(unsafe_destructor)]
#![feature(core)]
#![feature(collections)]
#![feature(std_misc)]
#![feature(hash)]
#![feature(libc)]
#![feature(rustc_private)]

extern crate libc;
#[macro_use] extern crate rustc_bitflags;

pub use glib::traits::Connect;
pub use gtk::widgets::GValuePublic;

pub use gtk::BoxTrait as GtkBoxTrait;
pub use gtk::ActionableTrait as GtkActionableTrait;
pub use gtk::AppChooserTrait as GtkAppChooserTrait;
pub use gtk::BinTrait as GtkBinTrait;
pub use gtk::ButtonTrait as GtkButtonTrait;
pub use gtk::CellEditableTrait as GtkCellEditableTrait;
pub use gtk::CellLayoutTrait as GtkCellLayoutTrait;
pub use gtk::CellRendererTrait as GtkCellRendererTrait;
pub use gtk::CheckMenuItemTrait as GtkCheckMenuItemTrait;
pub use gtk::ColorChooserTrait as GtkColorChooserTrait;
pub use gtk::ComboBoxTrait as GtkComboBoxTrait;
pub use gtk::ContainerTrait as GtkContainerTrait;
pub use gtk::DialogTrait as GtkDialogTrait;
pub use gtk::EditableTrait as GtkEditableTrait;
pub use gtk::EntryTrait as GtkEntryTrait;
pub use gtk::FileChooserTrait as GtkFileChooserTrait;
pub use gtk::FontChooserTrait as GtkFontChooserTrait;
pub use gtk::FrameTrait as GtkFrameTrait;
pub use gtk::GObjectTrait as GObjectTrait;
pub use gtk::LabelTrait as GtkLabelTrait;
pub use gtk::MenuItemTrait as GtkMenuItemTrait;
pub use gtk::MenuShellTrait as GtkMenuShellTrait;
pub use gtk::MiscTrait as GtkMiscTrait;
pub use gtk::OrientableTrait as GtkOrientableTrait;
pub use gtk::RangeTrait as GtkRangeTrait;
pub use gtk::RecentChooserTrait as GtkRecentChooserTrait;
pub use gtk::ScaleButtonTrait as GtkScaleButtonTrait;
pub use gtk::ScrollableTrait as GtkScrollableTrait;
pub use gtk::ScrolledWindowTrait as GtkScrolledWindowTrait;
pub use gtk::TextBufferTrait as GtkTextBufferTrait;
pub use gtk::ToggleButtonTrait as GtkToggleButtonTrait;
pub use gtk::ToggleToolButtonTrait as GtkToggleToolButtonTrait;
pub use gtk::ToolButtonTrait as GtkToolButtonTrait;
pub use gtk::ToolItemTrait as GtkToolItemTrait;
pub use gtk::ToolShellTrait as GtkToolShellTrait;
pub use gtk::WidgetTrait as GtkWidgetTrait;
pub use gtk::WindowTrait as GtkWindowTrait;

pub mod gtk;
pub mod cairo;
pub mod gdk;
pub mod glib;
<|endoftext|>


<commit_before><commit_msg>Improve solution to problem_9<commit_after><|endoftext|>


<commit_before><commit_msg>Create file for vec3<commit_after>
fn main() {

}<|endoftext|>


<commit_before>#![allow(missing_docs)]

use std::sync::Arc;

use {Wake, Tokens, IntoFuture};

mod channel;
mod iter;
pub use self::channel::{channel, Sender, Receiver};
pub use self::iter::{iter, IterStream};

mod and_then;
mod collect;
mod filter;
mod filter_map;
mod flat_map;
mod fold;
mod for_each;
mod future;
mod map;
mod map_err;
mod or_else;
mod skip_while;
mod then;
pub use self::and_then::AndThen;
pub use self::collect::Collect;
pub use self::filter::Filter;
pub use self::filter_map::FilterMap;
pub use self::flat_map::FlatMap;
pub use self::fold::Fold;
pub use self::for_each::ForEach;
pub use self::future::StreamFuture;
pub use self::map::Map;
pub use self::map_err::MapErr;
pub use self::or_else::OrElse;
pub use self::skip_while::SkipWhile;
pub use self::then::Then;

mod impls;

pub type StreamResult<T, E> = Result<Option<T>, E>;

pub trait Stream: Send + 'static {
    type Item: Send + 'static;
    type Error: Send + 'static;

    fn poll(&mut self, tokens: &Tokens)
            -> Option<StreamResult<Self::Item, Self::Error>>;

    fn schedule(&mut self, wake: Arc<Wake>);

    fn boxed(self) -> Box<Stream<Item=Self::Item, Error=Self::Error>>
        where Self: Sized
    {
        Box::new(self)
    }

    fn into_future(self) -> StreamFuture<Self>
        where Self: Sized
    {
        future::new(self)
    }

    fn map<U, F>(self, f: F) -> Map<Self, F>
        where F: FnMut(Self::Item) -> U + Send + 'static,
              U: Send + 'static,
              Self: Sized
    {
        map::new(self, f)
    }

    fn map_err<U, F>(self, f: F) -> MapErr<Self, F>
        where F: FnMut(Self::Error) -> U + Send + 'static,
              U: Send + 'static,
              Self: Sized
    {
        map_err::new(self, f)
    }

    fn filter<F>(self, f: F) -> Filter<Self, F>
        where F: FnMut(&Self::Item) -> bool + Send + 'static,
              Self: Sized
    {
        filter::new(self, f)
    }

    fn filter_map<F, B>(self, f: F) -> FilterMap<Self, F>
        where F: FnMut(Self::Item) -> Option<B> + Send + 'static,
              Self: Sized
    {
        filter_map::new(self, f)
    }

    fn then<F, U>(self, f: F) -> Then<Self, F, U>
        where F: FnMut(Result<Self::Item, Self::Error>) -> U + Send + 'static,
              U: IntoFuture,
              Self: Sized
    {
        then::new(self, f)
    }

    fn and_then<F, U>(self, f: F) -> AndThen<Self, F, U>
        where F: FnMut(Self::Item) -> U + Send + 'static,
              U: IntoFuture<Error=Self::Error>,
              Self: Sized
    {
        and_then::new(self, f)
    }

    fn or_else<F, U>(self, f: F) -> OrElse<Self, F, U>
        where F: FnMut(Self::Error) -> U + Send + 'static,
              U: IntoFuture<Item=Self::Item>,
              Self: Sized
    {
        or_else::new(self, f)
    }

    fn collect(self) -> Collect<Self> where Self: Sized {
        collect::new(self)
    }

    fn fold<F, T>(self, init: T, f: F) -> Fold<Self, F, T>
        where F: FnMut(T, Self::Item) -> T + Send + 'static,
              T: Send + 'static,
              Self: Sized
    {
        fold::new(self, f, init)
    }

    // fn flatten(self) -> Flatten<Self>
    //     where Self::Item: IntoFuture,
    //           <<Self as Stream>::Item as IntoFuture>::Error:
    //                 From<<Self as Stream>::Error>,
    //           Self: Sized
    // {
    //     Flatten {
    //         stream: self,
    //         future: None,
    //     }
    // }

    fn flat_map(self) -> FlatMap<Self>
        where Self::Item: Stream,
              <Self::Item as Stream>::Error: From<Self::Error>,
              Self: Sized
    {
        flat_map::new(self)
    }

    // TODO: should this closure return a Result?
    fn skip_while<P>(self, pred: P) -> SkipWhile<Self, P>
        where P: FnMut(&Self::Item) -> Result<bool, Self::Error> + Send + 'static,
              Self: Sized,
    {
        skip_while::new(self, pred)
    }

    // TODO: should this closure return a result?
    fn for_each<F>(self, f: F) -> ForEach<Self, F>
        where F: FnMut(Self::Item) -> Result<(), Self::Error> + Send + 'static,
              Self: Sized,
    {
        for_each::new(self, f)
    }
}
<commit_msg>Start adding documentation to Stream<commit_after>#![allow(missing_docs)]

use std::sync::Arc;

use {Wake, Tokens, IntoFuture};

mod channel;
mod iter;
pub use self::channel::{channel, Sender, Receiver};
pub use self::iter::{iter, IterStream};

mod and_then;
mod collect;
mod filter;
mod filter_map;
mod flat_map;
mod fold;
mod for_each;
mod future;
mod map;
mod map_err;
mod or_else;
mod skip_while;
mod then;
pub use self::and_then::AndThen;
pub use self::collect::Collect;
pub use self::filter::Filter;
pub use self::filter_map::FilterMap;
pub use self::flat_map::FlatMap;
pub use self::fold::Fold;
pub use self::for_each::ForEach;
pub use self::future::StreamFuture;
pub use self::map::Map;
pub use self::map_err::MapErr;
pub use self::or_else::OrElse;
pub use self::skip_while::SkipWhile;
pub use self::then::Then;

mod impls;

/// A simple typedef around the result that a stream can produce.
///
/// The `Ok` variant can contain a successful result of the stream, either the
/// next element or a signal that the strem has ended. The `Err` variant
/// contains the error that a stream encounterd, if any.
pub type StreamResult<T, E> = Result<Option<T>, E>;

/// A stream of values, not all of which have been produced yet.
///
/// `Stream` is a trait to represent any source of sequential events or items
/// which acts like an iterator but may block over time. Like `Future` the
/// methods of `Stream` never block and it is thus suitable for programming in
/// an asynchronous fashion. This trait is very similar to the `Iterator` trait
/// in the standard library where `Some` is used to signal elements of the
/// stream and `None` is used to indicate that the stream is finished.
///
/// Like futures a stream has basic combinators to transform the stream, perform
/// more work on each item, etc.
///
/// # Basic methods
///
/// Like futures, a `Stream` has two core methods which drive processing of data
/// and notifications of when new data might be ready. The `poll` method checks
/// the status of a stream and the `schedule` method is used to receive
/// notifications for when it may be ready to call `poll` again.
///
/// Also like future, a stream has an associated error type to represent that an
/// element of the computation failed for some reason. Errors, however, do not
/// signal the end of the stream.
///
/// # Streams as Futures
///
/// Any instance of `Stream` can also be viewed as a `Future` where the resolved
/// value is the next item in the stream along with the rest of the stream. The
/// `into_future` adaptor can be used here to convert any stream into a future
/// for use with other future methods like `join` and `select`.
// TODO: more here
pub trait Stream: Send + 'static {

    /// The type of item this stream will yield on success.
    type Item: Send + 'static;

    /// The type of error this stream may generate.
    type Error: Send + 'static;

    fn poll(&mut self, tokens: &Tokens)
            -> Option<StreamResult<Self::Item, Self::Error>>;

    fn schedule(&mut self, wake: Arc<Wake>);

    fn boxed(self) -> Box<Stream<Item=Self::Item, Error=Self::Error>>
        where Self: Sized
    {
        Box::new(self)
    }

    fn into_future(self) -> StreamFuture<Self>
        where Self: Sized
    {
        future::new(self)
    }

    fn map<U, F>(self, f: F) -> Map<Self, F>
        where F: FnMut(Self::Item) -> U + Send + 'static,
              U: Send + 'static,
              Self: Sized
    {
        map::new(self, f)
    }

    fn map_err<U, F>(self, f: F) -> MapErr<Self, F>
        where F: FnMut(Self::Error) -> U + Send + 'static,
              U: Send + 'static,
              Self: Sized
    {
        map_err::new(self, f)
    }

    fn filter<F>(self, f: F) -> Filter<Self, F>
        where F: FnMut(&Self::Item) -> bool + Send + 'static,
              Self: Sized
    {
        filter::new(self, f)
    }

    fn filter_map<F, B>(self, f: F) -> FilterMap<Self, F>
        where F: FnMut(Self::Item) -> Option<B> + Send + 'static,
              Self: Sized
    {
        filter_map::new(self, f)
    }

    fn then<F, U>(self, f: F) -> Then<Self, F, U>
        where F: FnMut(Result<Self::Item, Self::Error>) -> U + Send + 'static,
              U: IntoFuture,
              Self: Sized
    {
        then::new(self, f)
    }

    fn and_then<F, U>(self, f: F) -> AndThen<Self, F, U>
        where F: FnMut(Self::Item) -> U + Send + 'static,
              U: IntoFuture<Error=Self::Error>,
              Self: Sized
    {
        and_then::new(self, f)
    }

    fn or_else<F, U>(self, f: F) -> OrElse<Self, F, U>
        where F: FnMut(Self::Error) -> U + Send + 'static,
              U: IntoFuture<Item=Self::Item>,
              Self: Sized
    {
        or_else::new(self, f)
    }

    fn collect(self) -> Collect<Self> where Self: Sized {
        collect::new(self)
    }

    fn fold<F, T>(self, init: T, f: F) -> Fold<Self, F, T>
        where F: FnMut(T, Self::Item) -> T + Send + 'static,
              T: Send + 'static,
              Self: Sized
    {
        fold::new(self, f, init)
    }

    // fn flatten(self) -> Flatten<Self>
    //     where Self::Item: IntoFuture,
    //           <<Self as Stream>::Item as IntoFuture>::Error:
    //                 From<<Self as Stream>::Error>,
    //           Self: Sized
    // {
    //     Flatten {
    //         stream: self,
    //         future: None,
    //     }
    // }

    fn flat_map(self) -> FlatMap<Self>
        where Self::Item: Stream,
              <Self::Item as Stream>::Error: From<Self::Error>,
              Self: Sized
    {
        flat_map::new(self)
    }

    // TODO: should this closure return a Result?
    fn skip_while<P>(self, pred: P) -> SkipWhile<Self, P>
        where P: FnMut(&Self::Item) -> Result<bool, Self::Error> + Send + 'static,
              Self: Sized,
    {
        skip_while::new(self, pred)
    }

    // TODO: should this closure return a result?
    fn for_each<F>(self, f: F) -> ForEach<Self, F>
        where F: FnMut(Self::Item) -> Result<(), Self::Error> + Send + 'static,
              Self: Sized,
    {
        for_each::new(self, f)
    }
}
<|endoftext|>


<commit_before>use Renderable;
use context::Context;
use filters;
use error::Result;

pub struct Template {
    pub elements: Vec<Box<Renderable>>,
}

impl Renderable for Template {
    fn render(&self, context: &mut Context) -> Result<Option<String>> {

        context.maybe_add_filter("abs", Box::new(filters::abs));
        context.maybe_add_filter("append", Box::new(filters::append));
        context.maybe_add_filter("capitalize", Box::new(filters::capitalize));
        context.maybe_add_filter("ceil", Box::new(filters::ceil));
        context.maybe_add_filter("compact", Box::new(filters::compact));
        context.maybe_add_filter("concat", Box::new(filters::concat));
        context.maybe_add_filter("date", Box::new(filters::date));
        context.maybe_add_filter("default", Box::new(filters::default));
        context.maybe_add_filter("divided_by", Box::new(filters::divided_by));
        context.maybe_add_filter("downcase", Box::new(filters::downcase));
        context.maybe_add_filter("escape", Box::new(filters::escape));
        context.maybe_add_filter("escape_once", Box::new(filters::escape_once));
        context.maybe_add_filter("first", Box::new(filters::first));
        context.maybe_add_filter("floor", Box::new(filters::floor));
        context.maybe_add_filter("join", Box::new(filters::join));
        context.maybe_add_filter("last", Box::new(filters::last));
        context.maybe_add_filter("lstrip", Box::new(filters::lstrip));
        context.maybe_add_filter("map", Box::new(filters::map));
        context.maybe_add_filter("minus", Box::new(filters::minus));
        context.maybe_add_filter("modulo", Box::new(filters::modulo));
        context.maybe_add_filter("newline_to_br", Box::new(filters::newline_to_br));
        context.maybe_add_filter("plus", Box::new(filters::plus));
        context.maybe_add_filter("prepend", Box::new(filters::prepend));
        context.maybe_add_filter("remove", Box::new(filters::remove));
        context.maybe_add_filter("remove_first", Box::new(filters::remove_first));
        context.maybe_add_filter("replace", Box::new(filters::replace));
        context.maybe_add_filter("replace_first", Box::new(filters::replace_first));
        context.maybe_add_filter("reverse", Box::new(filters::reverse));
        context.maybe_add_filter("round", Box::new(filters::round));
        context.maybe_add_filter("rstrip", Box::new(filters::rstrip));
        context.maybe_add_filter("size", Box::new(filters::size));
        context.maybe_add_filter("slice", Box::new(filters::slice));
        context.maybe_add_filter("sort", Box::new(filters::sort));
        context.maybe_add_filter("sort_natural", Box::new(filters::sort_natural));
        context.maybe_add_filter("split", Box::new(filters::split));
        context.maybe_add_filter("strip", Box::new(filters::strip));
        context.maybe_add_filter("strip_html", Box::new(filters::strip_html));
        context.maybe_add_filter("strip_newlines", Box::new(filters::strip_newlines));
        context.maybe_add_filter("times", Box::new(filters::times));
        context.maybe_add_filter("truncate", Box::new(filters::truncate));
        context.maybe_add_filter("truncatewords", Box::new(filters::truncatewords));
        context.maybe_add_filter("uniq", Box::new(filters::uniq));
        context.maybe_add_filter("upcase", Box::new(filters::upcase));
        context.maybe_add_filter("url_decode", Box::new(filters::url_decode));
        context.maybe_add_filter("url_encode", Box::new(filters::url_encode));

        #[cfg(feature = "extra-filters")]
        context.maybe_add_filter("pluralize", Box::new(filters::pluralize));
        #[cfg(feature = "extra-filters")]
        context.maybe_add_filter("date_in_tz", Box::new(filters::date_in_tz));

        let mut buf = String::new();
        for el in &self.elements {
            if let Some(ref x) = try!(el.render(context)) {
                buf = buf + x;
            }

            // Did the last element we processed set an interrupt? If so, we
            // need to abandon the rest of our child elements and just
            // return what we've got. This is usually in response to a
            // `break` or `continue` tag being rendered.
            if context.interrupted() {
                break;
            }
        }
        Ok(Some(buf))
    }
}

impl Template {
    pub fn new(elements: Vec<Box<Renderable>>) -> Template {
        Template { elements: elements }
    }
}
<commit_msg>refactor: More to workaround rustfmt bug<commit_after>use Renderable;
use context::Context;
use filters;
use error::Result;

pub struct Template {
    pub elements: Vec<Box<Renderable>>,
}

impl Renderable for Template {
    fn render(&self, context: &mut Context) -> Result<Option<String>> {

        maybe_add_default_filters(context);
        maybe_add_extra_filters(context);

        let mut buf = String::new();
        for el in &self.elements {
            if let Some(ref x) = try!(el.render(context)) {
                buf = buf + x;
            }

            // Did the last element we processed set an interrupt? If so, we
            // need to abandon the rest of our child elements and just
            // return what we've got. This is usually in response to a
            // `break` or `continue` tag being rendered.
            if context.interrupted() {
                break;
            }
        }
        Ok(Some(buf))
    }
}

impl Template {
    pub fn new(elements: Vec<Box<Renderable>>) -> Template {
        Template { elements: elements }
    }
}

fn maybe_add_default_filters(context: &mut Context) {
    context.maybe_add_filter("abs", Box::new(filters::abs));
    context.maybe_add_filter("append", Box::new(filters::append));
    context.maybe_add_filter("capitalize", Box::new(filters::capitalize));
    context.maybe_add_filter("ceil", Box::new(filters::ceil));
    context.maybe_add_filter("compact", Box::new(filters::compact));
    context.maybe_add_filter("concat", Box::new(filters::concat));
    context.maybe_add_filter("date", Box::new(filters::date));
    context.maybe_add_filter("default", Box::new(filters::default));
    context.maybe_add_filter("divided_by", Box::new(filters::divided_by));
    context.maybe_add_filter("downcase", Box::new(filters::downcase));
    context.maybe_add_filter("escape", Box::new(filters::escape));
    context.maybe_add_filter("escape_once", Box::new(filters::escape_once));
    context.maybe_add_filter("first", Box::new(filters::first));
    context.maybe_add_filter("floor", Box::new(filters::floor));
    context.maybe_add_filter("join", Box::new(filters::join));
    context.maybe_add_filter("last", Box::new(filters::last));
    context.maybe_add_filter("lstrip", Box::new(filters::lstrip));
    context.maybe_add_filter("map", Box::new(filters::map));
    context.maybe_add_filter("minus", Box::new(filters::minus));
    context.maybe_add_filter("modulo", Box::new(filters::modulo));
    context.maybe_add_filter("newline_to_br", Box::new(filters::newline_to_br));
    context.maybe_add_filter("plus", Box::new(filters::plus));
    context.maybe_add_filter("prepend", Box::new(filters::prepend));
    context.maybe_add_filter("remove", Box::new(filters::remove));
    context.maybe_add_filter("remove_first", Box::new(filters::remove_first));
    context.maybe_add_filter("replace", Box::new(filters::replace));
    context.maybe_add_filter("replace_first", Box::new(filters::replace_first));
    context.maybe_add_filter("reverse", Box::new(filters::reverse));
    context.maybe_add_filter("round", Box::new(filters::round));
    context.maybe_add_filter("rstrip", Box::new(filters::rstrip));
    context.maybe_add_filter("size", Box::new(filters::size));
    context.maybe_add_filter("slice", Box::new(filters::slice));
    context.maybe_add_filter("sort", Box::new(filters::sort));
    context.maybe_add_filter("sort_natural", Box::new(filters::sort_natural));
    context.maybe_add_filter("split", Box::new(filters::split));
    context.maybe_add_filter("strip", Box::new(filters::strip));
    context.maybe_add_filter("strip_html", Box::new(filters::strip_html));
    context.maybe_add_filter("strip_newlines", Box::new(filters::strip_newlines));
    context.maybe_add_filter("times", Box::new(filters::times));
    context.maybe_add_filter("truncate", Box::new(filters::truncate));
    context.maybe_add_filter("truncatewords", Box::new(filters::truncatewords));
    context.maybe_add_filter("uniq", Box::new(filters::uniq));
    context.maybe_add_filter("upcase", Box::new(filters::upcase));
    context.maybe_add_filter("url_decode", Box::new(filters::url_decode));
    context.maybe_add_filter("url_encode", Box::new(filters::url_encode));
}

#[cfg(not(feature = "extra-filters"))]
fn maybe_add_extra_filters(context: &mut Context) {}

#[cfg(feature = "extra-filters")]
fn maybe_add_extra_filters(context: &mut Context) {
    context.maybe_add_filter("pluralize", Box::new(filters::pluralize));
    context.maybe_add_filter("date_in_tz", Box::new(filters::date_in_tz));
}
<|endoftext|>


<commit_before><commit_msg>#update for qadatastruct // get_stock_adv<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests for camera view matrix<commit_after><|endoftext|>


<commit_before>// xfail-test

enum color { red, green, blue, black, white, }

fn main() {
    assert (uint::to_str(red as uint, 10) == #fmt["%?", red]);
    assert (uint::to_str(green as uint, 10) == #fmt["%?", green]);
    assert (uint::to_str(white as uint, 10) == #fmt["%?", white]);
}

<commit_msg>test: Un-xfail run-pass/tag-auto-disr-val-shape<commit_after>enum color { red, green, blue, black, white, }

fn main() {
    // Ideally we would print the name of the variant, not the number
    assert (uint::to_str(red as uint, 10u) == #fmt["%?", red]);
    assert (uint::to_str(green as uint, 10u) == #fmt["%?", green]);
    assert (uint::to_str(white as uint, 10u) == #fmt["%?", white]);
}

<|endoftext|>


<commit_before>use into::IntoError;

#[macro_export]
macro_rules! generate_error_imports {
    () => {
        use std::error::Error;
        use std::fmt::Error as FmtError;
        use std::fmt::{Display, Formatter};

        use $crate::into::IntoError;
    }
}

#[macro_export]
macro_rules! generate_error_module {
    ( $exprs:item ) => {
        pub mod error {
            generate_error_imports!();
            $exprs
        }
    }
}

#[macro_export]
macro_rules! generate_custom_error_types {
    {
        $name: ident,
        $kindname: ident,
        $customMemberTypeName: ident,
        $($kind:ident => $string:expr),*
    } => {
        #[derive(Clone, Copy, Debug, PartialEq)]
        pub enum $kindname {
            $( $kind ),*
        }

        impl Display for $kindname {

            fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
                let s = match *self {
                    $( $kindname::$kind => $string ),*
                };
                try!(write!(fmt, "{}", s));
                Ok(())
            }

        }

        impl IntoError for $kindname {
            type Target = $name;

            fn into_error(self) -> Self::Target {
                $name::new(self, None)
            }

            fn into_error_with_cause(self, cause: Box<Error>) -> Self::Target {
                $name::new(self, Some(cause))
            }

        }

        #[derive(Debug)]
        pub struct $name {
            err_type: $kindname,
            cause: Option<Box<Error>>,
            custom_data: Option<$customMemberTypeName>,
        }

        impl $name {

            pub fn new(errtype: $kindname, cause: Option<Box<Error>>) -> $name {
                $name {
                    err_type: errtype,
                    cause: cause,
                    custom_data: None,
                }
            }

            pub fn err_type(&self) -> $kindname {
                self.err_type
            }

        }

        impl Into<$name> for $kindname {

            fn into(self) -> $name {
                $name::new(self, None)
            }

        }

        impl Display for $name {

            fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
                try!(write!(fmt, "[{}]", self.err_type));
                Ok(())
            }

        }

        impl Error for $name {

            fn description(&self) -> &str {
                match self.err_type {
                    $( $kindname::$kind => $string ),*
                }
            }

            fn cause(&self) -> Option<&Error> {
                self.cause.as_ref().map(|e| &**e)
            }

        }

    }
}

#[macro_export]
macro_rules! generate_result_helper {
    (
        $name: ident,
        $kindname: ident
    ) => {
        /// Trait to replace
        ///
        /// ```ignore
        /// foo.map_err(Box::new).map_err(|e| SomeType::SomeErrorKind.into_error_with_cause(e))
        /// // or:
        /// foo.map_err(|e| SomeType::SomeErrorKind.into_error_with_cause(Box::new(e)))
        /// ```
        ///
        /// with much nicer
        ///
        /// ```ignore
        /// foo.map_err_into(SomeType::SomeErrorKind)
        /// ```
        ///
        pub trait MapErrInto<T> {
            fn map_err_into(self, error_kind: $kindname) -> Result<T, $name>;
        }

        impl<T, E: Error + 'static> MapErrInto<T> for Result<T, E> {

            fn map_err_into(self, error_kind: $kindname) -> Result<T, $name> {
                self.map_err(Box::new)
                    .map_err(|e| error_kind.into_error_with_cause(e))
            }

        }
    }
}

#[macro_export]
macro_rules! generate_option_helper {
    (
        $name: ident,
        $kindname: ident
    ) => {
        /// Trait to replace
        ///
        /// ```ignore
        /// foo.ok_or(SomeType::SomeErrorKind.into_error())
        /// ```
        ///
        /// with
        ///
        /// ```ignore
        /// foo.ok_or_errkind(SomeType::SomeErrorKind)
        /// ```
        pub trait OkOrErr<T> {
            fn ok_or_errkind(self, kind: $kindname) -> Result<T, $name>;
        }

        impl<T> OkOrErr<T> for Option<T> {

            fn ok_or_errkind(self, kind: $kindname) -> Result<T, $name> {
                self.ok_or(kind.into_error())
            }

        }
    }
}

#[macro_export]
macro_rules! generate_error_types {
    (
        $name: ident,
        $kindname: ident,
        $($kind:ident => $string:expr),*
    ) => {
        #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)]
        pub struct SomeNotExistingTypeWithATypeNameNoOneWillEverChoose {}
        generate_custom_error_types!($name, $kindname,
                                     SomeNotExistingTypeWithATypeNameNoOneWillEverChoose,
                                     $($kind => $string),*);

        generate_result_helper!($name, $kindname);
        generate_option_helper!($name, $kindname);
    }
}

#[cfg(test)]
mod test {

    generate_error_module!(
        generate_error_types!(TestError, TestErrorKind,
            TestErrorKindA => "testerrorkind a",
            TestErrorKindB => "testerrorkind B");
    );

    #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)]
    pub struct CustomData {
        pub test: i32,
        pub othr: i64,
    }

    generate_error_imports!();

    generate_custom_error_types!(CustomTestError, CustomTestErrorKind,
        CustomData,
        CustomErrorKindA => "customerrorkind a",
        CustomErrorKindB => "customerrorkind B");

    impl CustomTestError {
        pub fn test(&self) -> i32 {
            match self.custom_data {
                Some(t) => t.test,
                None => 0,
            }
        }

        pub fn bar(&self) -> i64 {
            match self.custom_data {
                Some(t) => t.othr,
                None => 0,
            }
        }
    }

    #[test]
    fn test_a() {
        use self::error::{TestError, TestErrorKind};

        let kind = TestErrorKind::TestErrorKindA;
        assert_eq!(String::from("testerrorkind a"), format!("{}", kind));

        let e = TestError::new(kind, None);
        assert_eq!(String::from("[testerrorkind a]"), format!("{}", e));
    }

    #[test]
    fn test_b() {
        use self::error::{TestError, TestErrorKind};

        let kind = TestErrorKind::TestErrorKindB;
        assert_eq!(String::from("testerrorkind B"), format!("{}", kind));

        let e = TestError::new(kind, None);
        assert_eq!(String::from("[testerrorkind B]"), format!("{}", e));

    }

    #[test]
    fn test_ab() {
        use std::error::Error;
        use self::error::{TestError, TestErrorKind};

        let kinda = TestErrorKind::TestErrorKindA;
        let kindb = TestErrorKind::TestErrorKindB;
        assert_eq!(String::from("testerrorkind a"), format!("{}", kinda));
        assert_eq!(String::from("testerrorkind B"), format!("{}", kindb));

        let e = TestError::new(kinda, Some(Box::new(TestError::new(kindb, None))));
        assert_eq!(String::from("[testerrorkind a]"), format!("{}", e));
        assert_eq!(TestErrorKind::TestErrorKindA, e.err_type());
        assert_eq!(String::from("[testerrorkind B]"), format!("{}", e.cause().unwrap()));
    }

    pub mod anothererrormod {
        generate_error_imports!();
        generate_error_types!(TestError, TestErrorKind,
            TestErrorKindA => "testerrorkind a",
            TestErrorKindB => "testerrorkind B");
    }

    #[test]
    fn test_other_a() {
        use self::anothererrormod::{TestError, TestErrorKind};

        let kind = TestErrorKind::TestErrorKindA;
        assert_eq!(String::from("testerrorkind a"), format!("{}", kind));

        let e = TestError::new(kind, None);
        assert_eq!(String::from("[testerrorkind a]"), format!("{}", e));
    }

    #[test]
    fn test_other_b() {
        use self::anothererrormod::{TestError, TestErrorKind};

        let kind = TestErrorKind::TestErrorKindB;
        assert_eq!(String::from("testerrorkind B"), format!("{}", kind));

        let e = TestError::new(kind, None);
        assert_eq!(String::from("[testerrorkind B]"), format!("{}", e));

    }

    #[test]
    fn test_other_ab() {
        use std::error::Error;
        use self::anothererrormod::{TestError, TestErrorKind};

        let kinda = TestErrorKind::TestErrorKindA;
        let kindb = TestErrorKind::TestErrorKindB;
        assert_eq!(String::from("testerrorkind a"), format!("{}", kinda));
        assert_eq!(String::from("testerrorkind B"), format!("{}", kindb));

        let e = TestError::new(kinda, Some(Box::new(TestError::new(kindb, None))));
        assert_eq!(String::from("[testerrorkind a]"), format!("{}", e));
        assert_eq!(TestErrorKind::TestErrorKindA, e.err_type());
        assert_eq!(String::from("[testerrorkind B]"), format!("{}", e.cause().unwrap()));
    }

    #[test]
    fn test_error_kind_mapping() {
        use std::io::{Error, ErrorKind};
        use self::error::{OkOrErr, MapErrInto};
        use self::error::TestErrorKind;

        let err : Result<(), _> = Err(Error::new(ErrorKind::Other, ""));
        let err : Result<(), _> = err.map_err_into(TestErrorKind::TestErrorKindA);

        assert!(err.is_err());
        let err = err.unwrap_err();

        match err.err_type() {
            TestErrorKind::TestErrorKindA => assert!(true),
            _ => assert!(false),
        }
    }

    #[test]
    fn test_error_kind_double_mapping() {
        use std::io::{Error, ErrorKind};
        use self::error::{OkOrErr, MapErrInto};
        use self::error::TestErrorKind;

        let err : Result<(), _> = Err(Error::new(ErrorKind::Other, ""));
        let err : Result<(), _> = err.map_err_into(TestErrorKind::TestErrorKindA)
                                     .map_err_into(TestErrorKind::TestErrorKindB);

        assert!(err.is_err());
        let err = err.unwrap_err();
        match err.err_type() {
            TestErrorKind::TestErrorKindB => assert!(true),
            _ => assert!(false),
        }

        // not sure how to test that the inner error is of TestErrorKindA, actually...
        match err.cause() {
            Some(_) => assert!(true),
            None    => assert!(false),
        }

    }

}
<commit_msg>Add tests for Option::ok_or_errkind() extension function<commit_after>use into::IntoError;

#[macro_export]
macro_rules! generate_error_imports {
    () => {
        use std::error::Error;
        use std::fmt::Error as FmtError;
        use std::fmt::{Display, Formatter};

        use $crate::into::IntoError;
    }
}

#[macro_export]
macro_rules! generate_error_module {
    ( $exprs:item ) => {
        pub mod error {
            generate_error_imports!();
            $exprs
        }
    }
}

#[macro_export]
macro_rules! generate_custom_error_types {
    {
        $name: ident,
        $kindname: ident,
        $customMemberTypeName: ident,
        $($kind:ident => $string:expr),*
    } => {
        #[derive(Clone, Copy, Debug, PartialEq)]
        pub enum $kindname {
            $( $kind ),*
        }

        impl Display for $kindname {

            fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
                let s = match *self {
                    $( $kindname::$kind => $string ),*
                };
                try!(write!(fmt, "{}", s));
                Ok(())
            }

        }

        impl IntoError for $kindname {
            type Target = $name;

            fn into_error(self) -> Self::Target {
                $name::new(self, None)
            }

            fn into_error_with_cause(self, cause: Box<Error>) -> Self::Target {
                $name::new(self, Some(cause))
            }

        }

        #[derive(Debug)]
        pub struct $name {
            err_type: $kindname,
            cause: Option<Box<Error>>,
            custom_data: Option<$customMemberTypeName>,
        }

        impl $name {

            pub fn new(errtype: $kindname, cause: Option<Box<Error>>) -> $name {
                $name {
                    err_type: errtype,
                    cause: cause,
                    custom_data: None,
                }
            }

            pub fn err_type(&self) -> $kindname {
                self.err_type
            }

        }

        impl Into<$name> for $kindname {

            fn into(self) -> $name {
                $name::new(self, None)
            }

        }

        impl Display for $name {

            fn fmt(&self, fmt: &mut Formatter) -> Result<(), FmtError> {
                try!(write!(fmt, "[{}]", self.err_type));
                Ok(())
            }

        }

        impl Error for $name {

            fn description(&self) -> &str {
                match self.err_type {
                    $( $kindname::$kind => $string ),*
                }
            }

            fn cause(&self) -> Option<&Error> {
                self.cause.as_ref().map(|e| &**e)
            }

        }

    }
}

#[macro_export]
macro_rules! generate_result_helper {
    (
        $name: ident,
        $kindname: ident
    ) => {
        /// Trait to replace
        ///
        /// ```ignore
        /// foo.map_err(Box::new).map_err(|e| SomeType::SomeErrorKind.into_error_with_cause(e))
        /// // or:
        /// foo.map_err(|e| SomeType::SomeErrorKind.into_error_with_cause(Box::new(e)))
        /// ```
        ///
        /// with much nicer
        ///
        /// ```ignore
        /// foo.map_err_into(SomeType::SomeErrorKind)
        /// ```
        ///
        pub trait MapErrInto<T> {
            fn map_err_into(self, error_kind: $kindname) -> Result<T, $name>;
        }

        impl<T, E: Error + 'static> MapErrInto<T> for Result<T, E> {

            fn map_err_into(self, error_kind: $kindname) -> Result<T, $name> {
                self.map_err(Box::new)
                    .map_err(|e| error_kind.into_error_with_cause(e))
            }

        }
    }
}

#[macro_export]
macro_rules! generate_option_helper {
    (
        $name: ident,
        $kindname: ident
    ) => {
        /// Trait to replace
        ///
        /// ```ignore
        /// foo.ok_or(SomeType::SomeErrorKind.into_error())
        /// ```
        ///
        /// with
        ///
        /// ```ignore
        /// foo.ok_or_errkind(SomeType::SomeErrorKind)
        /// ```
        pub trait OkOrErr<T> {
            fn ok_or_errkind(self, kind: $kindname) -> Result<T, $name>;
        }

        impl<T> OkOrErr<T> for Option<T> {

            fn ok_or_errkind(self, kind: $kindname) -> Result<T, $name> {
                self.ok_or(kind.into_error())
            }

        }
    }
}

#[macro_export]
macro_rules! generate_error_types {
    (
        $name: ident,
        $kindname: ident,
        $($kind:ident => $string:expr),*
    ) => {
        #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)]
        pub struct SomeNotExistingTypeWithATypeNameNoOneWillEverChoose {}
        generate_custom_error_types!($name, $kindname,
                                     SomeNotExistingTypeWithATypeNameNoOneWillEverChoose,
                                     $($kind => $string),*);

        generate_result_helper!($name, $kindname);
        generate_option_helper!($name, $kindname);
    }
}

#[cfg(test)]
mod test {

    generate_error_module!(
        generate_error_types!(TestError, TestErrorKind,
            TestErrorKindA => "testerrorkind a",
            TestErrorKindB => "testerrorkind B");
    );

    #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)]
    pub struct CustomData {
        pub test: i32,
        pub othr: i64,
    }

    generate_error_imports!();

    generate_custom_error_types!(CustomTestError, CustomTestErrorKind,
        CustomData,
        CustomErrorKindA => "customerrorkind a",
        CustomErrorKindB => "customerrorkind B");

    impl CustomTestError {
        pub fn test(&self) -> i32 {
            match self.custom_data {
                Some(t) => t.test,
                None => 0,
            }
        }

        pub fn bar(&self) -> i64 {
            match self.custom_data {
                Some(t) => t.othr,
                None => 0,
            }
        }
    }

    #[test]
    fn test_a() {
        use self::error::{TestError, TestErrorKind};

        let kind = TestErrorKind::TestErrorKindA;
        assert_eq!(String::from("testerrorkind a"), format!("{}", kind));

        let e = TestError::new(kind, None);
        assert_eq!(String::from("[testerrorkind a]"), format!("{}", e));
    }

    #[test]
    fn test_b() {
        use self::error::{TestError, TestErrorKind};

        let kind = TestErrorKind::TestErrorKindB;
        assert_eq!(String::from("testerrorkind B"), format!("{}", kind));

        let e = TestError::new(kind, None);
        assert_eq!(String::from("[testerrorkind B]"), format!("{}", e));

    }

    #[test]
    fn test_ab() {
        use std::error::Error;
        use self::error::{TestError, TestErrorKind};

        let kinda = TestErrorKind::TestErrorKindA;
        let kindb = TestErrorKind::TestErrorKindB;
        assert_eq!(String::from("testerrorkind a"), format!("{}", kinda));
        assert_eq!(String::from("testerrorkind B"), format!("{}", kindb));

        let e = TestError::new(kinda, Some(Box::new(TestError::new(kindb, None))));
        assert_eq!(String::from("[testerrorkind a]"), format!("{}", e));
        assert_eq!(TestErrorKind::TestErrorKindA, e.err_type());
        assert_eq!(String::from("[testerrorkind B]"), format!("{}", e.cause().unwrap()));
    }

    pub mod anothererrormod {
        generate_error_imports!();
        generate_error_types!(TestError, TestErrorKind,
            TestErrorKindA => "testerrorkind a",
            TestErrorKindB => "testerrorkind B");
    }

    #[test]
    fn test_other_a() {
        use self::anothererrormod::{TestError, TestErrorKind};

        let kind = TestErrorKind::TestErrorKindA;
        assert_eq!(String::from("testerrorkind a"), format!("{}", kind));

        let e = TestError::new(kind, None);
        assert_eq!(String::from("[testerrorkind a]"), format!("{}", e));
    }

    #[test]
    fn test_other_b() {
        use self::anothererrormod::{TestError, TestErrorKind};

        let kind = TestErrorKind::TestErrorKindB;
        assert_eq!(String::from("testerrorkind B"), format!("{}", kind));

        let e = TestError::new(kind, None);
        assert_eq!(String::from("[testerrorkind B]"), format!("{}", e));

    }

    #[test]
    fn test_other_ab() {
        use std::error::Error;
        use self::anothererrormod::{TestError, TestErrorKind};

        let kinda = TestErrorKind::TestErrorKindA;
        let kindb = TestErrorKind::TestErrorKindB;
        assert_eq!(String::from("testerrorkind a"), format!("{}", kinda));
        assert_eq!(String::from("testerrorkind B"), format!("{}", kindb));

        let e = TestError::new(kinda, Some(Box::new(TestError::new(kindb, None))));
        assert_eq!(String::from("[testerrorkind a]"), format!("{}", e));
        assert_eq!(TestErrorKind::TestErrorKindA, e.err_type());
        assert_eq!(String::from("[testerrorkind B]"), format!("{}", e.cause().unwrap()));
    }

    #[test]
    fn test_error_kind_mapping() {
        use std::io::{Error, ErrorKind};
        use self::error::{OkOrErr, MapErrInto};
        use self::error::TestErrorKind;

        let err : Result<(), _> = Err(Error::new(ErrorKind::Other, ""));
        let err : Result<(), _> = err.map_err_into(TestErrorKind::TestErrorKindA);

        assert!(err.is_err());
        let err = err.unwrap_err();

        match err.err_type() {
            TestErrorKind::TestErrorKindA => assert!(true),
            _ => assert!(false),
        }
    }

    #[test]
    fn test_error_kind_double_mapping() {
        use std::io::{Error, ErrorKind};
        use self::error::{OkOrErr, MapErrInto};
        use self::error::TestErrorKind;

        let err : Result<(), _> = Err(Error::new(ErrorKind::Other, ""));
        let err : Result<(), _> = err.map_err_into(TestErrorKind::TestErrorKindA)
                                     .map_err_into(TestErrorKind::TestErrorKindB);

        assert!(err.is_err());
        let err = err.unwrap_err();
        match err.err_type() {
            TestErrorKind::TestErrorKindB => assert!(true),
            _ => assert!(false),
        }

        // not sure how to test that the inner error is of TestErrorKindA, actually...
        match err.cause() {
            Some(_) => assert!(true),
            None    => assert!(false),
        }

    }

    #[test]
    fn test_error_option_good() {
        use self::error::{OkOrErr, MapErrInto};
        use self::error::TestErrorKind;

        let something = Some(1);
        match something.ok_or_errkind(TestErrorKind::TestErrorKindA) {
            Ok(1) => assert!(true),
            _     => assert!(false),
        }
    }

    #[test]
    fn test_error_option_bad() {
        use self::error::{OkOrErr, MapErrInto};
        use self::error::TestErrorKind;

        let something : Option<i32> = None;
        match something.ok_or_errkind(TestErrorKind::TestErrorKindA) {
            Ok(_)  => assert!(false),
            Err(e) => assert!(true),
        }
    }

}
<|endoftext|>