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

struct Foo<T: ?Sized> {
    a: u16,
    b: T
}

trait Bar {
    fn get(&self) -> usize;
}

impl Bar for usize {
    fn get(&self) -> usize { *self }
}

struct Baz<T: ?Sized> {
    a: T
}

#[repr(packed)]
struct Packed<T: ?Sized> {
    a: u8,
    b: T
}

struct HasDrop<T: ?Sized> {
    ptr: Box<usize>,
    data: T
}

fn main() {
    // Test that zero-offset works properly
    let b : Baz<usize> = Baz { a: 7 };
    assert_eq!(b.a.get(), 7);
    let b : &Baz<Bar> = &b;
    assert_eq!(b.a.get(), 7);

    // Test that the field is aligned properly
    let f : Foo<usize> = Foo { a: 0, b: 11 };
    assert_eq!(f.b.get(), 11);
    let ptr1 : *const u8 = &f.b as *const _ as *const u8;

    let f : &Foo<Bar> = &f;
    let ptr2 : *const u8 = &f.b as *const _ as *const u8;
    assert_eq!(f.b.get(), 11);

    // The pointers should be the same
    assert_eq!(ptr1, ptr2);

    // Test that packed structs are handled correctly
    let p : Packed<usize> = Packed { a: 0, b: 13 };
    assert_eq!(p.b.get(), 13);
    let p : &Packed<Bar> = &p;
    assert_eq!(p.b.get(), 13);

    // Test that nested DSTs work properly
    let f : Foo<Foo<usize>> = Foo { a: 0, b: Foo { a: 1, b: 17 }};
    assert_eq!(f.b.b.get(), 17);
    let f : &Foo<Foo<Bar>> = &f;
    assert_eq!(f.b.b.get(), 17);

    // Test that get the pointer via destructuring works

    let f : Foo<usize> = Foo { a: 0, b: 11 };
    let f : &Foo<Bar> = &f;
    let &Foo { a: _, b: ref bar } = f;
    assert_eq!(bar.get(), 11);

    // Make sure that drop flags don't screw things up

    let d : HasDrop<Baz<[i32; 4]>> = HasDrop {
        ptr: Box::new(0),
        data: Baz { a: [1,2,3,4] }
    };
    assert_eq!([1,2,3,4], d.data.a);

    let d : &HasDrop<Baz<[i32]>> = &d;
    assert_eq!(&[1,2,3,4], &d.data.a);
}
<commit_msg>remove wrong packed struct test<commit_after>// Copyright 2015 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.

struct Foo<T: ?Sized> {
    a: u16,
    b: T
}

trait Bar {
    fn get(&self) -> usize;
}

impl Bar for usize {
    fn get(&self) -> usize { *self }
}

struct Baz<T: ?Sized> {
    a: T
}

#[repr(packed)]
struct Packed<T: ?Sized> {
    a: u8,
    b: T
}

struct HasDrop<T: ?Sized> {
    ptr: Box<usize>,
    data: T
}

fn main() {
    // Test that zero-offset works properly
    let b : Baz<usize> = Baz { a: 7 };
    assert_eq!(b.a.get(), 7);
    let b : &Baz<Bar> = &b;
    assert_eq!(b.a.get(), 7);

    // Test that the field is aligned properly
    let f : Foo<usize> = Foo { a: 0, b: 11 };
    assert_eq!(f.b.get(), 11);
    let ptr1 : *const u8 = &f.b as *const _ as *const u8;

    let f : &Foo<Bar> = &f;
    let ptr2 : *const u8 = &f.b as *const _ as *const u8;
    assert_eq!(f.b.get(), 11);

    // The pointers should be the same
    assert_eq!(ptr1, ptr2);

    // Test that nested DSTs work properly
    let f : Foo<Foo<usize>> = Foo { a: 0, b: Foo { a: 1, b: 17 }};
    assert_eq!(f.b.b.get(), 17);
    let f : &Foo<Foo<Bar>> = &f;
    assert_eq!(f.b.b.get(), 17);

    // Test that get the pointer via destructuring works

    let f : Foo<usize> = Foo { a: 0, b: 11 };
    let f : &Foo<Bar> = &f;
    let &Foo { a: _, b: ref bar } = f;
    assert_eq!(bar.get(), 11);

    // Make sure that drop flags don't screw things up

    let d : HasDrop<Baz<[i32; 4]>> = HasDrop {
        ptr: Box::new(0),
        data: Baz { a: [1,2,3,4] }
    };
    assert_eq!([1,2,3,4], d.data.a);

    let d : &HasDrop<Baz<[i32]>> = &d;
    assert_eq!(&[1,2,3,4], &d.data.a);
}
<|endoftext|>


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

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

// Case 1: The function body is not exported to metadata. If the body changes,
//         the hash of the HirBody node should change, but not the hash of
//         either the Hir or the Metadata node.

