<commit_before><commit_msg>Add some tests for indices handling<commit_after>#![feature(phase)]

#[phase(plugin)]
extern crate glium_macros;

extern crate glutin;
extern crate glium;

use std::default::Default;
use glium::Surface;

mod support;

fn build_program(display: &glium::Display) -> glium::Program {
    glium::Program::new(display,
        "
            #version 110

            attribute vec2 position;

            void main() {
                gl_Position = vec4(position, 0.0, 1.0);
            }
        ",
        "
            #version 110

            void main() {
                gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
            }
        ",
        None).unwrap()
}

#[vertex_format]
struct Vertex {
    position: [f32, ..2],
}

#[test]
fn triangles_list_cpu() {
    let display = support::build_display();
    let program = build_program(&display);

    let vb = glium::VertexBuffer::new(&display, vec![
        Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
        Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
    ]);

    let indices = glium::index_buffer::TrianglesList(vec![0u8, 1, 2, 2, 1, 3]);

    let mut target = display.draw();
    target.clear_color(0.0, 0.0, 0.0, 0.0);
    target.draw(&vb, &indices, &program, &glium::uniforms::EmptyUniforms, &Default::default());
    target.finish();

    let data: Vec<Vec<(u8, u8, u8)>> = display.read_front_buffer();

    assert_eq!(data[0][0], (255, 0, 0));
    assert_eq!(data.last().unwrap().last().unwrap(), &(255, 0, 0));
}

#[test]
fn triangle_strip_cpu() {
    let display = support::build_display();
    let program = build_program(&display);

    let vb = glium::VertexBuffer::new(&display, vec![
        Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
        Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
    ]);

    let indices = glium::index_buffer::TriangleStrip(vec![0u8, 1, 2, 3]);

    let mut target = display.draw();
    target.clear_color(0.0, 0.0, 0.0, 0.0);
    target.draw(&vb, &indices, &program, &glium::uniforms::EmptyUniforms, &Default::default());
    target.finish();

    let data: Vec<Vec<(u8, u8, u8)>> = display.read_front_buffer();

    assert_eq!(data[0][0], (255, 0, 0));
    assert_eq!(data.last().unwrap().last().unwrap(), &(255, 0, 0));
}

#[test]
fn triangles_list_gpu() {
    let display = support::build_display();
    let program = build_program(&display);

    let vb = glium::VertexBuffer::new(&display, vec![
        Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
        Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
    ]);

    let indices = glium::index_buffer::TrianglesList(vec![0u8, 1, 2, 2, 1, 3]);
    let indices = glium::IndexBuffer::new(&display, indices);

    let mut target = display.draw();
    target.clear_color(0.0, 0.0, 0.0, 0.0);
    target.draw(&vb, &indices, &program, &glium::uniforms::EmptyUniforms, &Default::default());
    target.finish();

    let data: Vec<Vec<(u8, u8, u8)>> = display.read_front_buffer();

    assert_eq!(data[0][0], (255, 0, 0));
    assert_eq!(data.last().unwrap().last().unwrap(), &(255, 0, 0));
}

#[test]
fn triangle_strip_gpu() {
    let display = support::build_display();
    let program = build_program(&display);

    let vb = glium::VertexBuffer::new(&display, vec![
        Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
        Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
    ]);

    let indices = glium::index_buffer::TriangleStrip(vec![0u8, 1, 2, 3]);
    let indices = glium::IndexBuffer::new(&display, indices);

    let mut target = display.draw();
    target.clear_color(0.0, 0.0, 0.0, 0.0);
    target.draw(&vb, &indices, &program, &glium::uniforms::EmptyUniforms, &Default::default());
    target.finish();

    let data: Vec<Vec<(u8, u8, u8)>> = display.read_front_buffer();

    assert_eq!(data[0][0], (255, 0, 0));
    assert_eq!(data.last().unwrap().last().unwrap(), &(255, 0, 0));
}
<|endoftext|>


<commit_before><commit_msg>FIX: unplug services api error<commit_after><|endoftext|>


<commit_before><commit_msg>[bonsai][Error] Add a file listing and documenting all the errors of the compiler. For now, it just serves for documentation purposes.<commit_after>// Copyright 2017 Pierre Talbot (IRCAM)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(non_snake_case)]

register_long_diagnostics! {
E0001: r##"Unknown bonsai module."##,
E0002: r##"Duplicate field in a module."##,
E0003: r##"Duplicate local variable in a process."##,
E0004: r##"Duplicate process in a module."##,
E0005: r##"`ref` variable occurrence in field initialization."##,
E0006: r##"Undeclared variable (local to the module)."##,
E0007: r##"Undeclared process (local to the module)."##,
E0008: r##"Access to an unknown field (external to the current module)."##,
E0009: r##"Invocation of an unknown process (external to the current module)."##,
E0010: r##"Process call on a foreign object (from the host language)."##,
E0011: r##"`ref` field must not be initialized."##,
E0012: r##"Multiple constructor in a module with `ref` fields."##,
E0013: r##"Missing constructor in a module with `ref` fields."##,
E0014: r##"Missing parameter initializing a `ref` field in the constructor of the module."##,
E0015: r##"Mismatch between constructor parameter and `ref` field of the module."##,
E0016: r##"Writing on a `pre` variable. For example: `pre x <- e`."##,
E0017: r##"Illegal kind of a variable under a `pre` operator."##,
E0018: r##"Local variables of kind `module` with `ref` fields must be instantiated with the `new` operator."##,
E0019: r##"Local variables of kind `module` must always be initialized."##,
E0020: r##"Illegal kind of `ref` field (must be of the `spacetime` kind)."##,
E0021: r##"Field of kind `module` where the module has `ref` fields must not be initialized."##,
E0022: r##"`ref` argument when calling a module constructor must be a variable."##,
E0023: r##"`ref` argument must match the type and kind of the called parameter's constructor."##,
E0024: r##"constructor parameter list and instantiation list differ in size."##,
}
<|endoftext|>


<commit_before><commit_msg>Forgot to compute mul tables for >4-bit constants<commit_after><|endoftext|>


<commit_before><commit_msg>alignment stuff<commit_after><|endoftext|>


<commit_before><commit_msg>Add forgotten try_msg macro<commit_after>#[macro_export]
macro_rules! try_msg {
    ($op:expr, $message:expr) => (
        try!(($op)
             .map_err(|e| format!($message, err=e)))
    );
    ($op:expr, $message:expr, $($key:ident=$value:expr)*) => (
        try!(($op)
             .map_err(|e| format!($message, err=e, $($key=$value),*)))
    );
}
<|endoftext|>


<commit_before><commit_msg>added expression parsing<commit_after><|endoftext|>


<commit_before>extern crate rusoto;
extern crate xml;

use xml::reader::*;
use rusoto::xmlutil::*;
use std::io::BufReader;
use std::fs::File;
use std::iter::Peekable;
use xml::reader::events::*;

#[test]
fn peek_at_name_happy_path() {
    let file = File::open("tests/sample-data/list_queues_with_queue.xml").unwrap();
    let file = BufReader::new(file);
    let mut my_parser  = EventReader::new(file);
    let my_stack = my_parser.events().peekable();
    let mut reader = XmlResponseFromFile::new(my_stack);

    loop {
        reader.next();
        match peek_at_name(&mut reader) {
            Ok(data) => {
                // println!("Got {}", data);
                if data == "QueueUrl" {
                    return;
                }
            }
            Err(_) => panic!("Couldn't peek at name")
        }
    }
}

// #[test]
// fn optional_string_field_happy_path() {
//     panic!("Not implemented");
// }
//
// #[test]
// fn string_field_happy_path() {
//     panic!("Not implemented");
// }
//
// #[test]
// fn characters_happy_path() {
//     panic!("Not implemented");
// }

#[test]
fn start_element_happy_path() {
    let file = File::open("tests/sample-data/list_queues_with_queue.xml").unwrap();
    let file = BufReader::new(file);
    let mut my_parser  = EventReader::new(file);
    let my_stack = my_parser.events().peekable();
    let mut reader = XmlResponseFromFile::new(my_stack);

    // skip two leading fields since we ignore them (xml declaration, return type declaration)
    reader.next();
    reader.next();

    match start_element("ListQueuesResult", &mut reader) {
        Ok(_) => println!("Got start"),
        Err(_) => panic!("Couldn't find start element")
    }
}

#[test]
fn end_element_happy_path() {
    let file = File::open("tests/sample-data/list_queues_with_queue.xml").unwrap();
    let file = BufReader::new(file);
    let mut my_parser  = EventReader::new(file);
    let my_stack = my_parser.events().peekable();
    let mut reader = XmlResponseFromFile::new(my_stack);

    // skip two leading fields since we ignore them (xml declaration, return type declaration)
    reader.next();
    reader.next();

    // TODO: this is fragile and not good: do some looping to find end element?
    // But need to do it without being dependent on peek_at_name.
    reader.next();
    reader.next();
    reader.next();
    reader.next();

    match end_element("ListQueuesResult", &mut reader) {
        Ok(_) => println!("Got end"),
        Err(_) => panic!("Couldn't find end element")
    }
}

pub struct XmlResponseFromFile<'a> {
	xml_stack: Peekable<Events<'a, BufReader<File>>>,
}

// I cannot explain how these lifetimes work to a child, therefore I need to understand them better:
impl <'a>XmlResponseFromFile<'a> {
	pub fn new<'c>(my_stack: Peekable<Events<'a, BufReader<File>>>) -> XmlResponseFromFile {
		return XmlResponseFromFile { xml_stack: my_stack };
	}
}

// Need peek and next implemented.
impl <'b> Peek for XmlResponseFromFile <'b> {
	fn peek(&mut self) -> Option<&XmlEvent> {
		return self.xml_stack.peek();
	}
}

impl <'b> Next for XmlResponseFromFile <'b> {
	fn next(&mut self) -> Option<XmlEvent> {
		return self.xml_stack.next();
	}
}
<commit_msg>Gets happy path unit testing done for the important xmlutils.<commit_after>extern crate rusoto;
extern crate xml;

