<commit_before><commit_msg>generic positioning<commit_after>
/// A coordinate that can be either valid or invalid.
#[derive(Copy, Clone)]
pub enum Coordinate<T> {
    Invalid,
    Valid(T),
}

impl<T> Coordinate<T> {
    /// Returns `true` if coordinate is invalid and `false` otherwise.
    pub fn is_invalid(&self) -> bool {
        match *self {
            Coordinate::Invalid => true,
            _ => false,
        }
    }

    /// Returns `true` if the coordinate is valid and `false` otherwise.
    pub fn is_valid(&self) -> bool {
        match *self {
            Coordinate::Invalid => false,
            _ => true,
        }
    }

    pub fn invalidate(&mut self) {
        *self = Coordinate::Invalid;
    }
}

/// A pair of coordinates.
pub type Pair = (usize, usize);

/// A trait for objects which have a position that can be expressed as coordinates.
pub trait Position<T> {
    /// Returns the current position's coordinates.
    fn pos(&self) -> Coordinate<T>;

    /// Sets the current position to the given coordinates and sets the last position's coordinates
    /// accordingly.
    fn set_pos(&mut self, newpos: Coordinate<T>);

    /// Invalidates the current position.
    fn invalidate_pos(&mut self);

    /// Returns the last position's coordinates.
    fn last_pos(&self) -> Coordinate<T>;

    /// Invalidates the last position.
    fn invalidate_last_pos(&mut self);
}

/// A cursor position.
pub struct Cursor {
    pos: Coordinate<Pair>,
    last_pos: Coordinate<Pair>,
}

impl Cursor {
    pub fn new() -> Cursor {
        Cursor {
            pos: Coordinate::Invalid,
            last_pos: Coordinate::Invalid,
        }
    }

    /// Checks whether the current and last coordinates are sequential and returns `true` if they
    /// are and `false` otherwise.
    pub fn is_seq(&self) -> bool {
        if let Coordinate::Valid((cx, cy)) =  self.pos {
            if let Coordinate::Valid((lx, ly)) = self.last_pos {
                (lx+1, ly) == (cx, cy)
            } else { false }
        } else { false }
    }

}

impl Position<Pair> for Cursor {
    fn pos(&self) -> Coordinate<Pair> {
        self.pos
    }

    fn set_pos(&mut self, newpos: Coordinate<Pair>) {
        self.last_pos = self.pos;
        self.pos = newpos;
    }

    fn invalidate_pos(&mut self) {
        self.pos.invalidate();
    }

    fn last_pos(&self) -> Coordinate<Pair> {
        self.last_pos
    }

    fn invalidate_last_pos(&mut self) {
        self.last_pos.invalidate();
    }
}
<|endoftext|>


<commit_before><commit_msg>FEAT(coincheck): Add depth<commit_after><|endoftext|>


<commit_before><commit_msg>Add ZipCrypto unit test<commit_after>// The following is a hexdump of a zip file containing the following
// ZipCrypto encrypted file:
// test.txt: 35 bytes, contents: `abcdefghijklmnopqrstuvwxyz123456789`, password: `test`
//
// 00000000  50 4b 03 04 14 00 01 00  00 00 54 bd b5 50 2f 20  |PK........T..P/ |
// 00000010  79 55 2f 00 00 00 23 00  00 00 08 00 00 00 74 65  |yU/...#.......te|
// 00000020  73 74 2e 74 78 74 ca 2d  1d 27 19 19 63 43 77 9a  |st.txt.-.'..cCw.|
// 00000030  71 76 c9 ec d1 6f d9 f5  22 67 b3 8f 52 b5 41 bc  |qv...o.."g..R.A.|
// 00000040  5c 36 f2 1d 84 c3 c0 28  3b fd e1 70 c2 cc 0c 11  |\6.....(;..p....|
// 00000050  0c c5 95 2f a4 50 4b 01  02 3f 00 14 00 01 00 00  |.../.PK..?......|
// 00000060  00 54 bd b5 50 2f 20 79  55 2f 00 00 00 23 00 00  |.T..P/ yU/...#..|
// 00000070  00 08 00 24 00 00 00 00  00 00 00 20 00 00 00 00  |...$....... ....|
// 00000080  00 00 00 74 65 73 74 2e  74 78 74 0a 00 20 00 00  |...test.txt.. ..|
// 00000090  00 00 00 01 00 18 00 31  b2 3b bf b8 2f d6 01 31  |.......1.;../..1|
// 000000a0  b2 3b bf b8 2f d6 01 a8  c4 45 bd b8 2f d6 01 50  |.;../....E../..P|
// 000000b0  4b 05 06 00 00 00 00 01  00 01 00 5a 00 00 00 55  |K..........Z...U|
// 000000c0  00 00 00 00 00                                    |.....|
// 000000c5

use std::io::Read;
use std::io::Cursor;

#[test]
fn encrypted_file() {
    let zip_file_bytes = &mut Cursor::new(vec![
        0x50, 0x4b, 0x03, 0x04, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00,
        0x54, 0xbd, 0xb5, 0x50, 0x2f, 0x20, 0x79, 0x55, 0x2f, 0x00,
        0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00,
        0x74, 0x65, 0x73, 0x74, 0x2e, 0x74, 0x78, 0x74, 0xca, 0x2d,
        0x1d, 0x27, 0x19, 0x19, 0x63, 0x43, 0x77, 0x9a, 0x71, 0x76,
        0xc9, 0xec, 0xd1, 0x6f, 0xd9, 0xf5, 0x22, 0x67, 0xb3, 0x8f,
        0x52, 0xb5, 0x41, 0xbc, 0x5c, 0x36, 0xf2, 0x1d, 0x84, 0xc3,
        0xc0, 0x28, 0x3b, 0xfd, 0xe1, 0x70, 0xc2, 0xcc, 0x0c, 0x11,
        0x0c, 0xc5, 0x95, 0x2f, 0xa4, 0x50, 0x4b, 0x01, 0x02, 0x3f,
        0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0x54, 0xbd, 0xb5,
        0x50, 0x2f, 0x20, 0x79, 0x55, 0x2f, 0x00, 0x00, 0x00, 0x23,
        0x00, 0x00, 0x00, 0x08, 0x00, 0x24, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x74, 0x78, 0x74, 0x0a,
        0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x18,
        0x00, 0x31, 0xb2, 0x3b, 0xbf, 0xb8, 0x2f, 0xd6, 0x01, 0x31,
        0xb2, 0x3b, 0xbf, 0xb8, 0x2f, 0xd6, 0x01, 0xa8, 0xc4, 0x45,
        0xbd, 0xb8, 0x2f, 0xd6, 0x01, 0x50, 0x4b, 0x05, 0x06, 0x00,
        0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x5a, 0x00, 0x00,
        0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00
    ]);

    let mut archive = zip::ZipArchive::new(zip_file_bytes).unwrap();

    assert_eq!(archive.len(), 1); //Only one file inside archive: `test.txt`

    {
        // No password
        let file = archive.by_index(0);
        assert!(file.is_err());
        if let Err(error) = file {
            match error {
                zip::result::ZipError::PasswordRequired => (),
                _ => panic!(),
            }
        } else {
            panic!();
        }
    }

    {
        // Wrong password
        let file = archive.by_index_decrypt(0, "wrong password".as_bytes());
        assert!(file.is_err());
        if let Err(error) = file {
            match error {
                zip::result::ZipError::InvalidPassword => (),
                _ => panic!(),
            }
        } else {
            panic!();
        }
    }

    {
        // Correct password, read contents
        let mut file = archive.by_index_decrypt(0, "test".as_bytes()).unwrap();
        let file_name = file.sanitized_name();
        assert_eq!(file_name, std::path::PathBuf::from("test.txt"));

        let mut data = Vec::new();
        file.read_to_end(&mut data).unwrap();
        assert_eq!(data, "abcdefghijklmnopqrstuvwxyz123456789".as_bytes());
    }
}
<|endoftext|>


<commit_before><commit_msg>Add camera module<commit_after>use core::{Entity, Vec2};

/// The camera
struct Cam<'a> {
  /// The former camera pos
  former_pos: Vec2<i64>,
  /// The entity in focus
  in_focus: &'a Entity,
  /// The transition state
  trans_state: f64,
}

// TODO: Make the camera locked to the player? (Or is this a bad idea?)

const VELOCITY: f64 = 0.1;

impl<'a> Cam<'a> {
  /// Creates a new Cam
  fn new(focus: &'a Entity) -> Cam {
    Cam {
      former_pos: focus.get_pos(),
      in_focus: focus,
      trans_state: 0.0,
    }
  }
  /// Updates the Cam
  fn update(&mut self, dt: f64) {
    self.trans_state += dt * VELOCITY;
    if self.trans_state > 1.0 {
      self.trans_state = 0.0;
      self.former_pos = self.in_focus.get_pos();
    }
  }
  /// Get position
  fn get_pos(&self) -> Vec2<f64> {
    let pos = Vec2(self.get_pos().x() as f64, self.get_pos().y() as f64);
    pos * self.trans_state
    + pos * (1.0 - self.trans_state)
  }
}
<|endoftext|>


<commit_before>//! Tests for various types of file (video, image, compressed, etc).
//!
//! Currently this is dependent on the file’s name and extension, because
//! those are the only metadata that we have access to without reading the
//! file’s contents.

use fs::File;

impl<'_> File<'_> {

    /// An “immediate” file is something that can be run or activated somehow
    /// in order to kick off the build of a project. It’s usually only present
    /// in directories full of source code.
    pub fn is_immediate(&self) -> bool {
        self.name.starts_with("README") || self.name_is_one_of( &[
            "Makefile", "Cargo.toml", "SConstruct", "CMakeLists.txt",
            "build.gradle", "Rakefile", "Gruntfile.js",
            "Gruntfile.coffee",
        ])
    }

    pub fn is_image(&self) -> bool {
        self.extension_is_one_of( &[
            "png", "jpeg", "jpg", "gif", "bmp", "tiff", "tif",
            "ppm", "pgm", "pbm", "pnm", "webp", "raw", "arw",
            "svg", "stl", "eps", "dvi", "ps", "cbr",
            "cbz", "xpm", "ico",
        ])
    }

    pub fn is_video(&self) -> bool {
        self.extension_is_one_of( &[
            "avi", "flv", "m2v", "mkv", "mov", "mp4", "mpeg",
            "mpg", "ogm", "ogv", "vob", "wmv",
        ])
    }

    pub fn is_music(&self) -> bool {
        self.extension_is_one_of( &[
            "aac", "m4a", "mp3", "ogg", "wma",
        ])
    }

    // Lossless music, rather than any other kind of data...
    pub fn is_lossless(&self) -> bool {
        self.extension_is_one_of( &[
            "alac", "ape", "flac", "wav",
        ])
    }

    pub fn is_crypto(&self) -> bool {
        self.extension_is_one_of( &[
            "zip", "tar", "Z", "gz", "bz2", "a", "ar", "7z",
            "iso", "dmg", "tc", "rar", "par",
        ])
    }

    pub fn is_document(&self) -> bool {
        self.extension_is_one_of( &[
            "djvu", "doc", "docx", "dvi", "eml", "eps", "fotd",
            "odp", "odt", "pdf", "ppt", "pptx", "rtf",
            "xls", "xlsx",
        ])
    }

    pub fn is_compressed(&self) -> bool {
        self.extension_is_one_of( &[
            "zip", "tar", "Z", "gz", "bz2", "a", "ar", "7z",
            "iso", "dmg", "tc", "rar", "par"
        ])
    }

