<commit_before>use error::{Result, Error};
use filters::Filter;
use std::collections::HashMap;
use token::Token::{self, Identifier, StringLiteral, NumberLiteral, BooleanLiteral};
use value::{Value, Object};

#[derive(Clone)]
pub enum Interrupt {
    Continue,
    Break,
}

#[derive(Default)]
pub struct Context {
    stack: Vec<Object>,
    globals: Object,

    /// The current interrupt state. The interrupt state is used by
    /// the `break` and `continue` tags to halt template rendering
    /// at a given point and unwind the `render` call stack until
    /// it reaches an enclosing `for_loop`. At that point the interrupt
    /// is cleared, and the `for_loop` carries on processing as directed.
    interrupt: Option<Interrupt>,

    /// The indices of all the cycles encountered during rendering.
    cycles: HashMap<String, usize>,

    // Public for backwards compatability
    pub filters: HashMap<String, Box<Filter>>,
}

impl Context {
    /// Creates a new, empty rendering context.
    ///
    /// # Examples
    ///
    /// ```
    /// # use liquid::Context;
    /// let ctx = Context::new();
    /// assert_eq!(ctx.get_val("test"), None);
    /// ```
    pub fn new() -> Context {
        Context::with_values_and_filters(Object::new(), HashMap::new())
    }

    pub fn with_values(values: Object) -> Context {
        Context::with_values_and_filters(values, HashMap::new())
    }

    pub fn with_filters(filters: HashMap<String, Box<Filter>>) -> Context {
        Context::with_values_and_filters(Object::new(), filters)
    }

    pub fn with_values_and_filters(values: Object,
                                   filters: HashMap<String, Box<Filter>>)
                                   -> Context {
        Context {
            stack: vec![Object::new()],
            interrupt: None,
            cycles: HashMap::new(),
            globals: values,
            filters: filters,
        }
    }

    pub fn cycle_element(&mut self, name: &str, values: &[Token]) -> Result<Option<Value>> {
        let index = {
            let i = self.cycles.entry(name.to_owned()).or_insert(0);
            let j = *i;
            *i = (*i + 1) % values.len();
            j
        };

        if index >= values.len() {
            return Err(Error::Render(format!("cycle index {} out of bounds {}",
                                             index,
                                             values.len())));
        }

        self.evaluate(&values[index])
    }

    /// Only add the given filter to the context if a filter with this name doesn't already exist.
    pub fn maybe_add_filter(&mut self, name: &str, filter: Box<Filter>) {
        if self.get_filter(name).is_none() {
            self.add_filter(name, filter)
        }
    }

    pub fn add_filter(&mut self, name: &str, filter: Box<Filter>) {
        self.filters.insert(name.to_owned(), filter);
    }

    pub fn get_filter<'b>(&'b self, name: &str) -> Option<&'b Box<Filter>> {
        self.filters.get(name)
    }

    pub fn interrupted(&self) -> bool {
        self.interrupt.is_some()
    }

    /// Sets the interrupt state. Any previous state is obliterated.
    pub fn set_interrupt(&mut self, interrupt: Interrupt) {
        self.interrupt = Some(interrupt);
    }

    /// Fetches and clears the interrupt state.
    pub fn pop_interrupt(&mut self) -> Option<Interrupt> {
        let rval = self.interrupt.clone();
        self.interrupt = None;
        rval
    }

    /// Creates a new variable scope chained to a parent scope.
    fn push_scope(&mut self) {
        self.stack.push(Object::new());
    }

    /// Removes the topmost stack frame from the local variable stack.
    ///
    /// # Panics
    ///
    /// This method will panic if popping the topmost frame results in an
    /// empty stack. Given that a context is created with a top-level stack
    /// frame already in place, empyting the stack should never happen in a
    /// well-formed program.
    fn pop_scope(&mut self) {
        if self.stack.pop().is_none() {
            panic!("Pop leaves empty stack")
        };
    }

    /// Sets up a new stack frame, executes the supplied function and then
    /// tears the stack frame down before returning the function's result
    /// to the caller.
    ///
    /// # Examples
    /// ```
    /// # use liquid::{Value, Context};
    /// let mut ctx = Context::new();
    /// ctx.set_val("test", Value::Num(42f32));
    /// ctx.run_in_scope(|mut stack_frame| {
    ///   // stack_frame inherits values from its parent context
    ///   assert_eq!(stack_frame.get_val("test"), Some(&Value::Num(42f32)));
    ///
    ///   // but can (optionally) override them
    ///   stack_frame.set_local_val("test", Value::Num(3.14f32));
    ///   assert_eq!(stack_frame.get_val("test"), Some(&Value::Num(3.14f32)));
    /// });
    /// // the original value is unchanged once the scope exits
    /// assert_eq!(ctx.get_val("test"), Some(&Value::Num(42f32)));
    /// ```
    pub fn run_in_scope<RvalT, FnT>(&mut self, f: FnT) -> RvalT
        where FnT: FnOnce(&mut Context) -> RvalT
    {
        self.push_scope();
        let result = f(self);
        self.pop_scope();
        result
    }

    /// Internal part of get_val. Walks the scope stack to try and find the
    /// reqested variable, and failing that checks the global pool.
    fn get<'a>(&'a self, name: &str) -> Option<&'a Value> {
        for frame in self.stack.iter().rev() {
            if let rval @ Some(_) = frame.get(name) {
                return rval;
            }
        }
        self.globals.get(name)
    }

    /// Gets a value from the rendering context. The name value can be a
    /// dot-separated path to a value. A value will only be returned if
    /// each link in the chain (excluding the final name) refers to a
    /// value of type Object.
    ///
    /// # Examples
    ///
    /// ```
    /// # use liquid::{Value, Context};
    /// let mut ctx = Context::new();
    /// ctx.set_val("test", Value::Num(42f32));
    /// assert_eq!(ctx.get_val("test").unwrap(), &Value::Num(42f32));
    /// ```
    pub fn get_val<'b>(&'b self, name: &str) -> Option<&'b Value> {
        let mut path = name.split('.');
        let key = path.next().unwrap_or("");
        let mut rval = self.get(key);

        // walk the chain of Object values, as specified by the path
        // passed in name
        for id in path {
            match rval {
                Some(&Value::Object(ref x)) => rval = x.get(id),
                _ => return None,
            }
        }

        rval
    }

    /// Sets a value in the global context.
    ///
    /// # Examples
    ///
    /// ```
    /// # use liquid::{Value, Context};
    /// let mut ctx = Context::new();
    /// ctx.set_val("test", Value::Num(42f32));
    /// assert_eq!(ctx.get_val("test"), Some(&Value::Num(42f32)));
    /// ```
    pub fn set_val(&mut self, name: &str, val: Value) -> Option<Value> {
        self.globals.insert(name.to_owned(), val)
    }

    /// Translates a Token to a Value, looking it up in the context if
    /// necessary
    pub fn evaluate(&self, t: &Token) -> Result<Option<Value>> {
        match *t {
            NumberLiteral(f) => Ok(Some(Value::Num(f))),
            StringLiteral(ref s) => Ok(Some(Value::Str(s.clone()))),
            BooleanLiteral(b) => Ok(Some(Value::Bool(b))),
            Identifier(ref id) => Ok(self.get_val(id).cloned()),
            _ => {
                let msg = format!("Cannot evaluate {}", t);
                Err(Error::Other(msg))
            }
        }
    }

    /// Sets a value to the rendering context.
    /// Note that it needs to be wrapped in a liquid::Value.
    ///
    /// # Panics
    ///
    /// Panics if there is no frame on the local values stack. Context
    /// instances are created with a top-level stack frame in place, so
    /// this should never happen in a well-formed program.
    ///
    /// # Examples
    ///
    /// ```
    /// # use liquid::{Value, Context};
    /// let mut ctx = Context::new();
    /// ctx.run_in_scope(|mut local_scope| {
    ///   local_scope.set_val("global", Value::Num(42f32));
    ///   local_scope.set_local_val("local", Value::Num(163f32));
    ///
    ///   assert_eq!(local_scope.get_val("global"), Some(&Value::Num(42f32)));
    ///   assert_eq!(local_scope.get_val("local"), Some(&Value::Num(163f32)));
    /// });
    /// assert_eq!(ctx.get_val("global"), Some(&Value::Num(42f32)));
    /// assert_eq!(ctx.get_val("local"), None);
    /// ```
    pub fn set_local_val(&mut self, name: &str, val: Value) -> Option<Value> {
        match self.stack.last_mut() {
            Some(frame) => frame.insert(name.to_owned(), val),
            None => panic!("Cannot insert into an empty stack"),
        }
    }
}

#[cfg(test)]
mod test {
    use super::Context;
    use value::Value;
    use std::collections::HashMap;

    #[test]
    fn get_val() {
        let mut ctx = Context::new();
        let mut post = HashMap::new();
        post.insert("number".to_owned(), Value::Num(42f32));
        ctx.set_val("post", Value::Object(post));
        assert_eq!(ctx.get_val("post.number").unwrap(), &Value::Num(42f32));
    }

    #[test]
    fn scoped_variables() {
        let mut ctx = Context::new();
        ctx.set_val("test", Value::Num(42f32));
        assert_eq!(ctx.get_val("test").unwrap(), &Value::Num(42f32));

        ctx.run_in_scope(|mut new_scope| {
            // assert that values are chained to the parent scope
            assert_eq!(new_scope.get_val("test").unwrap(), &Value::Num(42f32));

            // set a new local value, and assert that it overrides the previous value
            new_scope.set_local_val("test", Value::Num(3.14f32));
            assert_eq!(new_scope.get_val("test").unwrap(), &Value::Num(3.14f32));

            // sat a new val that we will pick up outside the scope
            new_scope.set_val("global", Value::str("some value"));
        });

        // assert that the value has reverted to the old one
        assert_eq!(ctx.get_val("test").unwrap(), &Value::Num(42f32));
        assert_eq!(ctx.get_val("global").unwrap(), &Value::str("some value"));
    }

    #[test]
    fn evaluate_handles_string_literals() {
        use token::Token::StringLiteral;

        let ctx = Context::new();
        let t = StringLiteral("hello".to_owned());
        assert_eq!(ctx.evaluate(&t).unwrap(), Some(Value::str("hello")));
    }

    #[test]
    fn evaluate_handles_number_literals() {
        use token::Token::NumberLiteral;

        let ctx = Context::new();
        assert_eq!(ctx.evaluate(&NumberLiteral(42f32)).unwrap(),
                   Some(Value::Num(42f32)));
    }

    #[test]
    fn evaluate_handles_boolean_literals() {
        use token::Token::BooleanLiteral;

        let ctx = Context::new();
        assert_eq!(ctx.evaluate(&BooleanLiteral(true)).unwrap(),
                   Some(Value::Bool(true)));

        assert_eq!(ctx.evaluate(&BooleanLiteral(false)).unwrap(),
                   Some(Value::Bool(false)));
    }

    #[test]
    fn evaluate_handles_identifiers() {
        use token::Token::Identifier;

        let mut ctx = Context::new();
        ctx.set_val("var0", Value::Num(42f32));
        assert_eq!(ctx.evaluate(&Identifier("var0".to_owned())).unwrap(),
                   Some(Value::Num(42f32)));
        assert_eq!(ctx.evaluate(&Identifier("nope".to_owned())).unwrap(), None);
    }

    #[test]
    fn evaluate_returns_none_on_invalid_token() {
        use token::Token::DotDot;
        let ctx = Context::new();
        assert!(ctx.evaluate(&DotDot).is_err());
    }
}
<commit_msg>fix: Remove `Box` from interface for clippy<commit_after>use error::{Result, Error};
use filters::Filter;
use std::collections::HashMap;
use token::Token::{self, Identifier, StringLiteral, NumberLiteral, BooleanLiteral};
use value::{Value, Object};