use xml::reader::*;
use rusoto::xmlutil::*;
use std::io::BufReader;
use std::fs::File;
use std::iter::Peekable;
use xml::reader::events::*;

#[test]
fn peek_at_name_happy_path() {
    let file = File::open("tests/sample-data/list_queues_with_queue.xml").unwrap();
    let file = BufReader::new(file);
    let mut my_parser  = EventReader::new(file);
    let my_stack = my_parser.events().peekable();
    let mut reader = XmlResponseFromFile::new(my_stack);

    loop {
        reader.next();
        match peek_at_name(&mut reader) {
            Ok(data) => {
                // println!("Got {}", data);
                if data == "QueueUrl" {
                    return;
                }
            }
            Err(_) => panic!("Couldn't peek at name")
        }
    }
}

#[test]
fn start_element_happy_path() {
    let file = File::open("tests/sample-data/list_queues_with_queue.xml").unwrap();
    let file = BufReader::new(file);
    let mut my_parser  = EventReader::new(file);
    let my_stack = my_parser.events().peekable();
    let mut reader = XmlResponseFromFile::new(my_stack);

    // skip two leading fields since we ignore them (xml declaration, return type declaration)
    reader.next();
    reader.next();

    match start_element("ListQueuesResult", &mut reader) {
        Ok(_) => println!("Got start"),
        Err(_) => panic!("Couldn't find start element")
    }
}

#[test]
fn string_field_happy_path() {
    let file = File::open("tests/sample-data/list_queues_with_queue.xml").unwrap();
    let file = BufReader::new(file);
    let mut my_parser  = EventReader::new(file);
    let my_stack = my_parser.events().peekable();
    let mut reader = XmlResponseFromFile::new(my_stack);

    // skip two leading fields since we ignore them (xml declaration, return type declaration)
    reader.next();
    reader.next();

    reader.next(); // reader now at ListQueuesResult

    // now we're set up to use string:
    let my_chars = string_field("QueueUrl", &mut reader);
    println!("Got {} for string", my_chars.unwrap());
}

#[test]
fn end_element_happy_path() {
    let file = File::open("tests/sample-data/list_queues_with_queue.xml").unwrap();
    let file = BufReader::new(file);
    let mut my_parser  = EventReader::new(file);
    let my_stack = my_parser.events().peekable();
    let mut reader = XmlResponseFromFile::new(my_stack);

    // skip two leading fields since we ignore them (xml declaration, return type declaration)
    reader.next();
    reader.next();

    // TODO: this is fragile and not good: do some looping to find end element?
    // But need to do it without being dependent on peek_at_name.
    reader.next();
    reader.next();
    reader.next();
    reader.next();

    match end_element("ListQueuesResult", &mut reader) {
        Ok(_) => println!("Got end"),
        Err(_) => panic!("Couldn't find end element")
    }
}

pub struct XmlResponseFromFile<'a> {
	xml_stack: Peekable<Events<'a, BufReader<File>>>,
}

// I cannot explain how these lifetimes work to a child, therefore I need to understand them better:
impl <'a>XmlResponseFromFile<'a> {
	pub fn new<'c>(my_stack: Peekable<Events<'a, BufReader<File>>>) -> XmlResponseFromFile {
		return XmlResponseFromFile { xml_stack: my_stack };
	}
}

// Need peek and next implemented.
impl <'b> Peek for XmlResponseFromFile <'b> {
	fn peek(&mut self) -> Option<&XmlEvent> {
		return self.xml_stack.peek();
	}
}

impl <'b> Next for XmlResponseFromFile <'b> {
	fn next(&mut self) -> Option<XmlEvent> {
		return self.xml_stack.next();
	}
}
<|endoftext|>


<commit_before><commit_msg>(feat) Add a modifier for adding headers.<commit_after><|endoftext|>


<commit_before>// Copyright 2012 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.

//! A type representing either success or failure

#[allow(missing_doc)];

use clone::Clone;
use cmp::Eq;
use either;
use either::Either;
use iterator::IteratorUtil;
use option::{None, Option, Some};
use vec;
use vec::{OwnedVector, ImmutableVector};
use container::Container;

/// The result type
#[deriving(Clone, Eq)]
pub enum Result<T, U> {
    /// Contains the successful result value
    Ok(T),
    /// Contains the error value
    Err(U)
}

/**
 * Get the value out of a successful result
 *
 * # Failure
 *
 * If the result is an error
 */
#[inline]
pub fn get<T:Clone,U>(res: &Result<T, U>) -> T {
    match *res {
      Ok(ref t) => (*t).clone(),
      Err(ref the_err) =>
        fail!("get called on error result: %?", *the_err)
    }
}

/**
 * Get the value out of an error result
 *
 * # Failure
 *
 * If the result is not an error
 */
#[inline]
pub fn get_err<T, U: Clone>(res: &Result<T, U>) -> U {
    match *res {
      Err(ref u) => (*u).clone(),
      Ok(_) => fail!("get_err called on ok result")
    }
}

/**
 * Convert to the `either` type
 *
 * `ok` result variants are converted to `either::right` variants, `err`
 * result variants are converted to `either::left`.
 */
#[inline]
pub fn to_either<T:Clone,U:Clone>(res: &Result<U, T>)
    -> Either<T, U> {
    match *res {
      Ok(ref res) => either::Right((*res).clone()),
      Err(ref fail_) => either::Left((*fail_).clone())
    }
}

/**
 * Call a function based on a previous result
 *
 * If `res` is `ok` then the value is extracted and passed to `op` whereupon
 * `op`s result is wrapped in `ok` and returned. if `res` is `err` then it is
 * immediately returned.  This function can be used to compose the results of
 * two functions.
 *
 * Example:
 *
 *     let res = map(read_file(file)) { |buf|
 *         parse_bytes(buf)
 *     }
 */
#[inline]
pub fn map<T, E: Clone, U: Clone>(res: &Result<T, E>, op: &fn(&T) -> U)
  -> Result<U, E> {
    match *res {
      Ok(ref t) => Ok(op(t)),
      Err(ref e) => Err((*e).clone())
    }
}

/**
 * Call a function based on a previous result
 *
 * If `res` is `err` then the value is extracted and passed to `op` whereupon
 * `op`s result is wrapped in an `err` and returned. if `res` is `ok` then it
 * is immediately returned.  This function can be used to pass through a
 * successful result while handling an error.
 */
#[inline]
pub fn map_err<T:Clone,E,F:Clone>(res: &Result<T, E>, op: &fn(&E) -> F)
  -> Result<T, F> {
    match *res {
      Ok(ref t) => Ok((*t).clone()),
      Err(ref e) => Err(op(e))
    }
}

impl<T, E> Result<T, E> {
    /**
     * Get a reference to the value out of a successful result
     *
     * # Failure
     *
     * If the result is an error
     */
    #[inline]
    pub fn get_ref<'a>(&'a self) -> &'a T {
        match *self {
        Ok(ref t) => t,
        Err(ref the_err) =>
            fail!("get_ref called on error result: %?", *the_err)
        }
    }

    /// Returns true if the result is `ok`
    #[inline]
    pub fn is_ok(&self) -> bool {
        match *self {
            Ok(_) => true,
            Err(_) => false
        }
    }

    /// Returns true if the result is `err`
    #[inline]
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }

    /**
     * Call a function based on a previous result
     *
     * If `*self` is `ok` then the value is extracted and passed to `op` whereupon
     * `op`s result is returned. if `*self` is `err` then it is immediately
     * returned. This function can be used to compose the results of two
     * functions.
     *
     * Example:
     *
     *     read_file(file).iter() { |buf|
     *         print_buf(buf)
     *     }
     */
    #[inline]
    pub fn iter(&self, f: &fn(&T)) {
        match *self {
            Ok(ref t) => f(t),
            Err(_) => ()
        }
    }

    /**
     * Call a function based on a previous result
     *
     * If `*self` is `err` then the value is extracted and passed to `op` whereupon
     * `op`s result is returned. if `*self` is `ok` then it is immediately returned.
     * This function can be used to pass through a successful result while
     * handling an error.
     */
    #[inline]
    pub fn iter_err(&self, f: &fn(&E)) {
        match *self {
            Ok(_) => (),
            Err(ref e) => f(e)
        }
    }

    /// Unwraps a result, assuming it is an `ok(T)`
    #[inline]
    pub fn unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(_) => fail!("unwrap called on an err result")
        }
    }

    /// Unwraps a result, assuming it is an `err(U)`
    #[inline]
    pub fn unwrap_err(self) -> E {
        match self {
            Err(u) => u,
            Ok(_) => fail!("unwrap called on an ok result")
        }
    }

    /**
     * Call a function based on a previous result
     *
     * If `self` is `ok` then the value is extracted and passed to `op` whereupon
     * `op`s result is returned. if `self` is `err` then it is immediately
     * returned. This function can be used to compose the results of two
     * functions.
     *
     * Example:
     *
     *     let res = read_file(file).chain(op) { |buf|
     *         ok(parse_bytes(buf))
     *     }
     */
    #[inline]
    pub fn chain<U>(self, op: &fn(T) -> Result<U,E>) -> Result<U,E> {
        match self {
            Ok(t) => op(t),
            Err(e) => Err(e)
        }
    }

    /**
    * Call a function based on a previous result
    *
    * If `self` is `err` then the value is extracted and passed to `op`
    * whereupon `op`s result is returned. if `self` is `ok` then it is
    * immediately returned.  This function can be used to pass through a
    * successful result while handling an error.
    */
    #[inline]
    pub fn chain_err<F>(self, op: &fn(E) -> Result<T,F>) -> Result<T,F> {
        match self {
            Ok(t) => Ok(t),
            Err(v) => op(v)
        }
    }
}