    pub fn is_temp(&self) -> bool {
        self.name.ends_with("~")
            || (self.name.starts_with("#") && self.name.ends_with("#"))
            || self.extension_is_one_of( &[ "tmp", "swp", "swo", "swn", "bak" ])
    }

    pub fn is_compiled(&self) -> bool {
        if self.extension_is_one_of( &[ "class", "elc", "hi", "o", "pyc" ]) {
            true
        }
        else if let Some(dir) = self.dir {
            self.get_source_files().iter().any(|path| dir.contains(path))
        }
        else {
            false
        }
    }
}

#[cfg(broken_test)]
mod test {
    use file::test::{dummy_stat, new_file};

    #[test]
    fn lowercase() {
        let file = new_file(dummy_stat(), "/barracks.wav");
        assert_eq!(FileType::Lossless, file.get_type())
    }

    #[test]
    fn uppercase() {
        let file = new_file(dummy_stat(), "/BARRACKS.WAV");
        assert_eq!(FileType::Lossless, file.get_type())
    }

    #[test]
    fn cargo() {
        let file = new_file(dummy_stat(), "/Cargo.toml");
        assert_eq!(FileType::Immediate, file.get_type())
    }

    #[test]
    fn not_cargo() {
        let file = new_file(dummy_stat(), "/cargo.toml");
        assert_eq!(FileType::Normal, file.get_type())
    }
}
<commit_msg>Correct the list of crypto extensions<commit_after>//! Tests for various types of file (video, image, compressed, etc).
//!
//! Currently this is dependent on the file’s name and extension, because
//! those are the only metadata that we have access to without reading the
//! file’s contents.

use fs::File;

impl<'_> File<'_> {

    /// An “immediate” file is something that can be run or activated somehow
    /// in order to kick off the build of a project. It’s usually only present
    /// in directories full of source code.
    pub fn is_immediate(&self) -> bool {
        self.name.starts_with("README") || self.name_is_one_of( &[
            "Makefile", "Cargo.toml", "SConstruct", "CMakeLists.txt",
            "build.gradle", "Rakefile", "Gruntfile.js",
            "Gruntfile.coffee",
        ])
    }

    pub fn is_image(&self) -> bool {
        self.extension_is_one_of( &[
            "png", "jpeg", "jpg", "gif", "bmp", "tiff", "tif",
            "ppm", "pgm", "pbm", "pnm", "webp", "raw", "arw",
            "svg", "stl", "eps", "dvi", "ps", "cbr",
            "cbz", "xpm", "ico",
        ])
    }

    pub fn is_video(&self) -> bool {
        self.extension_is_one_of( &[
            "avi", "flv", "m2v", "mkv", "mov", "mp4", "mpeg",
            "mpg", "ogm", "ogv", "vob", "wmv",
        ])
    }

    pub fn is_music(&self) -> bool {
        self.extension_is_one_of( &[
            "aac", "m4a", "mp3", "ogg", "wma",
        ])
    }

    // Lossless music, rather than any other kind of data...
    pub fn is_lossless(&self) -> bool {
        self.extension_is_one_of( &[
            "alac", "ape", "flac", "wav",
        ])
    }

    pub fn is_crypto(&self) -> bool {
        self.extension_is_one_of( &[
            "asc", "enc", "gpg", "pgp", "sig", "signature", "pfx", "p12",
        ])
    }

    pub fn is_document(&self) -> bool {
        self.extension_is_one_of( &[
            "djvu", "doc", "docx", "dvi", "eml", "eps", "fotd",
            "odp", "odt", "pdf", "ppt", "pptx", "rtf",
            "xls", "xlsx",
        ])
    }

    pub fn is_compressed(&self) -> bool {
        self.extension_is_one_of( &[
            "zip", "tar", "Z", "gz", "bz2", "a", "ar", "7z",
            "iso", "dmg", "tc", "rar", "par"
        ])
    }

    pub fn is_temp(&self) -> bool {
        self.name.ends_with("~")
            || (self.name.starts_with("#") && self.name.ends_with("#"))
            || self.extension_is_one_of( &[ "tmp", "swp", "swo", "swn", "bak" ])
    }

    pub fn is_compiled(&self) -> bool {
        if self.extension_is_one_of( &[ "class", "elc", "hi", "o", "pyc" ]) {
            true
        }
        else if let Some(dir) = self.dir {
            self.get_source_files().iter().any(|path| dir.contains(path))
        }
        else {
            false
        }
    }
}

#[cfg(broken_test)]
mod test {
    use file::test::{dummy_stat, new_file};

    #[test]
    fn lowercase() {
        let file = new_file(dummy_stat(), "/barracks.wav");
        assert_eq!(FileType::Lossless, file.get_type())
    }

    #[test]
    fn uppercase() {
        let file = new_file(dummy_stat(), "/BARRACKS.WAV");
        assert_eq!(FileType::Lossless, file.get_type())
    }

    #[test]
    fn cargo() {
        let file = new_file(dummy_stat(), "/Cargo.toml");
        assert_eq!(FileType::Immediate, file.get_type())
    }

    #[test]
    fn not_cargo() {
        let file = new_file(dummy_stat(), "/cargo.toml");
        assert_eq!(FileType::Normal, file.get_type())
    }
}
<|endoftext|>


<commit_before><commit_msg>smbus: implement smbus_read_word_data and smbus_write_word_data<commit_after><|endoftext|>


<commit_before><commit_msg>(refactor) Refactored Iron to use Request and Response types.<commit_after><|endoftext|>


<commit_before><commit_msg>(feat) Impl'ed iron.smelt.<commit_after><|endoftext|>


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

/*! Task-local reference counted boxes

The `Rc` type provides shared ownership of an immutable value. Destruction is deterministic, and
will occur as soon as the last owner is gone. It is marked as non-sendable because it avoids the
overhead of atomic reference counting.

*/

use ptr::RawPtr;
use unstable::intrinsics::transmute;
use ops::Drop;
use kinds::{Freeze, Send};
use clone::{Clone, DeepClone};

struct RcBox<T> {
    value: T,
    count: uint
}

/// Immutable reference counted pointer type
#[unsafe_no_drop_flag]
#[no_send]
pub struct Rc<T> {
    priv ptr: *mut RcBox<T>
}

impl<T: Freeze> Rc<T> {
    /// Construct a new reference-counted box from a `Freeze` value
    #[inline]
    pub fn new(value: T) -> Rc<T> {
        unsafe {
            Rc::new_unchecked(value)
        }
    }
}

impl<T: Send> Rc<T> {
    /// Construct a new reference-counted box from a `Send` value
    #[inline]
    pub fn from_send(value: T) -> Rc<T> {
        unsafe {
            Rc::new_unchecked(value)
        }
    }
}

impl<T> Rc<T> {
    /// Unsafety construct a new reference-counted box from any value.
    ///
    /// It is possible to create cycles, which will leak, and may interact
    /// poorly with managed pointers.
    #[inline]
    pub unsafe fn new_unchecked(value: T) -> Rc<T> {
        Rc{ptr: transmute(~RcBox{value: value, count: 1})}
    }

    /// Borrow the value contained in the reference-counted box
    #[inline]
    pub fn borrow<'r>(&'r self) -> &'r T {
        unsafe { &(*self.ptr).value }
    }
}

impl<T> Clone for Rc<T> {
    #[inline]
    fn clone(&self) -> Rc<T> {
        unsafe {
            (*self.ptr).count += 1;
            Rc{ptr: self.ptr}
        }
    }
}

impl<T: DeepClone> DeepClone for Rc<T> {
    #[inline]
    fn deep_clone(&self) -> Rc<T> {
        unsafe { Rc::new_unchecked(self.borrow().deep_clone()) }
    }
}

#[unsafe_destructor]
impl<T> Drop for Rc<T> {
    fn drop(&mut self) {
        unsafe {
            if self.ptr.is_not_null() {
                (*self.ptr).count -= 1;
                if (*self.ptr).count == 0 {
                    let _: ~RcBox<T> = transmute(self.ptr);
                }
            }
        }
    }
}

#[cfg(test)]
mod test_rc {
    use super::*;
    use cell::Cell;

    #[test]
    fn test_clone() {
        let x = Rc::from_send(Cell::new(5));
        let y = x.clone();
        do x.borrow().with_mut_ref |inner| {
            *inner = 20;
        }
        assert_eq!(y.borrow().take(), 20);
    }

    #[test]
    fn test_deep_clone() {
        let x = Rc::from_send(Cell::new(5));
        let y = x.deep_clone();
        do x.borrow().with_mut_ref |inner| {
            *inner = 20;
        }
        assert_eq!(y.borrow().take(), 5);
    }

    #[test]
    fn test_simple() {
        let x = Rc::new(5);
        assert_eq!(*x.borrow(), 5);
    }

    #[test]
    fn test_simple_clone() {
        let x = Rc::new(5);
        let y = x.clone();
        assert_eq!(*x.borrow(), 5);
        assert_eq!(*y.borrow(), 5);
    }

    #[test]
    fn test_destructor() {
        let x = Rc::from_send(~5);
        assert_eq!(**x.borrow(), 5);
    }
}
<commit_msg>Move Rc tests away from Cell<commit_after>// Copyright 2013 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.

/*! Task-local reference counted boxes

The `Rc` type provides shared ownership of an immutable value. Destruction is deterministic, and
will occur as soon as the last owner is gone. It is marked as non-sendable because it avoids the
overhead of atomic reference counting.

*/

use ptr::RawPtr;
use unstable::intrinsics::transmute;
use ops::Drop;
use kinds::{Freeze, Send};
use clone::{Clone, DeepClone};

struct RcBox<T> {
    value: T,
    count: uint
}

/// Immutable reference counted pointer type
#[unsafe_no_drop_flag]
#[no_send]
pub struct Rc<T> {
    priv ptr: *mut RcBox<T>
}

impl<T: Freeze> Rc<T> {
    /// Construct a new reference-counted box from a `Freeze` value
    #[inline]
    pub fn new(value: T) -> Rc<T> {
        unsafe {
            Rc::new_unchecked(value)
        }
    }
}

impl<T: Send> Rc<T> {
    /// Construct a new reference-counted box from a `Send` value
    #[inline]
    pub fn from_send(value: T) -> Rc<T> {
        unsafe {
            Rc::new_unchecked(value)
        }
    }
}

impl<T> Rc<T> {
    /// Unsafety construct a new reference-counted box from any value.
    ///
    /// It is possible to create cycles, which will leak, and may interact
    /// poorly with managed pointers.
    #[inline]
    pub unsafe fn new_unchecked(value: T) -> Rc<T> {
        Rc{ptr: transmute(~RcBox{value: value, count: 1})}
    }

    /// Borrow the value contained in the reference-counted box
    #[inline]
    pub fn borrow<'r>(&'r self) -> &'r T {
        unsafe { &(*self.ptr).value }
    }
}

impl<T> Clone for Rc<T> {
    #[inline]
    fn clone(&self) -> Rc<T> {
        unsafe {
            (*self.ptr).count += 1;
            Rc{ptr: self.ptr}
        }
    }
}

impl<T: DeepClone> DeepClone for Rc<T> {
    #[inline]
    fn deep_clone(&self) -> Rc<T> {
        unsafe { Rc::new_unchecked(self.borrow().deep_clone()) }
    }
}

