<commit_before><commit_msg>implementing PingFrame<commit_after>use super::super::StreamId;
use super::frames::*;

/// An enum representing the flags that a `PingFrame` can have.
/// The integer representation associated to each variant is that flag's
/// bitmask.
///
/// HTTP/2 spec, section 6.
#[derive(Clone)]
#[derive(PartialEq)]
#[derive(Debug)]
#[derive(Copy)]
pub enum PingFlag {
    Ack = 0x1,
}

impl Flag for PingFlag {
    #[inline]
    fn bitmask(&self) -> u8 {
        *self as u8
    }
}

/// A struct representing the DATA frames of HTTP/2, as defined in the HTTP/2
/// spec, section 6.1.
#[derive(PartialEq)]
#[derive(Debug)]
pub struct PingFrame {
    /// The data found in the frame as an opaque byte sequence. It never
    /// includes padding bytes.
    pub data: Vec<u8>,
    /// Represents the flags currently set on the `DataFrame`, packed into a
    /// single byte.
    flags: u8,
}

impl PingFrame {
    /// Creates a new empty `PingFrame`, associated to the connection
    pub fn new() -> PingFrame {
        PingFrame {
            // No data stored in the frame yet
            data: Vec::new(),
            // All flags unset by default
            flags: 0,
        }
    }

    /// A convenience constructor that returns a `PingFrame` with the ACK
    /// flag already set and no data.
    pub fn new_ack() -> PingFrame {
        PingFrame {
            data: Vec::new(),
            flag: PingFlag::Ack.bitmask(),
        }
    }

    /// Sets the ACK flag for the frame. This method is just a convenience
    /// method for calling `frame.set_flag(PingFlag::Ack)`.
    pub fn set_ack(&mut self) {
        self.set_flag(PingFlag::Ack)
    }

    /// Checks whether the `PingFrame` has an ACK flag attached to it.
    pub fn is_ack(&self) -> bool {
        self.is_set(PingFlag::Ack)
    }

    /// Returns the total length of the payload in bytes
    fn payload_len(&self) -> u32 {
        self.data.len() as u32
    }

    /// Parses the given slice as a PING frame's payload.
    ///
    /// # Returns
    ///
    /// A `Vec` of opaque data
    ///
    /// If the payload was invalid (i.e. the length of the payload is
    /// not 8 octets long, returns `None`
    fn parse_payload(payload: &[u8]) -> Option<(Vec<u8>)> {
        if payload.len() != 8 {
            return None;
        }

        Some(data.to_vec())
    }
}

impl Frame for PingFrame {
    /// The type that represents the flags that the particular `Frame` can take.
    /// This makes sure that only valid `Flag`s are used with each `Frame`.
    type FlagType = AckFlag;

    /// Creates a new `PingFrame` with the given `RawFrame` (i.e. header and payload),
    /// if possible.
    ///
    /// # Returns
    ///
    /// `None` if a valid `PingFrame` cannot be contructed from the given
    /// `RawFrame`. The stream ID *MUST* be 0 in order for the frame to be
    /// valid. If the `ACK` flag is set, there *MUST NOT* be a payload. The total
    /// payload length must be 8 bytes long.
    ///
    /// Otherwise, returns a newly constructed `PingFrame`.
    fn from_raw(raw_frame: RawFrame) -> Option<PingFrame> {
        // Unpack the header
        let (len, frame_type, flags, stream_id) = raw_frame.header;
        // Check that the frame type is correct for this fram implementation
        if frame_type != 0x6 {
            return None;
        }
        // Check that the length given in the header mathes the payload
        // length; if not, something went wrong and we do not consider this a
        // valid frame.
        if (len as usize) != raw_frame.payload.len() {
            return None;
        }
        // Check that the PING frame is associated to stream 0
        if stream_id != 0 {
            return None;
        }
        if (flags & PingFlag::Ack.bitmask()) != 0 {
            if len != 0 {
                // The PING flag MUST NOT have a payload if Ack is set
                return None;
            } else {
                // Ack is set and there's no payload => just an Ack frame
                return Some(PingFrame {
                    data: Vec::new(),
                    flags: flags,
                });
            }
        }
    }

    /// Tests if the given flag is set for the frame.
    fn is_set(&self, flag: PingFlag) -> bool {
        (self.flags & flag.bitmask()) != 0
    }

    /// Returns the `StreamId` of the stream to which the frame is associated.
    ///
    /// A `PingFrame` always has to be associated to stream `0`.
    fn get_stream_id(&self) -> StreamId {
        0
    }

    /// Returns a `FrameHeader` based on the current state of the `Frame`.
    fn get_header(&self) -> FrameHeader {
        (self.payload_len(). 0x6, self.flags, 0)
    }

    /// Sets the given flag for the frame.
    fn set_flag(&mut self, flag: PingFlag) {
        self.flags |= flag.bitmask();
    }

    /// Returns a `Vec` with the serialized representation of the frame.
    fn serialize(&self) -> Vec<u8> {
        let mut buf = Vec::with_capacity(self.payload_len() as usize);
        // First the header
        buf.extend(pack_header(&self.get_header()).to_vec().into_iter());
        // now the body
        for data in self.data.iter() {
            buf.extend(data.serialize().to_vec().into_iter());
        }

        buf
    }

}

<|endoftext|>


<commit_before>//! S3 bindings for Rust
#![allow(unused_variables, unused_mut)]
use credentials::*;
use xml::*;
use signature::*;
use params::*;
use error::*;
use xmlutil::*;
use std::str::FromStr;
// use hyper::header::Headers;
use hyper::client::Response;
use std::io::Read;

// include the code generated from the SQS botocore templates
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/codegen/s3.rs"));

pub struct S3Helper<'a> {
	client: S3Client<'a>
}