#[derive(Clone)]
pub enum Interrupt {
    Continue,
    Break,
}

#[derive(Default)]
pub struct Context {
    stack: Vec<Object>,
    globals: Object,

    /// The current interrupt state. The interrupt state is used by
    /// the `break` and `continue` tags to halt template rendering
    /// at a given point and unwind the `render` call stack until
    /// it reaches an enclosing `for_loop`. At that point the interrupt
    /// is cleared, and the `for_loop` carries on processing as directed.
    interrupt: Option<Interrupt>,

    /// The indices of all the cycles encountered during rendering.
    cycles: HashMap<String, usize>,

    // Public for backwards compatability
    pub filters: HashMap<String, Box<Filter>>,
}

impl Context {
    /// Creates a new, empty rendering context.
    ///
    /// # Examples
    ///
    /// ```
    /// # use liquid::Context;
    /// let ctx = Context::new();
    /// assert_eq!(ctx.get_val("test"), None);
    /// ```
    pub fn new() -> Context {
        Context::with_values_and_filters(Object::new(), HashMap::new())
    }

    pub fn with_values(values: Object) -> Context {
        Context::with_values_and_filters(values, HashMap::new())
    }

    pub fn with_filters(filters: HashMap<String, Box<Filter>>) -> Context {
        Context::with_values_and_filters(Object::new(), filters)
    }

    pub fn with_values_and_filters(values: Object,
                                   filters: HashMap<String, Box<Filter>>)
                                   -> Context {
        Context {
            stack: vec![Object::new()],
            interrupt: None,
            cycles: HashMap::new(),
            globals: values,
            filters: filters,
        }
    }

    pub fn cycle_element(&mut self, name: &str, values: &[Token]) -> Result<Option<Value>> {
        let index = {
            let i = self.cycles.entry(name.to_owned()).or_insert(0);
            let j = *i;
            *i = (*i + 1) % values.len();
            j
        };

        if index >= values.len() {
            return Err(Error::Render(format!("cycle index {} out of bounds {}",
                                             index,
                                             values.len())));
        }

        self.evaluate(&values[index])
    }

    /// Only add the given filter to the context if a filter with this name doesn't already exist.
    pub fn maybe_add_filter(&mut self, name: &str, filter: Box<Filter>) {
        if !self.filters.contains_key(name) {
            self.add_filter(name, filter)
        }
    }

    pub fn add_filter(&mut self, name: &str, filter: Box<Filter>) {
        self.filters.insert(name.to_owned(), filter);
    }

    pub fn get_filter<'b>(&'b self, name: &str) -> Option<&'b Filter> {
        self.filters.get(name).map(|f| f.as_ref())
    }

    pub fn interrupted(&self) -> bool {
        self.interrupt.is_some()
    }

    /// Sets the interrupt state. Any previous state is obliterated.
    pub fn set_interrupt(&mut self, interrupt: Interrupt) {
        self.interrupt = Some(interrupt);
    }

    /// Fetches and clears the interrupt state.
    pub fn pop_interrupt(&mut self) -> Option<Interrupt> {
        let rval = self.interrupt.clone();
        self.interrupt = None;
        rval
    }

    /// Creates a new variable scope chained to a parent scope.
    fn push_scope(&mut self) {
        self.stack.push(Object::new());
    }

    /// Removes the topmost stack frame from the local variable stack.
    ///
    /// # Panics
    ///
    /// This method will panic if popping the topmost frame results in an
    /// empty stack. Given that a context is created with a top-level stack
    /// frame already in place, empyting the stack should never happen in a
    /// well-formed program.
    fn pop_scope(&mut self) {
        if self.stack.pop().is_none() {
            panic!("Pop leaves empty stack")
        };
    }

    /// Sets up a new stack frame, executes the supplied function and then
    /// tears the stack frame down before returning the function's result
    /// to the caller.
    ///
    /// # Examples
    /// ```
    /// # use liquid::{Value, Context};
    /// let mut ctx = Context::new();
    /// ctx.set_val("test", Value::Num(42f32));
    /// ctx.run_in_scope(|mut stack_frame| {
    ///   // stack_frame inherits values from its parent context
    ///   assert_eq!(stack_frame.get_val("test"), Some(&Value::Num(42f32)));
    ///
    ///   // but can (optionally) override them
    ///   stack_frame.set_local_val("test", Value::Num(3.14f32));
    ///   assert_eq!(stack_frame.get_val("test"), Some(&Value::Num(3.14f32)));
    /// });
    /// // the original value is unchanged once the scope exits
    /// assert_eq!(ctx.get_val("test"), Some(&Value::Num(42f32)));
    /// ```
    pub fn run_in_scope<RvalT, FnT>(&mut self, f: FnT) -> RvalT
        where FnT: FnOnce(&mut Context) -> RvalT
    {
        self.push_scope();
        let result = f(self);
        self.pop_scope();
        result
    }

    /// Internal part of get_val. Walks the scope stack to try and find the
    /// reqested variable, and failing that checks the global pool.
    fn get<'a>(&'a self, name: &str) -> Option<&'a Value> {
        for frame in self.stack.iter().rev() {
            if let rval @ Some(_) = frame.get(name) {
                return rval;
            }
        }
        self.globals.get(name)
    }

    /// Gets a value from the rendering context. The name value can be a
    /// dot-separated path to a value. A value will only be returned if
    /// each link in the chain (excluding the final name) refers to a
    /// value of type Object.
    ///
    /// # Examples
    ///
    /// ```
    /// # use liquid::{Value, Context};
    /// let mut ctx = Context::new();
    /// ctx.set_val("test", Value::Num(42f32));
    /// assert_eq!(ctx.get_val("test").unwrap(), &Value::Num(42f32));
    /// ```
    pub fn get_val<'b>(&'b self, name: &str) -> Option<&'b Value> {
        let mut path = name.split('.');
        let key = path.next().unwrap_or("");
        let mut rval = self.get(key);

        // walk the chain of Object values, as specified by the path
        // passed in name
        for id in path {
            match rval {
                Some(&Value::Object(ref x)) => rval = x.get(id),
                _ => return None,
            }
        }

        rval
    }

    /// Sets a value in the global context.
    ///
    /// # Examples
    ///
    /// ```
    /// # use liquid::{Value, Context};
    /// let mut ctx = Context::new();
    /// ctx.set_val("test", Value::Num(42f32));
    /// assert_eq!(ctx.get_val("test"), Some(&Value::Num(42f32)));
    /// ```
    pub fn set_val(&mut self, name: &str, val: Value) -> Option<Value> {
        self.globals.insert(name.to_owned(), val)
    }

    /// Translates a Token to a Value, looking it up in the context if
    /// necessary
    pub fn evaluate(&self, t: &Token) -> Result<Option<Value>> {
        match *t {
            NumberLiteral(f) => Ok(Some(Value::Num(f))),
            StringLiteral(ref s) => Ok(Some(Value::Str(s.clone()))),
            BooleanLiteral(b) => Ok(Some(Value::Bool(b))),
            Identifier(ref id) => Ok(self.get_val(id).cloned()),
            _ => {
                let msg = format!("Cannot evaluate {}", t);
                Err(Error::Other(msg))
            }
        }
    }

    /// Sets a value to the rendering context.
    /// Note that it needs to be wrapped in a liquid::Value.
    ///
    /// # Panics
    ///
    /// Panics if there is no frame on the local values stack. Context
    /// instances are created with a top-level stack frame in place, so
    /// this should never happen in a well-formed program.
    ///
    /// # Examples
    ///
    /// ```
    /// # use liquid::{Value, Context};
    /// let mut ctx = Context::new();
    /// ctx.run_in_scope(|mut local_scope| {
    ///   local_scope.set_val("global", Value::Num(42f32));
    ///   local_scope.set_local_val("local", Value::Num(163f32));
    ///
    ///   assert_eq!(local_scope.get_val("global"), Some(&Value::Num(42f32)));
    ///   assert_eq!(local_scope.get_val("local"), Some(&Value::Num(163f32)));
    /// });
    /// assert_eq!(ctx.get_val("global"), Some(&Value::Num(42f32)));
    /// assert_eq!(ctx.get_val("local"), None);
    /// ```
    pub fn set_local_val(&mut self, name: &str, val: Value) -> Option<Value> {
        match self.stack.last_mut() {
            Some(frame) => frame.insert(name.to_owned(), val),
            None => panic!("Cannot insert into an empty stack"),
        }
    }
}

#[cfg(test)]
mod test {
    use super::Context;
    use value::Value;
    use std::collections::HashMap;

    #[test]
    fn get_val() {
        let mut ctx = Context::new();
        let mut post = HashMap::new();
        post.insert("number".to_owned(), Value::Num(42f32));
        ctx.set_val("post", Value::Object(post));
        assert_eq!(ctx.get_val("post.number").unwrap(), &Value::Num(42f32));
    }

    #[test]
    fn scoped_variables() {
        let mut ctx = Context::new();
        ctx.set_val("test", Value::Num(42f32));
        assert_eq!(ctx.get_val("test").unwrap(), &Value::Num(42f32));

        ctx.run_in_scope(|mut new_scope| {
            // assert that values are chained to the parent scope
            assert_eq!(new_scope.get_val("test").unwrap(), &Value::Num(42f32));

            // set a new local value, and assert that it overrides the previous value
            new_scope.set_local_val("test", Value::Num(3.14f32));
            assert_eq!(new_scope.get_val("test").unwrap(), &Value::Num(3.14f32));

            // sat a new val that we will pick up outside the scope
            new_scope.set_val("global", Value::str("some value"));
        });

        // assert that the value has reverted to the old one
        assert_eq!(ctx.get_val("test").unwrap(), &Value::Num(42f32));
        assert_eq!(ctx.get_val("global").unwrap(), &Value::str("some value"));
    }

    #[test]
    fn evaluate_handles_string_literals() {
        use token::Token::StringLiteral;

        let ctx = Context::new();
        let t = StringLiteral("hello".to_owned());
        assert_eq!(ctx.evaluate(&t).unwrap(), Some(Value::str("hello")));
    }

    #[test]
    fn evaluate_handles_number_literals() {
        use token::Token::NumberLiteral;

        let ctx = Context::new();
        assert_eq!(ctx.evaluate(&NumberLiteral(42f32)).unwrap(),
                   Some(Value::Num(42f32)));
    }

    #[test]
    fn evaluate_handles_boolean_literals() {
        use token::Token::BooleanLiteral;

        let ctx = Context::new();
        assert_eq!(ctx.evaluate(&BooleanLiteral(true)).unwrap(),
                   Some(Value::Bool(true)));

        assert_eq!(ctx.evaluate(&BooleanLiteral(false)).unwrap(),
                   Some(Value::Bool(false)));
    }

    #[test]
    fn evaluate_handles_identifiers() {
        use token::Token::Identifier;

        let mut ctx = Context::new();
        ctx.set_val("var0", Value::Num(42f32));
        assert_eq!(ctx.evaluate(&Identifier("var0".to_owned())).unwrap(),
                   Some(Value::Num(42f32)));
        assert_eq!(ctx.evaluate(&Identifier("nope".to_owned())).unwrap(), None);
    }

    #[test]
    fn evaluate_returns_none_on_invalid_token() {
        use token::Token::DotDot;
        let ctx = Context::new();
        assert!(ctx.evaluate(&DotDot).is_err());
    }
}
<|endoftext|>


<commit_before><commit_msg>Add fuzz failure to the fuzz-failures directory<commit_after>!('\<|endoftext|>


<commit_before><commit_msg>add response.rs for travis<commit_after>#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(warnings)]
#![allow(unused)]

use reqwest;
use request;
use reqwest::IntoUrl;
use serde_derive;
use serde_json;
use std;
use std::collections::HashMap;
use std::process::exit;
use std::result::Result;
use std::thread;
use types;
use std::time;
use error;

// Struct for storing api response without parsing type specific data
#[derive(Debug)]
pub struct Response<'a> {
    pub error: Option<i64>,
    pub message: Option<String>,
    pub data: Option<serde_json::Value>,
    pub request: request::Request<'a>,
}