#[unsafe_destructor]
impl<T> Drop for Rc<T> {
    fn drop(&mut self) {
        unsafe {
            if self.ptr.is_not_null() {
                (*self.ptr).count -= 1;
                if (*self.ptr).count == 0 {
                    let _: ~RcBox<T> = transmute(self.ptr);
                }
            }
        }
    }
}

#[cfg(test)]
mod test_rc {
    use super::*;
    use mutable::Mut;

    #[test]
    fn test_clone() {
        let x = Rc::from_send(Mut::new(5));
        let y = x.clone();
        do x.borrow().map_mut |inner| {
            *inner = 20;
        }
        assert_eq!(y.borrow().map(|v| *v), 20);
    }

    #[test]
    fn test_deep_clone() {
        let x = Rc::from_send(Mut::new(5));
        let y = x.deep_clone();
        do x.borrow().map_mut |inner| {
            *inner = 20;
        }
        assert_eq!(y.borrow().map(|v| *v), 5);
    }

    #[test]
    fn test_simple() {
        let x = Rc::new(5);
        assert_eq!(*x.borrow(), 5);
    }

    #[test]
    fn test_simple_clone() {
        let x = Rc::new(5);
        let y = x.clone();
        assert_eq!(*x.borrow(), 5);
        assert_eq!(*y.borrow(), 5);
    }

    #[test]
    fn test_destructor() {
        let x = Rc::from_send(~5);
        assert_eq!(**x.borrow(), 5);
    }
}
<|endoftext|>


<commit_before><commit_msg>remove debug trace, added oauth_web example<commit_after><|endoftext|>


<commit_before><commit_msg>Make 'http' public.<commit_after><|endoftext|>


<commit_before><commit_msg>Factorial in Rust<commit_after><|endoftext|>


<commit_before><commit_msg>Added an executable integration test of sorts<commit_after><|endoftext|>


<commit_before><commit_msg>(refactor) Make status optional, defaulting to 404 on write_back.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed term defining.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove 'ein' debug prefix<commit_after><|endoftext|>


<commit_before><commit_msg>Minor rejigging.<commit_after><|endoftext|>


<commit_before><commit_msg>Change layout<commit_after><|endoftext|>


<commit_before><commit_msg>Clean up<commit_after><|endoftext|>


<commit_before><commit_msg>Fix how we correct schedules that cross midnight.<commit_after><|endoftext|>


<commit_before><commit_msg>parsed nyaa title<commit_after><|endoftext|>


<commit_before><commit_msg>chat: Now uses `Json::from_reader()` directly.<commit_after><|endoftext|>


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

use driver::session::Session;
use middle::resolve;
use middle::ty;
use middle::typeck;
use util::ppaux;

use syntax::ast::*;
use syntax::codemap;
use syntax::{oldvisit, ast_util, ast_map};

pub fn check_crate(sess: Session,
                   crate: &Crate,
                   ast_map: ast_map::map,
                   def_map: resolve::DefMap,
                   method_map: typeck::method_map,
                   tcx: ty::ctxt) {
    oldvisit::visit_crate(crate, (false, oldvisit::mk_vt(@oldvisit::Visitor {
        visit_item: |a,b| check_item(sess, ast_map, def_map, a, b),
        visit_pat: check_pat,
        visit_expr: |a,b|
            check_expr(sess, def_map, method_map, tcx, a, b),
        .. *oldvisit::default_visitor()
    })));
    sess.abort_if_errors();
}

pub fn check_item(sess: Session,
                  ast_map: ast_map::map,
                  def_map: resolve::DefMap,
                  it: @item,
                  (_is_const, v): (bool,
                                   oldvisit::vt<bool>)) {
    match it.node {
      item_static(_, _, ex) => {
        (v.visit_expr)(ex, (true, v));
        check_item_recursion(sess, ast_map, def_map, it);
      }
      item_enum(ref enum_definition, _) => {
        for var in (*enum_definition).variants.iter() {
            for ex in var.node.disr_expr.iter() {
                (v.visit_expr)(*ex, (true, v));
            }
        }
      }
      _ => oldvisit::visit_item(it, (false, v))
    }
}

pub fn check_pat(p: @pat, (_is_const, v): (bool, oldvisit::vt<bool>)) {
    fn is_str(e: @expr) -> bool {
        match e.node {
            expr_vstore(
                @expr { node: expr_lit(@codemap::spanned {
                    node: lit_str(_),
                    _}),
                       _ },
                expr_vstore_uniq
            ) => true,
            _ => false
        }
    }
    match p.node {
      // Let through plain ~-string literals here
      pat_lit(a) => if !is_str(a) { (v.visit_expr)(a, (true, v)); },
      pat_range(a, b) => {
        if !is_str(a) { (v.visit_expr)(a, (true, v)); }
        if !is_str(b) { (v.visit_expr)(b, (true, v)); }
      }
      _ => oldvisit::visit_pat(p, (false, v))
    }
}

pub fn check_expr(sess: Session,
                  def_map: resolve::DefMap,
                  method_map: typeck::method_map,
                  tcx: ty::ctxt,
                  e: @expr,
                  (is_const, v): (bool,
                                  oldvisit::vt<bool>)) {
    if is_const {
        match e.node {
          expr_unary(_, deref, _) => { }
          expr_unary(_, box(_), _) | expr_unary(_, uniq, _) => {
            sess.span_err(e.span,
                          "disallowed operator in constant expression");
            return;
          }
          expr_lit(@codemap::spanned {node: lit_str(_), _}) => { }
          expr_binary(*) | expr_unary(*) => {
            if method_map.contains_key(&e.id) {
                sess.span_err(e.span, "user-defined operators are not \
                                       allowed in constant expressions");
            }
          }
          expr_lit(_) => (),
          expr_cast(_, _) => {
            let ety = ty::expr_ty(tcx, e);
            if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) {
                sess.span_err(e.span, ~"can not cast to `" +
                              ppaux::ty_to_str(tcx, ety) +
                              "` in a constant expression");
            }
          }
          expr_path(ref pth) => {
            // NB: In the future you might wish to relax this slightly
            // to handle on-demand instantiation of functions via
            // foo::<bar> in a const. Currently that is only done on
            // a path in trans::callee that only works in block contexts.
            if pth.types.len() != 0 {
                sess.span_err(
                    e.span, "paths in constants may only refer to \
                             items without type parameters");
            }
            match def_map.find(&e.id) {
              Some(&def_static(*)) |
              Some(&def_fn(_, _)) |
              Some(&def_variant(_, _)) |
              Some(&def_struct(_)) => { }

              Some(&def) => {
                debug!("(checking const) found bad def: %?", def);
                sess.span_err(
                    e.span,
                    "paths in constants may only refer to \
                     constants or functions");
              }
              None => {
                sess.span_bug(e.span, "unbound path in const?!");
              }
            }
          }
          expr_call(callee, _, NoSugar) => {
            match def_map.find(&callee.id) {
                Some(&def_struct(*)) => {}    // OK.
                Some(&def_variant(*)) => {}    // OK.
                _ => {
                    sess.span_err(
                        e.span,
                        "function calls in constants are limited to \
                         struct and enum constructors");
                }
            }
          }
          expr_paren(e) => { check_expr(sess, def_map, method_map,
                                         tcx, e, (is_const, v)); }
          expr_vstore(_, expr_vstore_slice) |
          expr_vec(_, m_imm) |
          expr_addr_of(m_imm, _) |
          expr_field(*) |
          expr_index(*) |
          expr_tup(*) |
          expr_struct(*) => { }
          expr_addr_of(*) => {
                sess.span_err(
                    e.span,
                    "borrowed pointers in constants may only refer to \
                     immutable values");
          }
          _ => {
            sess.span_err(e.span,
                          "constant contains unimplemented expression type");
            return;
          }
        }
    }
    match e.node {
      expr_lit(@codemap::spanned {node: lit_int(v, t), _}) => {
        if t != ty_char {
            if (v as u64) > ast_util::int_ty_max(
                if t == ty_i { sess.targ_cfg.int_type } else { t }) {
                sess.span_err(e.span, "literal out of range for its type");
            }
        }
      }
      expr_lit(@codemap::spanned {node: lit_uint(v, t), _}) => {
        if v > ast_util::uint_ty_max(
            if t == ty_u { sess.targ_cfg.uint_type } else { t }) {
            sess.span_err(e.span, "literal out of range for its type");
        }
      }
      _ => ()
    }
    oldvisit::visit_expr(e, (is_const, v));
}

#[deriving(Clone)]
struct env {
    root_it: @item,
    sess: Session,
    ast_map: ast_map::map,
    def_map: resolve::DefMap,
    idstack: @mut ~[NodeId]
}

// Make sure a const item doesn't recursively refer to itself
// FIXME: Should use the dependency graph when it's available (#1356)
pub fn check_item_recursion(sess: Session,
                            ast_map: ast_map::map,
                            def_map: resolve::DefMap,
                            it: @item) {
    let env = env {
        root_it: it,
        sess: sess,
        ast_map: ast_map,
        def_map: def_map,
        idstack: @mut ~[]
    };

    let visitor = oldvisit::mk_vt(@oldvisit::Visitor {
        visit_item: visit_item,
        visit_expr: visit_expr,
        .. *oldvisit::default_visitor()
    });
    (visitor.visit_item)(it, (env, visitor));

    fn visit_item(it: @item, (env, v): (env, oldvisit::vt<env>)) {
        if env.idstack.iter().any(|x| x == &(it.id)) {
            env.sess.span_fatal(env.root_it.span, "recursive constant");
        }
        env.idstack.push(it.id);
        oldvisit::visit_item(it, (env, v));
        env.idstack.pop();
    }

    fn visit_expr(e: @expr, (env, v): (env, oldvisit::vt<env>)) {
        match e.node {
            expr_path(*) => match env.def_map.find(&e.id) {
                Some(&def_static(def_id, _)) if ast_util::is_local(def_id) =>
                    match env.ast_map.get_copy(&def_id.node) {
                        ast_map::node_item(it, _) => {
                            (v.visit_item)(it, (env, v));
                        }
                        _ => fail!("const not bound to an item")
                    },
                _ => ()
            },
            _ => ()
        }
        oldvisit::visit_expr(e, (env, v));
    }
}
<commit_msg>Ported check_const from oldvisit to <V:Visitor> trait API.<commit_after>// Copyright 2012-2013 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.

use driver::session::Session;
use middle::resolve;
use middle::ty;
use middle::typeck;
use util::ppaux;

use syntax::ast::*;
use syntax::codemap;
use syntax::{ast_util, ast_map};
use syntax::visit::Visitor;
use syntax::visit;

struct CheckCrateVisitor {
    sess: Session,
    ast_map: ast_map::map,
    def_map: resolve::DefMap,
    method_map: typeck::method_map,
    tcx: ty::ctxt,
}

impl Visitor<bool> for CheckCrateVisitor {
    fn visit_item(&mut self, i:@item, env:bool) {
        check_item(self, self.sess, self.ast_map, self.def_map, i, env);
    }
    fn visit_pat(&mut self, p:@pat, env:bool) {
        check_pat(self, p, env);
    }
    fn visit_expr(&mut self, ex:@expr, env:bool) {
        check_expr(self, self.sess, self.def_map, self.method_map,
                   self.tcx, ex, env);
    }
}

pub fn check_crate(sess: Session,
                   crate: &Crate,
                   ast_map: ast_map::map,
                   def_map: resolve::DefMap,
                   method_map: typeck::method_map,
                   tcx: ty::ctxt) {
    let mut v = CheckCrateVisitor {
        sess: sess,
        ast_map: ast_map,
        def_map: def_map,
        method_map: method_map,
        tcx: tcx,
    };
    visit::walk_crate(&mut v, crate, false);
    sess.abort_if_errors();
}