impl<T:Clone,E> Result<T, E> {
    #[inline]
    pub fn get(&self) -> T { get(self) }

    #[inline]
    pub fn map_err<F:Clone>(&self, op: &fn(&E) -> F) -> Result<T,F> {
        map_err(self, op)
    }
}

impl<T, E:Clone> Result<T, E> {
    #[inline]
    pub fn get_err(&self) -> E { get_err(self) }

    #[inline]
    pub fn map<U:Clone>(&self, op: &fn(&T) -> U) -> Result<U,E> {
        map(self, op)
    }
}

/**
 * Maps each element in the vector `ts` using the operation `op`.  Should an
 * error occur, no further mappings are performed and the error is returned.
 * Should no error occur, a vector containing the result of each map is
 * returned.
 *
 * Here is an example which increments every integer in a vector,
 * checking for overflow:
 *
 *     fn inc_conditionally(x: uint) -> result<uint,str> {
 *         if x == uint::max_value { return err("overflow"); }
 *         else { return ok(x+1u); }
 *     }
 *     map(~[1u, 2u, 3u], inc_conditionally).chain {|incd|
 *         assert!(incd == ~[2u, 3u, 4u]);
 *     }
 */
#[inline]
pub fn map_vec<T,U,V>(ts: &[T], op: &fn(&T) -> Result<V,U>)
                      -> Result<~[V],U> {
    let mut vs: ~[V] = vec::with_capacity(ts.len());
    for ts.iter().advance |t| {
        match op(t) {
          Ok(v) => vs.push(v),
          Err(u) => return Err(u)
        }
    }
    return Ok(vs);
}

#[inline]
#[allow(missing_doc)]
pub fn map_opt<T,
               U,
               V>(
               o_t: &Option<T>,
               op: &fn(&T) -> Result<V,U>)
               -> Result<Option<V>,U> {
    match *o_t {
        None => Ok(None),
        Some(ref t) => match op(t) {
            Ok(v) => Ok(Some(v)),
            Err(e) => Err(e)
        }
    }
}

/**
 * Same as map, but it operates over two parallel vectors.
 *
 * A precondition is used here to ensure that the vectors are the same
 * length.  While we do not often use preconditions in the standard
 * library, a precondition is used here because result::t is generally
 * used in 'careful' code contexts where it is both appropriate and easy
 * to accommodate an error like the vectors being of different lengths.
 */
#[inline]
pub fn map_vec2<S,T,U,V>(ss: &[S], ts: &[T],
                op: &fn(&S,&T) -> Result<V,U>) -> Result<~[V],U> {

    assert!(vec::same_length(ss, ts));
    let n = ts.len();
    let mut vs = vec::with_capacity(n);
    let mut i = 0u;
    while i < n {
        match op(&ss[i],&ts[i]) {
          Ok(v) => vs.push(v),
          Err(u) => return Err(u)
        }
        i += 1u;
    }
    return Ok(vs);
}

/**
 * Applies op to the pairwise elements from `ss` and `ts`, aborting on
 * error.  This could be implemented using `map_zip()` but it is more efficient
 * on its own as no result vector is built.
 */
#[inline]
pub fn iter_vec2<S,T,U>(ss: &[S], ts: &[T],
                         op: &fn(&S,&T) -> Result<(),U>) -> Result<(),U> {

    assert!(vec::same_length(ss, ts));
    let n = ts.len();
    let mut i = 0u;
    while i < n {
        match op(&ss[i],&ts[i]) {
          Ok(()) => (),
          Err(u) => return Err(u)
        }
        i += 1u;
    }
    return Ok(());
}

#[cfg(test)]
mod tests {
    use result::{Err, Ok, Result, get, get_err};
    use result;

    pub fn op1() -> result::Result<int, ~str> { result::Ok(666) }

    pub fn op2(i: int) -> result::Result<uint, ~str> {
        result::Ok(i as uint + 1u)
    }

    pub fn op3() -> result::Result<int, ~str> { result::Err(~"sadface") }

    #[test]
    pub fn chain_success() {
        assert_eq!(get(&(op1().chain(op2))), 667u);
    }

    #[test]
    pub fn chain_failure() {
        assert_eq!(get_err(&op3().chain( op2)), ~"sadface");
    }

    #[test]
    pub fn test_impl_iter() {
        let mut valid = false;
        Ok::<~str, ~str>(~"a").iter(|_x| valid = true);
        assert!(valid);

        Err::<~str, ~str>(~"b").iter(|_x| valid = false);
        assert!(valid);
    }

    #[test]
    pub fn test_impl_iter_err() {
        let mut valid = true;
        Ok::<~str, ~str>(~"a").iter_err(|_x| valid = false);
        assert!(valid);

        valid = false;
        Err::<~str, ~str>(~"b").iter_err(|_x| valid = true);
        assert!(valid);
    }

    #[test]
    pub fn test_impl_map() {
        assert_eq!(Ok::<~str, ~str>(~"a").map(|_x| ~"b"), Ok(~"b"));
        assert_eq!(Err::<~str, ~str>(~"a").map(|_x| ~"b"), Err(~"a"));
    }

    #[test]
    pub fn test_impl_map_err() {
        assert_eq!(Ok::<~str, ~str>(~"a").map_err(|_x| ~"b"), Ok(~"a"));
        assert_eq!(Err::<~str, ~str>(~"a").map_err(|_x| ~"b"), Err(~"b"));
    }

    #[test]
    pub fn test_get_ref_method() {
        let foo: Result<int, ()> = Ok(100);
        assert_eq!(*foo.get_ref(), 100);
    }
}
<commit_msg>cleanup .get and .get_err<commit_after>// Copyright 2012 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.

//! A type representing either success or failure

#[allow(missing_doc)];

use clone::Clone;
use cmp::Eq;
use either;
use either::Either;
use iterator::IteratorUtil;
use option::{None, Option, Some};
use vec;
use vec::{OwnedVector, ImmutableVector};
use container::Container;

/// The result type
#[deriving(Clone, Eq)]
pub enum Result<T, U> {
    /// Contains the successful result value
    Ok(T),
    /// Contains the error value
    Err(U)
}

/**
 * Convert to the `either` type
 *
 * `ok` result variants are converted to `either::right` variants, `err`
 * result variants are converted to `either::left`.
 */
#[inline]
pub fn to_either<T:Clone,U:Clone>(res: &Result<U, T>)
    -> Either<T, U> {
    match *res {
      Ok(ref res) => either::Right((*res).clone()),
      Err(ref fail_) => either::Left((*fail_).clone())
    }
}

/**
 * Call a function based on a previous result
 *
 * If `res` is `ok` then the value is extracted and passed to `op` whereupon
 * `op`s result is wrapped in `ok` and returned. if `res` is `err` then it is
 * immediately returned.  This function can be used to compose the results of
 * two functions.
 *
 * Example:
 *
 *     let res = map(read_file(file)) { |buf|
 *         parse_bytes(buf)
 *     }
 */
#[inline]
pub fn map<T, E: Clone, U: Clone>(res: &Result<T, E>, op: &fn(&T) -> U)
  -> Result<U, E> {
    match *res {
      Ok(ref t) => Ok(op(t)),
      Err(ref e) => Err((*e).clone())
    }
}

/**
 * Call a function based on a previous result
 *
 * If `res` is `err` then the value is extracted and passed to `op` whereupon
 * `op`s result is wrapped in an `err` and returned. if `res` is `ok` then it
 * is immediately returned.  This function can be used to pass through a
 * successful result while handling an error.
 */
#[inline]
pub fn map_err<T:Clone,E,F:Clone>(res: &Result<T, E>, op: &fn(&E) -> F)
  -> Result<T, F> {
    match *res {
      Ok(ref t) => Ok((*t).clone()),
      Err(ref e) => Err(op(e))
    }
}

impl<T, E> Result<T, E> {
    /**
     * Get a reference to the value out of a successful result
     *
     * # Failure
     *
     * If the result is an error
     */
    #[inline]
    pub fn get_ref<'a>(&'a self) -> &'a T {
        match *self {
        Ok(ref t) => t,
        Err(ref the_err) =>
            fail!("get_ref called on error result: %?", *the_err)
        }
    }

    /// Returns true if the result is `ok`
    #[inline]
    pub fn is_ok(&self) -> bool {
        match *self {
            Ok(_) => true,
            Err(_) => false
        }
    }

    /// Returns true if the result is `err`
    #[inline]
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }

    /**
     * Call a function based on a previous result
     *
     * If `*self` is `ok` then the value is extracted and passed to `op` whereupon
     * `op`s result is returned. if `*self` is `err` then it is immediately
     * returned. This function can be used to compose the results of two
     * functions.
     *
     * Example:
     *
     *     read_file(file).iter() { |buf|
     *         print_buf(buf)
     *     }
     */
    #[inline]
    pub fn iter(&self, f: &fn(&T)) {
        match *self {
            Ok(ref t) => f(t),
            Err(_) => ()
        }
    }

    /**
     * Call a function based on a previous result
     *
     * If `*self` is `err` then the value is extracted and passed to `op` whereupon
     * `op`s result is returned. if `*self` is `ok` then it is immediately returned.
     * This function can be used to pass through a successful result while
     * handling an error.
     */
    #[inline]
    pub fn iter_err(&self, f: &fn(&E)) {
        match *self {
            Ok(_) => (),
            Err(ref e) => f(e)
        }
    }

    /// Unwraps a result, assuming it is an `ok(T)`
    #[inline]
    pub fn unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(_) => fail!("unwrap called on an err result")
        }
    }

    /// Unwraps a result, assuming it is an `err(U)`
    #[inline]
    pub fn unwrap_err(self) -> E {
        match self {
            Err(u) => u,
            Ok(_) => fail!("unwrap called on an ok result")
        }
    }

    /**
     * Call a function based on a previous result
     *
     * If `self` is `ok` then the value is extracted and passed to `op` whereupon
     * `op`s result is returned. if `self` is `err` then it is immediately
     * returned. This function can be used to compose the results of two
     * functions.
     *
     * Example:
     *
     *     let res = read_file(file).chain(op) { |buf|
     *         ok(parse_bytes(buf))
     *     }
     */
    #[inline]
    pub fn chain<U>(self, op: &fn(T) -> Result<U,E>) -> Result<U,E> {
        match self {
            Ok(t) => op(t),
            Err(e) => Err(e)
        }
    }

    /**
    * Call a function based on a previous result
    *
    * If `self` is `err` then the value is extracted and passed to `op`
    * whereupon `op`s result is returned. if `self` is `ok` then it is
    * immediately returned.  This function can be used to pass through a
    * successful result while handling an error.
    */
    #[inline]
    pub fn chain_err<F>(self, op: &fn(E) -> Result<T,F>) -> Result<T,F> {
        match self {
            Ok(t) => Ok(t),
            Err(v) => op(v)
        }
    }
}