#[allow(unused)]
impl<'a> Response<'a> {
    pub fn new(request: request::Request<'a>) -> Self {
        Self {
            error: None,
            message: None,
            data: None,
            request: request
        }
    }
}

impl<'a> Into<types::FullInfo> for Response<'a> {
    fn into(self) -> types::FullInfo {
        unimplemented!()
    }
}
<|endoftext|>


<commit_before>use std::sync::{Arc, RWLock};
use std::collections::HashMap;
use std::io::{IoResult, File};
use std::io::util::copy;
use std::path::BytesContainer;
use serialize::Encodable;
use http;
use http::server::ResponseWriter;
use time;
use mimes::get_media_type;
use mustache;
use mustache::{Template, Encoder, Error};

///A container for the response
pub struct Response<'a, 'b: 'a> {
    ///the original `http::server::ResponseWriter`
    pub origin: &'a mut ResponseWriter<'b>,
    templates: Arc<RWLock<HashMap<&'static str, Template>>>
}

impl<'a, 'b> Response<'a, 'b> {
    pub fn from_internal<'c, 'd>(response: &'c mut ResponseWriter<'d>,
                                 templates: Arc<RWLock<HashMap<&'static str, Template>>>)
                                -> Response<'c, 'd> {
        Response {
            origin: response,
            templates: templates
        }
    }

    /// Sets the content type by it's short form.
    /// Returns the response for chaining.
    ///
    /// # Example
    /// ```{rust,ignore}
    /// response.content_type("html");
    /// ```
    pub fn content_type(&mut self, text: &str) -> &mut Response<'a,'b> {
        self.origin.headers.content_type = get_media_type(text);
        self
    }

    /// Sets the status code and returns the response for chaining
    ///
    /// # Example
    /// ```{rust,ignore}
    /// response.status_code(http::status::NotFound);
    /// ```
    pub fn status_code(&mut self, status: http::status::Status) -> &mut Response<'a,'b> {
        self.origin.status = status;
        self
    }

    /// Writes a response
    ///
    /// # Example
    /// ```{rust,ignore}
    /// response.send("hello world");
    /// ```
    pub fn send<T: BytesContainer> (&mut self, text: T) {
        // TODO: This needs to be more sophisticated to return the correct headers
        // not just "some headers" :)
        Response::set_headers(self.origin);
        let _ = self.origin.write(text.container_as_bytes());
    }

    fn set_headers(response_writer: &mut http::server::ResponseWriter) {
        let ref mut headers = response_writer.headers;
        headers.date = Some(time::now_utc());

        // we don't need to set this https://github.com/Ogeon/rustful/issues/3#issuecomment-44787613
        headers.content_length = None;
        if headers.content_type.is_none() {
            headers.content_type = get_media_type("txt");
        }

        headers.server = Some(String::from_str("Nickel"));
    }

    pub fn send_file(&mut self, path: &Path) -> IoResult<()> {
        let mut file = try!(File::open(path));
        self.origin.headers.content_length = None;

        self.origin.headers.content_type = path.extension_str().and_then(get_media_type);
        self.origin.headers.server = Some(String::from_str("Nickel"));
        copy(&mut file, self.origin)
    }

    /// Renders the given template bound with the given data.
    ///
    /// # Example
    /// ```{rust,ignore}
    /// let mut data = HashMap::<&'static str, &'static str>::new();
    /// data.insert("name", "user");
    /// response.render("examples/assets/template.tpl", &data);
    /// ```
    pub fn render<'a, T: Encodable<Encoder<'a>, Error>>
        (&mut self, path: &'static str, data: &T) {
        // Fast path doesn't need writer lock
        let _ = match self.templates.read().find(&path) {
            Some(template) => template.render(self.origin, data),
            None => {
                // Search again incase there was a race to compile the template
                let mut templates = self.templates.write();
                let template = templates.find_or_insert_with(path, |_| {
                    let mut file = File::open(&Path::new(path));
                    let raw_template = file.read_to_string()
                                            .ok()
                                            .expect(format!("Couldn't open the template file: {}",
                                                            path).as_slice());
                    mustache::compile_str(raw_template.as_slice())
                });

                template.render(self.origin, data)
            }
        };
    }
}

#[test]
fn matches_content_type () {
    let path = &Path::new("test.txt");
    let content_type = path.extension_str().and_then(get_media_type).unwrap();

    assert_eq!(content_type.type_.as_slice(), "text");
    assert_eq!(content_type.subtype.as_slice(), "plain");
}
<commit_msg>docs(response): document send_file method<commit_after>use std::sync::{Arc, RWLock};
use std::collections::HashMap;
use std::io::{IoResult, File};
use std::io::util::copy;
use std::path::BytesContainer;
use serialize::Encodable;
use http;
use http::server::ResponseWriter;
use time;
use mimes::get_media_type;
use mustache;
use mustache::{Template, Encoder, Error};

///A container for the response
pub struct Response<'a, 'b: 'a> {
    ///the original `http::server::ResponseWriter`
    pub origin: &'a mut ResponseWriter<'b>,
    templates: Arc<RWLock<HashMap<&'static str, Template>>>
}

impl<'a, 'b> Response<'a, 'b> {
    pub fn from_internal<'c, 'd>(response: &'c mut ResponseWriter<'d>,
                                 templates: Arc<RWLock<HashMap<&'static str, Template>>>)
                                -> Response<'c, 'd> {
        Response {
            origin: response,
            templates: templates
        }
    }

    /// Sets the content type by it's short form.
    /// Returns the response for chaining.
    ///
    /// # Example
    /// ```{rust,ignore}
    /// response.content_type("html");
    /// ```
    pub fn content_type(&mut self, text: &str) -> &mut Response<'a,'b> {
        self.origin.headers.content_type = get_media_type(text);
        self
    }

    /// Sets the status code and returns the response for chaining
    ///
    /// # Example
    /// ```{rust,ignore}
    /// response.status_code(http::status::NotFound);
    /// ```
    pub fn status_code(&mut self, status: http::status::Status) -> &mut Response<'a,'b> {
        self.origin.status = status;
        self
    }

    /// Writes a response
    ///
    /// # Example
    /// ```{rust,ignore}
    /// response.send("hello world");
    /// ```
    pub fn send<T: BytesContainer> (&mut self, text: T) {
        // TODO: This needs to be more sophisticated to return the correct headers
        // not just "some headers" :)
        Response::set_headers(self.origin);
        let _ = self.origin.write(text.container_as_bytes());
    }

    fn set_headers(response_writer: &mut http::server::ResponseWriter) {
        let ref mut headers = response_writer.headers;
        headers.date = Some(time::now_utc());

        // we don't need to set this https://github.com/Ogeon/rustful/issues/3#issuecomment-44787613
        headers.content_length = None;
        if headers.content_type.is_none() {
            headers.content_type = get_media_type("txt");
        }

        headers.server = Some(String::from_str("Nickel"));
    }

    /// Writes a file to the output.
    ///
    /// # Example
    /// ```{rust,ignore}
    /// response.send_file(some_path);
    /// ```
    pub fn send_file(&mut self, path: &Path) -> IoResult<()> {
        let mut file = try!(File::open(path));
        self.origin.headers.content_length = None;

        self.origin.headers.content_type = path.extension_str().and_then(get_media_type);
        self.origin.headers.server = Some(String::from_str("Nickel"));
        copy(&mut file, self.origin)
    }

    /// Renders the given template bound with the given data.
    ///
    /// # Example
    /// ```{rust,ignore}
    /// let mut data = HashMap::<&'static str, &'static str>::new();
    /// data.insert("name", "user");
    /// response.render("examples/assets/template.tpl", &data);
    /// ```
    pub fn render<'a, T: Encodable<Encoder<'a>, Error>>
        (&mut self, path: &'static str, data: &T) {
        // Fast path doesn't need writer lock
        let _ = match self.templates.read().find(&path) {
            Some(template) => template.render(self.origin, data),
            None => {
                // Search again incase there was a race to compile the template
                let mut templates = self.templates.write();
                let template = templates.find_or_insert_with(path, |_| {
                    let mut file = File::open(&Path::new(path));
                    let raw_template = file.read_to_string()
                                            .ok()
                                            .expect(format!("Couldn't open the template file: {}",
                                                            path).as_slice());
                    mustache::compile_str(raw_template.as_slice())
                });

                template.render(self.origin, data)
            }
        };
    }
}

#[test]
fn matches_content_type () {
    let path = &Path::new("test.txt");
    let content_type = path.extension_str().and_then(get_media_type).unwrap();

    assert_eq!(content_type.type_.as_slice(), "text");
    assert_eq!(content_type.subtype.as_slice(), "plain");
}
<|endoftext|>


<commit_before><commit_msg>21 - mutability<commit_after>fn main() {
    let immutable_box = box 5u;

    println!("immutable_box contains {}", immutable_box);

    // Mutability error
    //*immutable_box = 4;

    // Hand over the box, changing the mutability
    let mut mutable_box = immutable_box;

    println!("mutable_box contained {}", mutable_box);

    // Modify the contents of the box
    *mutable_box = 4;

    println!("mutable_box now contains {}", mutable_box);
}
<|endoftext|>


<commit_before><commit_msg>Add quick & dirty loggers<commit_after>use log::{LogRecord, LogLevel, LogMetadata, Log};

pub struct DefaultLogger;
pub struct DebugLogger;

impl Log for DefaultLogger {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= LogLevel::Info
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            println!("{} - {}", record.level(), record.args());
        }
    }
}