pub fn check_item(v: &mut CheckCrateVisitor,
                  sess: Session,
                  ast_map: ast_map::map,
                  def_map: resolve::DefMap,
                  it: @item,
                  _is_const: bool) {
    match it.node {
      item_static(_, _, ex) => {
        v.visit_expr(ex, true);
        check_item_recursion(sess, ast_map, def_map, it);
      }
      item_enum(ref enum_definition, _) => {
        for var in (*enum_definition).variants.iter() {
            for ex in var.node.disr_expr.iter() {
                v.visit_expr(*ex, true);
            }
        }
      }
      _ => visit::walk_item(v, it, false)
    }
}

pub fn check_pat(v: &mut CheckCrateVisitor, p: @pat, _is_const: bool) {
    fn is_str(e: @expr) -> bool {
        match e.node {
            expr_vstore(
                @expr { node: expr_lit(@codemap::spanned {
                    node: lit_str(_),
                    _}),
                       _ },
                expr_vstore_uniq
            ) => true,
            _ => false
        }
    }
    match p.node {
      // Let through plain ~-string literals here
      pat_lit(a) => if !is_str(a) { v.visit_expr(a, true); },
      pat_range(a, b) => {
        if !is_str(a) { v.visit_expr(a, true); }
        if !is_str(b) { v.visit_expr(b, true); }
      }
      _ => visit::walk_pat(v, p, false)
    }
}

pub fn check_expr(v: &mut CheckCrateVisitor,
                  sess: Session,
                  def_map: resolve::DefMap,
                  method_map: typeck::method_map,
                  tcx: ty::ctxt,
                  e: @expr,
                  is_const: bool) {
    if is_const {
        match e.node {
          expr_unary(_, deref, _) => { }
          expr_unary(_, box(_), _) | expr_unary(_, uniq, _) => {
            sess.span_err(e.span,
                          "disallowed operator in constant expression");
            return;
          }
          expr_lit(@codemap::spanned {node: lit_str(_), _}) => { }
          expr_binary(*) | expr_unary(*) => {
            if method_map.contains_key(&e.id) {
                sess.span_err(e.span, "user-defined operators are not \
                                       allowed in constant expressions");
            }
          }
          expr_lit(_) => (),
          expr_cast(_, _) => {
            let ety = ty::expr_ty(tcx, e);
            if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) {
                sess.span_err(e.span, ~"can not cast to `" +
                              ppaux::ty_to_str(tcx, ety) +
                              "` in a constant expression");
            }
          }
          expr_path(ref pth) => {
            // NB: In the future you might wish to relax this slightly
            // to handle on-demand instantiation of functions via
            // foo::<bar> in a const. Currently that is only done on
            // a path in trans::callee that only works in block contexts.
            if pth.types.len() != 0 {
                sess.span_err(
                    e.span, "paths in constants may only refer to \
                             items without type parameters");
            }
            match def_map.find(&e.id) {
              Some(&def_static(*)) |
              Some(&def_fn(_, _)) |
              Some(&def_variant(_, _)) |
              Some(&def_struct(_)) => { }

              Some(&def) => {
                debug!("(checking const) found bad def: %?", def);
                sess.span_err(
                    e.span,
                    "paths in constants may only refer to \
                     constants or functions");
              }
              None => {
                sess.span_bug(e.span, "unbound path in const?!");
              }
            }
          }
          expr_call(callee, _, NoSugar) => {
            match def_map.find(&callee.id) {
                Some(&def_struct(*)) => {}    // OK.
                Some(&def_variant(*)) => {}    // OK.
                _ => {
                    sess.span_err(
                        e.span,
                        "function calls in constants are limited to \
                         struct and enum constructors");
                }
            }
          }
          expr_paren(e) => { check_expr(v, sess, def_map, method_map,
                                        tcx, e, is_const); }
          expr_vstore(_, expr_vstore_slice) |
          expr_vec(_, m_imm) |
          expr_addr_of(m_imm, _) |
          expr_field(*) |
          expr_index(*) |
          expr_tup(*) |
          expr_struct(*) => { }
          expr_addr_of(*) => {
                sess.span_err(
                    e.span,
                    "borrowed pointers in constants may only refer to \
                     immutable values");
          }
          _ => {
            sess.span_err(e.span,
                          "constant contains unimplemented expression type");
            return;
          }
        }
    }
    match e.node {
      expr_lit(@codemap::spanned {node: lit_int(v, t), _}) => {
        if t != ty_char {
            if (v as u64) > ast_util::int_ty_max(
                if t == ty_i { sess.targ_cfg.int_type } else { t }) {
                sess.span_err(e.span, "literal out of range for its type");
            }
        }
      }
      expr_lit(@codemap::spanned {node: lit_uint(v, t), _}) => {
        if v > ast_util::uint_ty_max(
            if t == ty_u { sess.targ_cfg.uint_type } else { t }) {
            sess.span_err(e.span, "literal out of range for its type");
        }
      }
      _ => ()
    }
    visit::walk_expr(v, e, is_const);
}

#[deriving(Clone)]
struct env {
    root_it: @item,
    sess: Session,
    ast_map: ast_map::map,
    def_map: resolve::DefMap,
    idstack: @mut ~[NodeId]
}

struct CheckItemRecursionVisitor;

// Make sure a const item doesn't recursively refer to itself
// FIXME: Should use the dependency graph when it's available (#1356)
pub fn check_item_recursion(sess: Session,
                            ast_map: ast_map::map,
                            def_map: resolve::DefMap,
                            it: @item) {
    let env = env {
        root_it: it,
        sess: sess,
        ast_map: ast_map,
        def_map: def_map,
        idstack: @mut ~[]
    };

    let mut visitor = CheckItemRecursionVisitor;
    visitor.visit_item(it, env);
}

impl Visitor<env> for CheckItemRecursionVisitor {
    fn visit_item(&mut self, it: @item, env: env) {
        if env.idstack.iter().any(|x| x == &(it.id)) {
            env.sess.span_fatal(env.root_it.span, "recursive constant");
        }
        env.idstack.push(it.id);
        visit::walk_item(self, it, env);
        env.idstack.pop();
    }

    fn visit_expr(&mut self, e: @expr, env: env) {
        match e.node {
            expr_path(*) => match env.def_map.find(&e.id) {
                Some(&def_static(def_id, _)) if ast_util::is_local(def_id) =>
                    match env.ast_map.get_copy(&def_id.node) {
                        ast_map::node_item(it, _) => {
                            self.visit_item(it, env);
                        }
                        _ => fail!("const not bound to an item")
                    },
                _ => ()
            },
            _ => ()
        }
        visit::walk_expr(self, e, env);
    }
}
<|endoftext|>


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

#![allow(non_snake_case)]

register_diagnostics! {
    E0154,
    E0157,
    E0153,
    E0251, // a named type or value has already been imported in this module
    E0252, // a named type or value has already been imported in this module
    E0253, // not directly importable
    E0254, // import conflicts with imported crate in this module
    E0255, // import conflicts with value in this module
    E0256, // import conflicts with type in this module
    E0257, // inherent implementations are only allowed on types defined in the current module
    E0258, // import conflicts with existing submodule
    E0259, // an extern crate has already been imported into this module
    E0260, // name conflicts with an external crate that has been imported into this module
    E0317, // user-defined types or type parameters cannot shadow the primitive types
    E0364, // item is private
    E0365  // item is private
}
<commit_msg>Rollup merge of #25267 - meqif:explain_e0317, r=alexcrichton<commit_after>// Copyright 2014 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.

#![allow(non_snake_case)]

// Error messages for EXXXX errors.
// Each message should start and end with a new line, and be wrapped to 80 characters.
// In vim you can `:set tw=80` and use `gq` to wrap paragraphs. Use `:set tw=0` to disable.
register_long_diagnostics! {

E0154: r##"
Imports (`use` statements) are not allowed after non-item statements, such as
variable declarations and expression statements.

Here is an example that demonstrates the error:
```
fn f() {
    // Variable declaration before import
    let x = 0;
    use std::io::Read;
    ...
}
```

The solution is to declare the imports at the top of the block, function, or
file.

Here is the previous example again, with the correct order:
```
fn f() {
    use std::io::Read;
    let x = 0;
    ...
}
```

See the Declaration Statements section of the reference for more information
about what constitutes an Item declaration and what does not:

http://doc.rust-lang.org/reference.html#statements
"##,

E0259: r##"
The name chosen for an external crate conflicts with another external crate that
has been imported into the current module.

Wrong example:
```
extern crate a;
extern crate crate_a as a;
```

The solution is to choose a different name that doesn't conflict with any
external crate imported into the current module.

Correct example:
```
extern crate a;
extern crate crate_a as other_name;
```
"##,

E0260: r##"
The name for an item declaration conflicts with an external crate's name.

For instance,
```
extern crate abc;

struct abc;
```

There are two possible solutions:

Solution #1: Rename the item.

```
extern crate abc;

struct xyz;
```

Solution #2: Import the crate with a different name.

```
extern crate abc as xyz;

struct abc;
```

See the Declaration Statements section of the reference for more information
about what constitutes an Item declaration and what does not:

http://doc.rust-lang.org/reference.html#statements
"##,

E0317: r##"
User-defined types or type parameters cannot shadow the primitive types.
This error indicates you tried to define a type, struct or enum with the same
name as an existing primitive type.

See the Types section of the reference for more information about the primitive
types:

http://doc.rust-lang.org/reference.html#types
"##

}

register_diagnostics! {
    E0157,
    E0153,
    E0251, // a named type or value has already been imported in this module
    E0252, // a named type or value has already been imported in this module
    E0253, // not directly importable
    E0254, // import conflicts with imported crate in this module
    E0255, // import conflicts with value in this module
    E0256, // import conflicts with type in this module
    E0257, // inherent implementations are only allowed on types defined in the current module
    E0258, // import conflicts with existing submodule
    E0364, // item is private
    E0365  // item is private
}
<|endoftext|>


<commit_before><commit_msg>Um pequeno evaluador quase decente de expressões só pra se livrar da dependência externa. A estrutura do resto é bem precária, mas funciona<commit_after>use std::str::Chars;
use std::fmt::{Display, Formatter, self};

#[cfg(target_pointer_width = "64")]
pub type NumericType = f64;

#[cfg(target_pointer_width = "32")]
pub type NumericType = f32;

#[derive(Debug, PartialEq, Clone)]
pub enum Value {
    Str(String),
    Num(NumericType),
    NullOrEmpty,
}

impl Value {
    fn do_operation(&self, right: &Value, operator: Operator) -> Result<Value, String> {
        // Really really super duper dumb implementation below. This is the old backend anyway

        match self {
            &Value::Str(ref ls) => {
                if operator != Operator::Plus {
                    return Err("O único operador que strings aceitam é o +".to_owned());
                }

                let mut result = String::from(ls.as_str());

                if let &Value::Str(ref rs) = right {
                    result.push_str(rs.as_str());
                } else {
                    // Transform the right into a string, then
                    result.push_str(right.as_string().as_str());
                }

                Ok(Value::Str(result))
            }
            _ => {
                let left_val = if let &Value::Num(n) = self {
                    n
                } else {
                    0.0 // Null or empty
                };

                if let &Value::Str(_) = right {
                    return Err("TRAPEZIO DESCENDENTE não possui quaisquer operadores compatíveis com FIBRA".to_owned());
                }

                let right_val = if let &Value::Num(n) = right {
                    n
                } else {
                    0.0 // Null or empty
                };

                let result = match operator {
                    Operator::Plus => left_val + right_val,
                    Operator::Minus => left_val - right_val,
                    Operator::Multiplication => left_val * right_val,
                    Operator::Division => left_val / right_val,
                    _ => unreachable!()
                };

                Ok(Value::Num(result))
            }
        }
    }