impl<T:Clone,E> Result<T, E> {
    /**
     * Get the value out of a successful result
     *
     * # Failure
     *
     * If the result is an error
     */
    #[inline]
    pub fn get(&self) -> T {
        match *self {
            Ok(ref t) => (*t).clone(),
            Err(ref e) => fail!("get called on error result: %?", *e),
        }
    }

    #[inline]
    pub fn map_err<F:Clone>(&self, op: &fn(&E) -> F) -> Result<T,F> {
        map_err(self, op)
    }
}

impl<T, E:Clone> Result<T, E> {
    /**
     * Get the value out of an error result
     *
     * # Failure
     *
     * If the result is not an error
     */
    #[inline]
    pub fn get_err(&self) -> E {
        match *self {
            Err(ref u) => (*u).clone(),
            Ok(_) => fail!("get_err called on ok result"),
        }
    }

    #[inline]
    pub fn map<U:Clone>(&self, op: &fn(&T) -> U) -> Result<U,E> {
        map(self, op)
    }
}

/**
 * Maps each element in the vector `ts` using the operation `op`.  Should an
 * error occur, no further mappings are performed and the error is returned.
 * Should no error occur, a vector containing the result of each map is
 * returned.
 *
 * Here is an example which increments every integer in a vector,
 * checking for overflow:
 *
 *     fn inc_conditionally(x: uint) -> result<uint,str> {
 *         if x == uint::max_value { return err("overflow"); }
 *         else { return ok(x+1u); }
 *     }
 *     map(~[1u, 2u, 3u], inc_conditionally).chain {|incd|
 *         assert!(incd == ~[2u, 3u, 4u]);
 *     }
 */
#[inline]
pub fn map_vec<T,U,V>(ts: &[T], op: &fn(&T) -> Result<V,U>)
                      -> Result<~[V],U> {
    let mut vs: ~[V] = vec::with_capacity(ts.len());
    for ts.iter().advance |t| {
        match op(t) {
          Ok(v) => vs.push(v),
          Err(u) => return Err(u)
        }
    }
    return Ok(vs);
}

#[inline]
#[allow(missing_doc)]
pub fn map_opt<T,
               U,
               V>(
               o_t: &Option<T>,
               op: &fn(&T) -> Result<V,U>)
               -> Result<Option<V>,U> {
    match *o_t {
        None => Ok(None),
        Some(ref t) => match op(t) {
            Ok(v) => Ok(Some(v)),
            Err(e) => Err(e)
        }
    }
}

/**
 * Same as map, but it operates over two parallel vectors.
 *
 * A precondition is used here to ensure that the vectors are the same
 * length.  While we do not often use preconditions in the standard
 * library, a precondition is used here because result::t is generally
 * used in 'careful' code contexts where it is both appropriate and easy
 * to accommodate an error like the vectors being of different lengths.
 */
#[inline]
pub fn map_vec2<S,T,U,V>(ss: &[S], ts: &[T],
                op: &fn(&S,&T) -> Result<V,U>) -> Result<~[V],U> {

    assert!(vec::same_length(ss, ts));
    let n = ts.len();
    let mut vs = vec::with_capacity(n);
    let mut i = 0u;
    while i < n {
        match op(&ss[i],&ts[i]) {
          Ok(v) => vs.push(v),
          Err(u) => return Err(u)
        }
        i += 1u;
    }
    return Ok(vs);
}

/**
 * Applies op to the pairwise elements from `ss` and `ts`, aborting on
 * error.  This could be implemented using `map_zip()` but it is more efficient
 * on its own as no result vector is built.
 */
#[inline]
pub fn iter_vec2<S,T,U>(ss: &[S], ts: &[T],
                         op: &fn(&S,&T) -> Result<(),U>) -> Result<(),U> {

    assert!(vec::same_length(ss, ts));
    let n = ts.len();
    let mut i = 0u;
    while i < n {
        match op(&ss[i],&ts[i]) {
          Ok(()) => (),
          Err(u) => return Err(u)
        }
        i += 1u;
    }
    return Ok(());
}

#[cfg(test)]
mod tests {
    use result::{Err, Ok, Result};
    use result;

    pub fn op1() -> result::Result<int, ~str> { result::Ok(666) }

    pub fn op2(i: int) -> result::Result<uint, ~str> {
        result::Ok(i as uint + 1u)
    }

    pub fn op3() -> result::Result<int, ~str> { result::Err(~"sadface") }

    #[test]
    pub fn chain_success() {
        assert_eq!(op1().chain(op2).get(), 667u);
    }

    #[test]
    pub fn chain_failure() {
        assert_eq!(op3().chain( op2).get_err(), ~"sadface");
    }

    #[test]
    pub fn test_impl_iter() {
        let mut valid = false;
        Ok::<~str, ~str>(~"a").iter(|_x| valid = true);
        assert!(valid);

        Err::<~str, ~str>(~"b").iter(|_x| valid = false);
        assert!(valid);
    }

    #[test]
    pub fn test_impl_iter_err() {
        let mut valid = true;
        Ok::<~str, ~str>(~"a").iter_err(|_x| valid = false);
        assert!(valid);

        valid = false;
        Err::<~str, ~str>(~"b").iter_err(|_x| valid = true);
        assert!(valid);
    }

    #[test]
    pub fn test_impl_map() {
        assert_eq!(Ok::<~str, ~str>(~"a").map(|_x| ~"b"), Ok(~"b"));
        assert_eq!(Err::<~str, ~str>(~"a").map(|_x| ~"b"), Err(~"a"));
    }

    #[test]
    pub fn test_impl_map_err() {
        assert_eq!(Ok::<~str, ~str>(~"a").map_err(|_x| ~"b"), Ok(~"a"));
        assert_eq!(Err::<~str, ~str>(~"a").map_err(|_x| ~"b"), Err(~"b"));
    }

    #[test]
    pub fn test_get_ref_method() {
        let foo: Result<int, ()> = Ok(100);
        assert_eq!(*foo.get_ref(), 100);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add BitSet<commit_after>struct BitSet {
    bytes: [uint, ..1024 / 32],
}

impl BitSet {

    fn new() -> BitSet {
        BitSet {
            bytes: [0, ..1024 / 32]
        }
    }

    fn index(&self, value: u32) -> uint {
        (value >> 5) as uint  // divide by 32
    }

    fn mask(&self, value: u32) -> uint {
        let offset = (value & 0x1F) as uint;  // mod 32
        0x1 << offset
    }

    fn clear(&mut self, value: u32) {
        let index = self.index(value);
        let mask = self.mask(value);
        self.bytes[index] &= !mask;
    }

    fn present(&self, value: u32) -> bool {
        let index = self.index(value);
        let mask = self.mask(value);
        self.bytes[index] & mask != 0
    }

    fn set(&mut self, value: u32) {
        let index = self.index(value);
        let mask = self.mask(value);
        self.bytes[index] |= mask;
    }

    fn first(&self) -> Option<uint> {
        for (i, byte) in self.bytes.iter().enumerate() {

            if *byte == 0xFFFFFFFF {
                continue
            }

            let mut mask = 0x1;

            for j in range(0, 32) {

                if *byte & mask == 0 {
                    return Some(i * 32 + j);
                }

                mask <<= 1;
            }
        }
        None
    }
}

#[test]
fn test_bitset() {
    let mut bitset = BitSet::new();

    assert_eq!(bitset.first().unwrap(), 0);

    bitset.set(0);
    assert!(bitset.present(0));
    assert_eq!(bitset.first().unwrap(), 1);

    bitset.clear(0);
    assert!(!bitset.present(0));
    assert_eq!(bitset.first().unwrap(), 0);

    for i in range(0, 42) {
        bitset.set(i);
        assert!(bitset.present(i));
    }

    assert_eq!(bitset.first().unwrap(), 42);

    bitset.clear(32);
    assert_eq!(bitset.first().unwrap(), 32);
}
<|endoftext|>


<commit_before><commit_msg>Add a test for assignment of bare functions<commit_after>fn main() {
    let f: fn#() = fn# () {
        log "This is a bare function"
    };
    let g;
    g = f;
}<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//!  - `#[privatize]` : Forces all fields in a struct/enum to be private
//!  - `#[jstraceable]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate
//!  - `#[must_root]` : Prevents data of the marked type from being used on the stack. See the lints module for more details
//!  - `#[dom_struct]` : Implies `#[privatize]`,`#[jstraceable]`, and `#[must_root]`.
//!     Use this for structs that correspond to a DOM type

#![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private, core, unicode)]

#![allow(missing_copy_implementations)]

#[plugin]
#[macro_use]
extern crate syntax;
#[plugin]
#[macro_use]
extern crate rustc;

use rustc::lint::LintPassObject;
use rustc::plugin::Registry;
use syntax::ext::base::{Decorator, Modifier};

use syntax::parse::token::intern;

// Public for documentation to show up
/// Handles the auto-deriving for `#[jstraceable]`
pub mod jstraceable;
/// Autogenerates implementations of Reflectable on DOM structs
pub mod reflector;
pub mod lints;
/// Utilities for writing plugins
pub mod utils;
pub mod casing;

#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_syntax_extension(intern("dom_struct"), Modifier(box jstraceable::expand_dom_struct));
    reg.register_syntax_extension(intern("jstraceable"), Decorator(box jstraceable::expand_jstraceable));
    reg.register_syntax_extension(intern("_generate_reflector"), Decorator(box reflector::expand_reflector));
    reg.register_macro("to_lower", casing::expand_lower);
    reg.register_macro("to_upper", casing::expand_upper);
    reg.register_lint_pass(box lints::transmute_type::TransmutePass as LintPassObject);
    reg.register_lint_pass(box lints::unrooted_must_root::UnrootedPass as LintPassObject);
    reg.register_lint_pass(box lints::privatize::PrivatizePass as LintPassObject);
    reg.register_lint_pass(box lints::inheritance_integrity::InheritancePass as LintPassObject);
    reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject);
    reg.register_lint_pass(box lints::ban::BanPass as LintPassObject);
}
<commit_msg>Remove plugin attributes from extern crates.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//!  - `#[privatize]` : Forces all fields in a struct/enum to be private
//!  - `#[jstraceable]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate
//!  - `#[must_root]` : Prevents data of the marked type from being used on the stack. See the lints module for more details
//!  - `#[dom_struct]` : Implies `#[privatize]`,`#[jstraceable]`, and `#[must_root]`.
//!     Use this for structs that correspond to a DOM type