impl Log for DebugLogger {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= LogLevel::Debug
    }

    fn log(&self, record: &LogRecord) {
        if self.enabled(record.metadata()) {
            println!("{} - {}", record.level(), record.args());
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Update ReceiptEventContent representation<commit_after><|endoftext|>


<commit_before><commit_msg>remove unnecessary mut declarations from tag/mod.rs, to fix compiler warnings<commit_after><|endoftext|>


<commit_before><commit_msg>Implement char flipping<commit_after><|endoftext|>


<commit_before><commit_msg>Added test on tar.gz decoding<commit_after>extern crate flate2;
extern crate tar;

use std::fs::File;
use flate2::read::GzDecoder;
use tar::Archive;

#[test]
fn targz() {
    let file = File::open("tests/simple.tar.gz").unwrap();
    let gz_decoder = GzDecoder::new(file).unwrap();
    let mut tar = Archive::new(gz_decoder);
    let expected = ["a", "b", "c/", "c/d"];
    let actual: Vec<_> = tar.files_mut().unwrap()
        .map(|f| f.unwrap().filename().unwrap().to_owned())
        .collect();
    assert_eq!(actual, expected);
}
<|endoftext|>


<commit_before><commit_msg>Add the stain file<commit_after>extern crate rand;
use self::rand::Rng;

use core::renderer::RGB;

use super::Filter;

use super::map::{Grid, Measurable, tile, Tile};

// Configuration

// Should be divisible by 2
pub const VISCERA_DIAMETER : usize = 5;

const VISCERA_FG : u8 = 40;
const VISCERA_BG : u8 = 50;

const MOSS_FG : u8 = 5;
const MOSS_BG : u8 = 10;

const FUNGUS_FG : u8 = 30;
const FUNGUS_BG : u8 = 40;

const CORRUPTION_FG : u8 = 100;
const CORRUPTION_BG : u8 = 100;

pub enum StainType {
  Viscera,
  Moss,
  Fungus,
  Corruption
}

///
/// Stain
///
/// 'Stains' are a graphical effect that permanently alters the colors of the tiles it is applied to.
/// Multiple variations are possible with customizable radii, chance, and color ammount.
///
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct Stain;

impl Stain {

  ///
  /// Add stain on a tile
  ///
  pub fn stain_linear(x: usize, y: usize, d: usize, grid: &mut Grid<Tile>, chance: usize, stain_type: StainType) {

    let mut rng = rand::thread_rng();

    // Coinflip to decide if a tile gets blood
    if rng.gen_range(0, chance) == 0 {
      // Match walls or floors only
      match grid[x - (d/2)][y - (d/2)].tiletype {
        tile::Type::Floor(_) => {

          match stain_type {

            StainType::Viscera => {
              grid[x - (d/2)][y - (d/2)].fg += RGB(12 + rng.gen_range(0, VISCERA_FG), 0, 0);
              grid[x - (d/2)][y - (d/2)].bg += RGB(22 + rng.gen_range(0, VISCERA_BG), 0, 0);
            },
            StainType::Moss => {
              grid[x - (d/2)][y - (d/2)].fg += RGB(0, rng.gen_range(0, MOSS_FG), 0);
              grid[x - (d/2)][y - (d/2)].bg += RGB(0, rng.gen_range(0, MOSS_BG), 0);
            },
            StainType::Fungus => {
              let fg = rng.gen_range(0, FUNGUS_FG);
              let bg = rng.gen_range(0, FUNGUS_BG);
              grid[x - (d/2)][y - (d/2)].fg += RGB(fg, 0, fg);
              grid[x - (d/2)][y - (d/2)].bg += RGB(fg, 0, bg);
            },
            StainType::Corruption => {
              let fg = rng.gen_range(0, CORRUPTION_FG);
              let bg = rng.gen_range(0, CORRUPTION_BG);
              grid[x - (d/2)][y - (d/2)].fg -= RGB(fg, fg, fg);
              grid[x - (d/2)][y - (d/2)].bg -= RGB(bg, bg, bg);
            }

          }

        },
        tile::Type::Wall(_) => {

          match stain_type {

            StainType::Viscera => {
              grid[x - (d/2)][y - (d/2)].fg += RGB(rng.gen_range(0, VISCERA_FG), 0, 0);
              grid[x - (d/2)][y - (d/2)].bg += RGB(rng.gen_range(0, VISCERA_BG), 0, 0);
            },
            StainType::Moss => {
              grid[x - (d/2)][y - (d/2)].fg += RGB(0, rng.gen_range(0, MOSS_FG), 0);
              grid[x - (d/2)][y - (d/2)].bg += RGB(0, rng.gen_range(0, MOSS_BG), 0);
            },
            StainType::Fungus => {
              let fg = rng.gen_range(0, FUNGUS_FG);
              let bg = rng.gen_range(0, FUNGUS_BG);
              grid[x - (d/2)][y - (d/2)].fg += RGB(fg, 0, fg);
              grid[x - (d/2)][y - (d/2)].bg += RGB(fg, 0, bg);
            },
            StainType::Corruption => {
              let fg = rng.gen_range(0, CORRUPTION_FG);
              let bg = rng.gen_range(0, CORRUPTION_BG);
              grid[x - (d/2)][y - (d/2)].fg -= RGB(fg, fg, fg);
              grid[x - (d/2)][y - (d/2)].bg -= RGB(bg, bg, bg);
            }

          }

        }
        _ => {}
      }
    }

  }

  pub fn add_viscera(x: usize, y: usize, d: usize, grid: &mut Grid<Tile>) {
    for i in 0..d {
      for j in 0..d {
        Stain::stain_linear(x + i, y + j, d, grid, 2, StainType::Viscera);
      }
    }
  }

    pub fn add_moss(x: usize, y: usize, d: usize, grid: &mut Grid<Tile>) {
    for i in 0..d {
      for j in 0..d {
        Stain::stain_linear(x + i, y + j, d, grid, 2, StainType::Moss);
      }
    }
  }

    pub fn add_fungus(x: usize, y: usize, d: usize, grid: &mut Grid<Tile>) {
    for i in 0..d {
      for j in 0..d {
        Stain::stain_linear(x + i, y + j, d, grid, 3, StainType::Fungus);
      }
    }
  }

  pub fn add_corruption(x: usize, y: usize, d: usize, grid: &mut Grid<Tile>) {
    for i in 0..d {
      for j in 0..d {
        Stain::stain_linear(x + i, y + j, d, grid, 1, StainType::Corruption);
      }
    }
  }

  ///
  /// Return a new `Stain`
  ///
  pub fn new() -> Self {
    Stain {}
  }

}

impl Filter for Stain {

  type Output = Tile;

  fn apply(&mut self, grid: &mut Grid<Self::Output>) {

    debugln!("stain", "spreading gore randomly...");

    let mut rng = rand::thread_rng();

    // Generate moss
    for _ in 0..rng.gen_range(1, 3) {

      // Get a random x y
      let x = rng.gen_range(15, grid.width() - 15 - 1);
      let y = rng.gen_range(15, grid.height() - 15 - 1);

      Stain::add_moss(x, y, 15, grid);

    }

    // Generate fungus
    for _ in 0..rng.gen_range(1, 3) {

      // Get a random x y
      let x = rng.gen_range(7, grid.width() - 7 - 1);
      let y = rng.gen_range(7, grid.height() - 7 - 1);

      Stain::add_fungus(x, y, 7, grid);

    }

    // Generate corruption
    for _ in 0..1 {

      // Get a random x y
      let x = rng.gen_range(9, grid.width() - 9 - 1);
      let y = rng.gen_range(9, grid.height() - 9 - 1);

      Stain::add_corruption(x, y, 9, grid);

    }

    // Generate blood stains
    for _ in 0..rng.gen_range(0, 2) {

      // Get a random x y
      let x = rng.gen_range(VISCERA_DIAMETER, grid.width() - VISCERA_DIAMETER - 1);
      let y = rng.gen_range(VISCERA_DIAMETER, grid.height() - VISCERA_DIAMETER - 1);

      Stain::add_viscera(x, y, VISCERA_DIAMETER, grid);

    }

  }

}<|endoftext|>


<commit_before><commit_msg>Test that autoref'ing beyond method receivers does not leak into two-phase borrows.<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// revisions: lxl nll g2p
//[lxl]compile-flags: -Z borrowck=mir -Z two-phase-borrows
//[nll]compile-flags: -Z borrowck=mir -Z two-phase-borrows -Z nll
//[g2p]compile-flags: -Z borrowck=mir -Z two-phase-borrows -Z nll -Z two-phase-beyond-autoref

#![feature(rustc_attrs)]

// This is a test checking that when we limit two-phase borrows to
// method receivers, we do not let other kinds of auto-ref to leak
// through.
//
// The g2p revision illustrates the "undesirable" behavior you would
// otherwise observe without limiting the phasing to autoref on method
// receivers (namely, that the test would pass).

fn bar(x: &mut u32) {
    foo(x, *x);
    //[lxl]~^ ERROR cannot use `*x` because it was mutably borrowed [E0503]
    //[nll]~^^ ERROR cannot use `*x` because it was mutably borrowed [E0503]
}

fn foo(x: &mut u32, y: u32) {
    *x += y;
}

#[rustc_error]
fn main() { //[g2p]~ ERROR compilation successful
    bar(&mut 5);
}
<|endoftext|>


<commit_before><commit_msg>Add tests for efloats<commit_after>extern crate rustracer as rt;
extern crate rand;
extern crate ieee754;

use rand::{Rng, StdRng, SeedableRng};
use ieee754::Ieee754;

use rt::efloat::EFloat;

const NUM_ITER: usize = 10000;

/// Return an exponentially distributed floating-point value
#[cfg(test)]
fn get_float<T: Rng>(rng: &mut T, min_exp: f32, max_exp: f32) -> EFloat {
    let logu: f32 = rng.gen_range(min_exp, max_exp);
    let val = (10.0_f32).powf(logu);

    let err: f32 = match rng.gen_range(0, 4) {
        0 => 0.0,
        1 => {
            let ulp_err: u32 = rng.gen_range(0, 1024);
            let offset: f32 = Ieee754::from_bits(val.bits() + ulp_err);
            (offset - val).abs()
        }
        2 => {
            let ulp_err: u32 = rng.gen_range(0, 1024 * 1024);
            let offset: f32 = Ieee754::from_bits(val.bits() + ulp_err);
            (offset - val).abs()
        }
        3 => (4.0 * rng.next_f32()) * val.abs(),
        _ => panic!("should not happen"),
    };
    let sign = if rng.next_f32() < 0.5 { -1.0 } else { 1.0 };
    EFloat::new(sign * val, err)
}

#[cfg(test)]
fn get_precise<T: Rng>(ef: &EFloat, rng: &mut T) -> f64 {
    match rng.gen_range(0, 3) {
        0 => ef.lower_bound() as f64,
        1 => ef.upper_bound() as f64,
        2 => {
            let t = rng.next_f64();
            let p: f64 = (1.0 - t) * ef.lower_bound() as f64 + t * ef.upper_bound() as f64;
            if p > ef.upper_bound() as f64 {
                ef.upper_bound() as f64
            } else if p < ef.lower_bound() as f64 {
                ef.lower_bound() as f64
            } else {
                p
            }
        }
        _ => panic!("should not happen"),
    }
}

#[test]
fn test_efloat_abs() {
    let mut rng = StdRng::from_seed(&[0]);
    for trial in 0..NUM_ITER {
        rng.reseed(&[trial]);
        let ef = get_float(&mut rng, -6.0, 6.0);
        let precise = get_precise(&ef, &mut rng);

        let result = ef.abs();
        let precise_result = precise.abs();

        assert!(precise_result >= result.lower_bound() as f64);
        assert!(precise_result <= result.upper_bound() as f64);
    }
}

#[test]
fn test_efloat_sqrt() {
    let mut rng = StdRng::from_seed(&[0]);
    for trial in 0..NUM_ITER {
        rng.reseed(&[trial]);
        let ef = get_float(&mut rng, -6.0, 6.0);
        let precise = get_precise(&ef, &mut rng);

        let result = ef.abs();
        let precise_result = precise.abs();

        assert!(precise_result >= result.lower_bound() as f64);
        assert!(precise_result <= result.upper_bound() as f64);
    }
}

#[test]
fn test_efloat_add() {
    let mut rng = StdRng::from_seed(&[0]);
    for trial in 0..NUM_ITER {
        rng.reseed(&[trial]);
        let a = get_float(&mut rng, -6.0, 6.0);
        let b = get_float(&mut rng, -6.0, 6.0);
        let ap = get_precise(&a, &mut rng);
        let bp = get_precise(&b, &mut rng);

        let result = a + b;
        let precise_result = ap + bp;

        assert!(precise_result >= result.lower_bound() as f64);
        assert!(precise_result <= result.upper_bound() as f64);
    }
}

#[test]
fn test_efloat_sub() {
    let mut rng = StdRng::from_seed(&[0]);
    for trial in 0..NUM_ITER {
        rng.reseed(&[trial]);
        let a = get_float(&mut rng, -6.0, 6.0);
        let b = get_float(&mut rng, -6.0, 6.0);
        let ap = get_precise(&a, &mut rng);
        let bp = get_precise(&b, &mut rng);

        let result = a - b;
        let precise_result = ap - bp;

        assert!(precise_result >= result.lower_bound() as f64);
        assert!(precise_result <= result.upper_bound() as f64);
    }
}

#[test]
fn test_efloat_mul() {
    let mut rng = StdRng::from_seed(&[0]);
    for trial in 0..NUM_ITER {
        rng.reseed(&[trial]);
        let a = get_float(&mut rng, -6.0, 6.0);
        let b = get_float(&mut rng, -6.0, 6.0);
        let ap = get_precise(&a, &mut rng);
        let bp = get_precise(&b, &mut rng);

        let result = a * b;
        let precise_result = ap * bp;

        assert!(precise_result >= result.lower_bound() as f64);
        assert!(precise_result <= result.upper_bound() as f64);
    }
}

#[test]
fn test_efloat_div() {
    let mut rng = StdRng::from_seed(&[0]);
    for trial in 0..NUM_ITER {
        rng.reseed(&[trial]);
        let a = get_float(&mut rng, -6.0, 6.0);
        let b = get_float(&mut rng, -6.0, 6.0);
        let ap = get_precise(&a, &mut rng);
        let bp = get_precise(&b, &mut rng);

        let result = a / b;
        let precise_result = ap / bp;

        assert!(precise_result >= result.lower_bound() as f64);
        assert!(precise_result <= result.upper_bound() as f64);
    }
}
<|endoftext|>


<commit_before><commit_msg>simple example of multiple types of agents<commit_after>//! Simple example of multiple types of agents.
//! You can use an enum, where each variant is a different type of agent.
//! Here we're just using fields on enum variants for state, but you could also define separate
//! state structs that you wrap enum variants around.

extern crate djinn;
extern crate redis;
extern crate redis_cluster;
extern crate rustc_serialize;

use std::thread;
use redis::{Commands, Client};
use djinn::{Agent, Manager, Simulation, Population, Worker, Uuid};

#[derive(RustcDecodable, RustcEncodable, Debug, PartialEq, Clone)]
pub enum MyState {
    Person { name: String, health: isize },
    Cat { name: String, purrs: usize },
}

#[derive(RustcDecodable, RustcEncodable, Debug, PartialEq, Clone)]
pub struct MyWorld {
    weather: String,
}

#[derive(RustcDecodable, RustcEncodable, Debug, PartialEq, Clone)]
pub enum MyUpdate {
    ChangeName(String),
    ChangeHealth(isize),
    Purr,
}

#[derive(Clone)]
pub struct MySimulation;

impl Simulation for MySimulation {
    type State = MyState;
    type Update = MyUpdate;
    type World = MyWorld;

    fn setup<C: Commands>(&self,
                          agent: Agent<Self::State>,
                          population: &Population<Self, C>)
                          -> () {
    }

    fn decide<C: Commands>(&self,
                           agent: Agent<Self::State>,
                           world: Self::World,
                           population: &Population<Self, C>)
                           -> Vec<(Uuid, Self::Update)> {
        let mut updates = Vec::new();
        match agent.state {
            MyState::Person { name, health } => {
                updates.push((agent.id, MyUpdate::ChangeHealth(-1)));
            }
            MyState::Cat { .. } => updates.push((agent.id, MyUpdate::Purr)),
        }
        updates
    }

    fn update(&self, state: Self::State, updates: Vec<Self::Update>) -> Self::State {
        let mut state = state.clone();
        for update in updates {
            match state {
                MyState::Cat { name, purrs } => {
                    state = self.update_cat(name, purrs, update);
                }
                MyState::Person { name, health } => {
                    state = self.update_person(name, health, update);
                }
            }
        }
        state
    }
}

impl MySimulation {
    fn update_cat(&self, name: String, purrs: usize, update: MyUpdate) -> MyState {
        match update {
            MyUpdate::Purr => {
                MyState::Cat {
                    name: name,
                    purrs: purrs + 1,
                }
            }
            _ => {
                MyState::Cat {
                    name: name,
                    purrs: purrs,
                }
            }
        }
    }

    fn update_person(&self, name: String, health: isize, update: MyUpdate) -> MyState {
        match update {
            MyUpdate::ChangeHealth(change) => {
                MyState::Person {
                    name: name,
                    health: health + change,
                }
            }
            _ => {
                MyState::Person {
                    name: name,
                    health: health,
                }
            }
        }
    }
}

fn main() {
    let person = MyState::Person {
        name: "hello".to_string(),
        health: 100,
    };
    let cat = MyState::Cat {
        name: "goodbye".to_string(),
        purrs: 0,
    };

    let sim = MySimulation {};
    let world = MyWorld { weather: "sunny".to_string() };

    // Setup the manager
    let addr = "redis://127.0.0.1/";
    let pop_client = Client::open(addr).unwrap();
    let mut manager = Manager::new(addr, pop_client, sim, world);

    // Spawn the population
    manager.population.spawn(person.clone());
    let id = manager.population.spawn(cat.clone());
    assert_eq!(manager.population.count(), 2);

    // Create a worker on a separate thread
    let worker_t = thread::spawn(move || {
        let sim = MySimulation {};
        let pop_client = Client::open(addr).unwrap();
        let worker = Worker::new(addr, pop_client, sim);
        worker.start();
    });

    let n_steps = 10;

    // Run the manager on a separate thread
    let manager_t = thread::spawn(move || {
        manager.run(n_steps);
        manager
    });

    manager = manager_t.join().unwrap();
    worker_t.join().unwrap();

    // Check that things are working
    let agent = match manager.population.get_agent(id) {
        Some(a) => a,
        None => panic!("Couldn't find the agent"),
    };
    println!("{:?}", agent);
}
<|endoftext|>


<commit_before><commit_msg>docs(examples): add example covering custom enums<commit_after><|endoftext|>


<commit_before><commit_msg>I'm not sure if I agree with these warnings or not!<commit_after>// warning: module `ʷE` should have a snake case name such as `ʷ_e`, #[warn(non_snake_case)] on by default
// warning: module `U` should have a snake case name such as `u`, #[warn(non_snake_case)] on by default
// warning: module `Ê̷ç̫Úʿᾈ` should have a snake case name such as `ê̷ç̫_úʿᾈ`, #[warn(non_snake_case)] on by default
#![feature(non_ascii_idents)]
  /* ᛭ĉþɍɅ */ //
 mod kʱ {  mod ʷE {  }  }  mod U {  mod Ê̷ç̫Úʿᾈ {  }  }
<|endoftext|>


<commit_before><commit_msg>Ugly implementation of printenv.<commit_after><|endoftext|>


<commit_before><commit_msg>Add TODO item<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #4<commit_after>use std;

fn to_palindromic(n: u64, dup_flag: bool) -> u64 {
    let cs = str::chars(u64::to_str(n, 10u));
    let s = str::from_chars(
        if dup_flag { cs + vec::tail(vec::reversed(cs)) } else { cs + vec::reversed(cs) }
    );
    alt u64::from_str(s, 10u) {
      none    { fail }
      some(x) { ret x }
    }
}

fn div_ceil(a: u64, b: u64) -> u64 {
    let d = a / b;
    ret if a % b != 0u64 { d + 1u64 } else { d };
}

fn dividable_pairs(num: u64, min: u64, max: u64) -> [(u64, u64)] {
    let div = u64::max(div_ceil(num, max), min);
    let result = [];
    while div * div <= num {
        if num % div == 0u64 {
            result += [(div, num / div)];
        }
        div += 1u64;
    }
    ret result;
}

fn main() {
    let dup_flag = false;
    while true {
        let seed = 999u64;
        while (seed >= 100u64) {
            let num = to_palindromic(seed, dup_flag);
            let pairs = dividable_pairs(num, 100u64, 999u64);
            if vec::is_not_empty(pairs) {
                std::io::print(#fmt("%u", num));
                for (d1, d2) in pairs {
                    std::io::print(#fmt(" = %u * %u", d1, d2));
                }
                std::io::print("\n");
            }
            seed -= 1u64;
        }
        if (!dup_flag) {
            dup_flag = true;
        } else {
            break
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add problem #24<commit_after>extern mod std;
extern mod euler;

use either::{ Either, Left, Right };
use cmp::{ Eq, Ord };
use to_bytes::{ IterBytes };
use hash::{ Hash };

use std::map::{ HashMap, hash_from_vec };
use std::sort::{ quick_sort };

use euler::calc::{ histogram, num_of_permutations };

fn get_at<T: Eq Ord IterBytes Hash Const Copy>(hist: HashMap<T, uint>, n: uint) -> Either<uint, ~[T]> {
    if hist.size() == 0 {
        return if n == 1 { Right(~[]) } else { Left(0) }
    }

    let perm = num_of_permutations(hist);
    if perm < n { return Left(perm); }

    let mut kv = ~[];
    for hist.each |k, v| { kv += [(k, v)]; }
    quick_sort(|a, b| a.first() <= b.first(), kv);

    let mut idx = 0;
    for kv.eachi |i, tp| {
        let &(k, v) = tp;
        let new_hist = if v > 1 {
            hash_from_vec(vec::slice(kv, 0, i) + [(k, v - 1)] + vec::view(kv, i + 1, kv.len()))
        } else {
            hash_from_vec(vec::slice(kv, 0, i) + vec::view(kv, i + 1, kv.len()))
        };

        match get_at(new_hist, n - idx) {
            Left(cnt) => idx += cnt,
            Right(ans) => return Right(~[k] + ans)
        }
    }

    util::unreachable();
}

fn main() {
    let nums = histogram(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
    io::println(fmt!("%?", either::unwrap_right(get_at(nums, 1000000))));
}<|endoftext|>


<commit_before><commit_msg>2019: Day 6, part 2.<commit_after>use std::collections::HashMap;
use std::io;
use std::io::BufRead;
use std::iter;

type Satellite = String;
type Orbits = HashMap<Satellite, Satellite>;
type Distance = usize;

fn main() -> io::Result<()> {
    let orbits: Orbits = io::BufReader::new(io::stdin())
        .lines()
        .map(|input| {
            input.map(|line| {
                let splits = line.split(")").collect::<Vec<&str>>();
                (splits[1].to_string(), splits[0].to_string())
            })
        })
        .collect::<io::Result<_>>()?;

    let transfers = distance("YOU", "SAN", &orbits) - 2;
    println!("{}", transfers);

    Ok(())
}

fn distance(start: &str, end: &str, orbits: &Orbits) -> Distance {
    let start_ancestors = ancestors(start, orbits).collect::<Vec<_>>();
    let end_ancestors = ancestors(end, orbits).collect::<Vec<_>>();
    let common_ancestor = start_ancestors
        .iter()
        .find(|ancestor| end_ancestors.contains(ancestor))
        .unwrap();
    let distance_from_start_to_common_ancestor = start_ancestors
        .iter()
        .position(|ancestor| ancestor == common_ancestor)
        .unwrap()
        + 1;
    let distance_from_common_ancestor_to_end = end_ancestors
        .iter()
        .position(|ancestor| ancestor == common_ancestor)
        .unwrap()
        + 1;
    return distance_from_start_to_common_ancestor + distance_from_common_ancestor_to_end;
}

fn ancestors(satellite: &str, orbits: &Orbits) -> Box<dyn Iterator<Item = Satellite>> {
    match orbits.get(satellite) {
        Some(next) => Box::new(iter::once(next.to_string()).chain(ancestors(next, orbits))),
        None => Box::new(iter::empty()),
    }
}
<|endoftext|>


<commit_before><commit_msg>unbreak BTree::{ stem_size, leaf_size }<commit_after><|endoftext|>


<commit_before><commit_msg>Add a utility for printing out a table of bytes<commit_after>pub fn print_byte_table<'a, T: Iterator<&'a u8>>(iter: T) {
    print!("    ");
    for x in range::<u8>(0, 16) {
        print!("  {:02x}", x);

        if x == 15 {
            print!("\n");
        }
    }

    for (i, value) in iter.enumerate() {
        if i % 16 == 0 {
            if i > 0 {
                println!("");
            }
            print!("{:04x}", i);
        }
        print!("  {:02x}", *value);
    }

    println!("\n");
}
<|endoftext|>


<commit_before><commit_msg>Fix(config): fix nasty bug where a path with embedded quotes was being added as a native path<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing source file. Ahem.<commit_after>use etcd;
use std::thread;
use std::fmt;
use std::time::Duration;
use std::sync::Arc;
use std::collections::BTreeMap;
use rustc_serialize::json;
use rustc_serialize::{Decodable,Encodable};

pub struct ConfigClient<T> {
    client: Arc<InnerClient<T>>,
    lease_mgr: thread::JoinHandle<()>,
    watcher: thread::JoinHandle<()>,
}

#[derive(Clone,Debug, Default)]
pub struct ConfigurationView<T> {
    this_node: String,
    members: BTreeMap<String, T>,
}

struct InnerClient<T> {
    etcd: etcd::Client,
    data: T,
    lease_time: Duration,
    callback: Box<Fn(ConfigurationView<T>) + Send + Sync + 'static>,
}

impl<T: 'static + Decodable + Encodable + fmt::Debug + Eq + Clone + Send + Sync> ConfigClient<T> {
    pub fn new<F: Fn(ConfigurationView<T>) + Send + Sync + 'static>(addr: &str, data: T, lease_time: Duration, callback: F)
        -> Result<ConfigClient<T>, ()> {
        let etcd = etcd::Client::new(addr).expect("etcd client");
        let client = Arc::new(InnerClient {
            etcd: etcd,
            data: data,
            lease_time: lease_time,
            callback: Box::new(callback),
        });
        client.setup();

        let lease_mgr = { let client = client.clone();
            thread::Builder::new().name("etcd config".to_string()).spawn(move || {
                client.run_lease()
            }).expect("etcd thread")
        };
        let watcher = {
            let client = client.clone();
            thread::Builder::new().name("etcd watcher".to_string()).spawn(move || {
                client.run_watch()
            }).expect("etcd watcher")
        };
        Ok(ConfigClient { client: client, lease_mgr: lease_mgr, watcher: watcher })
    }
}

const DIR : &'static str = "/chain";
const KEY_EXISTS : u64 = 105;

impl<T: Decodable + Encodable + fmt::Debug + Eq + Clone> InnerClient<T> {

    fn setup(&self) {
        match self.etcd.create_dir(DIR, None) {
            Ok(res) => info!("Created dir: {}: {:?}: ", DIR, res),
            Err(etcd::Error::Etcd (ref e)) if e.error_code == KEY_EXISTS => info!("Dir exists: {:?}: ", DIR),
            Err(e) => panic!("Unexpected error creating {}: {:?}", DIR, e),
        }
    }

    fn run_lease(&self) {
        let node_id = (&self) as *const _ as usize;
        let myttl = Some(self.lease_time.as_secs());
        let pausetime = self.lease_time / 2;
        let myvalue = json::encode(&self.data).expect("json encode");
        let me = self.etcd.create_in_order(DIR, &myvalue, myttl).expect("Create unique node");
        info!("My node! {:?}", me);
        let mykey = me.node.key.expect("Key name");
        let mut index = me.node.modified_index;
        let mut next_index = me.node.modified_index.map(|x| x+1);

        let mut curr_members = BTreeMap::new();
        loop {
            let members = self.list_members();

            trace!("Members: {:?}", members);
            if curr_members != members {
                curr_members = members;
                info!("Membership change! {:?}", curr_members);
                (self.callback)(ConfigurationView { this_node: mykey.clone(), members: curr_members.clone() })
            }

            thread::sleep(pausetime);
            trace!("touch node: {:?}={:?}", mykey, myvalue);
            let res = self.etcd.compare_and_swap(&mykey, &myvalue, myttl, Some(&myvalue), index).expect("Update lease");
            trace!("Update: {:?}", res);
            index = res.node.modified_index;

        }
    }
    fn list_members(&self) -> BTreeMap<String, T> {
        let current_listing = self.etcd.get(DIR, true, true, true).expect("List members");
        trace!("Listing: {:?}", current_listing);
        current_listing.node.nodes.expect("Node listing").into_iter()
                .filter_map(|n|
                    if let (Some(k), Some(v)) = (n.key, n.value) {
                        Some((k, json::decode(&v).expect("decode json"))) } else { None })
                .collect::<BTreeMap<String, T>>()
    }
    fn run_watch(&self) {
        info!("Starting etcd watcher");

        let current_listing = self.etcd.get(DIR, true, true, true).expect("List members");
        debug!("Listing: {:?}", current_listing);
        let mut last_observed_index = current_listing.node.nodes.unwrap_or_else(|| Vec::new()).into_iter()
            .filter_map(|x| x.modified_index).max();

        loop {
            debug!("Awaiting for {} from {:?}", DIR, last_observed_index);
            let res = self.etcd.watch(DIR, last_observed_index, true).expect("watch");
            info!("Watch: {:?}", res);
            last_observed_index = res.node.modified_index.map(|x| x+1);
        }

    }
}

impl<T: Clone> ConfigurationView<T> {
    fn head_key(&self) -> Option<&str> {
        self.members.keys().next().map(|s| &**s)
    }

    pub fn should_listen_for_clients(&self) -> bool {
        self.head_key() == Some(&self.this_node)
    }
    pub fn should_listen_for_upstream(&self) -> bool {
        self.head_key() != Some(&self.this_node)
    }
    pub fn should_connect_downstream(&self) -> Option<T> {
        let next = self.members.iter().filter_map(|(k, v)| if *k > self.this_node { Some((k, v)) } else { None }).next();
        next.map(|(_, val)| val.clone())
    }
}
<|endoftext|>


<commit_before>use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use {Future, Wake, Tokens};
use token::AtomicTokens;
use executor::{DEFAULT, Executor};
use slot::Slot;

type Thunk = Box<Future<Item=(), Error=()>>;

struct Forget {
    slot: Slot<(Thunk, Arc<Forget>)>,
    registered: AtomicBool,
    tokens: AtomicTokens,
}

pub fn forget<T: Future>(t: T) {
    let thunk = ThunkFuture { inner: t.boxed() }.boxed();
    let forget = Arc::new(Forget {
        slot: Slot::new(None),
        registered: AtomicBool::new(false),
        tokens: AtomicTokens::all(),
    });
    _forget(thunk, forget)
}

// FIXME(rust-lang/rust#34416) should just be able to use map/map_err, but that
//                             causes trans to go haywire.
struct ThunkFuture<T, E> {
    inner: Box<Future<Item=T, Error=E>>,
}

impl<T: Send + 'static, E: Send + 'static> Future for ThunkFuture<T, E> {
    type Item = ();
    type Error = ();

    fn poll(&mut self, tokens: &Tokens) -> Option<Result<(), ()>> {
        match self.inner.poll(tokens) {
            Some(Ok(_)) => Some(Ok(())),
            Some(Err(_)) => Some(Err(())),
            None => None,
        }
    }

    fn schedule(&mut self, wake: &Arc<Wake>) {
        self.inner.schedule(wake)
    }

    fn tailcall(&mut self) -> Option<Box<Future<Item=(), Error=()>>> {
        if let Some(f) = self.inner.tailcall() {
            self.inner = f;
        }
        None
    }
}

fn _forget(mut future: Thunk, forget: Arc<Forget>) {
    loop {
        // TODO: catch panics here?

        // Note that we need to poll at least once as the wake callback may have
        // received an empty set of tokens, but that's still a valid reason to
        // poll a future.
        if future.poll(&forget.tokens.get_tokens()).is_some() {
            return
        }
        future = match future.tailcall() {
            Some(f) => f,
            None => future,
        };
        if !forget.tokens.any() {
            break
        }
    }

    // Ok, we've seen that there are no tokens which show interest in the
    // future. Schedule interest on the future for when something is ready and
    // then relinquish the future and the forget back to the slot, which will
    // then pick it up once a wake callback has fired.
    //
    // TODO: can this clone() be removed?
    let forget2 = forget.clone();
    future.schedule(&(forget as Arc<Wake>));
    forget2.slot.try_produce((future, forget2.clone())).ok().unwrap();
}

impl Wake for Forget {
    fn wake(&self, tokens: &Tokens) {
        // First, add all our tokens provided into the shared token set.
        self.tokens.add(tokens);

        // Next, see if we can actually register an `on_full` callback. The
        // `Slot` requires that only one registration happens, and this flag
        // guards that.
        if self.registered.swap(true, Ordering::SeqCst) {
            return
        }

        // If we won the race to register a callback, do so now. Once the slot
        // is resolve we allow another registration **before we poll again**.
        // This allows any future which may be somewhat badly behaved to be
        // compatible with this.
        //
        // TODO: this store of `false` should *probably* be before the
        //       `schedule` call in forget above, need to think it through.
        self.slot.on_full(|slot| {
            let (future, forget) = slot.try_consume().ok().unwrap();
            forget.registered.store(false, Ordering::SeqCst);
            DEFAULT.execute(|| _forget(future, forget));
        });
    }
}
<commit_msg>Store an alias to eliminate a clone()<commit_after>use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use {Future, Wake, Tokens};
use token::AtomicTokens;
use executor::{DEFAULT, Executor};
use slot::Slot;

type Thunk = Box<Future<Item=(), Error=()>>;

struct Forget {
    slot: Slot<(Thunk, Arc<Forget>, Arc<Wake>)>,
    registered: AtomicBool,
    tokens: AtomicTokens,
}

pub fn forget<T: Future>(t: T) {
    let thunk = ThunkFuture { inner: t.boxed() }.boxed();
    let forget = Arc::new(Forget {
        slot: Slot::new(None),
        registered: AtomicBool::new(false),
        tokens: AtomicTokens::all(),
    });
    _forget(thunk, forget.clone(), forget)
}

// FIXME(rust-lang/rust#34416) should just be able to use map/map_err, but that
//                             causes trans to go haywire.
struct ThunkFuture<T, E> {
    inner: Box<Future<Item=T, Error=E>>,
}

impl<T: Send + 'static, E: Send + 'static> Future for ThunkFuture<T, E> {
    type Item = ();
    type Error = ();

    fn poll(&mut self, tokens: &Tokens) -> Option<Result<(), ()>> {
        match self.inner.poll(tokens) {
            Some(Ok(_)) => Some(Ok(())),
            Some(Err(_)) => Some(Err(())),
            None => None,
        }
    }

    fn schedule(&mut self, wake: &Arc<Wake>) {
        self.inner.schedule(wake)
    }

    fn tailcall(&mut self) -> Option<Box<Future<Item=(), Error=()>>> {
        if let Some(f) = self.inner.tailcall() {
            self.inner = f;
        }
        None
    }
}

fn _forget(mut future: Thunk,
           forget: Arc<Forget>,
           wake: Arc<Wake>) {
    loop {
        // TODO: catch panics here?

        // Note that we need to poll at least once as the wake callback may have
        // received an empty set of tokens, but that's still a valid reason to
        // poll a future.
        if future.poll(&forget.tokens.get_tokens()).is_some() {
            return
        }
        future = match future.tailcall() {
            Some(f) => f,
            None => future,
        };
        if !forget.tokens.any() {
            break
        }
    }

    // Ok, we've seen that there are no tokens which show interest in the
    // future. Schedule interest on the future for when something is ready and
    // then relinquish the future and the forget back to the slot, which will
    // then pick it up once a wake callback has fired.
    future.schedule(&wake);
    forget.slot.try_produce((future, forget.clone(), wake)).ok().unwrap();
}

impl Wake for Forget {
    fn wake(&self, tokens: &Tokens) {
        // First, add all our tokens provided into the shared token set.
        self.tokens.add(tokens);

        // Next, see if we can actually register an `on_full` callback. The
        // `Slot` requires that only one registration happens, and this flag
        // guards that.
        if self.registered.swap(true, Ordering::SeqCst) {
            return
        }

        // If we won the race to register a callback, do so now. Once the slot
        // is resolve we allow another registration **before we poll again**.
        // This allows any future which may be somewhat badly behaved to be
        // compatible with this.
        //
        // TODO: this store of `false` should *probably* be before the
        //       `schedule` call in forget above, need to think it through.
        self.slot.on_full(|slot| {
            let (future, forget, wake) = slot.try_consume().ok().unwrap();
            forget.registered.store(false, Ordering::SeqCst);
            DEFAULT.execute(|| _forget(future, forget, wake));
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>slice: add binary search<commit_after><|endoftext|>


<commit_before>use std::convert::From;
use std::convert::Into;
use std::ops::DerefMut;
use std::ops::Deref;

use toml::Value;

use std::collections::BTreeMap;

use libimagstore::store::Store;
use libimagstore::storeid::StoreIdIterator;
use libimagstore::store::FileLockEntry;
use libimagstore::storeid::StoreId;
use libimagstore::error::StoreError;
use libimagstore::store::Entry;
use libimagstore::storeid::IntoStoreId;

use module_path::ModuleEntryPath;
use result::Result;
use error::CounterError as CE;
use error::CounterErrorKind as CEK;

pub type CounterName = String;

pub struct Counter<'a> {
    fle: FileLockEntry<'a>,
}

impl<'a> Counter<'a> {

    pub fn new(store: &Store, name: CounterName, init: i64) -> Result<Counter> {
        use std::ops::DerefMut;

        debug!("Creating new counter: '{}' with value: {}", name, init);
        let fle = {
            let mut lockentry = store.create(ModuleEntryPath::new(name.clone()).into_storeid());
            if lockentry.is_err() {
                return Err(CE::new(CEK::StoreWriteError, Some(Box::new(lockentry.err().unwrap()))));
            }
            let mut lockentry = lockentry.unwrap();

            {
                let mut entry  = lockentry.deref_mut();
                let mut header = entry.get_header_mut();
                let setres = header.set("counter", Value::Table(BTreeMap::new()));
                if setres.is_err() {
                    return Err(CE::new(CEK::StoreWriteError, Some(Box::new(setres.err().unwrap()))));
                }

                let setres = header.set("counter.name", Value::String(name));
                if setres.is_err() {
                    return Err(CE::new(CEK::StoreWriteError, Some(Box::new(setres.err().unwrap()))));
                }

                let setres = header.set("counter.value", Value::Integer(init));
                if setres.is_err() {
                    return Err(CE::new(CEK::StoreWriteError, Some(Box::new(setres.err().unwrap()))));
                }
            }

            lockentry
        };

        Ok(Counter { fle: fle })
    }

    pub fn inc(&mut self) -> Result<()> {
        let mut header = self.fle.deref_mut().get_header_mut();
        match header.read("counter.value") {
            Ok(Some(Value::Integer(i))) => {
                header.set("counter.value", Value::Integer(i + 1))
                    .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
                    .map(|_| ())
            },
            Err(e) => Err(CE::new(CEK::StoreReadError, Some(Box::new(e)))),
            _ => Err(CE::new(CEK::StoreReadError, None)),
        }
    }

    pub fn dec(&mut self) -> Result<()> {
        let mut header = self.fle.deref_mut().get_header_mut();
        match header.read("counter.value") {
            Ok(Some(Value::Integer(i))) => {
                header.set("counter.value", Value::Integer(i - 1))
                    .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
                    .map(|_| ())
            },
            Err(e) => Err(CE::new(CEK::StoreReadError, Some(Box::new(e)))),
            _ => Err(CE::new(CEK::StoreReadError, None)),
        }
    }

    pub fn reset(&mut self) -> Result<()> {
        let mut header = self.fle.deref_mut().get_header_mut();
        header.set("counter.value", Value::Integer(0))
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
            .map(|_| ())
    }

    pub fn set(&mut self, v: i64) -> Result<()> {
        let mut header = self.fle.deref_mut().get_header_mut();
        header.set("counter.value", Value::Integer(v))
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
            .map(|_| ())
    }

    pub fn name(&self) -> Result<CounterName> {
        let mut header = self.fle.deref().get_header();
        header.read("counter.name")
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
            .and_then(|v| {
                match v {
                    Some(Value::String(s)) => Ok(s),
                    _ => Err(CE::new(CEK::HeaderTypeError, None)),
                }
            })
    }

    pub fn value(&self) -> Result<i64> {
        let mut header = self.fle.deref().get_header();
        header.read("counter.value")
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
            .and_then(|v| {
                match v {
                    Some(Value::Integer(i)) => Ok(i),
                    _ => Err(CE::new(CEK::HeaderTypeError, None)),
                }
            })
    }

    pub fn load(name: CounterName, store: &Store) -> Result<Counter> {
        debug!("Loading counter: '{}'", name);
        match store.retrieve(ModuleEntryPath::new(name).into_storeid()) {
            Err(e) => Err(CE::new(CEK::StoreReadError, Some(Box::new(e)))),
            Ok(c)  => Ok(Counter { fle: c }),
        }
    }

    pub fn delete(name: CounterName, store: &Store) -> Result<()> {
        debug!("Deleting counter: '{}'", name);
        store.delete(ModuleEntryPath::new(name).into_storeid())
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
    }

    pub fn all_counters(store: &Store) -> Result<CounterIterator> {
        store.retrieve_for_module("counter")
            .map(|iter| CounterIterator::new(store, iter))
            .map_err(|e| CE::new(CEK::StoreReadError, Some(Box::new(e))))
    }

}

trait FromStoreId {
    fn from_storeid<'a>(&'a Store, StoreId) -> Result<Counter<'a>>;
}

impl<'a> FromStoreId for Counter<'a> {

    fn from_storeid<'b>(store: &'b Store, id: StoreId) -> Result<Counter<'b>> {
        debug!("Loading counter from storeid: '{:?}'", id);
        match store.retrieve(id) {
            Err(e) => Err(CE::new(CEK::StoreReadError, Some(Box::new(e)))),
            Ok(c)  => Ok(Counter { fle: c }),
        }
    }

}

pub struct CounterIterator<'a> {
    store: &'a Store,
    iditer: StoreIdIterator,
}

impl<'a> CounterIterator<'a> {

    pub fn new(store: &'a Store, iditer: StoreIdIterator) -> CounterIterator<'a> {
        CounterIterator {
            store: store,
            iditer: iditer,
        }
    }

}

impl<'a> Iterator for CounterIterator<'a> {
    type Item = Result<Counter<'a>>;

    fn next(&mut self) -> Option<Result<Counter<'a>>> {
        self.iditer
            .next()
            .map(|id| Counter::from_storeid(self.store, id))
    }

}

<commit_msg>Remove unused keyword "mut"<commit_after>use std::convert::From;
use std::convert::Into;
use std::ops::DerefMut;
use std::ops::Deref;

use toml::Value;

use std::collections::BTreeMap;

use libimagstore::store::Store;
use libimagstore::storeid::StoreIdIterator;
use libimagstore::store::FileLockEntry;
use libimagstore::storeid::StoreId;
use libimagstore::error::StoreError;
use libimagstore::store::Entry;
use libimagstore::storeid::IntoStoreId;

use module_path::ModuleEntryPath;
use result::Result;
use error::CounterError as CE;
use error::CounterErrorKind as CEK;

pub type CounterName = String;

pub struct Counter<'a> {
    fle: FileLockEntry<'a>,
}

impl<'a> Counter<'a> {

    pub fn new(store: &Store, name: CounterName, init: i64) -> Result<Counter> {
        use std::ops::DerefMut;

        debug!("Creating new counter: '{}' with value: {}", name, init);
        let fle = {
            let lockentry = store.create(ModuleEntryPath::new(name.clone()).into_storeid());
            if lockentry.is_err() {
                return Err(CE::new(CEK::StoreWriteError, Some(Box::new(lockentry.err().unwrap()))));
            }
            let mut lockentry = lockentry.unwrap();

            {
                let mut entry  = lockentry.deref_mut();
                let mut header = entry.get_header_mut();
                let setres = header.set("counter", Value::Table(BTreeMap::new()));
                if setres.is_err() {
                    return Err(CE::new(CEK::StoreWriteError, Some(Box::new(setres.err().unwrap()))));
                }

                let setres = header.set("counter.name", Value::String(name));
                if setres.is_err() {
                    return Err(CE::new(CEK::StoreWriteError, Some(Box::new(setres.err().unwrap()))));
                }

                let setres = header.set("counter.value", Value::Integer(init));
                if setres.is_err() {
                    return Err(CE::new(CEK::StoreWriteError, Some(Box::new(setres.err().unwrap()))));
                }
            }

            lockentry
        };

        Ok(Counter { fle: fle })
    }

    pub fn inc(&mut self) -> Result<()> {
        let mut header = self.fle.deref_mut().get_header_mut();
        match header.read("counter.value") {
            Ok(Some(Value::Integer(i))) => {
                header.set("counter.value", Value::Integer(i + 1))
                    .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
                    .map(|_| ())
            },
            Err(e) => Err(CE::new(CEK::StoreReadError, Some(Box::new(e)))),
            _ => Err(CE::new(CEK::StoreReadError, None)),
        }
    }

    pub fn dec(&mut self) -> Result<()> {
        let mut header = self.fle.deref_mut().get_header_mut();
        match header.read("counter.value") {
            Ok(Some(Value::Integer(i))) => {
                header.set("counter.value", Value::Integer(i - 1))
                    .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
                    .map(|_| ())
            },
            Err(e) => Err(CE::new(CEK::StoreReadError, Some(Box::new(e)))),
            _ => Err(CE::new(CEK::StoreReadError, None)),
        }
    }

    pub fn reset(&mut self) -> Result<()> {
        let mut header = self.fle.deref_mut().get_header_mut();
        header.set("counter.value", Value::Integer(0))
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
            .map(|_| ())
    }

    pub fn set(&mut self, v: i64) -> Result<()> {
        let mut header = self.fle.deref_mut().get_header_mut();
        header.set("counter.value", Value::Integer(v))
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
            .map(|_| ())
    }

    pub fn name(&self) -> Result<CounterName> {
        self.fle.get_header().read("counter.name")
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
            .and_then(|v| {
                match v {
                    Some(Value::String(s)) => Ok(s),
                    _ => Err(CE::new(CEK::HeaderTypeError, None)),
                }
            })
    }

    pub fn value(&self) -> Result<i64> {
        self.fle.get_header().read("counter.value")
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
            .and_then(|v| {
                match v {
                    Some(Value::Integer(i)) => Ok(i),
                    _ => Err(CE::new(CEK::HeaderTypeError, None)),
                }
            })
    }

    pub fn load(name: CounterName, store: &Store) -> Result<Counter> {
        debug!("Loading counter: '{}'", name);
        match store.retrieve(ModuleEntryPath::new(name).into_storeid()) {
            Err(e) => Err(CE::new(CEK::StoreReadError, Some(Box::new(e)))),
            Ok(c)  => Ok(Counter { fle: c }),
        }
    }

    pub fn delete(name: CounterName, store: &Store) -> Result<()> {
        debug!("Deleting counter: '{}'", name);
        store.delete(ModuleEntryPath::new(name).into_storeid())
            .map_err(|e| CE::new(CEK::StoreWriteError, Some(Box::new(e))))
    }

    pub fn all_counters(store: &Store) -> Result<CounterIterator> {
        store.retrieve_for_module("counter")
            .map(|iter| CounterIterator::new(store, iter))
            .map_err(|e| CE::new(CEK::StoreReadError, Some(Box::new(e))))
    }

}

trait FromStoreId {
    fn from_storeid<'a>(&'a Store, StoreId) -> Result<Counter<'a>>;
}

impl<'a> FromStoreId for Counter<'a> {

    fn from_storeid<'b>(store: &'b Store, id: StoreId) -> Result<Counter<'b>> {
        debug!("Loading counter from storeid: '{:?}'", id);
        match store.retrieve(id) {
            Err(e) => Err(CE::new(CEK::StoreReadError, Some(Box::new(e)))),
            Ok(c)  => Ok(Counter { fle: c }),
        }
    }

}

pub struct CounterIterator<'a> {
    store: &'a Store,
    iditer: StoreIdIterator,
}

impl<'a> CounterIterator<'a> {

    pub fn new(store: &'a Store, iditer: StoreIdIterator) -> CounterIterator<'a> {
        CounterIterator {
            store: store,
            iditer: iditer,
        }
    }

}

impl<'a> Iterator for CounterIterator<'a> {
    type Item = Result<Counter<'a>>;

    fn next(&mut self) -> Option<Result<Counter<'a>>> {
        self.iditer
            .next()
            .map(|id| Counter::from_storeid(self.store, id))
    }

}

<|endoftext|>


<commit_before><commit_msg>Forgot that.<commit_after>pub mod output;
<|endoftext|>


<commit_before><commit_msg>Add terms for type ints in terms of pos bin nats<commit_after><|endoftext|>


<commit_before><commit_msg>Fix if/else, made use of defunct Value::Int<commit_after><|endoftext|>


<commit_before>use std::io::fs;
use std::io;
use std::os;

use colours::{Plain, Style, Black, Red, Green, Yellow, Blue, Purple, Cyan};
mod colours;

fn main() {
    match os::args().as_slice() {
        [] => unreachable!(),
        [_] => { list(Path::new(".")) },
        [_, ref p] => { list(Path::new(p.as_slice())) },
        _ => { fail!("args?") },
    }
}

enum Permissions {
    Permissions,
}

enum FileName {
    FileName,
}

struct FileSize {
    useSIPrefixes: bool,
}

trait Column {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str;
}

impl Column for FileName {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        file_colour(stat, filename).paint(filename.to_owned())
    }
}