    pub fn as_string(&self) -> String {
        match self {
            &Value::Str(ref sr) => sr.clone(),
            &Value::Num(num) => format!("{}", num),
            &Value::NullOrEmpty => "<nulo>".to_owned()
        }
    }

    pub fn try_parse(s: &str) -> Result<Value, String> {
        // If starts with a digit, is a number. Otherwise is a string
        if s.is_empty() {
            Ok(Value::Str(String::new()))
        } else {
            let first_char = s.chars().next().unwrap(); // Cannot fail since is not empty

            match first_char {
                '0' ... '9' => match s.parse::<NumericType>() {
                    Ok(v) => Ok(Value::Num(v)),
                    Err(e) => return Err(format!("{}", e)),
                }
                _ => Ok(Value::Str(s.to_owned()))
            }
        }
    }

    pub fn value_type(&self) -> ValueType {
        match self {
            &Value::Str(_) => ValueType::Str,
            &Value::Num(_) => ValueType::Num,
            &Value::NullOrEmpty => ValueType::NullOrEmpty,
        }
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            &Value::Num(x) => write!(f, "{}", x),
            &Value::Str(ref x) => write!(f, "{}", x),
            &Value::NullOrEmpty => write!(f, "<nulo>"), // Empty value
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum ValueType {
    Num,
    Str,
    NullOrEmpty,
}

const VALUETYPE_STR: &str = "FIBRA";
const VALUETYPE_NUM: &str = "TRAPEZIO DESCENDENTE";

impl ValueType {
    pub fn try_parse(expr: &str) -> Option<ValueType> {
        match expr.trim() {
            VALUETYPE_STR => Some(ValueType::Str),
            VALUETYPE_NUM => Some(ValueType::Num),
            _ => None,
        }
    }
}

pub trait ValueQuery {
    fn query(&self, _: &str) -> Option<Value> {
        unimplemented!()
    }

    fn query_raw(&self, _: &str) -> Option<String> {
        unimplemented!()
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
/// An operator that can be applied to one or more values
enum Operator {
    Plus,
    Minus,
    Division,
    Multiplication,
    Parenthesis,
}

impl Operator {
    fn from(c: char) -> Operator {
        match c {
            '+' => Operator::Plus,
            '-' => Operator::Minus,
            '/' => Operator::Division,
            '*' => Operator::Multiplication,
            '(' => Operator::Parenthesis,
            _ => unreachable!()
        }
    }
}

#[derive(Debug)]
/// An element of a expression
enum ExprElem {
    Value(Value),
    Operator(Operator),
}

// The base if for "should the parser quit when it finds the end of the input or a )?"
fn eval_scope<Query>(input: &mut Chars, query_func: &Query, base: bool) -> Result<Value, String>
    where Query: ValueQuery
{
    // Somehow this abomination works.

    // The stack is where the final evaluation is made
    let mut stack: Vec<ExprElem> = vec![];
    let mut last_value = Value::NullOrEmpty;
    let mut last_operator = Operator::Plus;
    let mut last_value_contents = String::new();
    // If the next value we find should be evaluated
    let mut eval_next = false;
    // Was the last value a variable?
    let mut was_last_variable = false;
    // Are we parsing a string?
    let mut is_inside_string = false;
    // Considering that we're currently inside a string, was the last character a escape?
    let mut last_character_was_escape = false;

    loop {
        if let Some(c) = input.next() {
            if c == '\n' {
                if !base {
                    return Err("O input terminou dentro de algum parentesis".to_owned());
                } else {
                    break;
                }
            } else if c == '\"' {
                if is_inside_string {
                    if last_character_was_escape {
                        last_character_was_escape = false;
                        last_value_contents.push(c);
                    } else {
                        is_inside_string = false;
                    }
                } else {
                    is_inside_string = true;
                }
            } else {
                match c {
                    '\\' if is_inside_string => {
                        if last_character_was_escape {
                            last_value_contents.push(c);
                            last_character_was_escape = false;
                        } else {
                            last_character_was_escape = true;
                        }
                    }

                    _ if is_inside_string => {
                        // Already checked for ", just push it
                        last_value_contents.push(c);
                    }

                    ')' => {
                        if !base {
                            break;
                        } else {
                            return Err("Parêntesis de fechamento sem nenhum aberto".to_owned());
                        }
                    }

                    '(' => {
                        if eval_next {
                            eval_next = false;

                            let paren = match eval_scope(input, query_func, false) {
                                Ok(v) => v,
                                Err(e) => return Err(e),
                            };

                            let result = match last_value.do_operation(&paren, last_operator) {
                                Ok(v) => v,
                                Err(e) => return Err(e)
                            };

                            last_value = Value::NullOrEmpty;

                            stack.push(ExprElem::Value(result));
                        } else {
                            let paren = match eval_scope(input, query_func, false) {
                                Ok(v) => v,
                                Err(e) => return Err(e)
                            };

                            stack.push(ExprElem::Value(paren));
                        }
                    }

                    ' ' if last_value_contents.is_empty() || !is_inside_string => {}

                    '+' | '-' | '/' | '*' => {
                        // Separator. Evaluate the value and do something that depends on the operator

                        if last_value_contents.is_empty() {
                            // Just push the operator and last value into the stack
                            if last_value != Value::NullOrEmpty {
                                stack.push(ExprElem::Value(last_value));
                                last_value = Value::NullOrEmpty;
                            }
                            stack.push(ExprElem::Operator(Operator::from(c)));
                            continue;
                        }

                        let mut current_val = if was_last_variable {
                            was_last_variable = false;
                            match query_func.query(&last_value_contents) {
                                Some(v) => v,
                                None => return Err(format!("A variável {} não foi encontrada", last_value_contents))
                            }
                        } else {
                            match Value::try_parse(&last_value_contents) {
                                Ok(v) => v,
                                Err(e) => return Err(e),
                            }
                        };

                        last_value_contents.clear();

                        if eval_next {
                            eval_next = false;

                            current_val = match last_value.do_operation(&current_val, last_operator) {
                                Ok(v) => v,
                                Err(e) => return Err(e)
                            };

                            last_value = Value::NullOrEmpty;
                        }

                        if c == ' ' { continue; }

                        // If the operator has low precedence, push it to the stack and that's all
                        // However, if the operator was high precedence, set it the value to the last one
                        // and set the flag to evaluate whatever is the next value, then push the result to the stack

                        if c == '+' || c == '-' {
                            stack.push(ExprElem::Value(current_val));
                            stack.push(ExprElem::Operator(Operator::from(c)));
                        } else {
                            last_value = current_val;
                            last_operator = Operator::from(c);
                            eval_next = true;
                        }
                    }

                    '_' | 'a' ... 'z' | 'A' ... 'Z' if last_value_contents.is_empty() => {
                        was_last_variable = true;
                        last_value_contents.push(c);
                    }

                    _ => {
                        last_value_contents.push(c);
                    }
                }
            }
        } else {
            if !base {
                return Err("O input terminou dentro de algum parentesis".to_owned());
            }
            break;
        }
    }

    // Check if no value was left behind
    if !last_value_contents.is_empty() {
        let res = if was_last_variable {
            match query_func.query(&last_value_contents) {
                Some(v) => v,
                None => return Err(format!("Variável {} não encontrada", last_value_contents))
            }
        } else {
            match Value::try_parse(&last_value_contents) {
                Ok(v) => v,
                Err(e) => return Err(e),
            }
        };

        if eval_next {
            stack.push(match last_value.do_operation(&res, last_operator) {
                Ok(v) => ExprElem::Value(v),
                Err(e) => return Err(e)
            });
        } else {
            stack.push(ExprElem::Value(res));
        }
    }

    // Evaluate the stack
    if stack.is_empty() {
        Err("Stack vazia".to_owned())
    } else if stack.len() == 1 {
        if let ExprElem::Value(v) = stack.pop().unwrap() {
            Ok(v)
        } else {
            Err("Stack só tem um elemento e é um operador :/".to_owned())
        }
    } else {
        let mut skip_first = false;
        let mut result = match &stack[0] {
            &ExprElem::Operator(_) => Value::NullOrEmpty,
            &ExprElem::Value(ref v) => {
                skip_first = true;
                v.clone()
            }
        };

        let mut stack_iter = stack.iter();

        if skip_first {
            let _ = stack_iter.next();
        }

        loop {
            // At each iteration, get one operator and one value (for the right) and operate with the result
            if let Some(elem) = stack_iter.next() {
                if let &ExprElem::Operator(op) = elem {
                    match stack_iter.next() {
                        Some(elem) => {
                            if let &ExprElem::Value(ref v) = elem {
                                result = match result.do_operation(v, op) {
                                    Ok(v) => v,
                                    Err(e) => return Err(e),
                                };
                            } else {
                                return Err(format!("Dois valores seguidos numa expressão. stack {:?}", stack));
                            }
                        }
                        None => break,
                    }
                } else {
                    return Err(format!("Dois valores seguidos numa expressão. stack {:?}", stack));
                }
            } else {
                break;
            }
        }

        println!("result is {:?}", result);

        Ok(result)
    }
}

/// Evaluate a expression and return the value wrapper in the Value enum
pub fn evaluate<Query>(expression: &str, query_func: &Query) -> Result<Value, String>
    where Query: ValueQuery
{
    let mut chars = expression.chars();
    eval_scope(&mut chars, query_func, true)
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue 2467<commit_after>enum test { thing = 3u } //! ERROR mismatched types
//!^ ERROR expected signed integer constant
fn main() {
    log(error, thing as int);
    assert(thing as int == 3);
}
<|endoftext|>


<commit_before>extern crate rsedis;

use rsedis::database::Database;
use rsedis::database::Value;

#[test]
fn set_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    let expected = Vec::clone(&value);
    database.set(&key, value);
    match database.get(&key) {
        Some(val) => {
            match val {
                &Value::Data(ref bytes) => assert_eq!(*bytes, expected),
            }
        }
        _ => assert!(false),
    }
}
<commit_msg>Add empty key test<commit_after>extern crate rsedis;

use rsedis::database::Database;
use rsedis::database::Value;

#[test]
fn set_get() {
    let mut database = Database::new();
    let key = vec![1u8];
    let value = vec![1u8, 2, 3, 4];
    let expected = Vec::clone(&value);
    database.set(&key, value);
    match database.get(&key) {
        Some(val) => {
            match val {
                &Value::Data(ref bytes) => assert_eq!(*bytes, expected),
            }
        }
        _ => assert!(false),
    }
}

#[test]
fn get_empty() {
    let database = Database::new();
    let key = vec![1u8];
    match database.get(&key) {
        None => {},
        _ => assert!(false),
    }
}
<|endoftext|>


<commit_before>// error-pattern:left: 14 does not equal right: 15

#[deriving(Eq)]
struct Point { x : int }

fn main() {
    assert_eq!(14,15);
}
<commit_msg>fix test<commit_after>// error-pattern:assertion failed: `(left == right) && (right == left)` (left: `14`, right: `15`)

#[deriving(Eq)]
struct Point { x : int }

fn main() {
    assert_eq!(14,15);
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #494 - johalun:dragonfly-ttycom, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>Add some comments and better variable names.<commit_after><|endoftext|>


<commit_before><commit_msg>Added auto-version example<commit_after>extern crate clap;

use clap::App;

fn main() {
    // You can have clap pull the application version directly from your Cargo.toml starting with
    // clap v0.4.14 on crates.io (or master#a81f915 on github)
    //
    // Thanks to https://github.com/jhelwig for pointing this out
    let version = format!("{}.{}.{}{}",
                          env!("CARGO_PKG_VERSION_MAJOR"),
                          env!("CARGO_PKG_VERSION_MINOR"),
                          env!("CARGO_PKG_VERSION_PATCH"),
                          option_env!("CARGO_PKG_VERSION_PRE").unwrap_or(""));

    let matches = App::new("myapp").about("does awesome things").version(&version[..]).get_matches();

    // running the this app with the -v or --version will display whatever version is in your
    // Cargo.toml, the default being: myapp 0.0.1
}<|endoftext|>


<commit_before>//! A simple crate for executing work on a thread pool, and getting back a
//! future.
//!
//! This crate provides a simple thread pool abstraction for running work
//! externally from the current thread that's running. An instance of `Future`
//! is handed back to represent that the work may be done later, and futher
//! computations can be chained along with it as well.
//!
//! ```rust
//! extern crate futures;
//! extern crate futures_cpupool;
//!
//! use std::sync::mpsc::channel;
//!
//! use futures::Future;
//! use futures_cpupool::CpuPool;
//!
//! # fn long_running_computation() -> u32 { 2 }
//! # fn long_running_computation2(a: u32) -> u32 { a }
//! # fn main() {
//!
//! // Create a worker thread pool with four threads
//! let pool = CpuPool::new(4);
//!
//! // Execute some work on the thread pool, optionally closing over data.
//! let a = pool.execute(long_running_computation);
//! let b = pool.execute(|| long_running_computation2(100));
//!
//! // Express some further computation once the work is completed on the thread
//! // pool.
//! let c = a.join(b).map(|(a, b)| a + b);
//!
//! // Block the current thread to get the result.
//! let (tx, rx) = channel();
//! c.then(move |res| {
//!     tx.send(res)
//! }).forget();
//! let res = rx.recv().unwrap();
//!
//! // Print out the result
//! println!("{:?}", res);
//! # }
//! ```

#![deny(missing_docs)]

extern crate crossbeam;
extern crate futures;
extern crate num_cpus;

use std::any::Any;
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

use crossbeam::sync::MsQueue;
use futures::{Future, oneshot, Oneshot, Poll};

/// A thread pool intended to run CPU intensive work.
///
/// This thread pool will hand out futures representing the completed work
/// that happens on the thread pool itself, and the futures can then be later
/// composed with other work as part of an overall computation.
///
/// The worker threads associated with a thread pool are kept alive so long as
/// there is an open handle to the `CpuPool` or there is work running on them. Once
/// all work has been drained and all references have gone away the worker
/// threads will be shut down.
///
/// Currently `CpuPool` implements `Clone` which just clones a new reference to
/// the underlying thread pool.
pub struct CpuPool {
    inner: Arc<Inner>,
}

fn _assert() {
    fn _assert_send<T: Send>() {}
    fn _assert_sync<T: Sync>() {}
    _assert_send::<CpuPool>();
    _assert_sync::<CpuPool>();
}

struct Inner {
    queue: MsQueue<Message>,
    cnt: AtomicUsize,
    size: u32,
}

/// The type of future returned from the `CpuPool::execute` function.
///
/// This future will either resolve to `R`, the completed value, or
/// `Box<Any+Send>` if the computation panics (with the payload of the panic).
pub struct CpuFuture<R: Send + 'static> {
    inner: Oneshot<thread::Result<R>>,
}

trait Thunk: Send + 'static {
    fn call_box(self: Box<Self>);
}

impl<F: FnOnce() + Send + 'static> Thunk for F {
    fn call_box(self: Box<Self>) {
        (*self)()
    }
}

enum Message {
    Run(Box<Thunk>),
    Close,
}

impl CpuPool {
    /// Creates a new thread pool with `size` worker threads associated with it.
    ///
    /// The returned handle can use `execute` to run work on this thread pool,
    /// and clones can be made of it to get multiple references to the same
    /// thread pool.
    pub fn new(size: u32) -> CpuPool {
        let pool = CpuPool {
            inner: Arc::new(Inner {
                queue: MsQueue::new(),
                cnt: AtomicUsize::new(1),
                size: size,
            }),
        };

        for _ in 0..size {
            let pool = CpuPool { inner: pool.inner.clone() };
            thread::spawn(|| pool.work());
        }

        return pool
    }

    /// Creates a new thread pool with a number of workers equal to the number
    /// of CPUs on the host.
    pub fn new_num_cpus() -> CpuPool {
        CpuPool::new(num_cpus::get() as u32)
    }

    /// Execute some work on this thread pool, returning a future to the work
    /// that's running on the thread pool.
    ///
    /// This function will execute the closure `f` on the associated thread
    /// pool, and return a future representing the finished computation. The
    /// future will either resolve to `R` if the computation finishes
    /// successfully or to `Box<Any+Send>` if it panics.
    pub fn execute<F, R>(&self, f: F) -> CpuFuture<R>
        where F: FnOnce() -> R + Send + 'static,
              R: Send + 'static,
    {
        let (tx, rx) = oneshot();
        self.inner.queue.push(Message::Run(Box::new(|| {
            // TODO: should check to see if `tx` is canceled by the time we're
            //       running, and if so we just skip the entire computation.
            tx.complete(panic::catch_unwind(AssertUnwindSafe(f)));
        })));
        CpuFuture { inner: rx }
    }

    fn work(self) {
        let mut done = false;
        while !done {
            match self.inner.queue.pop() {
                Message::Close => done = true,
                Message::Run(r) => r.call_box(),
            }
        }
    }
}

impl Clone for CpuPool {
    fn clone(&self) -> CpuPool {
        self.inner.cnt.fetch_add(1, Ordering::Relaxed);
        CpuPool { inner: self.inner.clone() }
    }
}

impl Drop for CpuPool {
    fn drop(&mut self) {
        if self.inner.cnt.fetch_sub(1, Ordering::Relaxed) > 1 {
            return
        }
        for _ in 0..self.inner.size {
            self.inner.queue.push(Message::Close);
        }
    }
}

impl<R: Send + 'static> Future for CpuFuture<R> {
    type Item = R;
    type Error = Box<Any + Send>;

    fn poll(&mut self) -> Poll<R, Box<Any + Send>> {
        match self.inner.poll() {
            Poll::Ok(res) => res.into(),
            Poll::Err(_) => panic!("shouldn't be canceled"),
            Poll::NotReady => Poll::NotReady,
        }
    }
}
<commit_msg>Take usize in CpuPool::new<commit_after>//! A simple crate for executing work on a thread pool, and getting back a
//! future.
//!
//! This crate provides a simple thread pool abstraction for running work
//! externally from the current thread that's running. An instance of `Future`
//! is handed back to represent that the work may be done later, and futher
//! computations can be chained along with it as well.
//!
//! ```rust
//! extern crate futures;
//! extern crate futures_cpupool;
//!
//! use std::sync::mpsc::channel;
//!
//! use futures::Future;
//! use futures_cpupool::CpuPool;
//!
//! # fn long_running_computation() -> u32 { 2 }
//! # fn long_running_computation2(a: u32) -> u32 { a }
//! # fn main() {
//!
//! // Create a worker thread pool with four threads
//! let pool = CpuPool::new(4);
//!
//! // Execute some work on the thread pool, optionally closing over data.
//! let a = pool.execute(long_running_computation);
//! let b = pool.execute(|| long_running_computation2(100));
//!
//! // Express some further computation once the work is completed on the thread
//! // pool.
//! let c = a.join(b).map(|(a, b)| a + b);
//!
//! // Block the current thread to get the result.
//! let (tx, rx) = channel();
//! c.then(move |res| {
//!     tx.send(res)
//! }).forget();
//! let res = rx.recv().unwrap();
//!
//! // Print out the result
//! println!("{:?}", res);
//! # }
//! ```

#![deny(missing_docs)]

extern crate crossbeam;
extern crate futures;
extern crate num_cpus;

use std::any::Any;
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;

use crossbeam::sync::MsQueue;
use futures::{Future, oneshot, Oneshot, Poll};

/// A thread pool intended to run CPU intensive work.
///
/// This thread pool will hand out futures representing the completed work
/// that happens on the thread pool itself, and the futures can then be later
/// composed with other work as part of an overall computation.
///
/// The worker threads associated with a thread pool are kept alive so long as
/// there is an open handle to the `CpuPool` or there is work running on them. Once
/// all work has been drained and all references have gone away the worker
/// threads will be shut down.
///
/// Currently `CpuPool` implements `Clone` which just clones a new reference to
/// the underlying thread pool.
pub struct CpuPool {
    inner: Arc<Inner>,
}

fn _assert() {
    fn _assert_send<T: Send>() {}
    fn _assert_sync<T: Sync>() {}
    _assert_send::<CpuPool>();
    _assert_sync::<CpuPool>();
}

struct Inner {
    queue: MsQueue<Message>,
    cnt: AtomicUsize,
    size: usize,
}

/// The type of future returned from the `CpuPool::execute` function.
///
/// This future will either resolve to `R`, the completed value, or
/// `Box<Any+Send>` if the computation panics (with the payload of the panic).
pub struct CpuFuture<R: Send + 'static> {
    inner: Oneshot<thread::Result<R>>,
}