#[cfg(cfail1)]
pub fn body_not_exported_to_metadata() -> u32 {
    1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn body_not_exported_to_metadata() -> u32 {
    2
}

// Case 2: The function body *is* exported to metadata because the function is
//         marked as #[inline]. Only the hash of the Hir depnode should be
//         unaffected by a change to the body.

#[cfg(cfail1)]
#[inline]
pub fn body_exported_to_metadata_because_of_inline() -> u32 {
    1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[inline]
pub fn body_exported_to_metadata_because_of_inline() -> u32 {
    2
}

// Case 2: The function body *is* exported to metadata because the function is
//         generic. Only the hash of the Hir depnode should be
//         unaffected by a change to the body.

#[cfg(cfail1)]
#[inline]
pub fn body_exported_to_metadata_because_of_generic() -> u32 {
    1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[inline]
pub fn body_exported_to_metadata_because_of_generic() -> u32 {
    2
}

<commit_msg>Updated exported incremental compilation hash tests<commit_after>// Copyright 2016 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.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

// Case 1: The function body is not exported to metadata. If the body changes,
//         the hash of the HirBody node should change, but not the hash of
//         either the Hir or the Metadata node.

#[cfg(cfail1)]
pub fn body_not_exported_to_metadata() -> u32 {
    1
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn body_not_exported_to_metadata() -> u32 {
    2
}

// Case 2: The function body *is* exported to metadata because the function is
//         marked as #[inline]. Only the hash of the Hir depnode should be
//         unaffected by a change to the body.

#[cfg(cfail1)]
#[inline]
pub fn body_exported_to_metadata_because_of_inline() -> u32 {
    1
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[inline]
pub fn body_exported_to_metadata_because_of_inline() -> u32 {
    2
}

// Case 2: The function body *is* exported to metadata because the function is
//         generic. Only the hash of the Hir depnode should be
//         unaffected by a change to the body.

#[cfg(cfail1)]
#[inline]
pub fn body_exported_to_metadata_because_of_generic() -> u32 {
    1
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[inline]
pub fn body_exported_to_metadata_because_of_generic() -> u32 {
    2
}

<|endoftext|>


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

// compile-flags: --test
extern crate test;

#[bench]
fn bench_explicit_return_type(_: &mut ::test::Bencher) -> () {}

#[test]
fn test_explicit_return_type() -> () {}

<commit_msg>don't run pretty-rpass for tests using #![main]<commit_after>// Copyright 2015 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.

// compile-flags: --test
// no-pretty-expanded
extern crate test;

#[bench]
fn bench_explicit_return_type(_: &mut ::test::Bencher) -> () {}

#[test]
fn test_explicit_return_type() -> () {}

<|endoftext|>


<commit_before><commit_msg>Somehow, someway, fix the ls issue with ralloc<commit_after><|endoftext|>


<commit_before>use std::rc::{Rc};
use std::cell::{RefCell};

pub struct Broker<T: Subscriber> {
    subscriptions: Subscriptions<T>,
}

impl<T: Subscriber> Broker<T> {
    pub fn new() -> Self {
        Broker{ subscriptions: Subscriptions::<T>::new()}
    }

    pub fn publish(&mut self, topic: &str, payload: &[u8]) {
        self.subscriptions.publish(topic, payload);
    }

    pub fn subscribe(&mut self, subscriber: Rc<RefCell<T>>, topics: &[&str]) {
        for sub in &self.subscriptions.subscribers {
            let sub1 = sub.clone();
            let sub2 = subscriber.clone();
            if sub1.borrow().id() == sub2.borrow().id() {
                sub2.borrow_mut().append_topics(topics);
                return;
            }
        }
        self.subscriptions.subscribers.push(subscriber);
        let lesub = self.subscriptions.subscribers[self.subscriptions.subscribers.len() - 1].clone();
        lesub.borrow_mut().append_topics(topics);
    }
}

pub struct Subscriptions<T: Subscriber> {
    subscribers: Vec<Rc<RefCell<T>>>,
}

impl<T: Subscriber> Subscriptions<T> {
    fn new() -> Self {
        return Subscriptions { subscribers: vec![], }
    }

    fn publish(&mut self, topic: &str, payload: &[u8]) {
        for s in &mut self.subscribers {
            let sub_clone = s.clone();
            let mut s = sub_clone.borrow_mut();

            for t in s.topics() {
                if t == topic {
                    s.new_message(payload);
                }
            }
        }
    }
}

pub trait Subscriber {
    fn new_message(&mut self, bytes: &[u8]);
    fn id(&self) -> i64;
    fn append_topics(&mut self, topics: &[&str]);
    fn topics(&self) -> Vec<String>;
}

#[cfg(test)]
struct TestSubscriber {
    msgs: Vec<Vec<u8>>,
    id: i64,
    topics: Vec<String>,
}
#[cfg(test)]
impl TestSubscriber {
    fn new(id: i64) -> Self {
        return TestSubscriber{msgs: vec![], id: id, topics: vec![]}
    }
}

#[cfg(test)]
impl Subscriber for TestSubscriber {

    fn new_message(&mut self, bytes: &[u8]) {
        self.msgs.push(bytes.to_vec());
    }

    fn id(&self) -> i64 {
        return self.id;
    }

    fn append_topics(&mut self, topics: &[&str]) {
        let mut new_topics = topics.to_vec().into_iter().map(|t| t.to_string()).collect();
        self.topics.append(&mut new_topics);
        println!("after append, len is {}", self.topics.len());
    }

    fn topics(&self) -> Vec<String> {
        println!("self topics len: {}", self.topics.len());
        self.topics.clone()
    }
}

#[test]
fn test_subscribe() {
    let mut broker = Broker::<TestSubscriber>::new();
    let sub_ref = Rc::new(RefCell::new(TestSubscriber::new(42)));
    let subscriber = sub_ref.clone();
    broker.publish("topics/foo", &[0, 1, 2]);
    assert_eq!(subscriber.borrow().msgs.len(), 0);

    broker.subscribe(subscriber.clone(), &["topics/foo"]);
    broker.publish("topics/foo", &[0, 1, 9]);
    broker.publish("topics/bar", &[2, 4, 6]);
    assert_eq!(subscriber.borrow().msgs.len(), 1);
    assert_eq!(subscriber.borrow().msgs[0], &[0, 1, 9]);

    broker.subscribe(subscriber.clone(), &["topics/bar"]);
    broker.publish("topics/foo", &[1, 3, 5, 7]);
    broker.publish("topics/bar", &[2, 4]);
    assert_eq!(subscriber.borrow().msgs.len(), 3);
    assert_eq!(subscriber.borrow().msgs[0], &[0, 1, 9]);
    assert_eq!(subscriber.borrow().msgs[1], &[1, 3, 5, 7]);
    assert_eq!(subscriber.borrow().msgs[2], &[2, 4]);
}
<commit_msg>Using pointer to self for identity<commit_after>use std::rc::{Rc};
use std::cell::{RefCell};
use std::mem::{transmute};

pub struct Broker<T: Subscriber> {
    subscriptions: Subscriptions<T>,
}

impl<T: Subscriber> Broker<T> {
    pub fn new() -> Self {
        Broker{ subscriptions: Subscriptions::<T>::new()}
    }

    pub fn publish(&mut self, topic: &str, payload: &[u8]) {
        self.subscriptions.publish(topic, payload);
    }

    pub fn subscribe(&mut self, subscriber: Rc<RefCell<T>>, topics: &[&str]) {
        for sub in &self.subscriptions.subscribers {
            let sub1 = sub.clone();
            let sub2 = subscriber.clone();
            if sub1.borrow().id() == sub2.borrow().id() {
                sub2.borrow_mut().append_topics(topics);
                return;
            }
        }
        self.subscriptions.subscribers.push(subscriber);
        let lesub = self.subscriptions.subscribers[self.subscriptions.subscribers.len() - 1].clone();
        lesub.borrow_mut().append_topics(topics);
    }
}

pub struct Subscriptions<T: Subscriber> {
    subscribers: Vec<Rc<RefCell<T>>>,
}

impl<T: Subscriber> Subscriptions<T> {
    fn new() -> Self {
        return Subscriptions { subscribers: vec![], }
    }

    fn publish(&mut self, topic: &str, payload: &[u8]) {
        for s in &mut self.subscribers {
            let sub_clone = s.clone();
            let mut s = sub_clone.borrow_mut();

            for t in s.topics() {
                if t == topic {
                    s.new_message(payload);
                }
            }
        }
    }
}

pub trait Subscriber {
    fn new_message(&mut self, bytes: &[u8]);
    fn id(&self) -> i64;
    fn append_topics(&mut self, topics: &[&str]);
    fn topics(&self) -> Vec<String>;
}

#[cfg(test)]
struct TestSubscriber {
    msgs: Vec<Vec<u8>>,
    topics: Vec<String>,
}
#[cfg(test)]
impl TestSubscriber {
    fn new() -> Self {
        return TestSubscriber{msgs: vec![], topics: vec![]}
    }
}

#[cfg(test)]
impl Subscriber for TestSubscriber {

    fn new_message(&mut self, bytes: &[u8]) {
        self.msgs.push(bytes.to_vec());
    }

    fn id(&self) -> i64 {
        self as *const TestSubscriber as i64
    }

    fn append_topics(&mut self, topics: &[&str]) {
        let mut new_topics = topics.to_vec().into_iter().map(|t| t.to_string()).collect();
        self.topics.append(&mut new_topics);
        println!("after append, len is {}", self.topics.len());
    }

    fn topics(&self) -> Vec<String> {
        println!("self topics len: {}", self.topics.len());
        self.topics.clone()
    }
}

#[test]
fn test_subscribe() {
    let mut broker = Broker::<TestSubscriber>::new();
    let sub_ref = Rc::new(RefCell::new(TestSubscriber::new()));
    let subscriber = sub_ref.clone();
    broker.publish("topics/foo", &[0, 1, 2]);
    assert_eq!(subscriber.borrow().msgs.len(), 0);

    broker.subscribe(subscriber.clone(), &["topics/foo"]);
    broker.publish("topics/foo", &[0, 1, 9]);
    broker.publish("topics/bar", &[2, 4, 6]);
    assert_eq!(subscriber.borrow().msgs.len(), 1);
    assert_eq!(subscriber.borrow().msgs[0], &[0, 1, 9]);

    broker.subscribe(subscriber.clone(), &["topics/bar"]);
    broker.publish("topics/foo", &[1, 3, 5, 7]);
    broker.publish("topics/bar", &[2, 4]);
    assert_eq!(subscriber.borrow().msgs.len(), 3);
    assert_eq!(subscriber.borrow().msgs[0], &[0, 1, 9]);
    assert_eq!(subscriber.borrow().msgs[1], &[1, 3, 5, 7]);
    assert_eq!(subscriber.borrow().msgs[2], &[2, 4]);
}
<|endoftext|>


<commit_before><commit_msg>Allow binops which start with identifiers<commit_after><|endoftext|>


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

// Test associated type references in structure fields.

trait Test {
    type V;

    fn test(&self, value: &Self::V) -> bool;
}

///////////////////////////////////////////////////////////////////////////

struct TesterPair<T:Test> {
    tester: T,
    value: T::V,
}

impl<T:Test> TesterPair<T> {
    fn new(tester: T, value: T::V) -> TesterPair<T> {
        TesterPair { tester: tester, value: value }
    }

    fn test(&self) -> bool {
        self.tester.test(&self.value)
    }
}

///////////////////////////////////////////////////////////////////////////

struct EqU32(u32);
impl Test for EqU32 {
    type V = u32;

    fn test(&self, value: &u32) -> bool {
        self.0 == *value
    }
}

struct EqI32(i32);
impl Test for EqI32 {
    type V = i32;

    fn test(&self, value: &i32) -> bool {
        self.0 == *value
    }
}

fn main() {
    let tester = TesterPair::new(EqU32(22), 23);
    tester.test();

    let tester = TesterPair::new(EqI32(22), 23);
    tester.test();
}
<|endoftext|>


<commit_before><commit_msg>iOS: os::last_os_error() fallout<commit_after><|endoftext|>


<commit_before><commit_msg>Added method to delete posts<commit_after>extern crate diesel_demo;
extern crate diesel;

use self::diesel::prelude::*;
use self::diesel_demo::*;
use std::env::args;

fn main () {
    use diesel_demo::schema::posts::dsl::*;

    let target = args().nth(1).expect("Expected a taget to match against");
    let pattern = format!("%{}%", target);

    let connection = establish_connection();
    let num_deleted = diesel::delete(posts.filter(title.like(pattern)))
        .execute(&connection)
        .expect("Error deleting posts");

    println!("Deleted {} posts", num_deleted);
}
<|endoftext|>


<commit_before><commit_msg>first commit<commit_after>//@ympons
trait Runnable {
    fn run(&mut self);
}

struct Engine {
    source: Vec<char>,
    ip: usize,
    tape: Vec<u8>,
    p: usize,
}

fn readchar() -> Option<char> {
    use std::io::Read;

    let input: Option<char> = std::io::stdin()
        .bytes()
        .next()
        .and_then(|result| result.ok())
        .map(|byte| byte as char);
    return input;
}

impl Runnable for Engine {
    fn run(&mut self) {
        while self.source.get(self.ip)!=None {
            let op = self.source[self.ip];
            self.ip += 1;
            match op {
                '>' => {
                    self.p += 1;
                },
                '<' => {
                    self.p -= 1;
                },
                '+' => {
                    self.tape[self.p] += 1;
                },
                '-' => {
                    self.tape[self.p] -= 1;
                },
                '.' => {
                    let item = self.tape[self.p] as char;
                    print!("{}", item);
                },
                ',' => {
                    match readchar() {
                        Some(item) => {
                            self.tape[self.p] = if item == '\x04' { 0 } else { item as u8 };
                        },
                        _ => {},
                    };
                },
                '[' => {
                    if self.tape[self.p] == 0 {
                        let mut nesting = 1;
                        while nesting != 0 {
                            let item = self.source[self.ip];
                            self.ip += 1;
                            if item == '[' { nesting += 1; }
                            if item == ']' { nesting -= 1; }
                        }
                    }
                },
                ']' => {
                    self.ip -= 1;
                    let mut nesting = 1;
                    while nesting != 0 {
                        self.ip -= 1;
                        let item = self.source[self.ip];
                        if item == ']' { nesting += 1; }
                        if item == '[' { nesting -= 1; }
                    }
                },
                _ => { break;}
            };
        }
    }
}

fn main() {
  let code = ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.>>>++++++++[<++++>-]<.>>>++++++++++[<+++++++++>-]<---.<<<<.+++.------.--------.>>+.";
  let mut e = Engine{source: code.chars().collect(), ip: 0, p: 0, tape: vec![0; 3000]};
  e.run();
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for Clone for [[T; 256]; 4] where T: Copy and not Clone<commit_after>// Copyright 2015 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.

// test for issue #30244

#[derive(Copy, Clone)]
struct Array {
    arr: [[u8; 256]; 4]
}

pub fn main() {}
<|endoftext|>


<commit_before><commit_msg>add iter_any test<commit_after>pub fn main() {
    let f = |x: &u8| { 10u8 == *x };
    f(&1u8);

    let g = |(), x: &u8| { 10u8 == *x };
    g((), &1u8);

    let h = |(), (), x: &u8| { 10u8 == *x };
    h((), (), &1u8);

    [1, 2, 3u8].into_iter().any(|elt| 10 == *elt);
}
<|endoftext|>


<commit_before><commit_msg>modified serve reachable from other machines<commit_after><|endoftext|>


<commit_before><commit_msg>take free bits for hidden permissions<commit_after><|endoftext|>


<commit_before><commit_msg>Add a example demonstrating how to manually create a context<commit_after>/*!

This example demonstrates how to manually create a glium context with any backend you want, most
notably without glutin.

There are three concepts in play:

 - The `Backend` trait, which defines how glium interfaces with the OpenGL context
   provider (glutin, SDL, glfw, etc.).

 - The `Context` struct, which is the main object of glium. The context also provides
   OpenGL-related functions like `get_free_video_memory` or `get_supported_glsl_version`.

 - The `Facade` trait, which is the trait required to be implemented on objects that you pass
   to functions like `VertexBuffer::new`. This trait is implemented on `Rc<Context>`, which
   means that you can direct pass the context.

*/

extern crate libc;
extern crate glutin;
extern crate glium;

use glium::Surface;
use std::rc::Rc;

fn main() {
    // building the glutin window
    // note that it's just `build` and not `build_glium`
    let window = glutin::WindowBuilder::new().build().unwrap();
    let window = Rc::new(window);

    // in order to create our context, we will need to provide an object which implements
    // the `Backend` trait
    struct Backend {
        window: Rc<glutin::Window>,
    }

    impl glium::backend::Backend for Backend {
        fn swap_buffers(&self) {
            self.window.swap_buffers();
        }

        // this function is called only after the OpenGL context has been made current
        unsafe fn get_proc_address(&self, symbol: &str) -> *const libc::c_void {
            self.window.get_proc_address(symbol)
        }

        // this function is used to adjust the viewport when the user wants to draw or blit on
        // the whole window
        fn get_framebuffer_dimensions(&self) -> (u32, u32) {
            // we default to a dummy value is the window no longer exists
            self.window.get_inner_size().unwrap_or((128, 128))
        }

        fn is_current(&self) -> bool {
            // if you are using a library that doesn't provide an equivalent to `is_current`, you
            // can just put `unimplemented!` and pass `false` when you create
            // the `Context` (see below)
            self.window.is_current()
        }

        unsafe fn make_current(&self) {
            self.window.make_current()
        }
    }

    // now building the context
    let context = unsafe {
        // The first parameter is our backend.
        //
        // The second parameter tells glium whether or not it should regularly call `is_current`
        // on the backend to make sure that the OpenGL context is still the current one.
        //
        // It is recommended to pass `true`, but you can pass `false` if you are sure that no
        // other OpenGL context will be made current in this thread.
        glium::backend::Context::new(Backend { window: window.clone() }, true)
    }.unwrap();

    // drawing a frame to prove that it works
    // note that constructing a `Frame` object manually is a bit hacky and may be changed
    // in the future
    let mut target = glium::Frame::new(context.clone(), context.get_framebuffer_dimensions());
    target.clear_color(0.0, 1.0, 0.0, 1.0);
    target.finish();

    // the window is still available
    for event in window.wait_events() {
        match event {
            glutin::Event::Closed => return,
            _ => ()
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>add additional checkt to detect errors<commit_after>use std::collections::BTreeMap;
use std::convert::TryInto;
use std::slice;

use net::NetworkInterface;
use smoltcp::iface::{EthernetInterfaceBuilder, NeighborCache, Routes};
#[cfg(feature = "trace")]
use smoltcp::phy::EthernetTracer;
use smoltcp::phy::{self, Device, DeviceCapabilities};
use smoltcp::socket::SocketSet;
use smoltcp::time::Instant;
use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr, Ipv4Address};

extern "Rust" {
	fn sys_get_mac_address() -> Result<[u8; 6], ()>;
	fn sys_get_mtu() -> Result<u16, ()>;
	fn sys_get_tx_buffer(len: usize) -> Result<(*mut u8, usize), ()>;
	fn sys_send_tx_buffer(handle: usize, len: usize) -> Result<(), ()>;
	fn sys_receive_rx_buffer() -> Result<&'static mut [u8], ()>;
	fn sys_rx_buffer_consumed() -> Result<(), ()>;
	fn sys_free_tx_buffer(handle: usize);
}

/// Data type to determine the mac address
#[derive(Debug, Copy, Clone)]
#[repr(C)]
pub struct HermitNet {
	pub mtu: u16,
}

impl HermitNet {
	pub fn new(mtu: u16) -> Self {
		Self { mtu }
	}
}

impl NetworkInterface<HermitNet> {
	pub fn new() -> Option<Self> {
		let mtu = match unsafe { sys_get_mtu() } {
			Ok(mtu) => mtu,
			Err(_) => {
				return None;
			}
		};
		let device = HermitNet::new(mtu);
		#[cfg(feature = "trace")]
		let device = EthernetTracer::new(device, |_timestamp, printer| {
			trace!("{}", printer);
		});

		let mac: [u8; 6] = match unsafe { sys_get_mac_address() } {
			Ok(mac) => mac,
			Err(_) => {
				return None;
			}
		};
		let myip: [u8; 4] = [10, 0, 5, 3];
		let mygw: [u8; 4] = [10, 0, 5, 1];
		let mymask: [u8; 4] = [255, 255, 255, 0];

		// calculate the netmask length
		// => count the number of contiguous 1 bits,
		// starting at the most significant bit in the first octet
		let mut prefix_len = (!mymask[0]).trailing_zeros();
		if prefix_len == 8 {
			prefix_len += (!mymask[1]).trailing_zeros();
		}
		if prefix_len == 16 {
			prefix_len += (!mymask[2]).trailing_zeros();
		}
		if prefix_len == 24 {
			prefix_len += (!mymask[3]).trailing_zeros();
		}

		let neighbor_cache = NeighborCache::new(BTreeMap::new());
		let ethernet_addr = EthernetAddress([mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]]);
		let ip_addrs = [IpCidr::new(
			IpAddress::v4(myip[0], myip[1], myip[2], myip[3]),
			prefix_len.try_into().unwrap(),
		)];
		let default_v4_gw = Ipv4Address::new(mygw[0], mygw[1], mygw[2], mygw[3]);
		let mut routes = Routes::new(BTreeMap::new());
		routes.add_default_ipv4_route(default_v4_gw).unwrap();

		info!("MAC address {}", ethernet_addr);
		info!("Configure network interface with address {}", ip_addrs[0]);
		info!("Configure gatway with address {}", default_v4_gw);
		info!("MTU: {} bytes", mtu);

		let iface = EthernetInterfaceBuilder::new(device)
			.ethernet_addr(ethernet_addr)
			.neighbor_cache(neighbor_cache)
			.ip_addrs(ip_addrs)
			.routes(routes)
			.finalize();

		Some(Self {
			iface: iface,
			sockets: SocketSet::new(vec![]),
			channels: BTreeMap::new(),
			timestamp: Instant::now(),
		})
	}
}

impl<'a> Device<'a> for HermitNet {
	type RxToken = RxToken;
	type TxToken = TxToken;

	fn capabilities(&self) -> DeviceCapabilities {
		let mut cap = DeviceCapabilities::default();
		cap.max_transmission_unit = self.mtu.into();
		cap
	}

	fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> {
		match unsafe { sys_receive_rx_buffer() } {
			Ok(buffer) => Some((RxToken::new(buffer), TxToken::new())),
			_ => None,
		}
	}

	fn transmit(&'a mut self) -> Option<Self::TxToken> {
		trace!("create TxToken to transfer data");
		Some(TxToken::new())
	}
}

#[doc(hidden)]
pub struct RxToken {
	buffer: &'static mut [u8],
}

impl RxToken {
	pub fn new(buffer: &'static mut [u8]) -> Self {
		Self { buffer }
	}
}

impl phy::RxToken for RxToken {
	fn consume<R, F>(mut self, _timestamp: Instant, f: F) -> smoltcp::Result<R>
	where
		F: FnOnce(&mut [u8]) -> smoltcp::Result<R>,
	{
		let result = f(self.buffer);
		if unsafe { sys_rx_buffer_consumed().is_ok() } {
			result
		} else {
			Err(smoltcp::Error::Exhausted)
		}
	}
}

#[doc(hidden)]
pub struct TxToken;

impl TxToken {
	pub fn new() -> Self {
		Self {}
	}
}

impl phy::TxToken for TxToken {
	fn consume<R, F>(self, _timestamp: Instant, len: usize, f: F) -> smoltcp::Result<R>
	where
		F: FnOnce(&mut [u8]) -> smoltcp::Result<R>,
	{
		let (tx_buffer, handle) =
			unsafe { sys_get_tx_buffer(len).map_err(|_| smoltcp::Error::Exhausted)? };
		let tx_slice: &'static mut [u8] = unsafe { slice::from_raw_parts_mut(tx_buffer, len) };
		match f(tx_slice) {
			Ok(result) => {
				if unsafe { sys_send_tx_buffer(handle, len).is_ok() } {
					Ok(result)
				} else {
					Err(smoltcp::Error::Exhausted)
				}
			}
			Err(e) => {
				unsafe { sys_free_tx_buffer(handle) };
				Err(e)
			}
		}
	}
}
<|endoftext|>


<commit_before><commit_msg>Add remove subcommand<commit_after><|endoftext|>


<commit_before><commit_msg>Config: eliminate sucky workaround by cloning toml map<commit_after><|endoftext|>


<commit_before><commit_msg>passable actors (ugh)<commit_after><|endoftext|>


<commit_before><commit_msg>define file name<commit_after><|endoftext|>


<commit_before><commit_msg>Use level triggering for receive loop/socket<commit_after><|endoftext|>


<commit_before><commit_msg>Minor refactoring<commit_after><|endoftext|>


<commit_before>use std::io::Error as IoError;
use hyper::Error as HyError;
use serde_json::Error as SjError;
use websocket::result::WebSocketError as WsError;

/// Discord API `Result` alias type.
pub type Result<T> = ::std::result::Result<T, Error>;

/// Discord API error type.
#[derive(Debug)]
pub enum Error {
	Hyper(HyError),
	Json(SjError),
	WebSocket(WsError),
	Io(IoError),
	Decode(&'static str, ::serde_json::Value),
	Status(::hyper::status::StatusCode),
	Other(&'static str),
}

impl From<IoError> for Error {
	fn from(err: IoError) -> Error {
		Error::Io(err)
	}
}

impl From<HyError> for Error {
	fn from(err: HyError) -> Error {
		Error::Hyper(err)
	}
}

impl From<SjError> for Error {
	fn from(err: SjError) -> Error {
		Error::Json(err)
	}
}

impl From<WsError> for Error {
	fn from(err: WsError) -> Error {
		Error::WebSocket(err)
	}
}
<commit_msg>Implement Error trait for Error<commit_after>use std::io::Error as IoError;
use std::error::Error as StdError;
use hyper::Error as HyError;
use serde_json::Error as SjError;
use websocket::result::WebSocketError as WsError;

/// Discord API `Result` alias type.
pub type Result<T> = ::std::result::Result<T, Error>;

/// Discord API error type.
#[derive(Debug)]
pub enum Error {
	Hyper(HyError),
	Json(SjError),
	WebSocket(WsError),
	Io(IoError),
	Decode(&'static str, ::serde_json::Value),
	Status(::hyper::status::StatusCode),
	Other(&'static str),
}

impl From<IoError> for Error {
	fn from(err: IoError) -> Error {
		Error::Io(err)
	}
}

impl From<HyError> for Error {
	fn from(err: HyError) -> Error {
		Error::Hyper(err)
	}
}

impl From<SjError> for Error {
	fn from(err: SjError) -> Error {
		Error::Json(err)
	}
}

impl From<WsError> for Error {
	fn from(err: WsError) -> Error {
		Error::WebSocket(err)
	}
}

impl ::std::fmt::Display for Error {
	fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
		write!(f, "Discord error ({})", self.description())
	}
}

impl StdError for Error {
	fn description(&self) -> &str {
		match *self {
			Error::Hyper(ref inner) => inner.description(),
			Error::Json(ref inner) => inner.description(),
			Error::WebSocket(ref inner) => inner.description(),
			Error::Io(ref inner) => inner.description(),
			Error::Decode(..) => "json decode error",
			Error::Status(_) => "erroneous HTTP status",
			Error::Other(msg) => msg,
		}
	}

	fn cause(&self) -> Option<&StdError> {
		match *self {
			Error::Hyper(ref inner) => Some(inner),
			Error::Json(ref inner) => Some(inner),
			Error::WebSocket(ref inner) => Some(inner),
			Error::Io(ref inner) => Some(inner),
			_ => None,
		}
	}
}
<|endoftext|>


<commit_before>#![crate_id(name="seq", vers="1.0.0", author="Daniel MacDougall")]

#![feature(macro_rules)]

// TODO: Make -w flag work with decimals
// TODO: Support -f flag

extern crate getopts;
extern crate libc;

use std::os;

#[path = "../common/util.rs"]
mod util;

static NAME: &'static str = "seq";

#[deriving(Clone)]
struct SeqOptions {
    separator: String,
    terminator: Option<String>,
    widths: bool
}

fn parse_float(s: &str) -> Result<f64, String>{
    match from_str(s) {
        Some(n) => Ok(n),
        None => Err(format!("seq: invalid floating point argument: {:s}", s))
    }
}

fn escape_sequences(s: &str) -> String {
    s.replace("\\n", "\n").
        replace("\\t", "\t")
}

fn parse_options(args: Vec<String>, options: &mut SeqOptions) -> Result<Vec<String>, int> {
    let mut seq_args = vec!();
    let program = args.get(0).clone();
    let mut iter = args.move_iter().skip(1);
    loop {
        match iter.next() {
            Some(arg) => match arg.as_slice() {
                "--help" | "-h" => {
                    print_help(&program);
                    return Err(0);
                }
                "--version" | "-V" => {
                    print_version();
                    return Err(0);
                }
                "-s" | "--separator" => match iter.next() {
                    Some(sep) => options.separator = sep,
                    None => {
                        show_error!("expected a separator after {}", arg);
                        return Err(1);
                    }
                },
                "-t" | "--terminator" => match iter.next() {
                    Some(term) => options.terminator = Some(term),
                    None => {
                        show_error!("expected a terminator after '{}'", arg);
                        return Err(1);
                    }
                },
                "-w" | "--widths" => options.widths = true,
                "--" => {
                    seq_args.push_all_move(iter.collect());
                    break;
                },
                _ => {
                    if arg.len() > 1 && arg.as_slice().char_at(0) == '-' {
                        let argptr: *String = &arg;  // escape from the borrow checker
                        let mut chiter = unsafe { (*argptr).as_slice() }.chars().skip(1);
                        let mut ch = ' ';
                        while match chiter.next() { Some(m) => { ch = m; true } None => false } {
                            match ch {
                                'h' => {
                                    print_help(&program);
                                    return Err(0);
                                }
                                'V' => {
                                    print_version();
                                    return Err(0);
                                }
                                's' => match iter.next() {
                                    Some(sep) => {
                                        options.separator = sep;
                                        let next = chiter.next();
                                        if next.is_some() {
                                            show_error!("unexpected character ('{}')", next.unwrap());
                                            return Err(1);
                                        }
                                    }
                                    None => {
                                        show_error!("expected a separator after {}", arg);
                                        return Err(1);
                                    }
                                },
                                't' => match iter.next() {
                                    Some(term) => {
                                        options.terminator = Some(term);
                                        let next = chiter.next();
                                        if next.is_some() {
                                            show_error!("unexpected character ('{}')", next.unwrap());
                                            return Err(1);
                                        }
                                    }
                                    None => {
                                        show_error!("expected a terminator after {}", arg);
                                        return Err(1);
                                    }
                                },
                                'w' => options.widths = true,
                                _ => { seq_args.push(arg); break }
                            }
                        }
                    } else {
                        seq_args.push(arg);
                    }
                }
            },
            None => break
        }
    }
    Ok(seq_args)
}

fn print_help(program: &String) {
    let opts = [
        getopts::optopt("s", "separator", "Separator character (defaults to \\n)", ""),
        getopts::optopt("t", "terminator", "Terminator character (defaults to separator)", ""),
        getopts::optflag("w", "widths", "Equalize widths of all numbers by padding with zeros"),
        getopts::optflag("h", "help", "print this help text and exit"),
        getopts::optflag("V", "version", "print version and exit"),
    ];
    println!("seq 1.0.0\n");
    println!("Usage:\n  {} [-w] [-s string] [-t string] [first [step]] last\n", *program);
    println!("{:s}", getopts::usage("Print sequences of numbers", opts));
}

fn print_version() {
    println!("seq 1.0.0\n");
}

#[allow(dead_code)]
fn main() { os::set_exit_status(uumain(os::args())); }

pub fn uumain(args: Vec<String>) -> int {
    let program = args.get(0).clone();
    let mut options = SeqOptions {
        separator: "\n".to_string(),
        terminator: None,
        widths: false
    };
    let free = match parse_options(args, &mut options) {
        Ok(m) => m,
        Err(f) => return f
    };
    if free.len() < 1 || free.len() > 3 {
        crash!(1, "too {} operands.\nTry '{} --help' for more information.",
               if free.len() < 1 { "few" } else { "many" }, program);
    }
    let first = if free.len() > 1 {
        match parse_float(free.get(0).as_slice()) {
            Ok(n) => n,
            Err(s) => { show_error!("{:s}", s); return 1; }
        }
    } else {
        1.0
    };
    let step = if free.len() > 2 {
        match parse_float(free.get(1).as_slice()) {
            Ok(n) => n,
            Err(s) => { show_error!("{:s}", s); return 1; }
        }
    } else {
        1.0
    };
    let last = match parse_float(free.get(free.len()-1).as_slice()) {
        Ok(n) => n,
        Err(s) => { show_error!("{:s}", s); return 1; }
    };
    let separator = escape_sequences(options.separator.as_slice());
    let terminator = match options.terminator {
        Some(term) => escape_sequences(term.as_slice()),
        None => separator.clone()
    };
    print_seq(first, step, last, separator, terminator, options.widths);

    0
}

#[inline(always)]
fn done_printing(next: f64, step: f64, last: f64) -> bool {
    if step > 0f64 {
        next > last
    } else {
        next < last
    }
}

fn print_seq(first: f64, step: f64, last: f64, separator: String, terminator: String, pad: bool) {
    let mut i = first;
    let maxlen = first.max(last).to_str().len();
    while !done_printing(i, step, last) {
        let ilen = i.to_str().len();
        if pad && ilen < maxlen {
            for _ in range(0, maxlen - ilen) {
                print!("0");
            }
        }
        print!("{:f}", i);
        i += step;
        if !done_printing(i, step, last) {
            print!("{:s}", separator);
        }
    }
    if i != first {
        print!("{:s}", terminator);
    }
}
<commit_msg>seq: pass all Busybox tests<commit_after>#![crate_id(name="seq", vers="1.0.0", author="Daniel MacDougall")]

#![feature(macro_rules)]

// TODO: Make -w flag work with decimals
// TODO: Support -f flag

extern crate getopts;
extern crate libc;

use std::cmp;
use std::os;

#[path = "../common/util.rs"]
mod util;

static NAME: &'static str = "seq";

#[deriving(Clone)]
struct SeqOptions {
    separator: String,
    terminator: Option<String>,
    widths: bool
}

fn parse_float(s: &str) -> Result<f64, String>{
    match from_str(s) {
        Some(n) => Ok(n),
        None => Err(format!("seq: invalid floating point argument: {:s}", s))
    }
}

fn escape_sequences(s: &str) -> String {
    s.replace("\\n", "\n").
        replace("\\t", "\t")
}

fn parse_options(args: Vec<String>, options: &mut SeqOptions) -> Result<Vec<String>, int> {
    let mut seq_args = vec!();
    let program = args.get(0).clone();
    let mut iter = args.move_iter().skip(1);
    loop {
        match iter.next() {
            Some(arg) => match arg.as_slice() {
                "--help" | "-h" => {
                    print_help(&program);
                    return Err(0);
                }
                "--version" | "-V" => {
                    print_version();
                    return Err(0);
                }
                "-s" | "--separator" => match iter.next() {
                    Some(sep) => options.separator = sep,
                    None => {
                        show_error!("expected a separator after {}", arg);
                        return Err(1);
                    }
                },
                "-t" | "--terminator" => match iter.next() {
                    Some(term) => options.terminator = Some(term),
                    None => {
                        show_error!("expected a terminator after '{}'", arg);
                        return Err(1);
                    }
                },
                "-w" | "--widths" => options.widths = true,
                "--" => {
                    seq_args.push_all_move(iter.collect());
                    break;
                },
                _ => {
                    if arg.len() > 1 && arg.as_slice().char_at(0) == '-' {
                        let argptr: *String = &arg;  // escape from the borrow checker
                        let mut chiter = unsafe { (*argptr).as_slice() }.chars().skip(1);
                        let mut ch = ' ';
                        while match chiter.next() { Some(m) => { ch = m; true } None => false } {
                            match ch {
                                'h' => {
                                    print_help(&program);
                                    return Err(0);
                                }
                                'V' => {
                                    print_version();
                                    return Err(0);
                                }
                                's' => match iter.next() {
                                    Some(sep) => {
                                        options.separator = sep;
                                        let next = chiter.next();
                                        if next.is_some() {
                                            show_error!("unexpected character ('{}')", next.unwrap());
                                            return Err(1);
                                        }
                                    }
                                    None => {
                                        show_error!("expected a separator after {}", arg);
                                        return Err(1);
                                    }
                                },
                                't' => match iter.next() {
                                    Some(term) => {
                                        options.terminator = Some(term);
                                        let next = chiter.next();
                                        if next.is_some() {
                                            show_error!("unexpected character ('{}')", next.unwrap());
                                            return Err(1);
                                        }
                                    }
                                    None => {
                                        show_error!("expected a terminator after {}", arg);
                                        return Err(1);
                                    }
                                },
                                'w' => options.widths = true,
                                _ => { seq_args.push(arg); break }
                            }
                        }
                    } else {
                        seq_args.push(arg);
                    }
                }
            },
            None => break
        }
    }
    Ok(seq_args)
}

fn print_help(program: &String) {
    let opts = [
        getopts::optopt("s", "separator", "Separator character (defaults to \\n)", ""),
        getopts::optopt("t", "terminator", "Terminator character (defaults to separator)", ""),
        getopts::optflag("w", "widths", "Equalize widths of all numbers by padding with zeros"),
        getopts::optflag("h", "help", "print this help text and exit"),
        getopts::optflag("V", "version", "print version and exit"),
    ];
    println!("seq 1.0.0\n");
    println!("Usage:\n  {} [-w] [-s string] [-t string] [first [step]] last\n", *program);
    println!("{:s}", getopts::usage("Print sequences of numbers", opts));
}

fn print_version() {
    println!("seq 1.0.0\n");
}

#[allow(dead_code)]
fn main() { os::set_exit_status(uumain(os::args())); }

pub fn uumain(args: Vec<String>) -> int {
    let program = args.get(0).clone();
    let mut options = SeqOptions {
        separator: "\n".to_string(),
        terminator: None,
        widths: false
    };
    let free = match parse_options(args, &mut options) {
        Ok(m) => m,
        Err(f) => return f
    };
    if free.len() < 1 || free.len() > 3 {
        crash!(1, "too {} operands.\nTry '{} --help' for more information.",
               if free.len() < 1 { "few" } else { "many" }, program);
    }
    let mut largest_dec = 0;
    let mut padding = 0;
    let first = if free.len() > 1 {
        let slice = free.get(0).as_slice();
        let len = slice.len();
        let dec = slice.find('.').unwrap_or(len);
        largest_dec = len - dec;
        padding = dec;
        match parse_float(slice) {
            Ok(n) => n,
            Err(s) => { show_error!("{:s}", s); return 1; }
        }
    } else {
        1.0
    };
    let step = if free.len() > 2 {
        let slice = free.get(1).as_slice();
        let len = slice.len();
        let dec = slice.find('.').unwrap_or(len);
        largest_dec = cmp::max(largest_dec, len - dec);
        padding = cmp::max(padding, dec);
        match parse_float(free.get(1).as_slice()) {
            Ok(n) => n,
            Err(s) => { show_error!("{:s}", s); return 1; }
        }
    } else {
        1.0
    };
    let last = {
        let slice = free.get(free.len() - 1).as_slice();
        padding = cmp::max(padding, slice.find('.').unwrap_or(slice.len()));
        match parse_float(slice) {
            Ok(n) => n,
            Err(s) => { show_error!("{:s}", s); return 1; }
        }
    };
    let separator = escape_sequences(options.separator.as_slice());
    let terminator = match options.terminator {
        Some(term) => escape_sequences(term.as_slice()),
        None => separator.clone()
    };
    print_seq(first, step, last, largest_dec, separator, terminator, options.widths, padding);

    0
}

#[inline(always)]
fn done_printing(next: f64, step: f64, last: f64) -> bool {
    if step >= 0f64 {
        next > last
    } else {
        next < last
    }
}

fn print_seq(first: f64, step: f64, last: f64, largest_dec: uint, separator: String, terminator: String, pad: bool, padding: uint) {
    let mut i = 0;
    let mut value = first + i as f64 * step;
    while !done_printing(value, step, last) {
        let istr = value.to_str();
        let ilen = istr.len();
        let before_dec = istr.as_slice().find('.').unwrap_or(ilen);
        if pad && before_dec < padding {
            for _ in range(0, padding - before_dec) {
                print!("0");
            }
        }
        print!("{}", istr);
        let mut idec = ilen - before_dec;
        if idec < largest_dec {
            if idec == 0 {
                print!(".");
                idec += 1;
            }
            for _ in range(idec, largest_dec) {
                print!("0")
            }
        }
        i += 1;
        value = first + i as f64 * step;
        if !done_printing(value, step, last) {
            print!("{:s}", separator);
        }
    }
    if (first >= last && step < 0f64) || (first <= last && step > 0f64) {
        print!("{:s}", terminator);
    }
}
<|endoftext|>


<commit_before>
extern crate time;
extern crate gl;
extern crate graphics;
extern crate piston;

use std::io::timer::sleep;
use self::gl::types::GLint;
use self::graphics::{
    Context,
    RelativeTransform2d,
    View,
};
use self::piston::{
    AssetStore,
    GlData,
    event,
    Game,
    GameWindow,
    Gl,
};
use {
    Event,
    EventCenter,
    EventType,
    KeyType,
};

impl KeyType for piston::keyboard::Key {
    fn id(&self) -> uint {
        // add the last enum item in piston::mouse::Button
        self.code() as uint + piston::mouse::Button8 as uint + 1
    }
}

impl KeyType for piston::mouse::Button {
    fn id(&self) -> uint {
        *self as uint
    }
}

impl EventType for piston::event::Event {
    fn is_press_key(&self, key: &KeyType) -> bool {
        match *self {
            piston::event::KeyPressed(k) if k.id() == key.id() => {
                true
            },
            piston::event::MouseButtonPressed(k) if k.id() == key.id() => {
                true
            },
            _ => {
                false
            },
        }
    }
    fn is_release_key(&self, key: &KeyType) -> bool {
        match *self {
            piston::event::KeyReleased(k) if k.id() == key.id() => {
                true
            },
            piston::event::MouseButtonReleased(k) if k.id() == key.id() => {
                true
            },
            _ => {
                false
            }
        }
    }
}

/// ******************************
/// * MOST CODE COPY FROM PISTON *
/// ******************************
///
/// Implemented by game application which want to use rust-event.
pub trait EventGame {
    /// Perform tasks for loading before showing anything.
    fn load(&mut self, _asset_store: &mut AssetStore) {}

    /// Register event before game loop
    fn register_event(&mut self, _event_center: &mut EventCenter<Self>) {}

    /// Sets up viewport.
    ///
    /// A viewport is the region of the window where graphics is rendered.
    #[inline(always)]
    fn viewport<W: GameWindow>(&self, game_window: &W) {
        let (w, h) = game_window.get_size();
        gl::Viewport(0, 0, w as GLint, h as GLint);
    }

    /// Whether the window should be closed.
    ///
    /// When this is `true` the application shuts down.
    /// This can be overridden to emulate a user closing the window.
    /// One can also override this method to prevent window from closing.
    fn should_close<W: GameWindow>(&self, game_window: &W) -> bool {
        game_window.should_close()
    }

    /// Swaps the front buffer with the back buffer.
    ///
    /// When called, This shows the next frame.
    /// The graphics is rendered to the back buffer.
    /// The front buffer is displayed on the screen.
    fn swap_buffers<W: GameWindow>(&self, game_window: &W) {
        game_window.swap_buffers()
    }

    /// Handle current window's event with EventCenter.
    fn handle_events<W: GameWindow>(
        &mut self,
        game_window: &mut W,
        event_center: &mut EventCenter<Self>
    ) {
        loop {
            let event = game_window.poll_event();
            match event {
                event::NoEvent => {
                    break;
                },
                _ => {
                    event_center.receive_event(&event);
                },
            }
        }
    }

    /// Update the physical state of the game.
    ///
    /// `dt` is the delta time from last update in seconds.
    fn update(&mut self, _dt: f64, _event_center: &mut EventCenter<Self>, _asset_store: &mut AssetStore) {}

    /// Render graphics.
    ///
    /// `context` is a Rust-Graphics context.
    /// `gl` is the Piston OpenGL back-end for Rust-Graphics.
    fn render(&self, _ext_dt: f64, _context: &Context, _gl: &mut Gl) {}

    /// Executes a game loop.
    fn run<W: GameWindow>(
        &mut self,
        game_window: &mut W,
        asset_store: &mut AssetStore
    ) {
        use graphics::{Clear, AddColor};

        let mut event_center = EventCenter::new();

        self.load(asset_store);
        self.register_event(&mut event_center);

        let mut gl_data = GlData::new();
        let context = Context::new();
        let bg = game_window.get_settings().background_color;
        let bg = context.rgba(bg[0], bg[1], bg[2], bg[3]);

        let billion: u64 = 1_000_000_000;
        let updates_per_second = 120.0;
        let dt: f64 = 1.0 / updates_per_second;
        let update_time_in_ns: u64 = billion / updates_per_second as u64;

        let max_frames_per_second: f64 = 60.0;
        let min_ns_per_frame = (billion as f64 / max_frames_per_second) as u64;

        let mut last_update = time::precise_time_ns();
        let mut lag = 0;
        while !self.should_close(game_window) {
            let now = time::precise_time_ns();
            let elapsed = now - last_update;
            last_update = now;
            lag += elapsed;

            // Perform updates by fixed time step until it catches up.
            while lag >= update_time_in_ns {
                // Handle user input.
                // This is handled every update to make it more responsive.
                self.handle_events(game_window, &mut event_center);

                // Update application state.
                event_center.update(self, dt);
                self.update(dt, &mut event_center, asset_store);
                lag -= update_time_in_ns;
            }

            // Render.
            let (w, h) = game_window.get_size();
            if w != 0 && h != 0 {
                self.viewport(game_window);
                let mut gl = Gl::new(&mut gl_data, asset_store);
                bg.clear(&mut gl);
                // Extrapolate time forward to allow smooth motion.
                // 'lag' is always less than 'update_time_in_ns'.
                let ext_dt = lag as f64 / update_time_in_ns as f64;
                self.render(
                    ext_dt,
                    &context
                    .trans(-1.0, 1.0)
                    .scale(2.0 / w as f64, -2.0 / h as f64)
                    .store_view(),
                    &mut gl
                );
                self.swap_buffers(game_window);
            }

            let used_frame_time = time::precise_time_ns() - now;
            if min_ns_per_frame > used_frame_time {
                sleep((min_ns_per_frame - used_frame_time) / 1_000_000);
            }
        }
    }
}

<commit_msg>Fixed a bug<commit_after>
extern crate time;
extern crate gl;
extern crate graphics;
extern crate piston;

use std::io::timer::sleep;
use self::gl::types::GLint;
use self::graphics::{
    Context,
    RelativeTransform2d,
    View,
};
use self::piston::{
    AssetStore,
    GlData,
    event,
    Game,
    GameWindow,
    Gl,
};
use {
    Event,
    EventCenter,
    EventType,
    KeyType,
};

impl KeyType for piston::keyboard::Key {
    fn id(&self) -> uint {
        // add the last enum item in piston::mouse::Button
        self.code() as uint + piston::mouse::Button8 as uint + 1
    }
}

impl KeyType for piston::mouse::Button {
    fn id(&self) -> uint {
        *self as uint
    }
}

impl EventType for piston::event::Event {
    fn is_press_key(&self, key: &KeyType) -> bool {
        match *self {
            piston::event::KeyPressed(k) if k.id() == key.id() => {
                true
            },
            piston::event::MouseButtonPressed(k) if k.id() == key.id() => {
                true
            },
            _ => {
                false
            },
        }
    }
    fn is_release_key(&self, key: &KeyType) -> bool {
        match *self {
            piston::event::KeyReleased(k) if k.id() == key.id() => {
                true
            },
            piston::event::MouseButtonReleased(k) if k.id() == key.id() => {
                true
            },
            _ => {
                false
            }
        }
    }
}

/// ******************************
/// * MOST CODE COPY FROM PISTON *
/// ******************************
///
/// Implemented by game application which want to use rust-event.
pub trait EventGame {
    /// Perform tasks for loading before showing anything.
    fn load(&mut self, _asset_store: &mut AssetStore) {}

    /// Register event before game loop
    fn register_event(&mut self, _event_center: &mut EventCenter<Self>) {}

    /// Sets up viewport.
    ///
    /// A viewport is the region of the window where graphics is rendered.
    #[inline(always)]
    fn viewport<W: GameWindow>(&self, game_window: &W) {
        let (w, h) = game_window.get_size();
        gl::Viewport(0, 0, w as GLint, h as GLint);
    }

    /// Whether the window should be closed.
    ///
    /// When this is `true` the application shuts down.
    /// This can be overridden to emulate a user closing the window.
    /// One can also override this method to prevent window from closing.
    fn should_close<W: GameWindow>(&self, game_window: &W) -> bool {
        game_window.should_close()
    }

    /// Swaps the front buffer with the back buffer.
    ///
    /// When called, This shows the next frame.
    /// The graphics is rendered to the back buffer.
    /// The front buffer is displayed on the screen.
    fn swap_buffers<W: GameWindow>(&self, game_window: &W) {
        game_window.swap_buffers()
    }

    /// Handle current window's event with EventCenter.
    fn handle_events<W: GameWindow>(
        &mut self,
        game_window: &mut W,
        event_center: &mut EventCenter<Self>
    ) {
        loop {
            let event = game_window.poll_event();
            match event {
                event::NoEvent => {
                    break;
                },
                _ => {
                    event_center.receive_event(&event);
                },
            }
        }
    }

    /// Update the physical state of the game.
    ///
    /// `dt` is the delta time from last update in seconds.
    fn update(&mut self, _dt: f64, _event_center: &mut EventCenter<Self>, _asset_store: &mut AssetStore) {}

    /// Render graphics.
    ///
    /// `context` is a Rust-Graphics context.
    /// `gl` is the Piston OpenGL back-end for Rust-Graphics.
    fn render(&self, _ext_dt: f64, _context: &Context, _gl: &mut Gl) {}

    /// Executes a game loop.
    fn run<W: GameWindow>(
        &mut self,
        game_window: &mut W,
        asset_store: &mut AssetStore
    ) {
        use graphics::{Clear, AddColor};

        let mut event_center = EventCenter::new();

        self.load(asset_store);
        self.register_event(&mut event_center);

        let mut gl_data = GlData::new();
        let context = Context::new();
        let bg = game_window.get_settings().background_color;
        let bg = context.rgba(bg[0], bg[1], bg[2], bg[3]);

        let billion: u64 = 1_000_000_000;
        let updates_per_second = 120.0;
        let dt: f64 = 1.0 / updates_per_second;
        let update_time_in_ns: u64 = billion / updates_per_second as u64;

        let max_frames_per_second: f64 = 60.0;
        let min_ns_per_frame = (billion as f64 / max_frames_per_second) as u64;

        let mut last_update = time::precise_time_ns();
        let mut lag = 0;
        while !self.should_close(game_window) {
            let now = time::precise_time_ns();
            let elapsed = now - last_update;
            last_update = now;
            lag += elapsed;

            // Perform updates by fixed time step until it catches up.
            while lag >= update_time_in_ns {
                // Handle user input.
                // This is handled every update to make it more responsive.
                self.handle_events(game_window, &mut event_center);

                // Update application state.
                event_center.update(self, dt);
                self.update(dt, &mut event_center, asset_store);
                lag -= update_time_in_ns;
            }

            // Render.
            let (w, h) = game_window.get_size();
            if w != 0 && h != 0 {
                self.viewport(game_window);
                let mut gl = Gl::new(&mut gl_data, asset_store);
                bg.clear(&mut gl);
                // Extrapolate time forward to allow smooth motion.
                // 'lag' is always less than 'update_time_in_ns'.
                let ext_dt = lag as f64 / update_time_in_ns as f64;
                self.render(
                    ext_dt,
                    &context
                    .trans(-1.0, 1.0)
                    .scale(2.0 / w as f64, -2.0 / h as f64)
                    .store_view(),
                    &mut gl
                );
                self.swap_buffers(game_window);
            }

            let used_frame_time = time::precise_time_ns() - now;
            // sleep at least 1 ms
            if min_ns_per_frame - used_frame_time > 1_000_000  {
                sleep((min_ns_per_frame - used_frame_time) / 1_000_000);
            }
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>impl Debug for BTree<commit_after><|endoftext|>


<commit_before><commit_msg>Read editor from configuration, ignore errors<commit_after><|endoftext|>


<commit_before><commit_msg>Added a multiply-by-scalar operator to Vector2<commit_after><|endoftext|>


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

use syntax::ast;
use llvm::LLVMRustHasFeature;
use rustc::session::Session;
use rustc_trans::back::write::create_target_machine;
use syntax::feature_gate::UnstableFeatures;
use syntax::symbol::Symbol;
use libc::c_char;

// WARNING: the features must be known to LLVM or the feature
// detection code will walk past the end of the feature array,
// leading to crashes.

const ARM_WHITELIST: &'static [&'static str] = &["neon\0", "vfp2\0", "vfp3\0", "vfp4\0"];

const X86_WHITELIST: &'static [&'static str] = &["avx\0", "avx2\0", "bmi\0", "bmi2\0", "sse\0",
                                                 "sse2\0", "sse3\0", "sse4.1\0", "sse4.2\0",
                                                 "ssse3\0", "tbm\0", "lzcnt\0", "popcnt\0",
                                                 "sse4a\0", "rdrnd\0", "rdseed\0"];

/// Add `target_feature = "..."` cfgs for a variety of platform
/// specific features (SSE, NEON etc.).
///
/// This is performed by checking whether a whitelisted set of
/// features is available on the target machine, by querying LLVM.
pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session) {
    let target_machine = create_target_machine(sess);

    let whitelist = match &*sess.target.target.arch {
        "arm" => ARM_WHITELIST,
        "x86" | "x86_64" => X86_WHITELIST,
        _ => &[],
    };

    let tf = Symbol::intern("target_feature");
    for feat in whitelist {
        assert_eq!(feat.chars().last(), Some('\0'));
        if unsafe { LLVMRustHasFeature(target_machine, feat.as_ptr() as *const c_char) } {
            cfg.insert((tf, Some(Symbol::intern(&feat[..feat.len() - 1]))));
        }
    }

    let requested_features = sess.opts.cg.target_feature.split(',');
    let unstable_options = sess.opts.debugging_opts.unstable_options;
    let is_nightly = UnstableFeatures::from_environment().is_nightly_build();
    let found_negative = requested_features.clone().any(|r| r == "-crt-static");
    let found_positive = requested_features.clone().any(|r| r == "+crt-static");

    // If the target we're compiling for requests a static crt by default,
    // then see if the `-crt-static` feature was passed to disable that.
    // Otherwise if we don't have a static crt by default then see if the
    // `+crt-static` feature was passed.
    let crt_static = if sess.target.target.options.crt_static_default {
        !found_negative
    } else {
        found_positive
    };

    // If we switched from the default then that's only allowed on nightly, so
    // gate that here.
    if (found_positive || found_negative) && (!is_nightly || !unstable_options) {
        sess.fatal("specifying the `crt-static` target feature is only allowed \
                    on the nightly channel with `-Z unstable-options` passed \
                    as well");
    }

    if crt_static {
        cfg.insert((tf, Some(Symbol::intern("crt-static"))));
    }
}
<commit_msg>rustc: Whitelist the FMA target feature<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use syntax::ast;
use llvm::LLVMRustHasFeature;
use rustc::session::Session;
use rustc_trans::back::write::create_target_machine;
use syntax::feature_gate::UnstableFeatures;
use syntax::symbol::Symbol;
use libc::c_char;

// WARNING: the features must be known to LLVM or the feature
// detection code will walk past the end of the feature array,
// leading to crashes.

const ARM_WHITELIST: &'static [&'static str] = &["neon\0", "vfp2\0", "vfp3\0", "vfp4\0"];

const X86_WHITELIST: &'static [&'static str] = &["avx\0", "avx2\0", "bmi\0", "bmi2\0", "sse\0",
                                                 "sse2\0", "sse3\0", "sse4.1\0", "sse4.2\0",
                                                 "ssse3\0", "tbm\0", "lzcnt\0", "popcnt\0",
                                                 "sse4a\0", "rdrnd\0", "rdseed\0", "fma\0"];

/// Add `target_feature = "..."` cfgs for a variety of platform
/// specific features (SSE, NEON etc.).
///
/// This is performed by checking whether a whitelisted set of
/// features is available on the target machine, by querying LLVM.
pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session) {
    let target_machine = create_target_machine(sess);

    let whitelist = match &*sess.target.target.arch {
        "arm" => ARM_WHITELIST,
        "x86" | "x86_64" => X86_WHITELIST,
        _ => &[],
    };

    let tf = Symbol::intern("target_feature");
    for feat in whitelist {
        assert_eq!(feat.chars().last(), Some('\0'));
        if unsafe { LLVMRustHasFeature(target_machine, feat.as_ptr() as *const c_char) } {
            cfg.insert((tf, Some(Symbol::intern(&feat[..feat.len() - 1]))));
        }
    }

    let requested_features = sess.opts.cg.target_feature.split(',');
    let unstable_options = sess.opts.debugging_opts.unstable_options;
    let is_nightly = UnstableFeatures::from_environment().is_nightly_build();
    let found_negative = requested_features.clone().any(|r| r == "-crt-static");
    let found_positive = requested_features.clone().any(|r| r == "+crt-static");

    // If the target we're compiling for requests a static crt by default,
    // then see if the `-crt-static` feature was passed to disable that.
    // Otherwise if we don't have a static crt by default then see if the
    // `+crt-static` feature was passed.
    let crt_static = if sess.target.target.options.crt_static_default {
        !found_negative
    } else {
        found_positive
    };

    // If we switched from the default then that's only allowed on nightly, so
    // gate that here.
    if (found_positive || found_negative) && (!is_nightly || !unstable_options) {
        sess.fatal("specifying the `crt-static` target feature is only allowed \
                    on the nightly channel with `-Z unstable-options` passed \
                    as well");
    }

    if crt_static {
        cfg.insert((tf, Some(Symbol::intern("crt-static"))));
    }
}
<|endoftext|>


<commit_before>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Shader parameter handling.

use std::cell::Cell;
use std::rc::Rc;
use s = device::shade;
use device::{RawBufferHandle, ProgramHandle, SamplerHandle, TextureHandle};

/// Helper trait to transform base types into their corresponding uniforms
pub trait ToUniform {
    /// Create a `UniformValue` representing this value.
    fn to_uniform(&self) -> s::UniformValue;
}

impl ToUniform for i32 {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueI32(*self)
    }
}

impl ToUniform for f32 {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueF32(*self)
    }
}

impl ToUniform for [i32, ..4] {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueI32Vec(*self)
    }
}

impl ToUniform for [f32, ..4] {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueF32Vec(*self)
    }
}
impl ToUniform for [[f32, ..4], ..4] {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueF32Matrix(*self)
    }
}

/// Variable index of a uniform.
pub type VarUniform = u16;

/// Variable index of a uniform block.
pub type VarBlock = u8;

/// Variable index of a texture.
pub type VarTexture = u8;

/// A texture parameter: consists of a texture handle with an optional sampler.
pub type TextureParam = (TextureHandle, Option<SamplerHandle>);

/// Borrowed parts of the `ProgramMeta`, used for data link construction
pub type ParamLinkInput<'a> = (
    &'a [s::UniformVar],
    &'a [s::BlockVar],
    &'a [s::SamplerVar]
);

/// A borrowed mutable storage for shader parameter values.
// Not sure if it's the best data structure to represent it.
pub struct ParamValues<'a> {
    /// uniform values to be provided
    pub uniforms: &'a mut [Option<s::UniformValue>],
    /// uniform buffers to be provided
    pub blocks  : &'a mut [Option<RawBufferHandle>],
    /// textures to be provided
    pub textures: &'a mut [Option<TextureParam>],
}

/// Encloses a shader program handle with its parameter
pub trait Program {
    /// Get the contained program
    fn get_program(&self) -> &ProgramHandle;
    /// Get all the contained parameter values
    fn fill_params(&self, ParamValues);
}

impl Program for ProgramHandle {
    fn get_program(&self) -> &ProgramHandle {
        self
    }

    fn fill_params(&self, params: ParamValues) {
        debug_assert!(
            params.uniforms.is_empty() &&
            params.blocks.is_empty() &&
            params.textures.is_empty(),
            "trying to bind a program that has uniforms ; please call renderer.connect_program first"
        );
    }
}

/// An error type on either the parameter storage or the program side
#[deriving(Clone, PartialEq, Show)]
pub enum ParameterError<'a> {
    /// Internal error
    ErrorInternal,
    /// Error with the named uniform
    ErrorUniform(&'a str),
    /// Error with the named uniform block
    ErrorBlock(&'a str),
    /// Error with the named texture.
    ErrorTexture(&'a str),
}

/// An error type for the link creation
#[deriving(Clone, PartialEq, Show)]
pub enum ParameterLinkError<'a> {
    /// A given parameter is not used by the program
    ErrorUnusedParameter(ParameterError<'a>),
    /// A program parameter that is not provided
    ErrorMissingParameter(ParameterError<'a>),
}

/// Abstracts the shader parameter structure, generated by the `shader_param` attribute
pub trait ShaderParam<L> {
    /// Creates a new link, self is passed as a workaround for Rust to not be lost in generics
    fn create_link(&self, ParamLinkInput) -> Result<L, ParameterError<'static>>;
    /// Get all the contained parameter values, using a given link.
    fn fill_params(&self, &L, ParamValues);
}

impl ShaderParam<()> for () {
    fn create_link(&self, (uniforms, blocks, textures): ParamLinkInput)
                   -> Result<(), ParameterError<'static>> {
        match uniforms.head() {
            Some(_) => return Err(ErrorUniform("_")),
            None => (),
        }
        match blocks.head() {
            Some(_) => return Err(ErrorBlock("_")),
            None => (),
        }
        match textures.head() {
            Some(_) => return Err(ErrorTexture("_")),
            None => (),
        }
        Ok(())
    }

    fn fill_params(&self, _: &(), _: ParamValues) {
        //empty
    }
}

/// A bundle that encapsulates a program and a custom user-provided
/// structure containing the program parameters.
/// # Type parameters:
///
/// * `L` - auto-generated structure that has a variable index for every field of T
/// * `T` - user-provided structure containing actual parameter values
#[deriving(Clone)]
pub struct UserProgram<L, T> {
    /// Shader program handle
    program: ProgramHandle,
    /// Hidden link that provides parameter indices for user data
    link: L,
    /// Global data in a user-provided struct
    pub data: T,    //TODO: move data out of the shell
}

impl<L, T: ShaderParam<L>> UserProgram<L, T> {
    /// Create a new user program
    pub fn new(program: ProgramHandle, link: L, data: T) -> UserProgram<L, T> {
        UserProgram {
            program: program,
            link: link,
            data: data,
        }
    }
}

impl<L, T: ShaderParam<L>> Program for UserProgram<L, T> {
    fn get_program(&self) -> &ProgramHandle {
        &self.program
    }

    fn fill_params(&self, params: ParamValues) {
        self.data.fill_params(&self.link, params);
    }
}

/// A named cell containing arbitrary value
pub struct NamedCell<T> {
    /// Name
    pub name: String,
    /// Value
    pub value: Cell<T>,
}

/// A dictionary of parameters, meant to be shared between different programs
pub struct ParamDictionary {
    /// Uniform dictionary
    pub uniforms: Vec<NamedCell<s::UniformValue>>,
    /// Block dictionary
    pub blocks: Vec<NamedCell<RawBufferHandle>>,
    /// Texture dictionary
    pub textures: Vec<NamedCell<TextureParam>>,
}

/// An associated link structure for `ParamDictionary` that redirects program
/// input to the relevant dictionary cell.
pub struct ParamDictionaryLink {
    uniforms: Vec<uint>,
    blocks: Vec<uint>,
    textures: Vec<uint>,
}

impl<'a> ShaderParam<ParamDictionaryLink> for &'a ParamDictionary {
    fn create_link(&self, (in_uni, in_buf, in_tex): ParamLinkInput)
                   -> Result<ParamDictionaryLink, ParameterError<'static>> {
        //TODO: proper error checks
        Ok(ParamDictionaryLink {
            uniforms: in_uni.iter().map(|var|
                self.uniforms.iter().position(|c| c.name == var.name).unwrap()
            ).collect(),
            blocks: in_buf.iter().map(|var|
                self.blocks  .iter().position(|c| c.name == var.name).unwrap()
            ).collect(),
            textures: in_tex.iter().map(|var|
                self.textures.iter().position(|c| c.name == var.name).unwrap()
            ).collect(),
        })
    }

    fn fill_params(&self, link: &ParamDictionaryLink, out: ParamValues) {
        for (&id, var) in link.uniforms.iter().zip(out.uniforms.mut_iter()) {
            *var = Some(self.uniforms[id].value.get());
        }
        for (&id, var) in link.blocks.iter().zip(out.blocks.mut_iter()) {
            *var = Some(self.blocks[id].value.get());
        }
        for (&id, var) in link.textures.iter().zip(out.textures.mut_iter()) {
            *var = Some(self.textures[id].value.get());
        }
    }
}

impl ShaderParam<ParamDictionaryLink> for Rc<ParamDictionary> {
    fn create_link(&self, input: ParamLinkInput) -> Result<ParamDictionaryLink,
                   ParameterError<'static>> {
        self.deref().create_link(input)
    }

    fn fill_params(&self, link: &ParamDictionaryLink, out: ParamValues) {
        self.deref().fill_params(link, out)
    }
}
<commit_msg>Implemented Clone for UserProgram<commit_after>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Shader parameter handling.

use std::cell::Cell;
use std::rc::Rc;
use s = device::shade;
use device::{RawBufferHandle, ProgramHandle, SamplerHandle, TextureHandle};

/// Helper trait to transform base types into their corresponding uniforms
pub trait ToUniform {
    /// Create a `UniformValue` representing this value.
    fn to_uniform(&self) -> s::UniformValue;
}

impl ToUniform for i32 {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueI32(*self)
    }
}