impl Column for Permissions {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        let bits = stat.perm;
        return format!("{}{}{}{}{}{}{}{}{}{}",
            type_char(stat.kind),
            bit(bits, io::UserRead, ~"r", Yellow.bold()),
            bit(bits, io::UserWrite, ~"w", Red.bold()),
            bit(bits, io::UserExecute, ~"x", Green.bold().underline()),
            bit(bits, io::GroupRead, ~"r", Yellow.normal()),
            bit(bits, io::GroupWrite, ~"w", Red.normal()),
            bit(bits, io::GroupExecute, ~"x", Green.normal()),
            bit(bits, io::OtherRead, ~"r", Yellow.normal()),
            bit(bits, io::OtherWrite, ~"w", Red.normal()),
            bit(bits, io::OtherExecute, ~"x", Green.normal()),
       );
    }
}

impl Column for FileSize {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        let sizeStr = if self.useSIPrefixes {
            formatBytes(stat.size, 1024, ~[ "B  ", "KiB", "MiB", "GiB", "TiB" ])
        } else {
            formatBytes(stat.size, 1000, ~[ "B ", "KB", "MB", "GB", "TB" ])
        };

        return if stat.kind == io::TypeDirectory {
            Green.normal()
        } else {
            Green.bold()
        }.paint(sizeStr);
    }
}