trait Thunk: Send + 'static {
    fn call_box(self: Box<Self>);
}

impl<F: FnOnce() + Send + 'static> Thunk for F {
    fn call_box(self: Box<Self>) {
        (*self)()
    }
}

enum Message {
    Run(Box<Thunk>),
    Close,
}

impl CpuPool {
    /// Creates a new thread pool with `size` worker threads associated with it.
    ///
    /// The returned handle can use `execute` to run work on this thread pool,
    /// and clones can be made of it to get multiple references to the same
    /// thread pool.
    pub fn new(size: usize) -> CpuPool {
        let pool = CpuPool {
            inner: Arc::new(Inner {
                queue: MsQueue::new(),
                cnt: AtomicUsize::new(1),
                size: size,
            }),
        };

        for _ in 0..size {
            let pool = CpuPool { inner: pool.inner.clone() };
            thread::spawn(|| pool.work());
        }

        return pool
    }

    /// Creates a new thread pool with a number of workers equal to the number
    /// of CPUs on the host.
    pub fn new_num_cpus() -> CpuPool {
        CpuPool::new(num_cpus::get())
    }

    /// Execute some work on this thread pool, returning a future to the work
    /// that's running on the thread pool.
    ///
    /// This function will execute the closure `f` on the associated thread
    /// pool, and return a future representing the finished computation. The
    /// future will either resolve to `R` if the computation finishes
    /// successfully or to `Box<Any+Send>` if it panics.
    pub fn execute<F, R>(&self, f: F) -> CpuFuture<R>
        where F: FnOnce() -> R + Send + 'static,
              R: Send + 'static,
    {
        let (tx, rx) = oneshot();
        self.inner.queue.push(Message::Run(Box::new(|| {
            // TODO: should check to see if `tx` is canceled by the time we're
            //       running, and if so we just skip the entire computation.
            tx.complete(panic::catch_unwind(AssertUnwindSafe(f)));
        })));
        CpuFuture { inner: rx }
    }