#![feature(plugin_registrar, quote, plugin, box_syntax, rustc_private, core, unicode)]

#![allow(missing_copy_implementations)]

#[macro_use]
extern crate syntax;
#[macro_use]
extern crate rustc;

use rustc::lint::LintPassObject;
use rustc::plugin::Registry;
use syntax::ext::base::{Decorator, Modifier};

use syntax::parse::token::intern;

// Public for documentation to show up
/// Handles the auto-deriving for `#[jstraceable]`
pub mod jstraceable;
/// Autogenerates implementations of Reflectable on DOM structs
pub mod reflector;
pub mod lints;
/// Utilities for writing plugins
pub mod utils;
pub mod casing;

#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_syntax_extension(intern("dom_struct"), Modifier(box jstraceable::expand_dom_struct));
    reg.register_syntax_extension(intern("jstraceable"), Decorator(box jstraceable::expand_jstraceable));
    reg.register_syntax_extension(intern("_generate_reflector"), Decorator(box reflector::expand_reflector));
    reg.register_macro("to_lower", casing::expand_lower);
    reg.register_macro("to_upper", casing::expand_upper);
    reg.register_lint_pass(box lints::transmute_type::TransmutePass as LintPassObject);
    reg.register_lint_pass(box lints::unrooted_must_root::UnrootedPass as LintPassObject);
    reg.register_lint_pass(box lints::privatize::PrivatizePass as LintPassObject);
    reg.register_lint_pass(box lints::inheritance_integrity::InheritancePass as LintPassObject);
    reg.register_lint_pass(box lints::str_to_string::StrToStringPass as LintPassObject);
    reg.register_lint_pass(box lints::ban::BanPass as LintPassObject);
}
<|endoftext|>


<commit_before><commit_msg>Add missing logger file.<commit_after><|endoftext|>


<commit_before><commit_msg>Handle man pages better on Windows.<commit_after><|endoftext|>


<commit_before><commit_msg>Also provide elim through inherent impl<commit_after><|endoftext|>


<commit_before><commit_msg>test(bindeps): target field specified and `optional = true` coexist<commit_after><|endoftext|>


<commit_before><commit_msg>Screen mod file<commit_after>pub trait Screen {
}
<|endoftext|>


<commit_before><commit_msg>Implemented SECS decorator<commit_after>#![feature(plugin_registrar, quote, rustc_private)]

extern crate rustc;
extern crate syntax;

use std::ops::Deref;
use syntax::{ast, ext, codemap};
use syntax::abi::Abi;
use syntax::owned_slice::OwnedSlice;
use syntax::parse::token;
use syntax::ptr::P;

#[plugin_registrar]
pub fn registrar(reg: &mut rustc::plugin::Registry) {
    reg.register_syntax_extension(token::intern("secs"),
        ext::base::Decorator(Box::new(SyntaxEcs))
    );
}

#[derive(Copy)]
pub struct SyntaxEcs;

impl ext::base::ItemDecorator for SyntaxEcs {
    fn expand(&self, context: &mut ext::base::ExtCtxt, span: codemap::Span,
              meta_item: &ast::MetaItem, item: &ast::Item,
              push: &mut FnMut(P<ast::Item>))
    {
        use syntax::ext::build::AstBuilder;
        //1: extract the path to `id` crate
        let id_path = match meta_item.node {
            ast::MetaList(_, ref list) if list.len() == 1 => {
                match list[0].node {
                    ast::MetaWord(ref path) => context.ident_of(path.deref()),
                    _ => {
                        context.span_err(span, "the `id` path should be a word");
                        return
                    }
                }
            },
            _ => {
                context.span_err(span, "use as `#[secs(id_path)]`");
                return
            }
        };
        //2: extract the prototype definition
        let (definition, generics) = match item.node {
            ast::ItemStruct(ref def, ref gen) => (def.deref(), gen),
            _ => {
                context.span_err(span, "#[secs] only works with structs");
                return
            }
        };
        let gen_types: Vec<_> = generics.ty_params.as_slice().iter().map(|typaram|
            context.ty_ident(typaram.span, typaram.ident)
        ).collect();
        //3: generate `struct Entity`
        let entity_ident = context.ident_of("Entity");
        let entity_ty = context.ty_path(context.path_all(span, false,
            vec![entity_ident], Vec::new(), gen_types.clone(), Vec::new()
        ));
        push(P(ast::Item {
            ident: entity_ident,
            attrs: Vec::new(),
            id: ast::DUMMY_NODE_ID,
            node: ast::ItemStruct(
                P(ast::StructDef {
                    fields: definition.fields.iter().map(|field| {
                        let ref ty = field.node.ty;
                        let mut f = field.clone();
                        f.node.attrs.clear();
                        f.node.ty = quote_ty!(context, Option<$id_path::Id<$ty>>);
                        f
                    }).collect(),
                    ctor_id: None,
                }),
                generics.clone()
            ),
            vis: item.vis,
            span: span,
        }));
        //4a: generate `struct Components`
        let comp_ident = context.ident_of("Components");
        let comp_ty = context.ty_path(context.path_all(span, false,
            vec![comp_ident], Vec::new(), gen_types.clone(), Vec::new()
        ));
        push(P(ast::Item {
            ident: comp_ident,
            attrs: Vec::new(),
            id: ast::DUMMY_NODE_ID,
            node: ast::ItemStruct(
                P(ast::StructDef {
                    fields: definition.fields.iter().map(|field| {
                        let ref ty = field.node.ty;
                        let mut f = field.clone();
                        f.node.attrs.clear();
                        f.node.ty = quote_ty!(context, $id_path::Array<$ty>>);
                        f
                    }).collect(),
                    ctor_id: None,
                }),
                generics.clone()
            ),
            vis: item.vis,
            span: span,
        }));
        //4b: generate `impl Components`
        let new_array = quote_expr!(context, $id_path::Array::new());
        fn make_generics() -> ast::Generics {
            ast::Generics {
                lifetimes: Vec::new(),
                ty_params: OwnedSlice::empty(),
                where_clause: ast::WhereClause {
                    id: ast::DUMMY_NODE_ID,
                    predicates: Vec::new(),
                },
            }
        }
        push(P(ast::Item {
            ident: comp_ident,
            attrs: Vec::new(),
            id: ast::DUMMY_NODE_ID,
            node: ast::ItemImpl(
                ast::Unsafety::Normal,
                ast::ImplPolarity::Positive,
                generics.clone(),
                None,   //TraitRef
                comp_ty.clone(),
                //method ::new() -> Components
                Some(P(ast::ImplItem {
                    id: ast::DUMMY_NODE_ID,
                    ident: context.ident_of("new"),
                    vis: item.vis,
                    attrs: Vec::new(),
                    node: ast::MethodImplItem(
                        ast::MethodSig {
                            unsafety: ast::Unsafety::Normal,
                            abi: Abi::Rust,
                            decl: context.fn_decl(Vec::new(), comp_ty.clone()),
                            generics: make_generics(),
                            explicit_self: codemap::Spanned {
                                node: ast::SelfStatic,
                                span: span,
                            },
                        },
                        context.block_expr(context.expr_struct_ident(
                            span, comp_ident, definition.fields.iter().map(|field|
                                context.field_imm(field.span, field.node.ident().unwrap(), new_array.clone())
                            ).collect()
                        ))
                    ),
                    span: span,
                })).into_iter()
                //TODO: add_X, get_X, mut_X, etc
                .collect()
            ),
            vis: item.vis,
            span: span,
        }));
        //5a: generate `struct World`
        let world_ident = context.ident_of("World");
        let world_ty = context.ty_path(context.path_all(span, false,
            vec![world_ident], Vec::new(), gen_types.clone(), Vec::new()
        ));
        push(P(ast::Item {
            ident: world_ident,
            attrs: Vec::new(),
            id: ast::DUMMY_NODE_ID,
            node: ast::ItemStruct(
                P(ast::StructDef {
                    fields: vec![
                        codemap::Spanned {
                            node: ast::StructField_ {
                                kind: ast::StructFieldKind::NamedField(
                                    context.ident_of("data"),
                                    ast::Visibility::Public,
                                ),
                                id: ast::DUMMY_NODE_ID,
                                ty: comp_ty,
                                attrs: Vec::new(),
                            },
                            span: span,
                        },
                        codemap::Spanned {
                            node: ast::StructField_ {
                                kind: ast::StructFieldKind::NamedField(
                                    context.ident_of("entities"),
                                    ast::Visibility::Public,
                                ),
                                id: ast::DUMMY_NODE_ID,
                                ty: quote_ty!(context, Vec<$entity_ty>),
                                attrs: Vec::new(),
                            },
                            span: span,
                        },
                    ],
                    ctor_id: None,
                }),
                generics.clone()
            ),
            vis: item.vis,
            span: span,
        }));
        //5b: generate `impl World`
        push(P(ast::Item {
            ident: world_ident,
            attrs: Vec::new(),
            id: ast::DUMMY_NODE_ID,
            node: ast::ItemImpl(
                ast::Unsafety::Normal,
                ast::ImplPolarity::Positive,
                generics.clone(),
                None,   //TraitRef
                world_ty.clone(),
                vec![
                    P(ast::ImplItem {
                        id: ast::DUMMY_NODE_ID,
                        ident: context.ident_of("new"),
                        vis: item.vis,
                        attrs: Vec::new(),
                        node: ast::MethodImplItem(
                            ast::MethodSig {
                                unsafety: ast::Unsafety::Normal,
                                abi: Abi::Rust,
                                decl: context.fn_decl(Vec::new(), world_ty.clone()),
                                generics: make_generics(),
                                explicit_self: codemap::Spanned {
                                    node: ast::SelfStatic,
                                    span: span,
                                },
                            },
                            context.block_expr(quote_expr!(context,
                                World {
                                    data: Components::new(),
                                    entities: Vec::new(),
                                }
                            ))
                        ),
                        span: span,
                    })
                ]
            ),
            vis: item.vis,
            span: span,
        }));
    }
}
<|endoftext|>