fn formatBytes(mut amount: u64, kilo: u64, prefixes: ~[&str]) -> ~str {
    let mut prefix = 0;
    while amount > kilo {
        amount /= kilo;
        prefix += 1;
    }
    return format!("{:4}{}", amount, prefixes[prefix]);
}

// Each file is definitely going to get `stat`ted at least once, if
// only to determine what kind of file it is, so carry the `stat`
// result around with the file for safe keeping.
struct File<'a> {
    name: &'a str,
    path: &'a Path,
    stat: io::FileStat,
}

impl<'a> File<'a> {
    fn from_path(path: &'a Path) -> File<'a> {
        let filename: &str = path.filename_str().unwrap();

        // We have to use lstat here instad of file.stat(), as it
        // doesn't follow symbolic links. Otherwise, the stat() call
        // will fail if it encounters a link that's target is
        // non-existent.
        let stat: io::FileStat = match fs::lstat(path) {
            Ok(stat) => stat,
            Err(e) => fail!("Couldn't stat {}: {}", filename, e),
        };

        return File { path: path, stat: stat, name: filename };
    }
}

fn list(path: Path) {
    let mut files = match fs::readdir(&path) {
        Ok(files) => files,
        Err(e) => fail!("readdir: {}", e),
    };
    files.sort_by(|a, b| a.filename_str().cmp(&b.filename_str()));
    for subpath in files.iter() {
        let file = File::from_path(subpath);

        let columns = ~[
            ~Permissions as ~Column,
            ~FileSize { useSIPrefixes: false } as ~Column,
            ~FileName as ~Column
        ];

        let mut cells = columns.iter().map(|c| c.display(&file.stat, file.name));

        let mut first = true;
        for cell in cells {
            if first {
                first = false;
            } else {
                print!(" ");
            }
            print!("{}", cell);
        }
        print!("\n");
    }
}

fn file_colour(stat: &io::FileStat, filename: &str) -> Style {
    if stat.kind == io::TypeDirectory {
        Blue.normal()
    } else if stat.perm & io::UserExecute == io::UserExecute {
        Green.normal()
    } else if filename.ends_with("~") {
        Black.bold()
    } else {
        Plain
    }
}

fn bit(bits: u32, bit: u32, other: ~str, style: Style) -> ~str {
    if bits & bit == bit {
        style.paint(other)
    } else {
        Black.bold().paint(~"-")
    }
}

fn type_char(t: io::FileType) -> ~str {
    return match t {
        io::TypeFile => ~".",
        io::TypeDirectory => Blue.paint("d"),
        io::TypeNamedPipe => Yellow.paint("|"),
        io::TypeBlockSpecial => Purple.paint("s"),
        io::TypeSymlink => Cyan.paint("l"),
        _ => ~"?",
    }
}
<commit_msg>Add --all command-line option<commit_after>extern crate getopts;
use std::io::fs;
use std::io;
use std::os;

use colours::{Plain, Style, Black, Red, Green, Yellow, Blue, Purple, Cyan};
mod colours;

struct Options {
    showInvisibles: bool,
}

fn main() {
    let args = os::args();
    let program = args[0].as_slice();
    let opts = ~[
        getopts::optflag("a", "all", "show dot-files")
    ];

    let matches = match getopts::getopts(args.tail(), opts) {
        Ok(m) => m,
        Err(f) => {
            fail!("Invalid options\n{}", f.to_err_msg());
            return
        }
    };

    let opts = Options {
        showInvisibles: matches.opt_present("all")
    };

    let strs = if matches.free.is_empty() {vec!(~"./")} else {matches.free.clone()};

    for dir in strs.move_iter() {
        list(opts, Path::new(dir))
    }
}

enum Permissions {
    Permissions,
}

enum FileName {
    FileName,
}

struct FileSize {
    useSIPrefixes: bool,
}

trait Column {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str;
}

impl Column for FileName {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        file_colour(stat, filename).paint(filename.to_owned())
    }
}