impl ToUniform for f32 {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueF32(*self)
    }
}

impl ToUniform for [i32, ..4] {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueI32Vec(*self)
    }
}

impl ToUniform for [f32, ..4] {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueF32Vec(*self)
    }
}
impl ToUniform for [[f32, ..4], ..4] {
    fn to_uniform(&self) -> s::UniformValue {
        s::ValueF32Matrix(*self)
    }
}

/// Variable index of a uniform.
pub type VarUniform = u16;

/// Variable index of a uniform block.
pub type VarBlock = u8;

/// Variable index of a texture.
pub type VarTexture = u8;

/// A texture parameter: consists of a texture handle with an optional sampler.
pub type TextureParam = (TextureHandle, Option<SamplerHandle>);

/// Borrowed parts of the `ProgramMeta`, used for data link construction
pub type ParamLinkInput<'a> = (
    &'a [s::UniformVar],
    &'a [s::BlockVar],
    &'a [s::SamplerVar]
);

/// A borrowed mutable storage for shader parameter values.
// Not sure if it's the best data structure to represent it.
pub struct ParamValues<'a> {
    /// uniform values to be provided
    pub uniforms: &'a mut [Option<s::UniformValue>],
    /// uniform buffers to be provided
    pub blocks  : &'a mut [Option<RawBufferHandle>],
    /// textures to be provided
    pub textures: &'a mut [Option<TextureParam>],
}