<commit_before><commit_msg>Added template from https://github.com/thejpster/bare-metal-arm-rust<commit_after>//! This is a template file.

// ****************************************************************************
//
// Imports
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Public Types
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Private Types
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Public Data
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Public Functions
//
// ****************************************************************************

// None

// ****************************************************************************
//
// Private Functions
//
// ****************************************************************************

// None

// ****************************************************************************
//
// End Of File
//
// ****************************************************************************
<|endoftext|>


<commit_before><commit_msg>Use tmpfiles for input / output.<commit_after><|endoftext|>


<commit_before><commit_msg>vector tests<commit_after>extern crate numrs;
use numrs::vector;
use numrs::vector::Vector;

#[test]
fn test_basic_vector() {
  let mut v = Vector::new(4, 0.0);
  assert_eq!(v.len(), 4);
  v[3] = 1.0;
  assert_eq!(v[0], 0.0);
  assert_eq!(v[1], 0.0);
  assert_eq!(v[2], 0.0);
  assert_eq!(v[3], 1.0);
}

#[test]
fn test_vector_add() {
  let elems = [1.0, 2.0, 3.0, 4.0];
  let v1 = vector::from_elems(&elems);
  let v2 = vector::from_elems(&elems);
  let res = v1 + v2;

  assert_eq!(res[0], 2.0);
  assert_eq!(res[1], 4.0);
  assert_eq!(res[2], 6.0);
  assert_eq!(res[3], 8.0);
}

#[test]
fn test_vector_multiply() {
  let elems = [1.0, 2.0, 3.0, 4.0];
  let v1 = vector::from_elems(&elems);
  let v2 = vector::from_elems(&elems);
  let res = v1 * v2;

  assert_eq!(res[0], 1.0);
  assert_eq!(res[1], 4.0);
  assert_eq!(res[2], 9.0);
  assert_eq!(res[3], 16.0);
}

#[test]
fn test_scalar_multiply() {
  let elems = [1.0, 2.0, 3.0, 4.0];
  let v = vector::from_elems(&elems);

  let mut v_ = -v.clone();
  assert_eq!(v_[0], -1.0);
  assert_eq!(v_[1], -2.0);
  assert_eq!(v_[2], -3.0);
  assert_eq!(v_[3], -4.0);

  v_ = v.clone() * 2.0;
  assert_eq!(v_[0], 2.0);
  assert_eq!(v_[1], 4.0);
  assert_eq!(v_[2], 6.0);
  assert_eq!(v_[3], 8.0);
}

#[test]
fn test_vector_clone() {
  let elems = [16.0, 3.0, 7.0, -11.0];
  let v1 = vector::from_elems(&elems);
  let v2 = v1.clone();
  assert_eq!(v2[0], 16.0);
  assert_eq!(v2[1], 3.0);
  assert_eq!(v2[2], 7.0);
  assert_eq!(v2[3], -11.0);
}

#[test]
fn test_vector_eq() {
  let elem1 = [1.0, 2.0, 3.0, 4.0];
  let v1 = vector::from_elems(&elem1);
  let elem2 = [1.0, 3.0, 3.0, 4.0];
  let v2 = vector::from_elems(&elem2);
  assert!(v1 != v2)
}
<|endoftext|>


<commit_before><commit_msg>nit: rearrange and make match exhaustive<commit_after><|endoftext|>


<commit_before><commit_msg>Lack of RLP encoding unittests for extra long bytes array<commit_after><|endoftext|>


<commit_before><commit_msg>22 - ref pattern<commit_after>#[deriving(Copy)]
struct Point { x: int, y: int }

fn main() {
    let point = Point { x: 0, y: 0 };

    let _copy_of_x = {
        // `ref_to_x` is a reference to the `x` field of `point`
        let Point { x: ref ref_to_x, y: _ } = point;

        // Return a copy of the `x` field of `point`
        *ref_to_x
    };

    // A mutable copy of `point`
    let mut mutable_point = point;

    {
        // `ref` can be paired with `mut` to take mutable references
        let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;

        // Mutate the `y` field of `mutable_point`, via a mutable reference
        *mut_ref_to_y = 1;
    }

    println!("point is ({}, {})", point.x, point.y);
    println!("mutable_point is ({}, {})", mutable_point.x, mutable_point.y);

    let mut tuple = (box 5u, 3u);

    {
        // `ref` can also be paired with `box` to take a mutable reference to
        // the data contained in the box
        let (box ref mut i, _) = tuple;

        *i = 3;
    }

    println!("tuple is {}", tuple);
}
<|endoftext|>


<commit_before><commit_msg>Add missing tests.<commit_after><|endoftext|>


<commit_before><commit_msg>Rust Hello World<commit_after>fn main(){
	println!("Hello, world!");
}<|endoftext|>


<commit_before><commit_msg>Create a.rs<commit_after>
<|endoftext|>


<commit_before>// -*- rust -*-

use std;
import std._str;

type t = tag(make_t(str), clam());

fn main() {
  let str s = "hi";     // ref up
  let t x = make_t(s);  // ref up

  alt (x) {
    case (make_t(y)) { log y; }  // ref up and ref down
    case (_) { log "?"; }
  }

  log _str.refcount(s);
  check (_str.refcount(s) == 2u);
}
<commit_msg>Tiny change to tighten up alt-pattern-drop.rs test.<commit_after>// -*- rust -*-

use std;
import std._str;

type t = tag(make_t(str), clam());

fn main() {
  let str s = "hi";     // ref up
  let t x = make_t(s);  // ref up

  alt (x) {
    case (make_t(y)) { log y; }  // ref up and ref down
    case (_) { log "?"; fail; }
  }

  log _str.refcount(s);
  check (_str.refcount(s) == 2u);
}
<|endoftext|>


<commit_before><commit_msg>New minimal test for current stage2 blocker.<commit_after>// xfail-stage0

obj ob[K](K k) {
  iter foo() -> @tup(K) {
    put @tup(k);
  }
}

fn x(&ob[str] o) {
  for each (@tup(str) i in o.foo()) {
  }
}

fn main() {
  auto o = ob[str]("hi" + "there");
  x(o);
}
<|endoftext|>


<commit_before><commit_msg>No log in bin<commit_after><|endoftext|>


<commit_before><commit_msg>constants<commit_after>use std::f32::consts;
static MAX_HEALTH: i32 = 100;
static GAME_NAME: &'static str = "Monster Attack";

fn main() {
    //const PI: f32 = 3.14;
    println!("{}", consts::PI);
    println!("你在玩的游戏是：{}.", GAME_NAME);
    println!("你的最初生命值是：{}", MAX_HEALTH);
    println!("游戏{0}，生命值{1},多少点：{1}", GAME_NAME, MAX_HEALTH);
    println!("你有多少点健康值：{points}", points=70);
}<|endoftext|>


<commit_before><commit_msg>queue for Rust experiments<commit_after>struct Queue {
  older: Vec<char>,
  younger: Vec<char>
}

impl Queue {
  fn push(self: &mut Queue, c: char) {
    self.younger.push(c);
  }

  fn pop(self: &mut Queue) -> Option<char> {
    if self.older.is_empty() {
      if self.younger.is_empty() {
        return None;
      }
      use std::mem::swap;
      swap(&mut self.older, &mut self.younger);
      self.older.reverse();
    }

    self.older.pop()
  }
}

let mut q = Queue { older: Vec::new(), younger: Vec::new() };
q.push('0');
q.push('1');
assert_eq!(q.pop(), Some('0'));

q.push('w');
assert_eq!(q.pop(), Some('1'));
assert_eq!(q.pop(), Some('w'));
assert_eq!(q.pop(), None);

<|endoftext|>


<commit_before>use std::cmp::Ordering;
use std::collections::Bound;
use std::collections::HashMap;

use skiplist::OrderedSkipList;

use dbutil::normalize_position;

/**
 * SortedSetMember is a wrapper around f64 to implement ordering and equality.
 * f64 does not implement those traits because comparing floats has problems
 * but in the context of rsedis this basic implementation should be enough.
 **/
#[derive(Debug, Clone)]
pub struct SortedSetMember {
    f: f64,
    s: Vec<u8>,
    // this is useful for inclusion/exclusion comparison
    // if true, it will ignore `s` and be the highest possible string
    upper_boundary: bool,
}