impl<'a> S3Helper<'a> {
	pub fn new(credentials:&'a AWSCredentials, region:&'a str) -> S3Helper<'a> {
		S3Helper { client: S3Client::new(credentials, region) }
	}

	pub fn list_buckets(&self) -> Result<ListBucketsOutput, AWSError> {
		self.client.list_buckets()
	}

	pub fn create_bucket(&self, bucket_name: &str) -> Result<CreateBucketOutput, AWSError> {
		let mut request = CreateBucketRequest::default();
		request.bucket = bucket_name.to_string();
		// println!("Creating bucket");
		let result = self.client.create_bucket(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn delete_bucket(&self, bucket_name: &str) -> Result<(), AWSError> {
		let mut request = DeleteBucketRequest::default();
		request.bucket = bucket_name.to_string();
		println!("Deleting bucket");
		let result = self.client.delete_bucket(&request);
		println!("Result is {:?}", result);
		result
	}

	pub fn get_object(&self, bucket_name: &str, object_name: &str) ->  Result<GetObjectOutput, AWSError> {
		let mut request = GetObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		let result = self.client.get_object(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn put_object(&self, bucket_name: &str, object_name: &str, object_as_bytes: &Vec<u8>) ->  Result<PutObjectOutput, AWSError> {
		let mut request = PutObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		request.body = Some(object_as_bytes.clone()); // this needs to be refactored to pass a reference
		let result = self.client.put_object(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn delete_object(&self, bucket_name: &str, object_name: &str) ->  Result<DeleteObjectOutput, AWSError> {
		let mut request = DeleteObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		let result = self.client.delete_object(&request);
		println!("Result is {:?}", result);
		result
	}
}

#[cfg(test)]
mod tests {
	use xml::reader::*;
	use std::io::BufReader;
	use std::fs::File;
	use super::ListBucketsOutputParser;
	use xmlutil::*;

	#[test]
	fn list_buckets_happy_path() {
		let file = File::open("tests/sample-data/s3_get_buckets.xml").unwrap();
	    let file = BufReader::new(file);
	    let mut my_parser  = EventReader::new(file);
	    let my_stack = my_parser.events().peekable();
	    let mut reader = XmlResponseFromFile::new(my_stack);
		reader.next(); // xml start node
		let result = ListBucketsOutputParser::parse_xml("ListAllMyBucketsResult", &mut reader);

		match result {
			Err(_) => panic!("Couldn't parse list_buckets"),
			Ok(_) => return,
		}
	}
}
<commit_msg>Starts work for constraining bucket creation location.<commit_after>//! S3 bindings for Rust
#![allow(unused_variables, unused_mut)]
use credentials::*;
use xml::*;
use signature::*;
use params::*;
use error::*;
use xmlutil::*;
use std::str::FromStr;
// use hyper::header::Headers;
use hyper::client::Response;
use std::io::Read;

// include the code generated from the SQS botocore templates
include!(concat!(env!("CARGO_MANIFEST_DIR"), "/codegen/s3.rs"));

pub struct S3Helper<'a> {
	client: S3Client<'a>
}

impl<'a> S3Helper<'a> {
	pub fn new(credentials:&'a AWSCredentials, region:&'a str) -> S3Helper<'a> {
		S3Helper { client: S3Client::new(credentials, region) }
	}

	pub fn list_buckets(&self) -> Result<ListBucketsOutput, AWSError> {
		self.client.list_buckets()
	}

	/// Creates bucket in default us-east-1/us-standard region.
	pub fn create_bucket(&self, bucket_name: &str) -> Result<CreateBucketOutput, AWSError> {
		// TODO: refactor to call create_bucket_in_region
		let mut request = CreateBucketRequest::default();
		request.bucket = bucket_name.to_string();
		// println!("Creating bucket");
		let result = self.client.create_bucket(&request);
		// println!("Result is {:?}", result);
		result
	}

	/// Creates bucket in specified region.
	// TODO: enum for region?
	pub fn create_bucket_in_region(&self, bucket_name: &str, region: &str) -> Result<CreateBucketOutput, AWSError> {
		// TODO: refactor to call create_bucket with location specified
		let mut request = CreateBucketRequest::default();
		// create_bucket_configuration needs to be specified.  It's of type Option<CreateBucketConfiguration>.
		let create_config = CreateBucketConfiguration {location_constraint: region.to_string()};
		request.create_bucket_configuration = Some(create_config);

		request.bucket = bucket_name.to_string();
		// println!("Creating bucket");
		let result = self.client.create_bucket(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn delete_bucket(&self, bucket_name: &str) -> Result<(), AWSError> {
		let mut request = DeleteBucketRequest::default();
		request.bucket = bucket_name.to_string();
		println!("Deleting bucket");
		let result = self.client.delete_bucket(&request);
		println!("Result is {:?}", result);
		result
	}

	pub fn get_object(&self, bucket_name: &str, object_name: &str) ->  Result<GetObjectOutput, AWSError> {
		let mut request = GetObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		let result = self.client.get_object(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn put_object(&self, bucket_name: &str, object_name: &str, object_as_bytes: &Vec<u8>) ->  Result<PutObjectOutput, AWSError> {
		let mut request = PutObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		request.body = Some(object_as_bytes.clone()); // this needs to be refactored to pass a reference
		let result = self.client.put_object(&request);
		// println!("Result is {:?}", result);
		result
	}

	pub fn delete_object(&self, bucket_name: &str, object_name: &str) ->  Result<DeleteObjectOutput, AWSError> {
		let mut request = DeleteObjectRequest::default();
		request.key = object_name.to_string();
		request.bucket = bucket_name.to_string();
		let result = self.client.delete_object(&request);
		println!("Result is {:?}", result);
		result
	}
}

#[cfg(test)]
mod tests {
	use xml::reader::*;
	use std::io::BufReader;
	use std::fs::File;
	use super::ListBucketsOutputParser;
	use xmlutil::*;

	#[test]
	fn list_buckets_happy_path() {
		let file = File::open("tests/sample-data/s3_get_buckets.xml").unwrap();
	    let file = BufReader::new(file);
	    let mut my_parser  = EventReader::new(file);
	    let my_stack = my_parser.events().peekable();
	    let mut reader = XmlResponseFromFile::new(my_stack);
		reader.next(); // xml start node
		let result = ListBucketsOutputParser::parse_xml("ListAllMyBucketsResult", &mut reader);

		match result {
			Err(_) => panic!("Couldn't parse list_buckets"),
			Ok(_) => return,
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>added yson.rs<commit_after>
pub enum YSONValue<'a> {
    Map{values: Vec<(YSONValue<'a>, YSONValue<'a>)>},
    Array{values: Vec<YSONValue<'a>>},
    Scalar{value: &'a str}
}

impl<'a> YSONValue<'a> {
    fn require(tok: &str, mut src: &'a str) -> &'a str {
        src = src.trim_left();
        if src.starts_with(tok) {
            src.split_at(tok.len()).1.trim_left()
        }
        else {
            panic!("Expected token {} not found.", tok)
        }
    }

    fn allow(tok: &str, mut src: &'a str) -> &'a str {
        src = src.trim_left();
        if src.starts_with(tok) {
            src.split_at(tok.len()).1.trim_left()
        }
        else {
            src
        }
    }

    pub fn parse_map(mut src: &str) -> (YSONValue, &str) {
        let mut values = Vec::new();
        src = YSONValue::require("{", src);
        while !src.starts_with('}') {
            let (key, src2) = YSONValue::parse_scalar(src);
            src = YSONValue::require(":", src2);
            let (value, src2) = YSONValue::parse(src);
            src = YSONValue::allow(",", src2);
            values.push((key, value));
        }
        YSONValue::require("}", src);
        println!("parsed map");
        (YSONValue::Map{values: values}, src)
    }

    pub fn parse_array(mut src: &str) -> (YSONValue, &str) {
        let mut values = Vec::new();
        src = YSONValue::require("[", src);
        while !src.starts_with(']') {
            let (value, src2) = YSONValue::parse(src);
            src = YSONValue::allow(",", src2);
            values.push(value);
        }
        YSONValue::require("]", src);
        println!("parsed array");
        (YSONValue::Array{values: values}, src)
    }

    pub fn parse_quoted_string(src: &str) -> (YSONValue, &str) {
        // Parse series of characters starting and ending with '"', including whitespace and
        // newlines.
        let mut chars = src.char_indices();
        let mut prev_char = '\\';
        loop {
            let (idx, this_char) = match chars.next() {
                None => panic!("Expected terminating \" not found."),
                Some((idx, ch)) => ((idx, ch))
            };
            if this_char == '"' && prev_char != '\\' {
                let (s, src) = src.split_at(idx + 1);
                println!("parsed quoted string: {}", s);
                return (YSONValue::Scalar{value: s}, src);
            }
            else {
                prev_char = this_char;
            }
        }
    }

    pub fn parse_literal(src: &str) -> (YSONValue, &str) {
        // Parse series of characters consisting of any character but: ":,]}", or
        // whitespace.
        match src.find(|ch| char::is_whitespace(ch) || ":,]}".contains(ch)) {
            None => panic!("End of input reached while parsing literal."),
            Some(idx) => {
                let (s, src) = src.split_at(idx);
                println!("parsed literal: {}", s);
                return (YSONValue::Scalar{value: s}, src);
            }
        }
    }

    pub fn parse_scalar(src: &str) -> (YSONValue, &str) {
        if src.starts_with('"') {
            return YSONValue::parse_quoted_string(src);
        }
        else {
            return YSONValue::parse_literal(src);
        };
    }

    pub fn parse(src: &str) -> (YSONValue, &str) {
        let src = src.trim_left();// strip leading whitespace
        if src.starts_with('{') {
            return YSONValue::parse_map(src);
        }
        else if src.starts_with('[') {
            return YSONValue::parse_array(src);
        }
        else {
            return YSONValue::parse_scalar(src);
        };
    }

    pub fn display(&self) {
        match *self {
            YSONValue::Map{ref values} => {
                print!("{{\n");
                for x in values {
                    x.0.display();
                    print!(":");
                    x.1.display();
                    print!(",\n");
                }
                print!("}}\n");
            },
            YSONValue::Array{ref values} => {
                print!("[\n");
                for x in values {
                    x.display();
                    print!(",\n");
                }
                print!("]\n");
            },
            YSONValue::Scalar{ref value} => print!("{}", value)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Ignore bad variable accesses for now<commit_after><|endoftext|>


<commit_before><commit_msg>adds joiner (symlink from tutorial)<commit_after><|endoftext|>


<commit_before><commit_msg>Adjust small timer interval<commit_after><|endoftext|>


<commit_before><commit_msg>Add a regression test for issue-65934<commit_after>// check-pass

trait Trait {
    type Assoc;
}

impl Trait for () {
    type Assoc = ();
}

fn unit() -> impl Into<<() as Trait>::Assoc> {}

pub fn ice() {
    Into::into(unit());
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Fixes #14 and Fixes #17 More AUR Support (#21)<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #19<commit_after>fn is_leap_year(y: uint) -> bool {
    if y % 400 == 0 { return true; }
    if y % 100 == 0 { return false; }
    if y % 4   == 0 { return true; }
    return false;
}

fn day_of_year(y: uint) -> uint {
    if is_leap_year(y) { 366 } else { 365 }
}

fn day_of_month(y: uint) -> [uint * 12] {
    [ 31, // Jan
     if is_leap_year(y) { 29 } else { 28 }, // Feb
     31, // Mar
     30, // Apr
     31, // May
     30, // Jun
     31, // Jul
     31, // Aug
     30, // Sep
     31, // Oct
     30, // Nov
     31  // Dec
    ]
}

fn append_day(y: uint, offset: uint, result: &[mut uint * 7]) -> uint {
    let mut day = offset;
    for day_of_month(y).each |n| {
        result[day] += 1;
        day = (day + *n) % 7;
    }
    return day;
}

fn main() {
    let result = [mut 0, 0, 0, 0, 0, 0, 0];
    let mut day = 1; // Monday
    day = (day + day_of_year(1900)) % 7;
    for uint::range(1901, 2000 + 1) |y| {
        day = append_day(y, day, &result);
        io::println(fmt!("%? %?", result, day));
    }
    io::println(fmt!("%u", result[0]));
}<|endoftext|>


<commit_before>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-tidy-linelength

// revisions: nll_beyond nll_target

// The following revisions are disabled due to missing support from two-phase beyond autorefs
//[nll_beyond]compile-flags: -Z borrowck=mir -Z two-phase-borrows -Z two-phase-beyond-autoref
//[nll_beyond] should-fail

//[nll_target]compile-flags: -Z borrowck=mir -Z two-phase-borrows

// This is a corner case that the current implementation is (probably)
// treating more conservatively than is necessary. But it also does
// not seem like a terribly important use case to cover.
//
// So this test is just making a note of the current behavior, with
// the caveat that in the future, the rules may be loosened, at which
// point this test might be thrown out.
//
// The convention for the listed revisions: "lxl" means lexical
// lifetimes (which can be easier to reason about). "nll" means
// non-lexical lifetimes. "nll_target" means the initial conservative
// two-phase borrows that only applies to autoref-introduced borrows.
// "nll_beyond" means the generalization of two-phase borrows to all
// `&mut`-borrows (doing so makes it easier to write code for specific
// corner cases).

fn main() {
    let mut vec = vec![0, 1];
    let delay: &mut Vec<_>;
    {
        let shared = &vec;

        // we reserve here, which could (on its own) be compatible
        // with the shared borrow. But in the current implementation,
        // its an error.
        delay = &mut vec;
        //[nll_beyond]~^  ERROR cannot borrow `vec` as mutable because it is also borrowed as immutable
        //[nll_target]~^^ ERROR cannot borrow `vec` as mutable because it is also borrowed as immutable

        shared[0];
    }

    // the &mut-borrow only becomes active way down here.
    //
    // (At least in theory; part of the reason this test fails is that
    // the constructed MIR throws in extra &mut reborrows which
    // flummoxes our attmpt to delay the activation point here.)
    delay.push(2);
}

<commit_msg>Disable two-phase-reservation-sharing-interference[nll_beyond]<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-tidy-linelength

// revisions: nll_target

// The following revisions are disabled due to missing support from two-phase beyond autorefs
//[nll_beyond]compile-flags: -Z borrowck=mir -Z two-phase-borrows -Z two-phase-beyond-autoref
//[nll_beyond] should-fail

//[nll_target]compile-flags: -Z borrowck=mir -Z two-phase-borrows

// This is a corner case that the current implementation is (probably)
// treating more conservatively than is necessary. But it also does
// not seem like a terribly important use case to cover.
//
// So this test is just making a note of the current behavior, with
// the caveat that in the future, the rules may be loosened, at which
// point this test might be thrown out.
//
// The convention for the listed revisions: "lxl" means lexical
// lifetimes (which can be easier to reason about). "nll" means
// non-lexical lifetimes. "nll_target" means the initial conservative
// two-phase borrows that only applies to autoref-introduced borrows.
// "nll_beyond" means the generalization of two-phase borrows to all
// `&mut`-borrows (doing so makes it easier to write code for specific
// corner cases).

fn main() {
    let mut vec = vec![0, 1];
    let delay: &mut Vec<_>;
    {
        let shared = &vec;

        // we reserve here, which could (on its own) be compatible
        // with the shared borrow. But in the current implementation,
        // its an error.
        delay = &mut vec;
        //[nll_beyond]~^  ERROR cannot borrow `vec` as mutable because it is also borrowed as immutable
        //[nll_target]~^^ ERROR cannot borrow `vec` as mutable because it is also borrowed as immutable

        shared[0];
    }

    // the &mut-borrow only becomes active way down here.
    //
    // (At least in theory; part of the reason this test fails is that
    // the constructed MIR throws in extra &mut reborrows which
    // flummoxes our attmpt to delay the activation point here.)
    delay.push(2);
}

<|endoftext|>


<commit_before>use redox::*;

pub struct FileManager {
    folder_icon: BMPFile,
    audio_icon: BMPFile,
    bin_icon: BMPFile,
    image_icon: BMPFile,
    source_icon: BMPFile,
    script_icon: BMPFile,
    text_icon: BMPFile,
    file_icon: BMPFile,
    files: Vec<String>,
    selected: isize,
}

fn load_icon(path: &str) -> BMPFile {
    let mut resource = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp"));

    let mut vec: Vec<u8> = Vec::new();
    resource.read_to_end(&mut vec);

    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            folder_icon: load_icon("inode-directory"),
            audio_icon: load_icon("audio-x-wav"),
            bin_icon: load_icon("application-x-executable"),
            image_icon: load_icon("image-x-generic"),
            source_icon: load_icon("text-x-makefile"),
            script_icon: load_icon("text-x-script"),
            text_icon: load_icon("text-x-generic"),
            file_icon: load_icon("unknown"),
            files: Vec::new(),
            selected: -1,
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set([255, 255, 255, 255]);

        let mut i = 0;
        let mut row = 0;
        for string in self.files.iter() {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, [224, 224, 224, 255]);
            }

            if string.ends_with('/') {
                window.image(0,
                             32 * row as isize,
                             self.folder_icon.width(),
                             self.folder_icon.height(),
                             self.folder_icon.as_slice());
            } else if string.ends_with(".wav") {
                window.image(0,
                             32 * row as isize,
                             self.audio_icon.width(),
                             self.audio_icon.height(),
                             self.audio_icon.as_slice());
            } else if string.ends_with(".bin") {
                window.image(0,
                             32 * row as isize,
                             self.bin_icon.width(),
                             self.bin_icon.height(),
                             self.bin_icon.as_slice());
            } else if string.ends_with(".bmp") {
                window.image(0,
                             32 * row as isize,
                             self.image_icon.width(),
                             self.image_icon.height(),
                             self.image_icon.as_slice());
            } else if string.ends_with(".rs") || string.ends_with(".asm") || string.ends_with(".list") {
                window.image(0,
                             32 * row as isize,
                             self.source_icon.width(),
                             self.source_icon.height(),
                             self.source_icon.as_slice());
            } else if string.ends_with(".sh") || string.ends_with(".lua") {
                window.image(0,
                             32 * row as isize,
                             self.script_icon.width(),
                             self.script_icon.height(),
                             self.script_icon.as_slice());
            } else if string.ends_with(".md") || string.ends_with(".txt") {
                window.image(0,
                             32 * row as isize,
                             self.text_icon.width(),
                             self.text_icon.height(),
                             self.text_icon.as_slice());
            } else {
                window.image(0,
                             32 * row as isize,
                             self.file_icon.width(),
                             self.file_icon.height(),
                             self.file_icon.as_slice());
            }

            let mut col = 0;
            for c in string.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }
            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = 160;
        let mut height = 0;
        {
            let mut resource = File::open(path);

            let mut vec: Vec<u8> = Vec::new();
            resource.read_to_end(&mut vec);

            for file in unsafe { String::from_utf8_unchecked(vec) }.split('\n') {
                if width < 40 + (file.len() + 1) * 8 {
                    width = 40 + (file.len() + 1) * 8;
                }
                self.files.push(file.to_string());
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     width,
                                     height,
                                     &path);

        self.draw_content(&mut window);

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            K_ESC => break,
                            K_HOME => self.selected = 0,
                            K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            K_END => self.selected = self.files.len() as isize - 1,
                            K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Option::Some(file) => OpenEvent {
                                                url_string: path.to_string() + &file,
                                            }.trigger(),
                                            Option::None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                self.selected = i;
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

                    if redraw {
                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => FileManager::new().main(arg),
        Option::None => FileManager::new().main("file:///"),
    }
}
<commit_msg>WIP double click<commit_after>use redox::*;
use redox::time::*;

pub struct FileManager {
    folder_icon: BMPFile,
    audio_icon: BMPFile,
    bin_icon: BMPFile,
    image_icon: BMPFile,
    source_icon: BMPFile,
    script_icon: BMPFile,
    text_icon: BMPFile,
    file_icon: BMPFile,
    files: Vec<String>,
    selected: isize,
    last_mouse_event: MouseEvent,
    click_time: Duration,
}

fn load_icon(path: &str) -> BMPFile {
    let mut resource = File::open(&("file:///ui/mimetypes/".to_string() + path + ".bmp"));

    let mut vec: Vec<u8> = Vec::new();
    resource.read_to_end(&mut vec);

    BMPFile::from_data(&vec)
}

impl FileManager {
    pub fn new() -> Self {
        FileManager {
            folder_icon: load_icon("inode-directory"),
            audio_icon: load_icon("audio-x-wav"),
            bin_icon: load_icon("application-x-executable"),
            image_icon: load_icon("image-x-generic"),
            source_icon: load_icon("text-x-makefile"),
            script_icon: load_icon("text-x-script"),
            text_icon: load_icon("text-x-generic"),
            file_icon: load_icon("unknown"),
            files: Vec::new(),
            selected: -1,
            last_mouse_event: MouseEvent {
                x: 0,
                y: 0,
                left_button: false,
                middle_button: false,
                right_button: false,
            }
            click_time: Duration::new(0, 0),
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        window.set([255, 255, 255, 255]);

        let mut i = 0;
        let mut row = 0;
        for string in self.files.iter() {
            if i == self.selected {
                let width = window.width();
                window.rect(0, 32 * row as isize, width, 32, [224, 224, 224, 255]);
            }

            if string.ends_with('/') {
                window.image(0,
                             32 * row as isize,
                             self.folder_icon.width(),
                             self.folder_icon.height(),
                             self.folder_icon.as_slice());
            } else if string.ends_with(".wav") {
                window.image(0,
                             32 * row as isize,
                             self.audio_icon.width(),
                             self.audio_icon.height(),
                             self.audio_icon.as_slice());
            } else if string.ends_with(".bin") {
                window.image(0,
                             32 * row as isize,
                             self.bin_icon.width(),
                             self.bin_icon.height(),
                             self.bin_icon.as_slice());
            } else if string.ends_with(".bmp") {
                window.image(0,
                             32 * row as isize,
                             self.image_icon.width(),
                             self.image_icon.height(),
                             self.image_icon.as_slice());
            } else if string.ends_with(".rs") || string.ends_with(".asm") || string.ends_with(".list") {
                window.image(0,
                             32 * row as isize,
                             self.source_icon.width(),
                             self.source_icon.height(),
                             self.source_icon.as_slice());
            } else if string.ends_with(".sh") || string.ends_with(".lua") {
                window.image(0,
                             32 * row as isize,
                             self.script_icon.width(),
                             self.script_icon.height(),
                             self.script_icon.as_slice());
            } else if string.ends_with(".md") || string.ends_with(".txt") {
                window.image(0,
                             32 * row as isize,
                             self.text_icon.width(),
                             self.text_icon.height(),
                             self.text_icon.as_slice());
            } else {
                window.image(0,
                             32 * row as isize,
                             self.file_icon.width(),
                             self.file_icon.height(),
                             self.file_icon.as_slice());
            }

            let mut col = 0;
            for c in string.chars() {
                if c == '\n' {
                    col = 0;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col < window.width() / 8 && row < window.height() / 32 {
                        window.char(8 * col as isize + 40,
                                    32 * row as isize + 8,
                                    c,
                                    [0, 0, 0, 255]);
                        col += 1;
                    }
                }
                if col >= window.width() / 8 {
                    col = 0;
                    row += 1;
                }
            }
            row += 1;
            i += 1;
        }

        window.sync();
    }

    fn main(&mut self, path: &str) {
        let mut width = 160;
        let mut height = 0;
        {
            let mut resource = File::open(path);

            let mut vec: Vec<u8> = Vec::new();
            resource.read_to_end(&mut vec);

            for file in unsafe { String::from_utf8_unchecked(vec) }.split('\n') {
                if width < 40 + (file.len() + 1) * 8 {
                    width = 40 + (file.len() + 1) * 8;
                }
                self.files.push(file.to_string());
            }

            if height < self.files.len() * 32 {
                height = self.files.len() * 32;
            }
        }

        let mut window = Window::new((rand() % 400 + 50) as isize,
                                     (rand() % 300 + 50) as isize,
                                     width,
                                     height,
                                     &path);

        self.draw_content(&mut window);

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        match key_event.scancode {
                            K_ESC => break,
                            K_HOME => self.selected = 0,
                            K_UP => if self.selected > 0 {
                                self.selected -= 1;
                            },
                            K_END => self.selected = self.files.len() as isize - 1,
                            K_DOWN => if self.selected < self.files.len() as isize - 1 {
                                self.selected += 1;
                            },
                            _ => match key_event.character {
                                '\0' => (),
                                '\n' => {
                                    if self.selected >= 0 &&
                                       self.selected < self.files.len() as isize {
                                        match self.files.get(self.selected as usize) {
                                            Option::Some(file) => OpenEvent {
                                                url_string: path.to_string() + &file,
                                            }.trigger(),
                                            Option::None => (),
                                        }
                                    }
                                }
                                _ => {
                                    let mut i = 0;
                                    for file in self.files.iter() {
                                        if file.starts_with(key_event.character) {
                                            self.selected = i;
                                            break;
                                        }
                                        i += 1;
                                    }
                                }
                            },
                        }

                        self.draw_content(&mut window);
                    }
                }
                EventOption::Mouse(mouse_event) => {
                    let mut redraw = false;
                    let mut i = 0;
                    let mut row = 0;
                    for file in self.files.iter() {
                        let mut col = 0;
                        for c in file.chars() {
                            if mouse_event.y >= 32 * row as isize &&
                               mouse_event.y < 32 * row as isize + 32 {
                                let click_time = Duration::realtime();
                                if self.selected == i {
                                    if click_time - self.click_time < Duration::new(0, 500 * NANOS_PER_MILLI) {
                                        match self.files.get(self.selected as usize) {
                                            Option::Some(file) => OpenEvent {
                                                url_string: path.to_string() + &file,
                                            }.trigger(),
                                            Option::None => (),
                                        }
                                        self.click_time = Duration::new(0, 0);
                                    }
                                } else {
                                    self.selected = i;
                                    self.click_time = click_time;
                                }
                                redraw = true;
                            }

                            if c == '\n' {
                                col = 0;
                                row += 1;
                            } else if c == '\t' {
                                col += 8 - col % 8;
                            } else {
                                if col < window.width() / 8 && row < window.height() / 32 {
                                    col += 1;
                                }
                            }
                            if col >= window.width() / 8 {
                                col = 0;
                                row += 1;
                            }
                        }
                        row += 1;
                        i += 1;
                    }

                    if redraw {
                        self.draw_content(&mut window);
                    }

                    self.last_mouse_event = mouse_event;
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => FileManager::new().main(arg),
        Option::None => FileManager::new().main("file:///"),
    }
}
<|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
//

#![deny(
    dead_code,
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_qualifications,
    while_true,
)]

#[macro_use] extern crate log;
extern crate glob;
extern crate toml;

extern crate libimagstore;
extern crate libimagrt;
#[macro_use] extern crate libimagerror;
extern crate libimagentryedit;

pub mod error;
pub mod builtin;
pub mod result;
pub mod viewer;

<commit_msg>Remove unused import of log crate<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
//

#![deny(
    dead_code,
    non_camel_case_types,
    non_snake_case,
    path_statements,
    trivial_numeric_casts,
    unstable_features,
    unused_allocation,
    unused_import_braces,
    unused_imports,
    unused_must_use,
    unused_mut,
    unused_qualifications,
    while_true,
)]

extern crate glob;
extern crate toml;

extern crate libimagstore;
extern crate libimagrt;
#[macro_use] extern crate libimagerror;
extern crate libimagentryedit;

pub mod error;
pub mod builtin;
pub mod result;
pub mod viewer;

<|endoftext|>


<commit_before><commit_msg>(feat) Added Response wrapper around HttpResponse.<commit_after><|endoftext|>


<commit_before>

// Simple ANSI color library.
//
// TODO: Windows support.
const u8 color_black = 0u8;

const u8 color_red = 1u8;

const u8 color_green = 2u8;

const u8 color_yellow = 3u8;

const u8 color_blue = 4u8;

const u8 color_magenta = 5u8;

const u8 color_cyan = 6u8;

const u8 color_light_gray = 7u8;

const u8 color_light_grey = 7u8;

const u8 color_dark_gray = 8u8;

const u8 color_dark_grey = 8u8;

const u8 color_bright_red = 9u8;

const u8 color_bright_green = 10u8;

const u8 color_bright_yellow = 11u8;

const u8 color_bright_blue = 12u8;

const u8 color_bright_magenta = 13u8;

const u8 color_bright_cyan = 14u8;

const u8 color_bright_white = 15u8;

fn esc(io::buf_writer writer) { writer.write([0x1bu8, '[' as u8]); }

fn reset(io::buf_writer writer) {
    esc(writer);
    writer.write(['0' as u8, 'm' as u8]);
}

fn color_supported() -> bool {
    ret generic_os::getenv("TERM") == option::some[str]("xterm-color");
}

fn set_color(io::buf_writer writer, u8 first_char, u8 color) {
    assert (color < 16u8);
    esc(writer);
    if (color >= 8u8) { writer.write(['1' as u8, ';' as u8]); color -= 8u8; }
    writer.write([first_char, ('0' as u8) + color, 'm' as u8]);
}

fn fg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '3' as u8, color);
}

fn bg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '4' as u8, color);
}
// export fg;
// export bg;
<commit_msg>stdlib: Add emacs variables to term.rs<commit_after>

// Simple ANSI color library.
//
// TODO: Windows support.
const u8 color_black = 0u8;

const u8 color_red = 1u8;

const u8 color_green = 2u8;

const u8 color_yellow = 3u8;

const u8 color_blue = 4u8;

const u8 color_magenta = 5u8;

const u8 color_cyan = 6u8;

const u8 color_light_gray = 7u8;

const u8 color_light_grey = 7u8;

const u8 color_dark_gray = 8u8;

const u8 color_dark_grey = 8u8;

const u8 color_bright_red = 9u8;

const u8 color_bright_green = 10u8;

const u8 color_bright_yellow = 11u8;

const u8 color_bright_blue = 12u8;

const u8 color_bright_magenta = 13u8;

const u8 color_bright_cyan = 14u8;

const u8 color_bright_white = 15u8;

fn esc(io::buf_writer writer) { writer.write([0x1bu8, '[' as u8]); }

fn reset(io::buf_writer writer) {
    esc(writer);
    writer.write(['0' as u8, 'm' as u8]);
}

fn color_supported() -> bool {

    ret generic_os::getenv("TERM") == option::some[str]("xterm-color");
}

fn set_color(io::buf_writer writer, u8 first_char, u8 color) {
    assert (color < 16u8);
    esc(writer);
    if (color >= 8u8) { writer.write(['1' as u8, ';' as u8]); color -= 8u8; }
    writer.write([first_char, ('0' as u8) + color, 'm' as u8]);
}

fn fg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '3' as u8, color);
}

fn bg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '4' as u8, color);
}
// export fg;
// export bg;

// Local Variables:
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before><commit_msg>Ignore create_dir errors in tests<commit_after><|endoftext|>


<commit_before>use std::os;
use std::io::fs;
use std::io::File;
use std::path::Path;

use document::Document;

pub struct Runner;

impl Runner {
    pub fn run(path_string: &str) {
        let base_path = os::make_absolute(&Path::new(path_string));
        let documents_path = os::make_absolute(&Path::new((path_string.to_string() + "/_posts").as_slice()));

        println!("Generating site in {}", base_path.as_str().unwrap());

        let documents = Runner::parse_documents(documents_path);
    }

    fn parse_documents(documents_path: Path) -> Vec<Document> {
        let paths = fs::readdir(&documents_path);
        let mut documents = vec!();

        if paths.is_ok() {
            for path in paths.unwrap().iter() {
                let attributes   = Runner::extract_attributes(path);
                let content      = Runner::extract_content(path);

                for attribute in attributes.iter() {
                    println!("{}", attribute);
                }

                documents.push(Document::new(attributes, content));
            }
        } else {
            println!("Path {} doesn't exist", documents_path.as_str().unwrap());
        }

        return documents;
    }

    fn extract_attributes(document_path: &Path) -> Vec<(String, String)> {
        let content = File::open(document_path).read_to_string().unwrap();

        // TODO: Regex matching for retrieving the attributes

        vec![
            ("Test Key".to_string(), "Test Value".to_string()),
            ("Test Key2".to_string(), "Test Value2".to_string())
        ]
    }

    fn extract_content(document_path: &Path) -> String {
        let content = File::open(document_path).read_to_string().unwrap();

        // TODO: Regex matching for retrieving the content

        return "Test".to_string();
    }
}
<commit_msg>Implemented parsing of documents - parsed in Document has following members: name, user-set attributes & content<commit_after>use std::os;
use std::io::fs;
use std::io::File;
use std::path::Path;

use document::Document;

pub struct Runner;

impl Runner {
    pub fn run(path_string: &str) {
        let base_path      = os::make_absolute(&Path::new(path_string));
        let documents_path = os::make_absolute(&Path::new((path_string.to_string() + "/_posts").as_slice()));

        println!("Generating site in {}", base_path.as_str().unwrap());

        let documents = Runner::parse_documents(documents_path);
    }

    fn parse_documents(documents_path: Path) -> Vec<Document> {
        let paths = fs::readdir(&documents_path);
        let mut documents = vec!();

        if paths.is_ok() {
            for path in paths.unwrap().iter() {
                if path.extension_str().unwrap() != "tpl" {
                    continue;
                }

                let attributes = Runner::extract_attributes(path);
                let content    = Runner::extract_content(path);

                documents.push(Document::new(attributes, content));
            }
        } else {
            println!("Path {} doesn't exist", documents_path.as_str().unwrap());
        }

        /*for document in documents.iter() {
            println!("{}", document.as_html());
        }*/

        return documents;
    }

    fn extract_attributes(document_path: &Path) -> Vec<(String, String)> {
        let mut attributes = vec!();
        attributes.push(("name".to_string(), document_path.filestem_str().unwrap().to_string()));

        let content = File::open(document_path).read_to_string().unwrap();

        let mut content_splits = content.as_slice().split_str("---");

        let attribute_string = content_splits.nth(0u).unwrap();

        for attribute_line in attribute_string.split_str("\n") {
            if !attribute_line.contains_char(':') {
                continue;
            }

            let mut attribute_split = attribute_line.split(':');

            let key   = attribute_split.nth(0u).unwrap().trim_chars(' ').to_string();
            let value = attribute_split.nth(0u).unwrap().trim_chars(' ').to_string();

            attributes.push((key, value));
        }

        return attributes;
    }

    fn extract_content(document_path: &Path) -> String {
        let content = File::open(document_path).read_to_string().unwrap();

        let mut content_splits = content.as_slice().split_str("---");

        content_splits.nth(1u).unwrap().to_string()
    }
}
<|endoftext|>


<commit_before><commit_msg>Fire up the Voight-Kampff machine<commit_after>#![feature(clone_closures)]

extern crate rayon;

use rayon::prelude::*;

fn check<I>(iter: I)
    where I: ParallelIterator + Clone,
          I::Item: std::fmt::Debug + PartialEq
{
    let a: Vec<_> = iter.clone().collect();
    let b: Vec<_> = iter.collect();
    assert_eq!(a, b);
}

#[test]
fn clone_binary_heap() {
    use std::collections::BinaryHeap;
    let heap: BinaryHeap<_> = (0..1000).collect();
    check(heap.par_iter());
    check(heap.into_par_iter());
}

#[test]
fn clone_btree_map() {
    use std::collections::BTreeMap;
    let map: BTreeMap<_,_> = (0..1000).enumerate().collect();
    check(map.par_iter());
}

#[test]
fn clone_btree_set() {
    use std::collections::BTreeSet;
    let set: BTreeSet<_> = (0..1000).collect();
    check(set.par_iter());
}

#[test]
fn clone_hash_map() {
    use std::collections::HashMap;
    let map: HashMap<_,_> = (0..1000).enumerate().collect();
    check(map.par_iter());
}

#[test]
fn clone_hash_set() {
    use std::collections::HashSet;
    let set: HashSet<_> = (0..1000).collect();
    check(set.par_iter());
}

#[test]
fn clone_linked_list() {
    use std::collections::LinkedList;
    let list: LinkedList<_> = (0..1000).collect();
    check(list.par_iter());
    check(list.into_par_iter());
}

#[test]
fn clone_vec_deque() {
    use std::collections::VecDeque;
    let deque: VecDeque<_> = (0..1000).collect();
    check(deque.par_iter());
    check(deque.into_par_iter());
}

#[test]
fn clone_option() {
    let option = Some(0);
    check(option.par_iter());
    check(option.into_par_iter());
}

#[test]
fn clone_result() {
    let result = Ok::<_, ()>(0);
    check(result.par_iter());
    // rust-lang/rust#45179
    // check(result.into_par_iter());
}

#[test]
fn clone_range() {
    check((0..1000).into_par_iter());
}

#[test]
fn clone_str() {
    let s = include_str!("clones.rs");
    check(s.par_chars());
    check(s.par_lines());
    check(s.par_split('\n'));
    check(s.par_split_terminator('\n'));
    check(s.par_split_whitespace());
}

#[test]
fn clone_vec() {
    let v: Vec<_> = (0..1000).collect();
    check(v.par_iter());
    check(v.par_chunks(42));
    check(v.par_windows(42));
    check(v.par_split(|x| x % 3 == 0));
    check(v.into_par_iter());
}

#[test]
fn clone_adaptors() {
    let v: Vec<_> = (0..1000).map(Some).collect();
    check(v.par_iter().chain(&v));
    check(v.par_iter().cloned());
    check(v.par_iter().enumerate());
    check(v.par_iter().filter(|_| true));
    check(v.par_iter().filter_map(|x| *x));
    check(v.par_iter().flat_map(|x| *x));
    check(v.par_iter().flatten());
    check(v.par_iter().with_max_len(1).fold(|| 0, |x, _| x));
    check(v.par_iter().with_max_len(1).fold_with(0, |x, _| x));
    check(v.par_iter().inspect(|_| ()));
    check(v.par_iter().interleave(&v));
    check(v.par_iter().interleave_shortest(&v));
    check(v.par_iter().intersperse(&None));
    check(v.par_iter().map(|x| x));
    check(v.par_iter().map_with(0, |_, x| x));
    check(v.par_iter().rev());
    check(v.par_iter().skip(1));
    check(v.par_iter().take(1));
    check(v.par_iter().cloned().while_some());
    check(v.par_iter().with_max_len(1));
    check(v.par_iter().with_min_len(1));
    check(v.par_iter().zip(&v));
    check(v.par_iter().zip_eq(&v));
}

#[test]
fn clone_repeat() {
    let x: Option<i32> = None;
    check(rayon::iter::repeat(x).while_some());
    check(rayon::iter::repeatn(x, 1000));
}

#[test]
fn clone_splitter() {
    check(rayon::iter::split((0..1000), |x| (x, None)));
}

<|endoftext|>


<commit_before><commit_msg>Add test for equality coercion<commit_after><|endoftext|>


<commit_before><commit_msg>v8 rub complete<commit_after><|endoftext|>


<commit_before>extern crate futures;

use std::thread;
use futures::sync::oneshot;
use futures::Future;
use futures::future::IntoShared;

fn send_shared_oneshot_and_wait_on_multiple_threads(threads_number: u32) {
    let (tx, rx) = oneshot::channel::<u32>();
    let f = rx.shared();
    let mut cloned_futures_waited_oneshots = vec![];
    for _ in 0..threads_number {
        let cloned_future = f.clone();
        let (tx2, rx2) = oneshot::channel::<()>();
        cloned_futures_waited_oneshots.push(rx2);
        thread::spawn(move || {
            assert!(*cloned_future.wait().unwrap() == 6);
            tx2.complete(());
        });
    }
    tx.complete(6);
    for f in cloned_futures_waited_oneshots {
        f.wait().unwrap();
    }
}

#[test]
fn one_threads() {
    send_shared_oneshot_and_wait_on_multiple_threads(2);
}

#[test]
fn two_threads() {
    send_shared_oneshot_and_wait_on_multiple_threads(2);
}

#[test]
fn many_threads() {
    send_shared_oneshot_and_wait_on_multiple_threads(10000);
}
<commit_msg>Reduce number of threads in many_threads() test<commit_after>extern crate futures;

use std::thread;
use futures::sync::oneshot;
use futures::Future;
use futures::future::IntoShared;

fn send_shared_oneshot_and_wait_on_multiple_threads(threads_number: u32) {
    let (tx, rx) = oneshot::channel::<u32>();
    let f = rx.shared();
    let mut cloned_futures_waited_oneshots = vec![];
    for _ in 0..threads_number {
        let cloned_future = f.clone();
        let (tx2, rx2) = oneshot::channel::<()>();
        cloned_futures_waited_oneshots.push(rx2);
        thread::spawn(move || {
            assert!(*cloned_future.wait().unwrap() == 6);
            tx2.complete(());
        });
    }
    tx.complete(6);
    for f in cloned_futures_waited_oneshots {
        f.wait().unwrap();
    }
}

#[test]
fn one_threads() {
    send_shared_oneshot_and_wait_on_multiple_threads(2);
}

#[test]
fn two_threads() {
    send_shared_oneshot_and_wait_on_multiple_threads(2);
}

#[test]
fn many_threads() {
    send_shared_oneshot_and_wait_on_multiple_threads(1000);
}
<|endoftext|>


<commit_before><commit_msg>Initial work to add cookies into store.<commit_after><|endoftext|>


<commit_before><commit_msg>Demonstrated rotated collision only works one-way<commit_after><|endoftext|>


<commit_before><commit_msg>need a fps lock, otherwise starting to look good<commit_after><|endoftext|>


<commit_before><commit_msg>updated to check/remove dirty file<commit_after><|endoftext|>


<commit_before>// Copyright 2015, Paul Osborne <osbpau@gmail.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/license/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.
//
// Portions of this implementation are based on work by Nat Pryce:
// https://github.com/npryce/rusty-pi/blob/master/src/pi/gpio.rs

#![crate_type = "lib"]
#![crate_name = "sysfs_gpio"]
#![feature(io)]

///! GPIO access under Linux using the GPIO sysfs interface
///!
///! The methods exposed by this library are centered around
///! the `Pin` struct and map pretty directly the API exposed
///! by the kernel in syfs (https://www.kernel.org/doc/Documentation/gpio/sysfs.txt).
///!
///! # Examples
///!
///! Typical usage for systems where one wants to ensure that
///! the pins in use are unexported upon completion looks like
///! the follwoing:
///!
///! ```rust,ignore
///! extern crate sysfs_gpio;
///! use sysfs_gpio::Pin;
///!
///!
///! ```

use std::io::prelude::*;
use std::io;
use std::io::{Error, ErrorKind};
use std::fs;
use std::fs::{File};

pub struct Pin {
    pin_num : u64,
}

#[derive(Copy,Debug)]
pub enum Direction {In, Out, High, Low}

#[derive(Copy,Debug)]
pub enum Edge {NoInterrupt, RisingEdge, FallingEdge, BothEdges}

#[macro_export]
macro_rules! try_unexport {
    ($gpio:ident, $e:expr) => (match $e {
        Ok(res) => res,
        Err(e) => { try!($gpio.unexport()); return Err(e) },
    });
}

impl Pin {
    /// Write all of the provided contents to the specified devFile
    fn write_to_device_file(&self, dev_file_name: &str, value: &str) -> io::Result<()> {
        let gpio_path = format!("/sys/class/gpio/gpio{}/{}", self.pin_num, dev_file_name);
        let mut dev_file = try!(File::create(&gpio_path));
        try!(dev_file.write_all(value.as_bytes()));
        Ok(())
    }

    /// Create a new Pin with the provided `pin_num`
    ///
    /// This function does not export the provided pin_num.
    pub fn new(pin_num : u64) -> Pin {
        Pin {
            pin_num: pin_num,
        }
    }

    /// Run a closure with the GPIO exported
    ///
    /// Prior to the provided closure being executed, the Gpio
    /// will be eported.  After the closure execution is complete,
    /// the Gpio will be unexported.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// gpio = Pin::new(24);
    /// let res = gpio::with_exported(|| {
    ///     println!("At this point, the Pin is exported");
    ///     try!(gpio.set_direction(Direction::Low));
    ///     try!(gpio.set_value(1));
    ///     // ...
    /// };
    /// ```
    #[inline]
    pub fn with_exported<F: FnOnce() -> io::Result<()>>(&self, closure : F) -> io::Result<()> {
        try!(self.export());
        match closure() {
            Ok(()) => { try!(self.unexport()); Ok(()) },
            Err(err) => { try!(self.unexport()); Err(err) },
        }
    }

    /// Export the GPIO
    ///
    /// This is equivalent to `echo N > /sys/class/gpio/export` with
    /// the exception that the case where the GPIO is already exported
    /// is not an error.
    ///
    /// # Errors
    ///
    /// The main cases in which this function will fail and return an
    /// error are the following:
    /// 1. The system does not support the GPIO sysfs interface
    /// 2. The requested GPIO is out of range and cannot be exported
    /// 3. The requested GPIO is in use by the kernel and cannot
    ///    be exported by use in userspace
    ///
    /// # Example
    /// ```rust,ignore
    /// use sysfs_gpio::Pin;
    ///
    /// gpio = Pin::new(24);
    /// match gpio.export() {
    ///     Ok(()) => println!("Gpio {} exported!", gpio.pin),
    ///     Err(err) => println!("Gpio {} could not be exported: {}", gpio.pin, err),
    /// }
    /// ```
    pub fn export(&self) -> io::Result<()> {
        match fs::metadata(&format!("/sys/class/gpio/gpio{}", self.pin_num)) {
            Ok(_) => {},
            Err(_) => {
                let mut export_file = try!(File::create("/sys/class/gpio/export"));
                try!(export_file.write_all(format!("{}", self.pin_num).as_bytes()));
            }
        };
        Ok(())
    }

    /// Unexport the GPIO
    ///
    /// This function will unexport the provided by from syfs if
    /// it is currently exported.  If the pin is not currently
    /// exported, it will return without error.  That is, whenever
    /// this function returns Ok, the GPIO is not exported.
    pub fn unexport(&self) -> io::Result<()> {
        match fs::metadata(&format!("/sys/class/gpio/gpio{}", self.pin_num)) {
            Ok(_) => {
                let mut unexport_file = try!(File::create("/sys/class/gpio/unexport"));
                try!(unexport_file.write_all(format!("{}", self.pin_num).as_bytes()));
            },
            Err(_) => {} // not exported
        };
        Ok(())
    }

    /// Set this GPIO as either an input or an output
    ///
    /// The basic values allowed here are `Direction::In` and
    /// `Direction::Out` which set the Pin as either an input
    /// or output respectively.  In addition to those, two
    /// additional settings of `Direction::High` and
    /// `Direction::Low`.  These both set the Pin as an output
    /// but do so with an initial value of high or low respectively.
    /// This allows for glitch-free operation.
    ///
    /// Note that this entry may not exist if the kernel does
    /// not support changing the direction of a pin in userspace.  If
    /// this is the case, you will get an error.
    pub fn set_direction(&self, dir : Direction) -> io::Result<()> {
        self.write_to_device_file("direction", match dir {
            Direction::In => "in",
            Direction::Out => "out",
            Direction::High => "high",
            Direction::Low => "low",
        })
    }

    /// Get the value of the Pin (0 or 1)
    ///
    /// If successful, 1 will be returned if the pin is high
    /// and 0 will be returned if the pin is low (this may or may
    /// not match the signal level of the actual signal depending
    /// on the GPIO "active_low" entry).
    pub fn get_value(&self) -> io::Result<u8> {
        let mut dev_file = try!(File::open(&format!("/sys/class/gpio/gpio{}/value", self.pin_num)));
        let mut s = String::with_capacity(10);
        try!(dev_file.read_to_string(&mut s));
        match s[..1].parse::<u8>() {
            Ok(n) => Ok(n),
            Err(_) => Err(Error::new(ErrorKind::Other, "Unexpected Error", None)),
        }
    }

    /// Set the value of the Pin
    ///
    /// This will set the value of the pin either high or low.
    /// A 0 value will set the pin low and any other value will
    /// set the pin high (1 is typical).
    pub fn set_value(&self, value : u8) -> io::Result<()> {
        let val = if value == 0 {
            "0"
        } else {
            "1"
        };
        self.write_to_device_file("value", val)
    }
}
<commit_msg>core: updates to work with rust 1.0.0 beta<commit_after>// Copyright 2015, Paul Osborne <osbpau@gmail.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/license/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.
//
// Portions of this implementation are based on work by Nat Pryce:
// https://github.com/npryce/rusty-pi/blob/master/src/pi/gpio.rs

#![crate_type = "lib"]
#![crate_name = "sysfs_gpio"]

///! GPIO access under Linux using the GPIO sysfs interface
///!
///! The methods exposed by this library are centered around
///! the `Pin` struct and map pretty directly the API exposed
///! by the kernel in syfs (https://www.kernel.org/doc/Documentation/gpio/sysfs.txt).
///!
///! # Examples
///!
///! Typical usage for systems where one wants to ensure that
///! the pins in use are unexported upon completion looks like
///! the follwoing:
///!
///! ```rust,ignore
///! extern crate sysfs_gpio;
///! use sysfs_gpio::Pin;
///!
///!
///! ```

use std::io::prelude::*;
use std::io;
use std::io::{Error, ErrorKind};
use std::fs;
use std::fs::{File};

pub struct Pin {
    pin_num : u64,
}

#[derive(Clone,Debug)]
pub enum Direction {In, Out, High, Low}

#[derive(Clone,Debug)]
pub enum Edge {NoInterrupt, RisingEdge, FallingEdge, BothEdges}

#[macro_export]
macro_rules! try_unexport {
    ($gpio:ident, $e:expr) => (match $e {
        Ok(res) => res,
        Err(e) => { try!($gpio.unexport()); return Err(e) },
    });
}

impl Pin {
    /// Write all of the provided contents to the specified devFile
    fn write_to_device_file(&self, dev_file_name: &str, value: &str) -> io::Result<()> {
        let gpio_path = format!("/sys/class/gpio/gpio{}/{}", self.pin_num, dev_file_name);
        let mut dev_file = try!(File::create(&gpio_path));
        try!(dev_file.write_all(value.as_bytes()));
        Ok(())
    }

    /// Create a new Pin with the provided `pin_num`
    ///
    /// This function does not export the provided pin_num.
    pub fn new(pin_num : u64) -> Pin {
        Pin {
            pin_num: pin_num,
        }
    }

    /// Run a closure with the GPIO exported
    ///
    /// Prior to the provided closure being executed, the Gpio
    /// will be eported.  After the closure execution is complete,
    /// the Gpio will be unexported.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// gpio = Pin::new(24);
    /// let res = gpio::with_exported(|| {
    ///     println!("At this point, the Pin is exported");
    ///     try!(gpio.set_direction(Direction::Low));
    ///     try!(gpio.set_value(1));
    ///     // ...
    /// };
    /// ```
    #[inline]
    pub fn with_exported<F: FnOnce() -> io::Result<()>>(&self, closure : F) -> io::Result<()> {
        try!(self.export());
        match closure() {
            Ok(()) => { try!(self.unexport()); Ok(()) },
            Err(err) => { try!(self.unexport()); Err(err) },
        }
    }

    /// Export the GPIO
    ///
    /// This is equivalent to `echo N > /sys/class/gpio/export` with
    /// the exception that the case where the GPIO is already exported
    /// is not an error.
    ///
    /// # Errors
    ///
    /// The main cases in which this function will fail and return an
    /// error are the following:
    /// 1. The system does not support the GPIO sysfs interface
    /// 2. The requested GPIO is out of range and cannot be exported
    /// 3. The requested GPIO is in use by the kernel and cannot
    ///    be exported by use in userspace
    ///
    /// # Example
    /// ```rust,ignore
    /// use sysfs_gpio::Pin;
    ///
    /// gpio = Pin::new(24);
    /// match gpio.export() {
    ///     Ok(()) => println!("Gpio {} exported!", gpio.pin),
    ///     Err(err) => println!("Gpio {} could not be exported: {}", gpio.pin, err),
    /// }
    /// ```
    pub fn export(&self) -> io::Result<()> {
        match fs::metadata(&format!("/sys/class/gpio/gpio{}", self.pin_num)) {
            Ok(_) => {},
            Err(_) => {
                let mut export_file = try!(File::create("/sys/class/gpio/export"));
                try!(export_file.write_all(format!("{}", self.pin_num).as_bytes()));
            }
        };
        Ok(())
    }

    /// Unexport the GPIO
    ///
    /// This function will unexport the provided by from syfs if
    /// it is currently exported.  If the pin is not currently
    /// exported, it will return without error.  That is, whenever
    /// this function returns Ok, the GPIO is not exported.
    pub fn unexport(&self) -> io::Result<()> {
        match fs::metadata(&format!("/sys/class/gpio/gpio{}", self.pin_num)) {
            Ok(_) => {
                let mut unexport_file = try!(File::create("/sys/class/gpio/unexport"));
                try!(unexport_file.write_all(format!("{}", self.pin_num).as_bytes()));
            },
            Err(_) => {} // not exported
        };
        Ok(())
    }

    /// Set this GPIO as either an input or an output
    ///
    /// The basic values allowed here are `Direction::In` and
    /// `Direction::Out` which set the Pin as either an input
    /// or output respectively.  In addition to those, two
    /// additional settings of `Direction::High` and
    /// `Direction::Low`.  These both set the Pin as an output
    /// but do so with an initial value of high or low respectively.
    /// This allows for glitch-free operation.
    ///
    /// Note that this entry may not exist if the kernel does
    /// not support changing the direction of a pin in userspace.  If
    /// this is the case, you will get an error.
    pub fn set_direction(&self, dir : Direction) -> io::Result<()> {
        self.write_to_device_file("direction", match dir {
            Direction::In => "in",
            Direction::Out => "out",
            Direction::High => "high",
            Direction::Low => "low",
        })
    }

    /// Get the value of the Pin (0 or 1)
    ///
    /// If successful, 1 will be returned if the pin is high
    /// and 0 will be returned if the pin is low (this may or may
    /// not match the signal level of the actual signal depending
    /// on the GPIO "active_low" entry).
    pub fn get_value(&self) -> io::Result<u8> {
        let mut dev_file = try!(File::open(&format!("/sys/class/gpio/gpio{}/value", self.pin_num)));
        let mut s = String::with_capacity(10);
        try!(dev_file.read_to_string(&mut s));
        match s[..1].parse::<u8>() {
            Ok(n) => Ok(n),
            Err(_) => Err(Error::new(ErrorKind::Other, "Unexpected Error")),
        }
    }

    /// Set the value of the Pin
    ///
    /// This will set the value of the pin either high or low.
    /// A 0 value will set the pin low and any other value will
    /// set the pin high (1 is typical).
    pub fn set_value(&self, value : u8) -> io::Result<()> {
        let val = if value == 0 {
            "0"
        } else {
            "1"
        };
        self.write_to_device_file("value", val)
    }
}
<|endoftext|>


<commit_before><commit_msg>Increase recursion limit (for macro expansion)<commit_after><|endoftext|>


<commit_before><commit_msg>not pushing input frame buffer into cross-thread channel unless it has contents<commit_after><|endoftext|>


<commit_before><commit_msg>tests: server dispatch_idle<commit_after>use std::cell::Cell;
use std::rc::Rc;

mod helpers;

use helpers::TestServer;

#[test]
fn dispatch_idle() {
    // Server setup
    //
    let mut server = TestServer::new();

    let dispatched = Rc::new(Cell::new(false));

    let impl_dispatched = dispatched.clone();
    server
        .event_loop
        .token()
        .add_idle_event_source(move |_, _| impl_dispatched.set(true));

    server.event_loop.dispatch(Some(1)).unwrap();

    assert!(dispatched.get());
}
<|endoftext|>


<commit_before><commit_msg>Add missing file :facepalm:<commit_after>use std::sync::Arc;

use light_arena::Allocator;

use bsdf::{BxDF, BxDFHolder, FourierBSDF, FourierBSDFTable, BSDF};
use interaction::SurfaceInteraction;
use material::{Material, TransportMode};
use paramset::TextureParams;
use texture::TextureFloat;

#[derive(Debug)]
pub struct FourierMaterial {
    bsdf_table: Box<FourierBSDFTable>,
    bump_map: Option<Arc<TextureFloat>>,
}

impl FourierMaterial {
    pub fn create(mp: &TextureParams) -> Arc<Material> {
        let bump_map = mp.get_float_texture_or_none("bumpmap");
        let filename = mp.find_filename("bsdffile", "");
        let bsdf_table = Box::new(FourierBSDFTable::read(filename).unwrap()); // TODO error
        Arc::new(FourierMaterial {
            bsdf_table,
            bump_map,
        })
    }
}

impl Material for FourierMaterial {
    fn compute_scattering_functions<'a, 'b>(
        &self,
        si: &mut SurfaceInteraction<'a, 'b>,
        mode: TransportMode,
        allow_multiple_lobes: bool,
        arena: &'b Allocator,
    ) {
        let mut bxdfs = BxDFHolder::new(arena);

        if let Some(ref bump) = self.bump_map {
            super::bump(bump, si);
        }
        bxdfs.add(arena <- FourierBSDF::new(&self.bsdf_table, mode));
        let bsdf = BSDF::new(si, 1.0, bxdfs.into_slice());
        si.bsdf = Some(Arc::new(bsdf));
    }
}
<|endoftext|>


<commit_before><commit_msg>cleaned up a stray comment and adjusted default font size to something that looks better<commit_after><|endoftext|>


<commit_before><commit_msg>remove unneeded test<commit_after><|endoftext|>


<commit_before><commit_msg>Adding DecodingError and Result type.<commit_after><|endoftext|>


<commit_before><commit_msg>Make max lengths public.<commit_after><|endoftext|>


<commit_before><commit_msg>run_command API update<commit_after><|endoftext|>


<commit_before><commit_msg>add_history_persist<commit_after><|endoftext|>


<commit_before><commit_msg>Add full round-trip test<commit_after>extern crate bitstream_io;
use bitstream_io::{BitReaderBE, BitReaderLE, BitRead};
use bitstream_io::{BitWriterBE, BitWriterLE, BitWrite};
use std::io::Cursor;

macro_rules! define_roundtrip {
    ($func_name:ident, $reader_type:ident, $writer_type:ident) => {
       #[test]
        fn $func_name() {
            /*unsigned values*/
            for bits in 1..17 {
                let max = 1 << bits;
                let mut output: Vec<u8> = Vec::with_capacity(max);
                {
                    let mut writer = $writer_type::new(&mut output);
                    for value in 0..max {
                        writer.write(bits, value as u32).unwrap();
                    }
                    writer.byte_align().unwrap();
                }
                {
                    let mut c = Cursor::new(&output);
                    let mut reader = $reader_type::new(&mut c);
                    for value in 0..max {
                        assert_eq!(reader.read::<u32>(bits).unwrap(),
                                   value as u32);
                    }
                }
            }

            /*signed values*/
            for bits in 2..17 {
                let min = -1i32 << (bits - 1);
                let max = 1i32 << (bits - 1);
                let mut output: Vec<u8> = Vec::with_capacity(max as usize);
                {
                    let mut writer = $writer_type::new(&mut output);
                    for value in min..max {
                        writer.write_signed(bits, value as i32).unwrap();
                    }
                    writer.byte_align().unwrap();
                }
                {
                    let mut c = Cursor::new(&output);
                    let mut reader = $reader_type::new(&mut c);
                    for value in min..max {
                        assert_eq!(reader.read_signed::<i32>(bits).unwrap(),
                                   value as i32);
                    }
                }
            }

        }
    }
}

define_roundtrip!(test_roundtrip_be, BitReaderBE, BitWriterBE);
define_roundtrip!(test_roundtrip_le, BitReaderLE, BitWriterLE);
<|endoftext|>


<commit_before>use check_gl;
use gl;
use gl::types::{GLint, GLuint, GLenum, GLsizeiptr};
use libc;
use libc::c_void;
use std::mem;

type IndexType = u16;

#[allow(raw_pointer_deriving)]
#[deriving(Clone)]
struct VertexAttribute {
    layout: GLuint,
    gl_type: GLenum,
    size: GLint,
    normalized: u8,
    offset: *const c_void
}

pub struct BufferBuilder<VertexType: Copy> {
    attributes: Vec<VertexAttribute>,
    used_layouts: Vec<bool>,
    vertex_size: uint
}
impl<VertexType: Copy>  BufferBuilder<VertexType> {
    pub fn new(capacity: uint) -> BufferBuilder<VertexType> {
        BufferBuilder {
            attributes: Vec::with_capacity(capacity),
            used_layouts: Vec::with_capacity(capacity),
            vertex_size: 0,
        }
    }

    pub fn max_attribute_size_left(&self) -> uint {
        let final_size = mem::size_of::<VertexType>();
        assert!(final_size >= self.vertex_size);
        final_size - self.vertex_size
    }

    pub fn attribute_f32(&mut self, layout: uint, offset: *const c_void)
            -> &mut BufferBuilder<VertexType> {
        self.new_attribute(layout, gl::FLOAT, 1, false, offset)
    }

    pub fn attribute_vec2f(&mut self, layout: uint, offset: *const c_void)
            -> &mut BufferBuilder<VertexType> {
        self.new_attribute(layout, gl::FLOAT, 2, false, offset)
    }

    pub fn attribute_vec3f(&mut self, layout: uint, offset: *const c_void)
            -> &mut BufferBuilder<VertexType> {
        self.new_attribute(layout, gl::FLOAT, 3, false, offset)
    }

    pub fn new_attribute(&mut self, layout: uint, gl_type: GLenum,
                         size: uint, normalized: bool, offset: *const c_void)
            -> &mut BufferBuilder<VertexType> {
        let attr_size = size * match gl_type {
            gl::FLOAT => mem::size_of::<f32>(),
            _ => fail!("Unsupported attribute type.")
        };
        assert!(self.max_attribute_size_left() >= attr_size);
        self.vertex_size += attr_size;
        if self.used_layouts.len() > layout {
            assert!(!self.used_layouts[layout]);
            *self.used_layouts.get_mut(layout) = true;
        } else {
            for _ in range(0, layout - self.used_layouts.len()) {
                self.used_layouts.push(false);
            }
            self.used_layouts.push(true);
        }
        self.attributes.push(VertexAttribute {
            layout: layout as GLuint,
            gl_type: gl_type,
            size: size as GLint,
            normalized: normalized as u8,
            offset: offset,
        });
        self
    }

    pub fn build(&self) -> VertexBuffer {
        assert_eq!(self.max_attribute_size_left(), 0);
        VertexBuffer::new(self.vertex_size, self.attributes.clone())
    }
}

fn bind_attributes(stride: uint, attributes: &[VertexAttribute]) {
    let stride = stride as i32;
    for attr in attributes.iter() {
        check_gl!(gl::EnableVertexAttribArray(attr.layout));
        check_gl_unsafe!(gl::VertexAttribPointer(attr.layout, attr.size,
                                                 attr.gl_type, attr.normalized,
                                                 stride, attr.offset));
    }
}

fn unbind_attributes(attributes: &[VertexAttribute]) {
    for attr in attributes.iter() {
        check_gl!(gl::DisableVertexAttribArray(attr.layout));
    }
}

struct VboId {
    id: GLuint
}
impl VboId {
    fn new_orphaned() -> VboId {
        VboId { id: 0 }
    }

    fn orphan(&mut self) -> &mut VboId {
        if self.id != 0 {
            check_gl_unsafe!(gl::DeleteBuffers(1, &self.id));
            self.id = 0;
        }
        self
    }

    fn reset(&mut self) -> &mut VboId {
        self.orphan();
        check_gl_unsafe!(gl::GenBuffers(1, &mut self.id));
        assert!(self.id != 0);
        self
    }

    fn bind(&self) -> &VboId {
        check_gl!(gl::BindBuffer(gl::ARRAY_BUFFER, self.id));
        self
    }

    fn unbind(&self) -> &VboId {
        check_gl!(gl::BindBuffer(gl::ARRAY_BUFFER, 0));
        self
    }

    fn id(&self) -> GLuint { self.id }
}

pub struct VertexBuffer {
    id: VboId,
    length: uint,
    attributes: Vec<VertexAttribute>,
    vertex_size: uint,
}

impl VertexBuffer {
    fn new(vertex_size: uint, attributes: Vec<VertexAttribute>)
            -> VertexBuffer {
        VertexBuffer {
            id: VboId::new_orphaned(),
            length: 0,
            vertex_size: vertex_size,
            attributes: attributes,
        }
    }

    pub fn draw_triangles(&self) -> &VertexBuffer {
        check_gl!(gl::BindBuffer(gl::ARRAY_BUFFER, self.id.id()));
        bind_attributes(self.vertex_size, self.attributes.as_slice());
        check_gl!(gl::DrawArrays(gl::TRIANGLES, 0, self.length as i32));
        unbind_attributes(self.attributes.as_slice());
        check_gl!(gl::BindBuffer(gl::ARRAY_BUFFER, 0));
        self
    }

    pub fn len(&self) -> uint { self.length }

    pub fn set_data<V: Copy> (&mut self, usage: GLenum, data: &[V])
            -> &mut VertexBuffer {
        assert_eq!(self.vertex_size, mem::size_of::<V>());
        self.id.reset().bind();
        self.length = data.len();
        check_gl_unsafe!(gl::BufferData(
                gl::ARRAY_BUFFER, (data.len() * self.vertex_size) as GLsizeiptr,
                data.as_ptr() as *const libc::c_void, usage));
        self.id.unbind();
        self
    }
}
<commit_msg>Added u8 vertex attributes<commit_after>use check_gl;
use gl;
use gl::types::{GLint, GLuint, GLenum, GLsizeiptr};
use libc;
use libc::c_void;
use std::mem;

type IndexType = u16;

#[allow(raw_pointer_deriving)]
#[deriving(Clone)]
struct VertexAttribute {
    layout: GLuint,
    gl_type: GLenum,
    size: GLint,
    normalized: u8,
    offset: *const c_void
}

pub struct BufferBuilder<VertexType: Copy> {
    attributes: Vec<VertexAttribute>,
    used_layouts: Vec<bool>,
    vertex_size: uint
}
impl<VertexType: Copy>  BufferBuilder<VertexType> {
    pub fn new(capacity: uint) -> BufferBuilder<VertexType> {
        BufferBuilder {
            attributes: Vec::with_capacity(capacity),
            used_layouts: Vec::with_capacity(capacity),
            vertex_size: 0,
        }
    }

    pub fn max_attribute_size_left(&self) -> uint {
        let final_size = mem::size_of::<VertexType>();
        assert!(final_size >= self.vertex_size);
        final_size - self.vertex_size
    }

    pub fn attribute_u8(&mut self, layout: uint, offset: *const c_void)
            -> &mut BufferBuilder<VertexType> {
        self.new_attribute(layout, gl::UNSIGNED_BYTE, 1, false, offset)
    }

    pub fn attribute_f32(&mut self, layout: uint, offset: *const c_void)
            -> &mut BufferBuilder<VertexType> {
        self.new_attribute(layout, gl::FLOAT, 1, false, offset)
    }

    pub fn attribute_vec2f(&mut self, layout: uint, offset: *const c_void)
            -> &mut BufferBuilder<VertexType> {
        self.new_attribute(layout, gl::FLOAT, 2, false, offset)
    }

    pub fn attribute_vec3f(&mut self, layout: uint, offset: *const c_void)
            -> &mut BufferBuilder<VertexType> {
        self.new_attribute(layout, gl::FLOAT, 3, false, offset)
    }

    pub fn new_attribute(&mut self, layout: uint, gl_type: GLenum,
                         size: uint, normalized: bool, offset: *const c_void)
            -> &mut BufferBuilder<VertexType> {
        let attr_size = size * match gl_type {
            gl::FLOAT => mem::size_of::<f32>(),
            gl::UNSIGNED_BYTE => mem::size_of::<u8>(),
            _ => fail!("Unsupported attribute type.")
        };
        assert!(self.max_attribute_size_left() >= attr_size);
        self.vertex_size += attr_size;
        if self.used_layouts.len() > layout {
            assert!(!self.used_layouts[layout]);
            *self.used_layouts.get_mut(layout) = true;
        } else {
            for _ in range(0, layout - self.used_layouts.len()) {
                self.used_layouts.push(false);
            }
            self.used_layouts.push(true);
        }
        self.attributes.push(VertexAttribute {
            layout: layout as GLuint,
            gl_type: gl_type,
            size: size as GLint,
            normalized: normalized as u8,
            offset: offset,
        });
        self
    }

    pub fn build(&self) -> VertexBuffer {
        assert_eq!(self.max_attribute_size_left(), 0);
        VertexBuffer::new(self.vertex_size, self.attributes.clone())
    }
}

fn bind_attributes(stride: uint, attributes: &[VertexAttribute]) {
    let stride = stride as i32;
    for attr in attributes.iter() {
        check_gl!(gl::EnableVertexAttribArray(attr.layout));
        match attr.gl_type {
            gl::FLOAT => check_gl_unsafe!(gl::VertexAttribPointer(
                attr.layout, attr.size, attr.gl_type, attr.normalized,
                stride, attr.offset)),
            gl::UNSIGNED_BYTE => check_gl_unsafe!(gl::VertexAttribIPointer(
                attr.layout, attr.size, attr.gl_type, stride, attr.offset)),
            _ => fail!("Missing attribute type from attrib ptr.")
        }
    }
}

fn unbind_attributes(attributes: &[VertexAttribute]) {
    for attr in attributes.iter() {
        check_gl!(gl::DisableVertexAttribArray(attr.layout));
    }
}

struct VboId {
    id: GLuint
}
impl VboId {
    fn new_orphaned() -> VboId {
        VboId { id: 0 }
    }

    fn orphan(&mut self) -> &mut VboId {
        if self.id != 0 {
            check_gl_unsafe!(gl::DeleteBuffers(1, &self.id));
            self.id = 0;
        }
        self
    }

    fn reset(&mut self) -> &mut VboId {
        self.orphan();
        check_gl_unsafe!(gl::GenBuffers(1, &mut self.id));
        assert!(self.id != 0);
        self
    }

    fn bind(&self) -> &VboId {
        check_gl!(gl::BindBuffer(gl::ARRAY_BUFFER, self.id));
        self
    }

    fn unbind(&self) -> &VboId {
        check_gl!(gl::BindBuffer(gl::ARRAY_BUFFER, 0));
        self
    }

    fn id(&self) -> GLuint { self.id }
}

pub struct VertexBuffer {
    id: VboId,
    length: uint,
    attributes: Vec<VertexAttribute>,
    vertex_size: uint,
}

impl VertexBuffer {
    fn new(vertex_size: uint, attributes: Vec<VertexAttribute>)
            -> VertexBuffer {
        VertexBuffer {
            id: VboId::new_orphaned(),
            length: 0,
            vertex_size: vertex_size,
            attributes: attributes,
        }
    }

    pub fn draw_triangles(&self) -> &VertexBuffer {
        check_gl!(gl::BindBuffer(gl::ARRAY_BUFFER, self.id.id()));
        bind_attributes(self.vertex_size, self.attributes.as_slice());
        check_gl!(gl::DrawArrays(gl::TRIANGLES, 0, self.length as i32));
        unbind_attributes(self.attributes.as_slice());
        check_gl!(gl::BindBuffer(gl::ARRAY_BUFFER, 0));
        self
    }

    pub fn len(&self) -> uint { self.length }

    pub fn set_data<V: Copy> (&mut self, usage: GLenum, data: &[V])
            -> &mut VertexBuffer {
        assert_eq!(self.vertex_size, mem::size_of::<V>());
        self.id.reset().bind();
        self.length = data.len();
        check_gl_unsafe!(gl::BufferData(
                gl::ARRAY_BUFFER, (data.len() * self.vertex_size) as GLsizeiptr,
                data.as_ptr() as *const libc::c_void, usage));
        self.id.unbind();
        self
    }
}
<|endoftext|>


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


<commit_before><commit_msg>Corrected for Cstr / CString types<commit_after><|endoftext|>


<commit_before><commit_msg>Some experiments<commit_after><|endoftext|>


<commit_before><commit_msg>Create cpuinfo.rs<commit_after>use std::io;
use std::io::Read;
use std::io::prelude;
use std::str;
use nom::{not_line_ending,line_ending};
use nom::IResult;
use std::fs::{OpenOptions, File};

#[derive(Debug)]
pub struct Cpuinfo<'a> {
    pub field: Option<&'a str>,
    pub value: Option<Vec<&'a str>>,
}

impl<'a> Cpuinfo<'a> {
    fn new() -> Cpuinfo<'a> {
        Cpuinfo {
            field: None,
            value: None,
        }
    }

    pub fn read_cpuinfo() {
        let mut input = OpenOptions::new().read(true).open("/proc/cpuinfo").unwrap();
        let mut rtv = Vec::new();
        input.read_to_end(&mut rtv);
        match Cpuinfo::parse_cpuinfo(rtv.as_slice()) {
            IResult::Done(_,o) => {
                print!("{:?}", o);
                for o in o {
                    println!("{:?}", o.field);
                    println!("{:?}", o.value);
                }
            }
            _                  => panic!("Error")
        }
    }

    fn parse_cpuinfo(input:&[u8]) -> IResult<&[u8],Vec<Cpuinfo>> {
        many0!(input,
               chain!(
                   field: map_res!( is_not!("\t"), str::from_utf8) ~
                   value: many0!(terminated!(map_res!( tag!(": "), str::from_utf8), tag!("\n"))),
                   ||{
                       Cpuinfo {
                           field: Some(field),
                           value: Some(value)
                       }
                   }
                )
            )
    }

}
<|endoftext|>


<commit_before><commit_msg>Add missing file<commit_after>use fixedbitset::FixedBitSet;

#[derive(Debug, Clone)]
pub struct AdjMatrix {
    n: usize,
    m: FixedBitSet,
}

impl AdjMatrix {
    pub fn new(n: usize) -> AdjMatrix {
        AdjMatrix {
            n: n,
            m: FixedBitSet::with_capacity(n * n),
        }
    }

    pub fn set(&mut self, i: usize, j: usize) {
        self.m.insert(i * self.n + j);
    }

    fn contains(&self, i: usize, j: usize) -> bool {
        self.m.contains(i * self.n + j)
    }

    /// This is O(n**4) in worst case.
    /// XXX: This needs a test for correctness
    pub fn transitive_closure(mut self) -> AdjMatrix {
        loop {
            let mut counts = 0;
            for i in 0..self.n {
                for j in 0..self.n {
                    if self.contains(i, j) {
                        // look column for j
                        for k in 0..self.n {
                            if self.contains(j, k) {
                                if !self.contains(i, k) {
                                    self.set(i, k);
                                    counts += 1;
                                }
                            }
                        }
                    }
                }
            }
            if counts == 0 {
                break;
            }
        }
        self
    }

    pub fn unconnected_pairs_no_cycle(&self) -> Vec<(usize, usize)> {
        let mut pairs = Vec::new();
        for i in 0..self.n {
            for j in 0..self.n {
                if i != j {
                    if !(self.contains(i, j) || self.contains(j, i)) {
                        // make sure we don't introduce a cycle
                        pairs.push((i, j));
                    }
                }
            }
        }
        pairs
    }
}
<|endoftext|>


<commit_before><commit_msg>Make some preliminary implementations of Word2Vec<commit_after><|endoftext|>


<commit_before><commit_msg>Playing with polymorhism examples, it doesn't work, we need copy<commit_after>use std::rc::Rc;

struct Pig {
    name: &'static str
}

struct Dog {
    name: &'static str
}

trait Animal {
    fn sound(&self);
}

impl Animal for Pig {
    fn sound(&self) {
        println!("this is a {} pig", self.name);
    }
}

impl Animal for Dog {
    fn sound(&self) {
        println!("this is a {} dog", self.name);
    }
}

struct Farm {
    animal: Rc<dyn Animal>
}

struct Family {
   animal: Rc<dyn Animal>
}

fn main () {
    let pig = Pig{name: "pig1"};
    pig.sound();
    let dog = Dog{name: "dog1"};
    dog.sound();
    let farm = Farm{animal: Rc::new(pig)};
    let farm2 = Farm{animal: Rc::new(pig)};

    // hello example

}
<|endoftext|>


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


<commit_before><commit_msg>get_tag now panic<commit_after><|endoftext|>


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


<commit_before><commit_msg>Use rust methods<commit_after><|endoftext|>


<commit_before><commit_msg>example socket code<commit_after>extern crate websocket;

use std::thread;
use websocket::OwnedMessage;
use websocket::sync::Server;

fn main() {
	let server = Server::bind("127.0.0.1:8500").unwrap();

	for request in server.filter_map(Result::ok) {
		// Spawn a new thread for each connection.
		thread::spawn(move || {
			if !request.protocols().contains(&"rust-websocket".to_string()) {
				request.reject().unwrap();
				return;
			}

			let mut client = request.use_protocol("rust-websocket").accept().unwrap();

			let ip = client.peer_addr().unwrap();

			println!("Connection from {}", ip);

			let message = OwnedMessage::Text("Hello".to_string());
			client.send_message(&message).unwrap();

			let (mut receiver, mut sender) = client.split().unwrap();

			for message in receiver.incoming_messages() {
				let message = message.unwrap();

				match message {
					OwnedMessage::Close(_) => {
						let message = OwnedMessage::Close(None);
						sender.send_message(&message).unwrap();
						println!("Client {} disconnected", ip);
						return;
					}
					OwnedMessage::Ping(ping) => {
						let message = OwnedMessage::Pong(ping);
						sender.send_message(&message).unwrap();
					}
					_ => sender.send_message(&message).unwrap(),
				}
			}
		});
	}
}
<|endoftext|>


<commit_before><commit_msg>practise rust version<commit_after>fn two_sum(nums: Vec<i32>, target: i32) -> Vec<u32> {
    let len = nums.len();
    for i in 0..len {
        for j in i + 1..len {
            if nums[i] + nums[j] == target {
                return vec![i as u32, j as u32];
            }
        }
    }
    return vec![];
}

fn main() {
    let testcase0 = vec![2, 7, 11, 15];
    let testcase1 = vec![0, 4, 3, 0];
    let testcase2 = vec![-3, 4, 3, 90];

    println!("{:?}", two_sum(testcase0, 9));
    println!("{:?}", two_sum(testcase1, 0));
    println!("{:?}", two_sum(testcase2, 0));
}
<|endoftext|>


<commit_before><commit_msg>Add hitbox<commit_after>use specs::{Component, VecStorage};
use specs_derive::*;

#[derive(Component, Debug, Default)]
#[storage(VecStorage)]
pub struct HitBox {
    pub w: u32,
    pub h: u32,
}
<|endoftext|>


<commit_before><commit_msg>:green_heart: Add test for fetch_unscheduled_tasks<commit_after><|endoftext|>


<commit_before><commit_msg>util: Add iterator join method<commit_after><|endoftext|>