/// Encloses a shader program handle with its parameter
pub trait Program {
    /// Get the contained program
    fn get_program(&self) -> &ProgramHandle;
    /// Get all the contained parameter values
    fn fill_params(&self, ParamValues);
}

impl Program for ProgramHandle {
    fn get_program(&self) -> &ProgramHandle {
        self
    }

    fn fill_params(&self, params: ParamValues) {
        debug_assert!(
            params.uniforms.is_empty() &&
            params.blocks.is_empty() &&
            params.textures.is_empty(),
            "trying to bind a program that has uniforms ; please call renderer.connect_program first"
        );
    }
}

/// An error type on either the parameter storage or the program side
#[deriving(Clone, PartialEq, Show)]
pub enum ParameterError<'a> {
    /// Internal error
    ErrorInternal,
    /// Error with the named uniform
    ErrorUniform(&'a str),
    /// Error with the named uniform block
    ErrorBlock(&'a str),
    /// Error with the named texture.
    ErrorTexture(&'a str),
}

/// An error type for the link creation
#[deriving(Clone, PartialEq, Show)]
pub enum ParameterLinkError<'a> {
    /// A given parameter is not used by the program
    ErrorUnusedParameter(ParameterError<'a>),
    /// A program parameter that is not provided
    ErrorMissingParameter(ParameterError<'a>),
}

/// Abstracts the shader parameter structure, generated by the `shader_param` attribute
pub trait ShaderParam<L> {
    /// Creates a new link, self is passed as a workaround for Rust to not be lost in generics
    fn create_link(&self, ParamLinkInput) -> Result<L, ParameterError<'static>>;
    /// Get all the contained parameter values, using a given link.
    fn fill_params(&self, &L, ParamValues);
}

impl ShaderParam<()> for () {
    fn create_link(&self, (uniforms, blocks, textures): ParamLinkInput)
                   -> Result<(), ParameterError<'static>> {
        match uniforms.head() {
            Some(_) => return Err(ErrorUniform("_")),
            None => (),
        }
        match blocks.head() {
            Some(_) => return Err(ErrorBlock("_")),
            None => (),
        }
        match textures.head() {
            Some(_) => return Err(ErrorTexture("_")),
            None => (),
        }
        Ok(())
    }

    fn fill_params(&self, _: &(), _: ParamValues) {
        //empty
    }
}

/// A bundle that encapsulates a program and a custom user-provided
/// structure containing the program parameters.
/// # Type parameters:
///
/// * `L` - auto-generated structure that has a variable index for every field of T
/// * `T` - user-provided structure containing actual parameter values
pub struct UserProgram<L, T> {
    /// Shader program handle
    program: ProgramHandle,
    /// Hidden link that provides parameter indices for user data
    link: L,
    /// Global data in a user-provided struct
    pub data: T,    //TODO: move data out of the shell
}

impl<L: Copy, T: Copy> Clone for UserProgram<L, T> {
    fn clone(&self) -> UserProgram<L, T> {
        UserProgram {
            program: self.program.clone(),
            link: self.link,
            data: self.data,
        }
    }
}

impl<L, T: ShaderParam<L>> UserProgram<L, T> {
    /// Create a new user program
    pub fn new(program: ProgramHandle, link: L, data: T) -> UserProgram<L, T> {
        UserProgram {
            program: program,
            link: link,
            data: data,
        }
    }
}

impl<L, T: ShaderParam<L>> Program for UserProgram<L, T> {
    fn get_program(&self) -> &ProgramHandle {
        &self.program
    }

    fn fill_params(&self, params: ParamValues) {
        self.data.fill_params(&self.link, params);
    }
}

/// A named cell containing arbitrary value
pub struct NamedCell<T> {
    /// Name
    pub name: String,
    /// Value
    pub value: Cell<T>,
}

/// A dictionary of parameters, meant to be shared between different programs
pub struct ParamDictionary {
    /// Uniform dictionary
    pub uniforms: Vec<NamedCell<s::UniformValue>>,
    /// Block dictionary
    pub blocks: Vec<NamedCell<RawBufferHandle>>,
    /// Texture dictionary
    pub textures: Vec<NamedCell<TextureParam>>,
}

/// An associated link structure for `ParamDictionary` that redirects program
/// input to the relevant dictionary cell.
pub struct ParamDictionaryLink {
    uniforms: Vec<uint>,
    blocks: Vec<uint>,
    textures: Vec<uint>,
}

impl<'a> ShaderParam<ParamDictionaryLink> for &'a ParamDictionary {
    fn create_link(&self, (in_uni, in_buf, in_tex): ParamLinkInput)
                   -> Result<ParamDictionaryLink, ParameterError<'static>> {
        //TODO: proper error checks
        Ok(ParamDictionaryLink {
            uniforms: in_uni.iter().map(|var|
                self.uniforms.iter().position(|c| c.name == var.name).unwrap()
            ).collect(),
            blocks: in_buf.iter().map(|var|
                self.blocks  .iter().position(|c| c.name == var.name).unwrap()
            ).collect(),
            textures: in_tex.iter().map(|var|
                self.textures.iter().position(|c| c.name == var.name).unwrap()
            ).collect(),
        })
    }

    fn fill_params(&self, link: &ParamDictionaryLink, out: ParamValues) {
        for (&id, var) in link.uniforms.iter().zip(out.uniforms.mut_iter()) {
            *var = Some(self.uniforms[id].value.get());
        }
        for (&id, var) in link.blocks.iter().zip(out.blocks.mut_iter()) {
            *var = Some(self.blocks[id].value.get());
        }
        for (&id, var) in link.textures.iter().zip(out.textures.mut_iter()) {
            *var = Some(self.textures[id].value.get());
        }
    }
}

impl ShaderParam<ParamDictionaryLink> for Rc<ParamDictionary> {
    fn create_link(&self, input: ParamLinkInput) -> Result<ParamDictionaryLink,
                   ParameterError<'static>> {
        self.deref().create_link(input)
    }

    fn fill_params(&self, link: &ParamDictionaryLink, out: ParamValues) {
        self.deref().fill_params(link, out)
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement Serialize and Deserialize for MessageType.<commit_after><|endoftext|>


<commit_before><commit_msg>added larger segmented sieve example<commit_after><|endoftext|>


<commit_before>#![feature(io)]

use std::process::Command;
use std::io::prelude::*;

static PANGRAM: &'static str =
"the quick brown fox jumped over the lazy dog\n";

fn main() {
    // Spawn the `wc` command
    let process = match Command::new("wc").spawn() {
        Err(why) => panic!("couldn't spawn wc: {}", why.description()),
        Ok(process) => process,
    };

    {
        // Write a string to the stdin of `wc`
        match process.stdin.unwrap().write_all(PANGRAM.as_bytes()) {
            Err(why) => panic!("couldn't write to wc stdin: {}",
                               why.description()),
            Ok(_) => println!("sent pangram to wc"),
        }

        // `stdin` gets `drop`ed here, and the pipe is closed
        // This is very important, otherwise `wc` wouldn't start processing the
        // input we just sent
    }

    // The `stdout` field also has type `Option<PipeStream>`
    // the `as_mut` method will return a mutable reference to the value
    // wrapped in a `Some` variant
    let mut s = String::new();
    match process.stdout.unwrap().read_to_string(&mut s) {
        Err(why) => panic!("couldn't read wc stdout: {}",
                           why.description()),
        Ok(_) => print!("wc responded with:\n{}", s),
    }
}
<commit_msg>Fix warnings/errors in process/pipe<commit_after>#![feature(core)]

use std::error::Error;
use std::io::prelude::*;
use std::process::{Command, Stdio};

static PANGRAM: &'static str =
"the quick brown fox jumped over the lazy dog\n";

fn main() {
    // Spawn the `wc` command
    let process = match Command::new("wc")
                                .stdin(Stdio::piped())
                                .stdout(Stdio::piped())
                                .spawn() {
        Err(why) => panic!("couldn't spawn wc: {}", Error::description(&why)),
        Ok(process) => process,
    };

    {
        // Write a string to the stdin of `wc`
        match process.stdin.unwrap().write_all(PANGRAM.as_bytes()) {
            Err(why) => panic!("couldn't write to wc stdin: {}",
                               Error::description(&why)),
            Ok(_) => println!("sent pangram to wc"),
        }

        // `stdin` gets `drop`ed here, and the pipe is closed
        // This is very important, otherwise `wc` wouldn't start processing the
        // input we just sent
    }

    // The `stdout` field also has type `Option<PipeStream>`
    // the `as_mut` method will return a mutable reference to the value
    // wrapped in a `Some` variant
    let mut s = String::new();
    match process.stdout.unwrap().read_to_string(&mut s) {
        Err(why) => panic!("couldn't read wc stdout: {}",
                           Error::description(&why)),
        Ok(_) => print!("wc responded with:\n{}", s),
    }
}
<|endoftext|>