impl SortedSetMember {
    pub fn new(f: f64, s: Vec<u8>) -> SortedSetMember {
        SortedSetMember {f: f, s: s, upper_boundary: false}
    }

    pub fn set_upper_boundary(&mut self, upper_boundary: bool) {
        self.upper_boundary = upper_boundary;
    }

    pub fn get_f64(&self) -> &f64 {
        &self.f
    }

    pub fn set_f64(&mut self, f: f64)  {
        self.f = f;
    }

    pub fn get_vec(&self) -> &Vec<u8> {
        &self.s
    }

    pub fn set_vec(&mut self, s: Vec<u8>)  {
        self.s = s;
    }
}

impl Eq for SortedSetMember {}

impl PartialEq for SortedSetMember {
    fn eq(&self, other: &Self) -> bool {
        self.f == other.f && self.s == other.s
    }
}

impl Ord for SortedSetMember {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl PartialOrd for SortedSetMember {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(if self.f < other.f { Ordering::Less }
        else if self.f > other.f { Ordering::Greater }
        else if other.upper_boundary { Ordering::Less }
        else if self.upper_boundary { Ordering::Greater }
        else { return self.s.partial_cmp(&other.s) })
    }

    fn lt(&self, other: &Self) -> bool { self.f < other.f || (self.f == other.f && self.s < other.s) }
    fn le(&self, other: &Self) -> bool { self.f < other.f || (self.f == other.f && self.s <= other.s) }
    fn gt(&self, other: &Self) -> bool { self.f > other.f || (self.f == other.f && self.s > other.s) }
    fn ge(&self, other: &Self) -> bool { self.f > other.f || (self.f == other.f && self.s >= other.s) }
}

fn is_range_valid<T: Ord>(min: Bound<T>, max: Bound<T>) -> bool {
    let mut both_in = true;
    let v1 = match min {
        Bound::Included(ref v) => v,
        Bound::Excluded(ref v) => { both_in = false; v },
        Bound::Unbounded => return true,
    };

    let v2 = match max {
        Bound::Included(ref v) => v,
        Bound::Excluded(ref v) => { both_in = false; v },
        Bound::Unbounded => return true,
    };

    return v1 < v2 || (v1 == v2 && both_in);
}

#[derive(PartialEq, Debug)]
pub enum ValueSortedSet {
    Data(OrderedSkipList<SortedSetMember>, HashMap<Vec<u8>, f64>),
}

impl ValueSortedSet {
    pub fn new() -> Self {
        let skiplist = OrderedSkipList::new();
        let hmap = HashMap::new();
        ValueSortedSet::Data(skiplist, hmap)
    }

    pub fn zadd(&mut self, s: f64, el: Vec<u8>, nx: bool, xx: bool, ch: bool, incr: bool) -> bool {
        match *self {
            ValueSortedSet::Data(ref mut skiplist, ref mut hmap) => {
                let mut score = s.clone();
                let contains = hmap.contains_key(&el);
                if contains && nx {
                    return false;
                }
                if !contains && xx {
                    return false;
                }
                if contains {
                    let val = hmap.get(&el).unwrap();
                    if ch && !incr && val == &s {
                        return false;
                    }
                    skiplist.remove(&SortedSetMember::new(val.clone(), el.clone()));
                    if incr {
                        score += val.clone();
                    }
                }
                skiplist.insert(SortedSetMember::new(score.clone(), el.clone()));
                hmap.insert(el, score);
                if ch {
                    true
                } else {
                    !contains
                }
            },
        }
    }

    pub fn zincrby(&mut self, increment: f64, member: Vec<u8>) -> f64 {
        match *self {
            ValueSortedSet::Data(ref mut skiplist, ref mut hmap) => {
                let mut val = match hmap.get(&member) {
                    Some(val) => {
                        skiplist.remove(&SortedSetMember::new(val.clone(), member.clone()));
                        val.clone()
                    },
                    None => 0.0,
                };
                val += increment;
                skiplist.insert(SortedSetMember::new(val.clone(), member.clone()));
                hmap.insert(member, val.clone());
                val
            },
        }
    }

    pub fn zcount(&self, min: Bound<f64>, max: Bound<f64>) -> usize {
        let skiplist = match *self {
            ValueSortedSet::Data(ref skiplist, _) => skiplist,
        };
        let mut f1 = SortedSetMember::new(0.0, vec![]);
        let mut f2 = SortedSetMember::new(0.0, vec![]);
        let m1 = match min {
            Bound::Included(f) => { f1.set_f64(f); Bound::Included(&f1) },
            Bound::Excluded(f) => { f1.set_f64(f); f1.set_upper_boundary(true); Bound::Excluded(&f1) },
            Bound::Unbounded => Bound::Unbounded,
        };

        let m2 = match max {
            Bound::Included(f) => { f2.set_f64(f); f2.set_upper_boundary(true); Bound::Included(&f2) },
            Bound::Excluded(f) => { f2.set_f64(f); Bound::Excluded(&f2) },
            Bound::Unbounded => Bound::Unbounded,
        };

        skiplist.range(m1, m2).collect::<Vec<_>>().len()
    }

    pub fn zrange(&self, _start: i64, _stop: i64, withscores: bool, rev: bool) -> Vec<Vec<u8>> {
        let skiplist = match *self {
            ValueSortedSet::Data(ref skiplist, _) => skiplist,
        };

        let len = skiplist.len();
        let (start, stop) = if rev {
            (match normalize_position(- _stop - 1, len) {
                Ok(i) => i,
                Err(i) => if i == 0 { 0 } else { return vec![]; },
            },
            match normalize_position(- _start - 1, len) {
                Ok(i) => i,
                Err(i) => if i == 0 { return vec![]; } else { i },
            })
        } else {
            (match normalize_position(_start, len) {
                Ok(i) => i,
                Err(i) => if i == 0 { 0 } else { return vec![]; },
            },
            match normalize_position(_stop, len) {
                Ok(i) => i,
                Err(i) => if i == 0 { return vec![]; } else { i },
            })
        };

        if stop < start {
            return vec![];
        }
        let first = skiplist.get(&start).unwrap();
        let mut r = vec![];
        if rev {
            for member in skiplist.range(Bound::Included(first), Bound::Unbounded).take(stop - start + 1) {
                if withscores {
                    r.push(format!("{}", member.get_f64()).into_bytes());
                }
                r.push(member.get_vec().clone());
            }
            r = r.iter().rev().cloned().collect::<Vec<_>>();
        } else {
            for member in skiplist.range(Bound::Included(first), Bound::Unbounded).take(stop - start + 1) {
                r.push(member.get_vec().clone());
                if withscores {
                    r.push(format!("{}", member.get_f64()).into_bytes());
                }
            }
        }
        r
    }

    pub fn zrangebyscore(&self, _min: Bound<f64>, _max: Bound<f64>, withscores: bool, offset: usize, count: usize, rev: bool) -> Vec<Vec<u8>> {
        let skiplist = match *self {
            ValueSortedSet::Data(ref skiplist, _) => skiplist,
        };

        // FIXME: duplicated code from ZCOUNT. Trying to create a factory
        // function for this, but I failed because allocation was going
        // out of scope.
        // Probably more function will copy this until I can figure out
        // a better way.
        let mut f1 = SortedSetMember::new(0.0, vec![]);
        let mut f2 = SortedSetMember::new(0.0, vec![]);

        let (min, max) = if rev {
            (_max, _min)
        } else {
            (_min, _max)
        };

        let m1 = match min {
            Bound::Included(f) => { f1.set_f64(f); Bound::Included(&f1) },
            Bound::Excluded(f) => { f1.set_f64(f); f1.set_upper_boundary(true); Bound::Excluded(&f1) },
            Bound::Unbounded => Bound::Unbounded,
        };

        let m2 = match max {
            Bound::Included(f) => { f2.set_f64(f); f2.set_upper_boundary(true); Bound::Included(&f2) },
            Bound::Excluded(f) => { f2.set_f64(f); Bound::Excluded(&f2) },
            Bound::Unbounded => Bound::Unbounded,
        };

        if !is_range_valid(m1, m2) {
            return vec![];
        }

        // FIXME: skiplist crashes when using .range().rev()
        let mut r = vec![];
        if rev {
            let len = skiplist.len();
            let mut c = count;
            if c + offset > len {
                c = len - offset;
            }
            for member in skiplist.range(m1, m2).skip(skiplist.len() - offset - c).take(c) {
                if withscores {
                    r.push(format!("{}", member.get_f64()).into_bytes());
                }
                r.push(member.get_vec().clone());
            }
            r.iter().cloned().rev().collect::<Vec<_>>()
        } else {
            for member in skiplist.range(m1, m2).skip(offset).take(count) {
                r.push(member.get_vec().clone());
                if withscores {
                    r.push(format!("{}", member.get_f64()).into_bytes());
                }
            }
            r
        }
    }

    pub fn zrank(&self, el: Vec<u8>) -> Option<usize> {
        let (skiplist, hashmap) = match *self {
            ValueSortedSet::Data(ref skiplist, ref hashmap) => (skiplist, hashmap),
        };

        let score = match hashmap.get(&el) {
            Some(s) => s,
            None => return None,
        };

        let member = SortedSetMember::new(score.clone(), el);
        return Some(skiplist.range(Bound::Unbounded, Bound::Included(&member)).collect::<Vec<_>>().len() - 1);
    }
}
<commit_msg>Use skiplist.range().rev()<commit_after>use std::cmp::Ordering;
use std::collections::Bound;
use std::collections::HashMap;

use skiplist::OrderedSkipList;

use dbutil::normalize_position;

/**
 * SortedSetMember is a wrapper around f64 to implement ordering and equality.
 * f64 does not implement those traits because comparing floats has problems
 * but in the context of rsedis this basic implementation should be enough.
 **/
#[derive(Debug, Clone)]
pub struct SortedSetMember {
    f: f64,
    s: Vec<u8>,
    // this is useful for inclusion/exclusion comparison
    // if true, it will ignore `s` and be the highest possible string
    upper_boundary: bool,
}