    fn work(self) {
        let mut done = false;
        while !done {
            match self.inner.queue.pop() {
                Message::Close => done = true,
                Message::Run(r) => r.call_box(),
            }
        }
    }
}

impl Clone for CpuPool {
    fn clone(&self) -> CpuPool {
        self.inner.cnt.fetch_add(1, Ordering::Relaxed);
        CpuPool { inner: self.inner.clone() }
    }
}

impl Drop for CpuPool {
    fn drop(&mut self) {
        if self.inner.cnt.fetch_sub(1, Ordering::Relaxed) > 1 {
            return
        }
        for _ in 0..self.inner.size {
            self.inner.queue.push(Message::Close);
        }
    }
}

impl<R: Send + 'static> Future for CpuFuture<R> {
    type Item = R;
    type Error = Box<Any + Send>;

    fn poll(&mut self) -> Poll<R, Box<Any + Send>> {
        match self.inner.poll() {
            Poll::Ok(res) => res.into(),
            Poll::Err(_) => panic!("shouldn't be canceled"),
            Poll::NotReady => Poll::NotReady,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>start new<commit_after>fn main() {
    let test = vec![
        30, 63, 83, 40, 15, 45, 46, 15, 56, 39, 82, 97, 59, 88, 3, 1, 40, 95, 83, 32, 38, 70, 4,
        87, 54, 48, 19, 8, 52, 49, 64, 72, 46, 72, 59, 36, 21, 68, 81, 34, 23, 6, 70, 80, 80, 12,
        32, 84, 17, 19, 28, 58, 68, 19, 65, 46, 43, 22, 12, 95, 89, 15, 39, 88, 64, 95, 99, 25, 2,
        7, 86, 36, 73, 90, 30, 31, 0, 62, 73, 35, 4, 26, 0, 93, 91, 77, 34, 92, 31, 56, 34, 61, 23,
        47, 78, 5, 5, 26, 36, 71, 50, 5, 59, 22, 21, 0, 72, 72, 72, 69, 5, 11, 95, 5, 0, 14, 34,
        91, 4, 27, 46, 21, 94, 96, 48, 58, 79, 21, 65, 35, 17, 16, 57, 91, 36, 50, 16, 82, 92, 1,
        29, 52, 74, 90, 48, 79, 81, 53, 46, 82, 36, 43, 64, 24, 55, 48, 27, 21, 69, 93, 49, 70, 58,
        8, 50, 97, 30, 68, 1, 34, 15, 38, 52, 27, 50, 10, 22, 67, 25, 37, 84, 91, 13, 15, 0, 5, 31,
        18, 5, 31, 49, 93, 95, 3, 86, 11, 37, 68, 43, 74,
    ];
}
<|endoftext|>


<commit_before><commit_msg>Add std::char::is_whitespace<commit_after>pred is_whitespace(c: char) -> bool {
    const ch_space: char = '\u0020';
    const ch_ogham_space_mark: char = '\u1680';
    const ch_mongolian_vowel_sep: char = '\u180e';
    const ch_en_quad: char = '\u2000';
    const ch_em_quad: char = '\u2001';
    const ch_en_space: char = '\u2002';
    const ch_em_space: char = '\u2003';
    const ch_three_per_em_space: char = '\u2004';
    const ch_four_per_em_space: char = '\u2005';
    const ch_six_per_em_space: char = '\u2006';
    const ch_figure_space: char = '\u2007';
    const ch_punctuation_space: char = '\u2008';
    const ch_thin_space: char = '\u2009';
    const ch_hair_space: char = '\u200a';
    const ch_narrow_no_break_space: char = '\u202f';
    const ch_medium_mathematical_space: char = '\u205f';
    const ch_ideographic_space: char = '\u3000';
    const ch_line_separator: char = '\u2028';
    const ch_paragraph_separator: char = '\u2029';
    const ch_character_tabulation: char = '\u0009';
    const ch_line_feed: char = '\u000a';
    const ch_line_tabulation: char = '\u000b';
    const ch_form_feed: char = '\u000c';
    const ch_carriage_return: char = '\u000d';
    const ch_next_line: char = '\u0085';
    const ch_no_break_space: char = '\u00a0';

    if c == ch_space { true }
    else if c == ch_ogham_space_mark { true }
    else if c == ch_mongolian_vowel_sep { true }
    else if c == ch_en_quad { true }
    else if c == ch_em_quad { true }
    else if c == ch_en_space { true }
    else if c == ch_em_space { true }
    else if c == ch_three_per_em_space { true }
    else if c == ch_four_per_em_space { true }
    else if c == ch_six_per_em_space { true }
    else if c == ch_figure_space { true }
    else if c == ch_punctuation_space { true }
    else if c == ch_thin_space { true }
    else if c == ch_hair_space { true }
    else if c == ch_narrow_no_break_space { true }
    else if c == ch_medium_mathematical_space { true }
    else if c == ch_ideographic_space { true }
    else if c == ch_line_tabulation { true }
    else if c == ch_paragraph_separator { true }
    else if c == ch_character_tabulation { true }
    else if c == ch_line_feed { true }
    else if c == ch_line_tabulation { true }
    else if c == ch_form_feed { true }
    else if c == ch_carriage_return { true }
    else if c == ch_next_line { true }
    else if c == ch_no_break_space { true }
    else { false }
}<|endoftext|>


<commit_before><commit_msg>Add problem #105<commit_after>#[link(name = "prob0105", vers = "0.0")];
#[crate_type = "lib"];

extern mod common;
extern mod extra;

use std::{io, uint, vec};
use std::io::Reader;
use std::iterator::AdditiveIterator;
use extra::sort::Sort;
use common::problem::Problem;

pub static problem: Problem<'static> = Problem {
    id: 105,
    answer: "73702",
    solver: solve
};

pub trait ReaderIterator<T> {
    fn line_iter<'a>(&'a self) -> ReaderLineIterator<'a, T>;
}

impl<T: Reader> ReaderIterator<T> for T {
    fn line_iter<'a>(&'a self) -> ReaderLineIterator<'a, T> {
        ReaderLineIterator { reader: self }
    }
}

struct ReaderLineIterator<'self, T> {
    priv reader: &'self T
}

impl<'self, T: Reader> Iterator<~str> for ReaderLineIterator<'self, T> {
    fn next(&mut self) -> Option<~str> {
        if self.reader.eof() {
            None
        } else {
            Some(self.reader.read_line())
        }
    }
}

pub fn is_sss(nums: ~[uint]) -> bool {
    let mut sums: ~[uint] = ~[0];
    for nums.iter().advance |&n| {
        let mut i = 0;
        let mut j = 0;
        let len = sums.len();
        let mut new_sums = vec::with_capacity(len * 2);
        while i < len {
            assert!(j <= i);
            match sums[i].cmp(&(sums[j] + n)) {
                Equal => { return false; }
                Less => {
                    new_sums.push(sums[i]);
                    i += 1;
                }
                Greater => {
                    new_sums.push(sums[j] + n);
                    j += 1;
                }
            }
        }

        while j < len {
            new_sums.push(sums[j] + n);
            j += 1;
        }

        sums = new_sums;
    }

    return true;
}

pub fn solve() -> ~str {
    let result = io::file_reader(&Path("files/sets.txt"))
        .map(|reader| {
            reader
                .line_iter()
                .transform(|line| {
                    line.split_iter(',')
                        .filter_map(uint::from_str)
                        .collect::<~[uint]>()
                }).transform(|mut nums| { nums.qsort(); nums })
                .filter(|nums| {
                    let len = nums.len();
                    let len_hd = (len + 1) / 2;
                    let len_tl = len_hd - 1;
                    let mut hd = nums.slice(0, len_hd).iter().transform(|&x| x);
                    let mut tl = nums.slice(len - len_tl, len).iter().transform(|&x| x);
                    hd.sum() > tl.sum()
                }).filter(|&nums| is_sss(nums))
                .transform(|nums| nums.iter().transform(|&x| x).sum())
                .sum()
        });

    match result {
        Err(msg) => fail!(msg),
        Ok(value) => return value.to_str()
    }
}
<|endoftext|>


<commit_before><commit_msg>doubler future for rust<commit_after>pub struct Doubler<T> {
    inner: T,
}

pub fn double<T>(inner: T) -> Doubler<T> {
    Doubler { inner }
}