impl Column for Permissions {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        let bits = stat.perm;
        return format!("{}{}{}{}{}{}{}{}{}{}",
            type_char(stat.kind),
            bit(bits, io::UserRead, ~"r", Yellow.bold()),
            bit(bits, io::UserWrite, ~"w", Red.bold()),
            bit(bits, io::UserExecute, ~"x", Green.bold().underline()),
            bit(bits, io::GroupRead, ~"r", Yellow.normal()),
            bit(bits, io::GroupWrite, ~"w", Red.normal()),
            bit(bits, io::GroupExecute, ~"x", Green.normal()),
            bit(bits, io::OtherRead, ~"r", Yellow.normal()),
            bit(bits, io::OtherWrite, ~"w", Red.normal()),
            bit(bits, io::OtherExecute, ~"x", Green.normal()),
       );
    }
}

impl Column for FileSize {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        let sizeStr = if self.useSIPrefixes {
            formatBytes(stat.size, 1024, ~[ "B  ", "KiB", "MiB", "GiB", "TiB" ])
        } else {
            formatBytes(stat.size, 1000, ~[ "B ", "KB", "MB", "GB", "TB" ])
        };

        return if stat.kind == io::TypeDirectory {
            Green.normal()
        } else {
            Green.bold()
        }.paint(sizeStr);
    }
}