impl SortedSetMember {
    pub fn new(f: f64, s: Vec<u8>) -> SortedSetMember {
        SortedSetMember {f: f, s: s, upper_boundary: false}
    }

    pub fn set_upper_boundary(&mut self, upper_boundary: bool) {
        self.upper_boundary = upper_boundary;
    }

    pub fn get_f64(&self) -> &f64 {
        &self.f
    }

    pub fn set_f64(&mut self, f: f64)  {
        self.f = f;
    }

    pub fn get_vec(&self) -> &Vec<u8> {
        &self.s
    }

    pub fn set_vec(&mut self, s: Vec<u8>)  {
        self.s = s;
    }
}

impl Eq for SortedSetMember {}

impl PartialEq for SortedSetMember {
    fn eq(&self, other: &Self) -> bool {
        self.f == other.f && self.s == other.s
    }
}

impl Ord for SortedSetMember {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl PartialOrd for SortedSetMember {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(if self.f < other.f { Ordering::Less }
        else if self.f > other.f { Ordering::Greater }
        else if other.upper_boundary { Ordering::Less }
        else if self.upper_boundary { Ordering::Greater }
        else { return self.s.partial_cmp(&other.s) })
    }

    fn lt(&self, other: &Self) -> bool { self.f < other.f || (self.f == other.f && self.s < other.s) }
    fn le(&self, other: &Self) -> bool { self.f < other.f || (self.f == other.f && self.s <= other.s) }
    fn gt(&self, other: &Self) -> bool { self.f > other.f || (self.f == other.f && self.s > other.s) }
    fn ge(&self, other: &Self) -> bool { self.f > other.f || (self.f == other.f && self.s >= other.s) }
}

fn is_range_valid<T: Ord>(min: Bound<T>, max: Bound<T>) -> bool {
    let mut both_in = true;
    let v1 = match min {
        Bound::Included(ref v) => v,
        Bound::Excluded(ref v) => { both_in = false; v },
        Bound::Unbounded => return true,
    };

    let v2 = match max {
        Bound::Included(ref v) => v,
        Bound::Excluded(ref v) => { both_in = false; v },
        Bound::Unbounded => return true,
    };

    return v1 < v2 || (v1 == v2 && both_in);
}

#[derive(PartialEq, Debug)]
pub enum ValueSortedSet {
    Data(OrderedSkipList<SortedSetMember>, HashMap<Vec<u8>, f64>),
}

impl ValueSortedSet {
    pub fn new() -> Self {
        let skiplist = OrderedSkipList::new();
        let hmap = HashMap::new();
        ValueSortedSet::Data(skiplist, hmap)
    }

    pub fn zadd(&mut self, s: f64, el: Vec<u8>, nx: bool, xx: bool, ch: bool, incr: bool) -> bool {
        match *self {
            ValueSortedSet::Data(ref mut skiplist, ref mut hmap) => {
                let mut score = s.clone();
                let contains = hmap.contains_key(&el);
                if contains && nx {
                    return false;
                }
                if !contains && xx {
                    return false;
                }
                if contains {
                    let val = hmap.get(&el).unwrap();
                    if ch && !incr && val == &s {
                        return false;
                    }
                    skiplist.remove(&SortedSetMember::new(val.clone(), el.clone()));
                    if incr {
                        score += val.clone();
                    }
                }
                skiplist.insert(SortedSetMember::new(score.clone(), el.clone()));
                hmap.insert(el, score);
                if ch {
                    true
                } else {
                    !contains
                }
            },
        }
    }

    pub fn zincrby(&mut self, increment: f64, member: Vec<u8>) -> f64 {
        match *self {
            ValueSortedSet::Data(ref mut skiplist, ref mut hmap) => {
                let mut val = match hmap.get(&member) {
                    Some(val) => {
                        skiplist.remove(&SortedSetMember::new(val.clone(), member.clone()));
                        val.clone()
                    },
                    None => 0.0,
                };
                val += increment;
                skiplist.insert(SortedSetMember::new(val.clone(), member.clone()));
                hmap.insert(member, val.clone());
                val
            },
        }
    }

    pub fn zcount(&self, min: Bound<f64>, max: Bound<f64>) -> usize {
        let skiplist = match *self {
            ValueSortedSet::Data(ref skiplist, _) => skiplist,
        };
        let mut f1 = SortedSetMember::new(0.0, vec![]);
        let mut f2 = SortedSetMember::new(0.0, vec![]);
        let m1 = match min {
            Bound::Included(f) => { f1.set_f64(f); Bound::Included(&f1) },
            Bound::Excluded(f) => { f1.set_f64(f); f1.set_upper_boundary(true); Bound::Excluded(&f1) },
            Bound::Unbounded => Bound::Unbounded,
        };

        let m2 = match max {
            Bound::Included(f) => { f2.set_f64(f); f2.set_upper_boundary(true); Bound::Included(&f2) },
            Bound::Excluded(f) => { f2.set_f64(f); Bound::Excluded(&f2) },
            Bound::Unbounded => Bound::Unbounded,
        };

        skiplist.range(m1, m2).collect::<Vec<_>>().len()
    }

    pub fn zrange(&self, _start: i64, _stop: i64, withscores: bool, rev: bool) -> Vec<Vec<u8>> {
        let skiplist = match *self {
            ValueSortedSet::Data(ref skiplist, _) => skiplist,
        };

        let len = skiplist.len();
        let (start, stop) = if rev {
            (match normalize_position(- _stop - 1, len) {
                Ok(i) => i,
                Err(i) => if i == 0 { 0 } else { return vec![]; },
            },
            match normalize_position(- _start - 1, len) {
                Ok(i) => i,
                Err(i) => if i == 0 { return vec![]; } else { i },
            })
        } else {
            (match normalize_position(_start, len) {
                Ok(i) => i,
                Err(i) => if i == 0 { 0 } else { return vec![]; },
            },
            match normalize_position(_stop, len) {
                Ok(i) => i,
                Err(i) => if i == 0 { return vec![]; } else { i },
            })
        };

        if stop < start {
            return vec![];
        }
        let first = skiplist.get(&start).unwrap();
        let mut r = vec![];
        if rev {
            for member in skiplist.range(Bound::Included(first), Bound::Unbounded).take(stop - start + 1) {
                if withscores {
                    r.push(format!("{}", member.get_f64()).into_bytes());
                }
                r.push(member.get_vec().clone());
            }
            r = r.iter().rev().cloned().collect::<Vec<_>>();
        } else {
            for member in skiplist.range(Bound::Included(first), Bound::Unbounded).take(stop - start + 1) {
                r.push(member.get_vec().clone());
                if withscores {
                    r.push(format!("{}", member.get_f64()).into_bytes());
                }
            }
        }
        r
    }

    pub fn zrangebyscore(&self, _min: Bound<f64>, _max: Bound<f64>, withscores: bool, offset: usize, count: usize, rev: bool) -> Vec<Vec<u8>> {
        let skiplist = match *self {
            ValueSortedSet::Data(ref skiplist, _) => skiplist,
        };

        // FIXME: duplicated code from ZCOUNT. Trying to create a factory
        // function for this, but I failed because allocation was going
        // out of scope.
        // Probably more function will copy this until I can figure out
        // a better way.
        let mut f1 = SortedSetMember::new(0.0, vec![]);
        let mut f2 = SortedSetMember::new(0.0, vec![]);

        let (min, max) = if rev {
            (_max, _min)
        } else {
            (_min, _max)
        };

        let m1 = match min {
            Bound::Included(f) => { f1.set_f64(f); Bound::Included(&f1) },
            Bound::Excluded(f) => { f1.set_f64(f); f1.set_upper_boundary(true); Bound::Excluded(&f1) },
            Bound::Unbounded => Bound::Unbounded,
        };

        let m2 = match max {
            Bound::Included(f) => { f2.set_f64(f); f2.set_upper_boundary(true); Bound::Included(&f2) },
            Bound::Excluded(f) => { f2.set_f64(f); Bound::Excluded(&f2) },
            Bound::Unbounded => Bound::Unbounded,
        };

        if !is_range_valid(m1, m2) {
            return vec![];
        }

        let mut r = vec![];
        if rev {
            let len = skiplist.len();
            let mut c = count;
            if c + offset > len {
                c = len - offset;
            }
            for member in skiplist.range(m1, m2).rev().skip(offset).take(c) {
                r.push(member.get_vec().clone());
                if withscores {
                    r.push(format!("{}", member.get_f64()).into_bytes());
                }
            }
            r.iter().cloned().collect::<Vec<_>>()
        } else {
            for member in skiplist.range(m1, m2).skip(offset).take(count) {
                r.push(member.get_vec().clone());
                if withscores {
                    r.push(format!("{}", member.get_f64()).into_bytes());
                }
            }
            r
        }
    }

    pub fn zrank(&self, el: Vec<u8>) -> Option<usize> {
        let (skiplist, hashmap) = match *self {
            ValueSortedSet::Data(ref skiplist, ref hashmap) => (skiplist, hashmap),
        };

        let score = match hashmap.get(&el) {
            Some(s) => s,
            None => return None,
        };

        let member = SortedSetMember::new(score.clone(), el);
        return Some(skiplist.range(Bound::Unbounded, Bound::Included(&member)).collect::<Vec<_>>().len() - 1);
    }
}
<|endoftext|>


<commit_before><commit_msg>Ignore closing of PportTimetable element.<commit_after><|endoftext|>


<commit_before><commit_msg>Add a bench for tensor!<commit_after>#![feature(test)]

#[macro_use]
extern crate numeric;
extern crate test;

#[bench]
fn tensor(bencher: &mut test::Bencher) {
    const T: f64 = 42.0;
    bencher.iter(|| {
        let tensor = tensor![
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
            T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T;
        ];
        test::black_box(tensor);
    });
}
<|endoftext|>