impl<T> Future for Doubler<T>
    where T: Future<Item = usize>
{
    type Item = usize;
    type Error = T::Error;

    fn poll(&mut self) -> Result<Async<usize>, T::Error> {
        // Do not return NotReady unless you got NotReady from an inner future
        match self.inner.poll()? {
            Async::Ready(v) => Ok(Async::Ready(v * 2)),
            Async::NotReady => Ok(Async::NotReady),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>add FrameStrata enum and make enums public<commit_after><|endoftext|>


<commit_before><commit_msg>Add test.<commit_after>#![feature(start, lang_items, panic_implementation, core_intrinsics)]
#![no_std]

use core::intrinsics;
use core::panic::PanicInfo;

// Pull in the system libc library for what crt0.o likely requires
extern crate libc;
extern crate raw_cpuid;

// Entry point for this program
#[start]
fn start(_argc: isize, _argv: *const *const u8) -> isize {
    let _c = raw_cpuid::CpuId::new();
    0
}

// These functions and traits are used by the compiler, but not
// for a bare-bones hello world. These are normally
// provided by libstd.
#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

#[panic_implementation]
fn panic(_info: &PanicInfo) -> ! {
    unsafe { intrinsics::abort() }
}
<|endoftext|>


<commit_before>enum DataType {
    Unknown = 0,
    Boolean,
    Byte,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
    String, // TODO: What to name this string type?
    ByteArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Int64Array,
    Uint64Array,
    StringArray,
    Hrtime,
    Nvlist, // TODO: What to name this ?
    NvlistArray,
    BooleanValue,
    Int8,
    Uint8,
    BooleanArray,
    Int8Array,
    Uint8Array
}

struct NvPair {
    nvp_size:       i32, // size of this nvpair
    nvp_name_sz:    i16, // length of name string
    nvp_reserve:    i16, // not used
    nvp_value_elem: i32, // number of elements for array types
    nvp_type:       DataType, // type of value
    // name string
    // aligned ptr array for string arrays
    // aligned array of data for value
}

// nvlist header
struct NvList {
    nvl_version: i32
    nvl_nvflag:  u32 // persistent flags
    nvl_priv:    u64 // ptr to private data if not packed
    nvl_flag:    u32
    nvl_pad:     i32 // currently not used, for alignment
}

// nvp implementation version
const NV_VERSION: i32 = 0;

// nvlist pack encoding
const NV_ENCODE_NATIVE: u8 = 0;
const NV_ENCODE_XDR:    u8 = 1;

// nvlist persistent unique name flags, stored in nvl_nvflags
const NV_UNIQUE_NAME:      u32 = 0x1;
const NV_UNIQUE_NAME_TYPE: u32 = 0x2;

// nvlist lookup pairs related flags
const NV_FLAG_NOENTOK: isize = 0x1;

/* What to do about these macros?
// convenience macros
#define NV_ALIGN(x)     (((ulong_t)(x) + 7ul) & ~7ul)
#define NV_ALIGN4(x)        (((x) + 3) & ~3)

#define NVP_SIZE(nvp)       ((nvp)->nvp_size)
#define NVP_NAME(nvp)       ((char *)(nvp) + sizeof (nvpair_t))
#define NVP_TYPE(nvp)       ((nvp)->nvp_type)
#define NVP_NELEM(nvp)      ((nvp)->nvp_value_elem)
#define NVP_VALUE(nvp)      ((char *)(nvp) + NV_ALIGN(sizeof (nvpair_t) \
                + (nvp)->nvp_name_sz))

#define NVL_VERSION(nvl)    ((nvl)->nvl_version)
#define NVL_SIZE(nvl)       ((nvl)->nvl_size)
#define NVL_FLAG(nvl)       ((nvl)->nvl_flag)
*/

// NV allocator framework
struct NvAllocOps;

struct NvAlloc<> {
    nva_ops: &'static NvAllocOps,
    nva_arg: Any, // This was a void pointer type.
                  // Not sure if Any is the correct type.
}

struct NvAllocOps {
    int (*nv_ao_init)(nv_alloc_t *, __va_list);
    void (*nv_ao_fini)(nv_alloc_t *);
    void *(*nv_ao_alloc)(nv_alloc_t *, size_t);
    void (*nv_ao_free)(nv_alloc_t *, void *, size_t);
    void (*nv_ao_reset)(nv_alloc_t *);
}
<commit_msg>Forgot to comment out unrustified code<commit_after>enum DataType {
    Unknown = 0,
    Boolean,
    Byte,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
    String, // TODO: What to name this string type?
    ByteArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Int64Array,
    Uint64Array,
    StringArray,
    Hrtime,
    Nvlist, // TODO: What to name this ?
    NvlistArray,
    BooleanValue,
    Int8,
    Uint8,
    BooleanArray,
    Int8Array,
    Uint8Array
}

struct NvPair {
    nvp_size:       i32, // size of this nvpair
    nvp_name_sz:    i16, // length of name string
    nvp_reserve:    i16, // not used
    nvp_value_elem: i32, // number of elements for array types
    nvp_type:       DataType, // type of value
    // name string
    // aligned ptr array for string arrays
    // aligned array of data for value
}

// nvlist header
struct NvList {
    nvl_version: i32
    nvl_nvflag:  u32 // persistent flags
    nvl_priv:    u64 // ptr to private data if not packed
    nvl_flag:    u32
    nvl_pad:     i32 // currently not used, for alignment
}

// nvp implementation version
const NV_VERSION: i32 = 0;

// nvlist pack encoding
const NV_ENCODE_NATIVE: u8 = 0;
const NV_ENCODE_XDR:    u8 = 1;

// nvlist persistent unique name flags, stored in nvl_nvflags
const NV_UNIQUE_NAME:      u32 = 0x1;
const NV_UNIQUE_NAME_TYPE: u32 = 0x2;

// nvlist lookup pairs related flags
const NV_FLAG_NOENTOK: isize = 0x1;

/* What to do about these macros?
// convenience macros
#define NV_ALIGN(x)     (((ulong_t)(x) + 7ul) & ~7ul)
#define NV_ALIGN4(x)        (((x) + 3) & ~3)

#define NVP_SIZE(nvp)       ((nvp)->nvp_size)
#define NVP_NAME(nvp)       ((char *)(nvp) + sizeof (nvpair_t))
#define NVP_TYPE(nvp)       ((nvp)->nvp_type)
#define NVP_NELEM(nvp)      ((nvp)->nvp_value_elem)
#define NVP_VALUE(nvp)      ((char *)(nvp) + NV_ALIGN(sizeof (nvpair_t) \
                + (nvp)->nvp_name_sz))

#define NVL_VERSION(nvl)    ((nvl)->nvl_version)
#define NVL_SIZE(nvl)       ((nvl)->nvl_size)
#define NVL_FLAG(nvl)       ((nvl)->nvl_flag)
*/

// NV allocator framework
struct NvAllocOps;

struct NvAlloc<> {
    nva_ops: &'static NvAllocOps,
    nva_arg: Any, // This was a void pointer type.
                  // Not sure if Any is the correct type.
}

/*
struct NvAllocOps {
    int (*nv_ao_init)(nv_alloc_t *, __va_list);
    void (*nv_ao_fini)(nv_alloc_t *);
    void *(*nv_ao_alloc)(nv_alloc_t *, size_t);
    void (*nv_ao_free)(nv_alloc_t *, void *, size_t);
    void (*nv_ao_reset)(nv_alloc_t *);
}
*/
<|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use std::path::PathBuf;

use toml::Value;

use libimagstore::hook::Hook;
use libimagstore::hook::error::HookErrorKind as HEK;
use libimagstore::hook::accessor::HookDataAccessor as HDA;
use libimagstore::hook::accessor::HookDataAccessorProvider;
use libimagstore::hook::accessor::NonMutableHookDataAccessor;
use libimagstore::hook::result::HookResult;
use libimagstore::store::FileLockEntry;
use libimagentrylink::internal::InternalLinker;
use libimagerror::trace::trace_error;

mod error {
    generate_error_imports!();
    generate_error_types!(NoLinksLeftCheckerHookError, NoLinksLeftCheckerHookErrorKind,
        LinksLeft => "The entry has links and therefor cannot be deleted."
    );
}
use self::error::NoLinksLeftCheckerHookError as NLLCHE;
use self::error::NoLinksLeftCheckerHookErrorKind as NLLCHEK;
use self::error::MapErrInto;

#[derive(Debug, Clone)]
pub struct DenyDeletionOfLinkedEntriesHook {
    abort: bool
}

impl DenyDeletionOfLinkedEntriesHook {

    pub fn new() -> DenyDeletionOfLinkedEntriesHook {
        DenyDeletionOfLinkedEntriesHook {
            abort: true // by default, this hook aborts actions
        }
    }

}

impl Hook for DenyDeletionOfLinkedEntriesHook {

    fn name(&self) -> &'static str {
        "stdhook_linked_entries_cannot_be_deleted"
    }

    fn set_config(&mut self, v: &Value) {
        self.abort = match v.lookup("aborting") {
            Some(&Value::Boolean(b)) => b,
            Some(_) => {
                warn!("Configuration error, 'aborting' must be a Boolean (true|false).");
                warn!("Assuming 'true' now.");
                true
            },
            None => {
                warn!("No key 'aborting' - Assuming 'true'");
                true
            },
        };
    }

}

impl HookDataAccessorProvider for DenyDeletionOfLinkedEntriesHook {

    fn accessor(&self) -> HDA {
        HDA::NonMutableAccess(self)
    }

}

impl NonMutableHookDataAccessor for DenyDeletionOfLinkedEntriesHook {

    fn access(&self, fle: &FileLockEntry) -> HookResult<()> {
        use libimagutil::warn_result::*;
        use libimagutil::debug_result::*;
        use libimagerror::trace::MapErrTrace;
        use libimagerror::into::IntoError;
        use libimagstore::hook::error::MapErrInto;

        debug!("[NO LINKS LEFT CHECKER HOOK] {:?}", fle.get_location());

        let n = fle
            .get_internal_links()
            .map(|i| i.count())
            .map_warn_err_str("[NO LINKS LEFT CHECKER HOOK]: Cannot get internal links")
            .map_warn_err_str("[NO LINKS LEFT CHECKER HOOK]: Assuming 1 to automatically abort")
            .map_dbg_err_str("[NO LINKS LEFT CHECKER HOOK]: Printing trace now")
            .map_err_trace()
            .unwrap_or(1);

        if n > 0 {
            Err(NLLCHEK::LinksLeft.into_error())
                .map_err(Box::new)
                .map_err(|e| HEK::HookExecutionError.into_error_with_cause(e))
        } else {
            Ok(())
        }
    }

}

<commit_msg>Remove unused imports<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use toml::Value;

use libimagstore::hook::Hook;
use libimagstore::hook::error::HookErrorKind as HEK;
use libimagstore::hook::accessor::HookDataAccessor as HDA;
use libimagstore::hook::accessor::HookDataAccessorProvider;
use libimagstore::hook::accessor::NonMutableHookDataAccessor;
use libimagstore::hook::result::HookResult;
use libimagstore::store::FileLockEntry;
use libimagentrylink::internal::InternalLinker;

mod error {
    generate_error_imports!();
    generate_error_types!(NoLinksLeftCheckerHookError, NoLinksLeftCheckerHookErrorKind,
        LinksLeft => "The entry has links and therefor cannot be deleted."
    );
}
use self::error::NoLinksLeftCheckerHookErrorKind as NLLCHEK;

#[derive(Debug, Clone)]
pub struct DenyDeletionOfLinkedEntriesHook {
    abort: bool
}

impl DenyDeletionOfLinkedEntriesHook {

    pub fn new() -> DenyDeletionOfLinkedEntriesHook {
        DenyDeletionOfLinkedEntriesHook {
            abort: true // by default, this hook aborts actions
        }
    }

}

impl Hook for DenyDeletionOfLinkedEntriesHook {

    fn name(&self) -> &'static str {
        "stdhook_linked_entries_cannot_be_deleted"
    }

    fn set_config(&mut self, v: &Value) {
        self.abort = match v.lookup("aborting") {
            Some(&Value::Boolean(b)) => b,
            Some(_) => {
                warn!("Configuration error, 'aborting' must be a Boolean (true|false).");
                warn!("Assuming 'true' now.");
                true
            },
            None => {
                warn!("No key 'aborting' - Assuming 'true'");
                true
            },
        };
    }

}

impl HookDataAccessorProvider for DenyDeletionOfLinkedEntriesHook {

    fn accessor(&self) -> HDA {
        HDA::NonMutableAccess(self)
    }

}

impl NonMutableHookDataAccessor for DenyDeletionOfLinkedEntriesHook {

    fn access(&self, fle: &FileLockEntry) -> HookResult<()> {
        use libimagutil::warn_result::*;
        use libimagutil::debug_result::*;
        use libimagerror::trace::MapErrTrace;
        use libimagerror::into::IntoError;

        debug!("[NO LINKS LEFT CHECKER HOOK] {:?}", fle.get_location());

        let n = fle
            .get_internal_links()
            .map(|i| i.count())
            .map_warn_err_str("[NO LINKS LEFT CHECKER HOOK]: Cannot get internal links")
            .map_warn_err_str("[NO LINKS LEFT CHECKER HOOK]: Assuming 1 to automatically abort")
            .map_dbg_err_str("[NO LINKS LEFT CHECKER HOOK]: Printing trace now")
            .map_err_trace()
            .unwrap_or(1);

        if n > 0 {
            Err(NLLCHEK::LinksLeft.into_error())
                .map_err(Box::new)
                .map_err(|e| HEK::HookExecutionError.into_error_with_cause(e))
        } else {
            Ok(())
        }
    }

}

<|endoftext|>


<commit_before><commit_msg>Formatting<commit_after><|endoftext|>


<commit_before><commit_msg>A commit<commit_after><|endoftext|>


<commit_before><commit_msg>Simplify command parsing and move it to another thread<commit_after><|endoftext|>


<commit_before><commit_msg>pat_gridcular_seq<commit_after><|endoftext|>


<commit_before><commit_msg>Replaced depreciated std::thread::sleep_ms with std::thread::sleep.<commit_after><|endoftext|>


<commit_before><commit_msg>Shrinking size of vec by size of offset_bins<commit_after><|endoftext|>


<commit_before><commit_msg>chore: rwlock<commit_after><|endoftext|>


<commit_before><commit_msg>Rename absurd to elim<commit_after><|endoftext|>


<commit_before><commit_msg>Use dotenv to load in environment variables<commit_after><|endoftext|>


<commit_before><commit_msg>Fix looping<commit_after><|endoftext|>