fn formatBytes(mut amount: u64, kilo: u64, prefixes: ~[&str]) -> ~str {
    let mut prefix = 0;
    while amount > kilo {
        amount /= kilo;
        prefix += 1;
    }
    return format!("{:4}{}", amount, prefixes[prefix]);
}

// Each file is definitely going to get `stat`ted at least once, if
// only to determine what kind of file it is, so carry the `stat`
// result around with the file for safe keeping.
struct File<'a> {
    name: &'a str,
    path: &'a Path,
    stat: io::FileStat,
}

impl<'a> File<'a> {
    fn from_path(path: &'a Path) -> File<'a> {
        let filename: &str = path.filename_str().unwrap();

        // We have to use lstat here instad of file.stat(), as it
        // doesn't follow symbolic links. Otherwise, the stat() call
        // will fail if it encounters a link that's target is
        // non-existent.
        let stat: io::FileStat = match fs::lstat(path) {
            Ok(stat) => stat,
            Err(e) => fail!("Couldn't stat {}: {}", filename, e),
        };

        return File { path: path, stat: stat, name: filename };
    }
}

fn list(opts: Options, path: Path) {
    let mut files = match fs::readdir(&path) {
        Ok(files) => files,
        Err(e) => fail!("readdir: {}", e),
    };
    files.sort_by(|a, b| a.filename_str().cmp(&b.filename_str()));
    for subpath in files.iter() {
        let file = File::from_path(subpath);

        if file.name.starts_with(".") && !opts.showInvisibles {
            continue;
        }

        let columns = ~[
            ~Permissions as ~Column,
            ~FileSize { useSIPrefixes: false } as ~Column,
            ~FileName as ~Column
        ];

        let mut cells = columns.iter().map(|c| c.display(&file.stat, file.name));

        let mut first = true;
        for cell in cells {
            if first {
                first = false;
            } else {
                print!(" ");
            }
            print!("{}", cell);
        }
        print!("\n");
    }
}

fn file_colour(stat: &io::FileStat, filename: &str) -> Style {
    if stat.kind == io::TypeDirectory {
        Blue.normal()
    } else if stat.perm & io::UserExecute == io::UserExecute {
        Green.normal()
    } else if filename.ends_with("~") {
        Black.bold()
    } else {
        Plain
    }
}

fn bit(bits: u32, bit: u32, other: ~str, style: Style) -> ~str {
    if bits & bit == bit {
        style.paint(other)
    } else {
        Black.bold().paint(~"-")
    }
}

fn type_char(t: io::FileType) -> ~str {
    return match t {
        io::TypeFile => ~".",
        io::TypeDirectory => Blue.paint("d"),
        io::TypeNamedPipe => Yellow.paint("|"),
        io::TypeBlockSpecial => Purple.paint("s"),
        io::TypeSymlink => Cyan.paint("l"),
        _ => ~"?",
    }
}
<|endoftext|>


<commit_before><commit_msg>Create diamonds example<commit_after>use valora::prelude::*;
use itertools::iproduct;

fn main() -> Result<()> {
    run_fn(Options::from_args(), |_gpu, world, _rng| {
        Ok(move |ctx: Context, canvas: &mut Canvas| {
            canvas.set_color(LinSrgb::new(1., 1., 1.));
            canvas.paint(Filled(ctx.world));

            let sq_size = 400.;
            let bottom_left = world.center() - V2::new(sq_size / 2., sq_size / 2.);

            let grid_size = 10;
            let sq_size = sq_size / (grid_size as f32);
            iproduct!(0..grid_size, 0..grid_size).map(|(i, j)| {
                let x = sq_size * i as f32;
                let y = sq_size * j as f32;
                let shift_to_center = sq_size / 2.;
                let shift_to_center = V2::new(shift_to_center, shift_to_center);

                let center = bottom_left + P2::new(x, y).to_vector() + shift_to_center;
                (Ngon::diamond(center, sq_size / 3.), x + y)
            }).for_each(|(d, hue)| {
                canvas.set_color(Hsv::new(hue, 0.7, 0.8));
                canvas.paint(Filled(d));
            });
        })
    })
}
<|endoftext|>