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

use libc;
use cell::UnsafeCell;
use sync::atomic::{AtomicUsize, Ordering};

pub struct RWLock {
    inner: UnsafeCell<libc::pthread_rwlock_t>,
    write_locked: UnsafeCell<bool>,
    num_readers: AtomicUsize,
}

unsafe impl Send for RWLock {}
unsafe impl Sync for RWLock {}

impl RWLock {
    pub const fn new() -> RWLock {
        RWLock {
            inner: UnsafeCell::new(libc::PTHREAD_RWLOCK_INITIALIZER),
            write_locked: UnsafeCell::new(false),
            num_readers: AtomicUsize::new(0),
        }
    }
    #[inline]
    pub unsafe fn read(&self) {
        let r = libc::pthread_rwlock_rdlock(self.inner.get());

        // According to the pthread_rwlock_rdlock spec, this function **may**
        // fail with EDEADLK if a deadlock is detected. On the other hand
        // pthread mutexes will *never* return EDEADLK if they are initialized
        // as the "fast" kind (which ours always are). As a result, a deadlock
        // situation may actually return from the call to pthread_rwlock_rdlock
        // instead of blocking forever (as mutexes and Windows rwlocks do). Note
        // that not all unix implementations, however, will return EDEADLK for
        // their rwlocks.
        //
        // We roughly maintain the deadlocking behavior by panicking to ensure
        // that this lock acquisition does not succeed.
        //
        // We also check whether there this lock is already write locked. This
        // is only possible if it was write locked by the current thread and
        // the implementation allows recursive locking. The POSIX standard
        // doesn't require recursivly locking a rwlock to deadlock, but we can't
        // allow that because it could lead to aliasing issues.
        if r == libc::EAGAIN {
            panic!("rwlock maximum reader count exceeded");
        } else if r == libc::EDEADLK || *self.write_locked.get() {
            if r == 0 {
                self.raw_unlock();
            }
            panic!("rwlock read lock would result in deadlock");
        } else {
            debug_assert_eq!(r, 0);
            self.num_readers.fetch_add(1, Ordering::Relaxed);
        }
    }
    #[inline]
    pub unsafe fn try_read(&self) -> bool {
        let r = libc::pthread_rwlock_tryrdlock(self.inner.get());
        if r == 0 {
            if *self.write_locked.get() {
                self.raw_unlock();
                false
            } else {
                self.num_readers.fetch_add(1, Ordering::Relaxed);
                true
            }
        } else {
            false
        }
    }
    #[inline]
    pub unsafe fn write(&self) {
        let r = libc::pthread_rwlock_wrlock(self.inner.get());
        // See comments above for why we check for EDEADLK and write_locked. We
        // also need to check that num_readers is 0.
        if r == libc::EDEADLK || *self.write_locked.get() ||
           self.num_readers.load(Ordering::Relaxed) != 0 {
            if r == 0 {
                self.raw_unlock();
            }
            panic!("rwlock write lock would result in deadlock");
        } else {
            debug_assert_eq!(r, 0);
        }
        *self.write_locked.get() = true;
    }
    #[inline]
    pub unsafe fn try_write(&self) -> bool {
        let r = libc::pthread_rwlock_trywrlock(self.inner.get());
        if r == 0 {
            if *self.write_locked.get() || self.num_readers.load(Ordering::Relaxed) != 0 {
                self.raw_unlock();
                false
            } else {
                *self.write_locked.get() = true;
                true
            }
        } else {
            false
        }
    }
    #[inline]
    unsafe fn raw_unlock(&self) {
        let r = libc::pthread_rwlock_unlock(self.inner.get());
        debug_assert_eq!(r, 0);
    }
    #[inline]
    pub unsafe fn read_unlock(&self) {
        debug_assert!(!*self.write_locked.get());
        self.num_readers.fetch_sub(1, Ordering::Relaxed);
        self.raw_unlock();
    }
    #[inline]
    pub unsafe fn write_unlock(&self) {
        debug_assert_eq!(self.num_readers.load(Ordering::Relaxed), 0);
        debug_assert!(*self.write_locked.get());
        *self.write_locked.get() = false;
        self.raw_unlock();
    }
    #[inline]
    pub unsafe fn destroy(&self) {
        let r = libc::pthread_rwlock_destroy(self.inner.get());
        // On DragonFly pthread_rwlock_destroy() returns EINVAL if called on a
        // rwlock that was just initialized with
        // libc::PTHREAD_RWLOCK_INITIALIZER. Once it is used (locked/unlocked)
        // or pthread_rwlock_init() is called, this behaviour no longer occurs.
        if cfg!(target_os = "dragonfly") {
            debug_assert!(r == 0 || r == libc::EINVAL);
        } else {
            debug_assert_eq!(r, 0);
        }
    }
}
<commit_msg>Fix typos in unix/rwlock.rs<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.

use libc;
use cell::UnsafeCell;
use sync::atomic::{AtomicUsize, Ordering};

pub struct RWLock {
    inner: UnsafeCell<libc::pthread_rwlock_t>,
    write_locked: UnsafeCell<bool>,
    num_readers: AtomicUsize,
}

unsafe impl Send for RWLock {}
unsafe impl Sync for RWLock {}

impl RWLock {
    pub const fn new() -> RWLock {
        RWLock {
            inner: UnsafeCell::new(libc::PTHREAD_RWLOCK_INITIALIZER),
            write_locked: UnsafeCell::new(false),
            num_readers: AtomicUsize::new(0),
        }
    }
    #[inline]
    pub unsafe fn read(&self) {
        let r = libc::pthread_rwlock_rdlock(self.inner.get());

        // According to the pthread_rwlock_rdlock spec, this function **may**
        // fail with EDEADLK if a deadlock is detected. On the other hand
        // pthread mutexes will *never* return EDEADLK if they are initialized
        // as the "fast" kind (which ours always are). As a result, a deadlock
        // situation may actually return from the call to pthread_rwlock_rdlock
        // instead of blocking forever (as mutexes and Windows rwlocks do). Note
        // that not all unix implementations, however, will return EDEADLK for
        // their rwlocks.
        //
        // We roughly maintain the deadlocking behavior by panicking to ensure
        // that this lock acquisition does not succeed.
        //
        // We also check whether this lock is already write locked. This
        // is only possible if it was write locked by the current thread and
        // the implementation allows recursive locking. The POSIX standard
        // doesn't require recursively locking a rwlock to deadlock, but we can't
        // allow that because it could lead to aliasing issues.
        if r == libc::EAGAIN {
            panic!("rwlock maximum reader count exceeded");
        } else if r == libc::EDEADLK || *self.write_locked.get() {
            if r == 0 {
                self.raw_unlock();
            }
            panic!("rwlock read lock would result in deadlock");
        } else {
            debug_assert_eq!(r, 0);
            self.num_readers.fetch_add(1, Ordering::Relaxed);
        }
    }
    #[inline]
    pub unsafe fn try_read(&self) -> bool {
        let r = libc::pthread_rwlock_tryrdlock(self.inner.get());
        if r == 0 {
            if *self.write_locked.get() {
                self.raw_unlock();
                false
            } else {
                self.num_readers.fetch_add(1, Ordering::Relaxed);
                true
            }
        } else {
            false
        }
    }
    #[inline]
    pub unsafe fn write(&self) {
        let r = libc::pthread_rwlock_wrlock(self.inner.get());
        // See comments above for why we check for EDEADLK and write_locked. We
        // also need to check that num_readers is 0.
        if r == libc::EDEADLK || *self.write_locked.get() ||
           self.num_readers.load(Ordering::Relaxed) != 0 {
            if r == 0 {
                self.raw_unlock();
            }
            panic!("rwlock write lock would result in deadlock");
        } else {
            debug_assert_eq!(r, 0);
        }
        *self.write_locked.get() = true;
    }
    #[inline]
    pub unsafe fn try_write(&self) -> bool {
        let r = libc::pthread_rwlock_trywrlock(self.inner.get());
        if r == 0 {
            if *self.write_locked.get() || self.num_readers.load(Ordering::Relaxed) != 0 {
                self.raw_unlock();
                false
            } else {
                *self.write_locked.get() = true;
                true
            }
        } else {
            false
        }
    }
    #[inline]
    unsafe fn raw_unlock(&self) {
        let r = libc::pthread_rwlock_unlock(self.inner.get());
        debug_assert_eq!(r, 0);
    }
    #[inline]
    pub unsafe fn read_unlock(&self) {
        debug_assert!(!*self.write_locked.get());
        self.num_readers.fetch_sub(1, Ordering::Relaxed);
        self.raw_unlock();
    }
    #[inline]
    pub unsafe fn write_unlock(&self) {
        debug_assert_eq!(self.num_readers.load(Ordering::Relaxed), 0);
        debug_assert!(*self.write_locked.get());
        *self.write_locked.get() = false;
        self.raw_unlock();
    }
    #[inline]
    pub unsafe fn destroy(&self) {
        let r = libc::pthread_rwlock_destroy(self.inner.get());
        // On DragonFly pthread_rwlock_destroy() returns EINVAL if called on a
        // rwlock that was just initialized with
        // libc::PTHREAD_RWLOCK_INITIALIZER. Once it is used (locked/unlocked)
        // or pthread_rwlock_init() is called, this behaviour no longer occurs.
        if cfg!(target_os = "dragonfly") {
            debug_assert!(r == 0 || r == libc::EINVAL);
        } else {
            debug_assert_eq!(r, 0);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Update tests slice macro to use new String refs<commit_after><|endoftext|>


<commit_before><commit_msg>clear<commit_after><|endoftext|>


<commit_before><commit_msg>static vars declared and used<commit_after><|endoftext|>


<commit_before><commit_msg>Implement Bind; Expose safe API; Fix #1<commit_after><|endoftext|>


<commit_before><commit_msg>Impl. get_left_child<commit_after><|endoftext|>


<commit_before><commit_msg>feat(example): add text example<commit_after>extern crate rustbox;
extern crate yoga;
extern crate yoga_rustbox;
extern crate yoga_wrapper;

use yoga::Backend;

use std::error::Error;
use std::default::Default;

use rustbox::RustBox;
use rustbox::Key;

fn main() {
    let rustbox = match RustBox::init(Default::default()) {
        Result::Ok(v) => v,
        Result::Err(e) => panic!("{}", e),
    };

    let mut root = yoga_wrapper::Node::new();
    root.set_width(50.0);
    root.set_height(12.0);
    root.set_flex_direction(yoga_wrapper::FlexDirection::Row);
    root.set_padding(yoga_wrapper::Edge::All, 2.0);

    let mut text = yoga_wrapper::Node::new();
    text.set_measure_func(yoga_wrapper::measure);
    text.set_context(&mut yoga_wrapper::Context::new("Yo!!!", &yoga_rustbox::Measurer {}));

    root.insert_child(&text, 0);

    root.calculate_layout();

    yoga_rustbox::Backend::new(&rustbox).render(&root);

    loop {
        match rustbox.poll_event(false) {
            Ok(rustbox::Event::KeyEvent(key)) => {
                match key {
                    Key::Char('q') => {
                        break;
                    }
                    _ => {}
                }
            }
            Err(e) => panic!("{}", e.description()),
            _ => {}
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Haiku: Add in final missing pthread pubs<commit_after><|endoftext|>


<commit_before><commit_msg>Add a new test case to verify behavior.<commit_after>// run-pass
#![feature(trait_upcasting)]
#![allow(incomplete_features)]

trait Foo<T: Default + ToString>: Bar<i32> + Bar<T> {}
trait Bar<T: Default + ToString> {
    fn bar(&self) -> String {
        T::default().to_string()
    }
}

struct S1;

impl Bar<i32> for S1 {}
impl Foo<i32> for S1 {}

struct S2;
impl Bar<i32> for S2 {}
impl Bar<bool> for S2 {}
impl Foo<bool> for S2 {}

fn test1(x: &dyn Foo<i32>) {
    let s = x as &dyn Bar<i32>;
    assert_eq!("0", &s.bar().to_string());
}

fn test2(x: &dyn Foo<bool>) {
    let p = x as &dyn Bar<i32>;
    assert_eq!("0", &p.bar().to_string());
    let q = x as &dyn Bar<bool>;
    assert_eq!("false", &q.bar().to_string());
}

fn main() {
    let s1 = S1;
    test1(&s1);
    let s2 = S2;
    test2(&s2);
}
<|endoftext|>


<commit_before><commit_msg>Update itertypes with mutable iterator and iterate_mut() impl<commit_after><|endoftext|>


<commit_before><commit_msg>Add display_test<commit_after>#[macro_use]
extern crate yoga;

use yoga::{Direction, Display, FlexDirection, Node, Percent, Point, Undefined};
use yoga::FlexStyle::*;

#[test]
fn test_display_none() {
	let mut root = Node::new();

	style!(root,
		FlexDirection(FlexDirection::Row),
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		FlexGrow(1.0)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		FlexGrow(1.0),
		Display(Display::None)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(0.0, child_1_layout.width);
	assert_eq!(0.0, child_1_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(0.0, child_1_layout.width);
	assert_eq!(0.0, child_1_layout.height);
}

#[test]
fn test_display_none_fixed_size() {
	let mut root = Node::new();

	style!(root,
		FlexDirection(FlexDirection::Row),
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		FlexGrow(1.0)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		Width(20 pt),
		Height(20 pt),
		Display(Display::None)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(0.0, child_1_layout.width);
	assert_eq!(0.0, child_1_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(0.0, child_1_layout.width);
	assert_eq!(0.0, child_1_layout.height);
}

#[test]
fn test_display_none_with_margin() {
	let mut root = Node::new();

	style!(root,
		FlexDirection(FlexDirection::Row),
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		MarginLeft(10 pt),
		MarginTop(10 pt),
		MarginRight(10 pt),
		MarginBottom(10 pt),
		Width(20 pt),
		Height(20 pt),
		Display(Display::None)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		FlexGrow(1.0)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(0.0, child_0_layout.width);
	assert_eq!(0.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(100.0, child_1_layout.width);
	assert_eq!(100.0, child_1_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(0.0, child_0_layout.width);
	assert_eq!(0.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(100.0, child_1_layout.width);
	assert_eq!(100.0, child_1_layout.height);
}

#[test]
fn test_display_none_with_child() {
	let mut root = Node::new();

	style!(root,
		FlexDirection(FlexDirection::Row),
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		FlexGrow(1.0),
		FlexShrink(1.0),
		FlexBasis(0 %)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		FlexGrow(1.0),
		FlexShrink(1.0),
		FlexBasis(0 %),
		Display(Display::None)
	);

	let mut root_child_1_child_0 = Node::new();

	style!(root_child_1_child_0,
		FlexGrow(1.0),
		FlexShrink(1.0),
		FlexBasis(0 %),
		Width(20 pt),
		MinWidth(0 pt),
		MinHeight(0 pt)
	);

	let mut root_child_2 = Node::new();

	style!(root_child_2,
		FlexGrow(1.0),
		FlexShrink(1.0),
		FlexBasis(0 %)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root_child_1.insert_child(&mut root_child_1_child_0, 0);
	root.insert_child(&mut root_child_2, 2);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_1_child_0_layout = root_child_1_child_0.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(50.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(0.0, child_1_layout.width);
	assert_eq!(0.0, child_1_layout.height);

	assert_eq!(0.0, child_1_child_0_layout.left);
	assert_eq!(0.0, child_1_child_0_layout.top);
	assert_eq!(0.0, child_1_child_0_layout.width);
	assert_eq!(0.0, child_1_child_0_layout.height);

	assert_eq!(50.0, child_2_layout.left);
	assert_eq!(0.0, child_2_layout.top);
	assert_eq!(50.0, child_2_layout.width);
	assert_eq!(100.0, child_2_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();
	let child_1_child_0_layout = root_child_1_child_0.get_layout();
	let child_2_layout = root_child_2.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(50.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(50.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(0.0, child_1_layout.width);
	assert_eq!(0.0, child_1_layout.height);

	assert_eq!(0.0, child_1_child_0_layout.left);
	assert_eq!(0.0, child_1_child_0_layout.top);
	assert_eq!(0.0, child_1_child_0_layout.width);
	assert_eq!(0.0, child_1_child_0_layout.height);

	assert_eq!(0.0, child_2_layout.left);
	assert_eq!(0.0, child_2_layout.top);
	assert_eq!(50.0, child_2_layout.width);
	assert_eq!(100.0, child_2_layout.height);
}

#[test]
fn test_display_none_with_position() {
	let mut root = Node::new();

	style!(root,
		FlexDirection(FlexDirection::Row),
		Width(100 pt),
		Height(100 pt)
	);

	let mut root_child_0 = Node::new();

	style!(root_child_0,
		FlexGrow(1.0)
	);

	let mut root_child_1 = Node::new();

	style!(root_child_1,
		FlexGrow(1.0),
		Top(10 pt),
		Display(Display::None)
	);

	root.insert_child(&mut root_child_0, 0);
	root.insert_child(&mut root_child_1, 1);
	root.calculate_layout(Undefined, Undefined, Direction::LTR);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(0.0, child_1_layout.width);
	assert_eq!(0.0, child_1_layout.height);

	root.calculate_layout(Undefined, Undefined, Direction::RTL);

	let root_layout = root.get_layout();
	let child_0_layout = root_child_0.get_layout();
	let child_1_layout = root_child_1.get_layout();

	assert_eq!(0.0, root_layout.left);
	assert_eq!(0.0, root_layout.top);
	assert_eq!(100.0, root_layout.width);
	assert_eq!(100.0, root_layout.height);

	assert_eq!(0.0, child_0_layout.left);
	assert_eq!(0.0, child_0_layout.top);
	assert_eq!(100.0, child_0_layout.width);
	assert_eq!(100.0, child_0_layout.height);

	assert_eq!(0.0, child_1_layout.left);
	assert_eq!(0.0, child_1_layout.top);
	assert_eq!(0.0, child_1_layout.width);
	assert_eq!(0.0, child_1_layout.height);
}
<|endoftext|>


<commit_before><commit_msg>Check permissions on all commands<commit_after><|endoftext|>


<commit_before><commit_msg>Added some default shaders<commit_after>#[allow(dead_code)]
extern crate rand;

use super::vid;
use super::start;

macro_rules! shader {
    ($b:block) => (|triangle: &vid::Triangle, window: &mut start::Window| $b);
}

pub fn wireframe(id: u16) -> vid::Shader {
    let wireframe_shader = |triangle: &vid::Triangle, window: &mut start::Window| {
        let flat_1 = triangle.p1.clone().flat_point(window.screen_x, window.screen_y,
                                            triangle.x + window.camera_x,
                                            triangle.y + window.camera_y,
                                            triangle.z + window.camera_z);
        let flat_2 = triangle.p2.clone().flat_point(window.screen_x, window.screen_y,
                                            triangle.x + window.camera_x,
                                            triangle.y + window.camera_y,
                                            triangle.z + window.camera_z);
        let flat_3 = triangle.p3.clone().flat_point(window.screen_x, window.screen_y,
                                            triangle.x + window.camera_x,
                                            triangle.y + window.camera_y,
                                            triangle.z + window.camera_z);

        window.window.line(flat_1.x, flat_1.y, flat_2.x, flat_2.y, triangle.color.orb_color());
        window.window.line(flat_3.x, flat_3.y, flat_2.x, flat_2.y, triangle.color.orb_color());
        window.window.line(flat_1.x, flat_1.y, flat_3.x, flat_3.y, triangle.color.orb_color());
    };

    vid::Shader {id: id, shader: Box::new(wireframe_shader)}
}

pub fn disco_wireframe(id: u16) -> vid::Shader {
    let noise_shader = |triangle: &vid::Triangle, window: &mut start::Window| {
        let flat_1 = triangle.p1.clone().flat_point(window.screen_x, window.screen_y,
                                            triangle.x + window.camera_x,
                                            triangle.y + window.camera_y,
                                            triangle.z + window.camera_z);
        let flat_2 = triangle.p2.clone().flat_point(window.screen_x, window.screen_y,
                                            triangle.x + window.camera_x,
                                            triangle.y + window.camera_y,
                                            triangle.z + window.camera_z);
        let flat_3 = triangle.p3.clone().flat_point(window.screen_x, window.screen_y,
                                            triangle.x + window.camera_x,
                                            triangle.y + window.camera_y,
                                            triangle.z + window.camera_z);

        window.window.line(flat_1.x, flat_1.y, flat_2.x, flat_2.y, vid::Color::new(rand::random::<u8>(),
                                                                                rand::random::<u8>(),
                                                                                rand::random::<u8>()).orb_color());
        window.window.line(flat_3.x, flat_3.y, flat_2.x, flat_2.y, vid::Color::new(rand::random::<u8>(),
                                                                                rand::random::<u8>(),
                                                                                rand::random::<u8>()).orb_color());
        window.window.line(flat_1.x, flat_1.y, flat_3.x, flat_3.y, vid::Color::new(rand::random::<u8>(),
                                                                                rand::random::<u8>(),
                                                                                rand::random::<u8>()).orb_color());
    };

    vid::Shader {id: id, shader: Box::new(noise_shader)}
}

/// GARBAGE, WILL REMOVE SOON
pub fn garbage_filled(id: u16) -> vid::Shader {
    let rasterize_shader = |triangle: &vid::Triangle, window: &mut start::Window| {

        fn bottom_flat(top: vid::FlatPoint, left: vid::FlatPoint, right: vid::FlatPoint, triangle: &vid::Triangle, window: &mut start::Window) {
            if (left.y - top.y) != 0 && (right.y - top.y) != 0 {
                let left_slope = -(left.x - top.x) as f64 / (left.y - top.y) as f64;
                let right_slope = -(right.x - top.x) as f64 / (right.y - top.y) as f64;

                for i in 0..left.y - top.y {
                    window.window.line(right.x + (right_slope * i as f64) as i32, right.y - i,
                                       left.x + (left_slope * i as f64) as i32, left.y - i, triangle.color.orb_color());
                }
            }
        }

        fn top_flat(left: vid::FlatPoint, right: vid::FlatPoint, top: vid::FlatPoint, triangle: &vid::Triangle, window: &mut start::Window) {
            if (left.y - top.y) != 0 && (right.y - top.y) != 0 {
                let left_slope = -(left.x - top.x) as f64 / (left.y - top.y) as f64;
                let right_slope = -(right.x - top.x) as f64 / (right.y - top.y) as f64;

                for i in 0..top.y - left.y {
                    window.window.line(right.x + (right_slope * -i as f64) as i32, right.y + i,
                                       left.x + (left_slope * -i as f64) as i32, left.y + i, triangle.color.orb_color());
                }
            }
        }

        let p1 = triangle.p1.clone().flat_point(window.screen_x, window.screen_y,
                                                triangle.x + window.camera_x,
                                                triangle.y + window.camera_y,
                                                triangle.z + window.camera_z);
        let p2 = triangle.p2.clone().flat_point(window.screen_x, window.screen_y,
                                                triangle.x + window.camera_x,
                                                triangle.y + window.camera_y,
                                                triangle.z + window.camera_z);
        let p3 = triangle.p3.clone().flat_point(window.screen_x, window.screen_y,
                                                triangle.x + window.camera_x,
                                                triangle.y + window.camera_y,
                                                triangle.z + window.camera_z);

        let points = [p1, p2, p3];

        let top = points.iter().max_by_key(|p| -p.y).unwrap().clone();
        let left = points.iter().max_by_key(|p| -p.x).unwrap().clone();
        let right = points.iter().max_by_key(|p| p.x).unwrap().clone();

        /*if top.y == left.y { // top flat
            println!("{:?} {:?}", top.y, left.y);
            let top = points.iter().max_by_key(|p| p.y).unwrap().clone();
            top_flat(left, right, top, &triangle, window);
            println!("top_flat");
        } else if left.y == right.y { // bottom flat
            bottom_flat(top, left, right, &triangle, window);
            println!("bot_flat");
        } else {*/
            let left_and_right = [left.clone(), right.clone()];
            let middle = left_and_right.iter().max_by_key(|p| -p.y).unwrap().clone();
            let low = left_and_right.iter().max_by_key(|p| p.y).unwrap().clone();

            let magic = (top.x as f32 + ((middle.y - top.y) as f32 / (low.y - top.y) as f32) * (low.x - top.x) as f32) as i32;

            let new_point = vid::FlatPoint { x: magic , y: middle.y };

            bottom_flat(top, middle, new_point, &triangle, window);
            top_flat(middle, new_point, low,  &triangle, window);
            println!("comm");
        //}

    };

    vid::Shader {id: id, shader: Box::new(rasterize_shader)}
}
<|endoftext|>


<commit_before><commit_msg>Some logic cleanups in envelope<commit_after><|endoftext|>


<commit_before><commit_msg>Add set_txninfo()<commit_after><|endoftext|>


<commit_before><commit_msg>chore: type alias<commit_after><|endoftext|>


<commit_before><commit_msg>add missing file<commit_after>// (c) 2016 Productize SPRL <joost@productize.be>

use Result;
use Sexp;
use parse_error;

#[derive(Default)]
struct Parser {
    data: Vec<char>,
    position: usize,
    line: usize,
    line_position: usize,
}

impl Parser {
    fn peek(&self) -> Result<char> {
        try!(self.eof());
        Ok(self.data[self.position])
    }

    fn get(&mut self) -> Result<char> {
        try!(self.eof());
        let c = self.data[self.position];
        self.position += 1;
        if c == '\n' {
            self.line += 1;
            self.line_position = 0;
        }
        Ok(c)
    }

    fn eat(&mut self) -> Result<()> {
        let _:char = try!(self.get());
        Ok(())
    }

    fn eof(&self) -> Result<()> {
        if self.position >= self.data.len() {
            try!(self.parse_error("end of file reached").into())
        }
        Ok(())
    }

    fn parse_error<T>(&self, msg:&str) -> Result<T> {
        parse_error(self.line, self.line_position, msg.to_string())
    }
}

/// parse a &str to a symbolic-expression
pub fn parse_str(sexp: &str) -> Result<Sexp> {
    if sexp.is_empty() {
        return Ok(Sexp::new_empty());
    }
    let mut parser = Parser::default();
    parser.data = sexp.chars().collect();
    parse(&mut parser)
}

fn parse(parser:&mut Parser) -> Result<Sexp> {
    try!(eat_space(parser));
    // TODO
    Ok(Sexp::new_empty())
}

fn eat_space(parser:&mut Parser) -> Result<()> {
    loop {
        let c = try!(parser.peek());
        if c == ' ' || c == '\t' {
            try!(parser.eat());
            continue
        }
        break
    }
    Ok(())
}
<|endoftext|>


<commit_before>// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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.

//! Private functions and items to be used with the high-level library wrapper.

use std::cast;
use std::hashmap::*;
use std::libc::*;
use std::local_data;
use std::ptr;
use std::str;

use super::*;

///
/// Holds the callback functions associated with a window
///
pub struct WindowData {
    pos_fun:                Option<WindowPosFun>,
    size_fun:               Option<WindowSizeFun>,
    close_fun:              Option<WindowCloseFun>,
    refresh_fun:            Option<WindowRefreshFun>,
    focus_fun:              Option<WindowFocusFun>,
    iconify_fun:            Option<WindowIconifyFun>,
    framebuffer_size_fun:   Option<FramebufferSizeFun>,
    mouse_button_fun:       Option<MouseButtonFun>,
    cursor_pos_fun:         Option<CursorPosFun>,
    cursor_enter_fun:       Option<CursorEnterFun>,
    scroll_fun:             Option<ScrollFun>,
    key_fun:                Option<KeyFun>,
    char_fun:               Option<CharFun>,
}

impl WindowData {
    /// Initialize the struct with all callbacks set to `None`.
    pub fn new() -> WindowData {
        WindowData {
            pos_fun:                None,
            size_fun:               None,
            close_fun:              None,
            refresh_fun:            None,
            focus_fun:              None,
            iconify_fun:            None,
            framebuffer_size_fun:   None,
            mouse_button_fun:       None,
            cursor_pos_fun:         None,
            cursor_enter_fun:       None,
            scroll_fun:             None,
            key_fun:                None,
            char_fun:               None,
        }
    }
}

///
/// A map of window data to be stored in task-local storage.
///
pub struct WindowDataMap(HashMap<*ffi::GLFWwindow, @mut WindowData>);

impl WindowDataMap {
    /// Function stub used for retrieving a the map of window data from
    /// task-local storage.
    priv fn tls_key(_: @@mut WindowDataMap) {}

    /// Initializes a map of window data in task-local storage.
    pub fn init() {
        unsafe {
            local_data::set(
                WindowDataMap::tls_key,
                @@mut WindowDataMap(HashMap::new())
            )
        }
    }

    /// Retrieves a mutable pointer to the map of window data stored task-local
    /// storage, failing if the map could not be found.
    pub fn get() -> @mut WindowDataMap {
      unsafe {
        do local_data::get(WindowDataMap::tls_key) |data|
        {
          match data
          {
            Some(&@local_data) => local_data,
            None => fail!("Could not find a WindowDataMap in thread-local storage."),
          }
        }
      }
    }

    /// Clears all external callbacks and removes the window from the map.
    /// Returns `true` if the window was present in the map, otherwise `false`.
    pub fn remove(&mut self, window: &*ffi::GLFWwindow) -> bool {
        do self.pop(window).map |&data| {
            unsafe {
                // Clear all external callbacks
                data.pos_fun.map                (|_| ffi::glfwSetWindowPosCallback(*window, ptr::null()));
                data.size_fun.map               (|_| ffi::glfwSetWindowSizeCallback(*window, ptr::null()));
                data.close_fun.map              (|_| ffi::glfwSetWindowCloseCallback(*window, ptr::null()));
                data.refresh_fun.map            (|_| ffi::glfwSetWindowRefreshCallback(*window, ptr::null()));
                data.focus_fun.map              (|_| ffi::glfwSetWindowFocusCallback(*window, ptr::null()));
                data.iconify_fun.map            (|_| ffi::glfwSetWindowIconifyCallback(*window, ptr::null()));
                data.framebuffer_size_fun.map   (|_| ffi::glfwSetFramebufferSizeCallback(*window, ptr::null()));
                data.mouse_button_fun.map       (|_| ffi::glfwSetMouseButtonCallback(*window, ptr::null()));
                data.cursor_pos_fun.map         (|_| ffi::glfwSetCursorPosCallback(*window, ptr::null()));
                data.cursor_enter_fun.map       (|_| ffi::glfwSetCursorEnterCallback(*window, ptr::null()));
                data.scroll_fun.map             (|_| ffi::glfwSetScrollCallback(*window, ptr::null()));
                data.key_fun.map                (|_| ffi::glfwSetKeyCallback(*window, ptr::null()));
                data.char_fun.map               (|_| ffi::glfwSetCharCallback(*window, ptr::null()));
            }
        }.is_some()
    }
}

// Global callbacks

fn error_fun_tls_key(_: @ErrorFun) {}

pub extern "C" fn error_callback(error: c_int, description: *c_char) {
    unsafe {
        do local_data::get(error_fun_tls_key) |data|
        {
          do data.map |& &@cb| {
            cb(error, str::raw::from_c_str(description))
          };
        }
    }
}

pub fn set_error_fun(cbfun: ErrorFun, f: &fn(ffi::GLFWerrorfun) ) {
    unsafe {
        local_data::set(error_fun_tls_key, @cbfun);
        f(error_callback);
    }
}

fn monitor_fun_tls_key(_: @MonitorFun) {}

pub extern "C" fn monitor_callback(monitor: *ffi::GLFWmonitor, event: c_int) {
    unsafe {
        do local_data::get(monitor_fun_tls_key) |data|
        {
          do data.map |& &@cb| {
            cb(&Monitor { ptr: monitor }, event)
          };
        }
    }
}

pub fn set_monitor_fun(cbfun: MonitorFun, f: &fn(ffi::GLFWmonitorfun) ) {
    unsafe {
        local_data::set(monitor_fun_tls_key, @cbfun);
        f(monitor_callback);
    }
}

// External window callbacks

macro_rules! window_callback(
    (fn $name:ident () => $field:ident()) => (
        pub extern "C" fn $name(window: *ffi::GLFWwindow) {
            let window_ = Window { ptr: window };
            do window_.get_local_data().$field.map |&cb| {
                cb(&window_)
            };
            unsafe { cast::forget(window_); }
        }
    );
    (fn $name:ident ($($ext_arg:ident: $ext_arg_ty:ty),*) => $field:ident($($arg_conv:expr),*)) => (
        pub extern "C" fn $name(window: *ffi::GLFWwindow $(, $ext_arg: $ext_arg_ty)*) {
            let window_ = Window { ptr: window };
            do window_.get_local_data().$field.map |&cb| {
                cb(&window_ $(, $arg_conv)*)
            };
            unsafe { cast::forget(window_); }
        }
    );
)

window_callback!(fn window_pos_callback(xpos: c_int, ypos: c_int)                           => pos_fun(xpos as int, ypos as int))
window_callback!(fn window_size_callback(width: c_int, height: c_int)                       => size_fun(width as int, height as int))
window_callback!(fn window_close_callback()                                                 => close_fun())
window_callback!(fn window_refresh_callback()                                               => refresh_fun())
window_callback!(fn window_focus_callback(focused: c_int)                                   => focus_fun(focused as bool))
window_callback!(fn window_iconify_callback(iconified: c_int)                               => iconify_fun(iconified as bool))
window_callback!(fn framebuffer_size_callback(width: c_int, height: c_int)                  => framebuffer_size_fun(width as int, height as int))
window_callback!(fn mouse_button_callback(button: c_int, action: c_int, mods: c_int)        => mouse_button_fun(button, action, mods))
window_callback!(fn cursor_pos_callback(xpos: c_double, ypos: c_double)                     => cursor_pos_fun(xpos as float, ypos as float))
window_callback!(fn cursor_enter_callback(entered: c_int)                                   => cursor_enter_fun(entered as bool))
window_callback!(fn scroll_callback(xpos: c_double, ypos: c_double)                         => scroll_fun(xpos as float, ypos as float))
window_callback!(fn key_callback(key: c_int, scancode: c_int, action: c_int, mods: c_int)   => key_fun(key, scancode, action, mods))
window_callback!(fn char_callback(character: c_uint)                                        => char_fun(character as char))
<commit_msg>Fixes to work with the new TLS api.<commit_after>// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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.

//! Private functions and items to be used with the high-level library wrapper.

use std::cast;
use std::hashmap::*;
use std::libc::*;
use std::local_data;
use std::ptr;
use std::str;

use super::*;

///
/// Holds the callback functions associated with a window
///
pub struct WindowData {
    pos_fun:                Option<WindowPosFun>,
    size_fun:               Option<WindowSizeFun>,
    close_fun:              Option<WindowCloseFun>,
    refresh_fun:            Option<WindowRefreshFun>,
    focus_fun:              Option<WindowFocusFun>,
    iconify_fun:            Option<WindowIconifyFun>,
    framebuffer_size_fun:   Option<FramebufferSizeFun>,
    mouse_button_fun:       Option<MouseButtonFun>,
    cursor_pos_fun:         Option<CursorPosFun>,
    cursor_enter_fun:       Option<CursorEnterFun>,
    scroll_fun:             Option<ScrollFun>,
    key_fun:                Option<KeyFun>,
    char_fun:               Option<CharFun>,
}

impl WindowData {
    /// Initialize the struct with all callbacks set to `None`.
    pub fn new() -> WindowData {
        WindowData {
            pos_fun:                None,
            size_fun:               None,
            close_fun:              None,
            refresh_fun:            None,
            focus_fun:              None,
            iconify_fun:            None,
            framebuffer_size_fun:   None,
            mouse_button_fun:       None,
            cursor_pos_fun:         None,
            cursor_enter_fun:       None,
            scroll_fun:             None,
            key_fun:                None,
            char_fun:               None,
        }
    }
}

///
/// A map of window data to be stored in task-local storage.
///
pub struct WindowDataMap(HashMap<*ffi::GLFWwindow, @mut WindowData>);

/// Key used for retrieving the map of window data from
/// task-local storage.
static tls_key: local_data::Key<@@mut WindowDataMap> = &local_data::Key;

impl WindowDataMap {
    /// Initializes a map of window data in task-local storage.
    pub fn init() {
        local_data::set(
            tls_key,
            @@mut WindowDataMap(HashMap::new())
        )
    }

    /// Retrieves a mutable pointer to the map of window data stored task-local
    /// storage, failing if the map could not be found.
    pub fn get() -> @mut WindowDataMap {
        do local_data::get(tls_key) |data|
        {
          match data
          {
            Some(&@local_data) => local_data,
            None => fail!("Could not find a WindowDataMap in thread-local storage."),
          }
        }
    }

    /// Clears all external callbacks and removes the window from the map.
    /// Returns `true` if the window was present in the map, otherwise `false`.
    pub fn remove(&mut self, window: &*ffi::GLFWwindow) -> bool {
        do self.pop(window).map |&data| {
            unsafe {
                // Clear all external callbacks
                data.pos_fun.map                (|_| ffi::glfwSetWindowPosCallback(*window, ptr::null()));
                data.size_fun.map               (|_| ffi::glfwSetWindowSizeCallback(*window, ptr::null()));
                data.close_fun.map              (|_| ffi::glfwSetWindowCloseCallback(*window, ptr::null()));
                data.refresh_fun.map            (|_| ffi::glfwSetWindowRefreshCallback(*window, ptr::null()));
                data.focus_fun.map              (|_| ffi::glfwSetWindowFocusCallback(*window, ptr::null()));
                data.iconify_fun.map            (|_| ffi::glfwSetWindowIconifyCallback(*window, ptr::null()));
                data.framebuffer_size_fun.map   (|_| ffi::glfwSetFramebufferSizeCallback(*window, ptr::null()));
                data.mouse_button_fun.map       (|_| ffi::glfwSetMouseButtonCallback(*window, ptr::null()));
                data.cursor_pos_fun.map         (|_| ffi::glfwSetCursorPosCallback(*window, ptr::null()));
                data.cursor_enter_fun.map       (|_| ffi::glfwSetCursorEnterCallback(*window, ptr::null()));
                data.scroll_fun.map             (|_| ffi::glfwSetScrollCallback(*window, ptr::null()));
                data.key_fun.map                (|_| ffi::glfwSetKeyCallback(*window, ptr::null()));
                data.char_fun.map               (|_| ffi::glfwSetCharCallback(*window, ptr::null()));
            }
        }.is_some()
    }
}

// Global callbacks

static error_fun_tls_key: local_data::Key<@ErrorFun> = &local_data::Key;

pub extern "C" fn error_callback(error: c_int, description: *c_char) {
    unsafe {
        do local_data::get(error_fun_tls_key) |data|
        {
          do data.map |& &@cb| {
            cb(error, str::raw::from_c_str(description))
          };
        }
    }
}

pub fn set_error_fun(cbfun: ErrorFun, f: &fn(ffi::GLFWerrorfun) ) {
    local_data::set(error_fun_tls_key, @cbfun);
    f(error_callback);
}

static monitor_fun_tls_key: local_data::Key<@MonitorFun> = &local_data::Key;

pub extern "C" fn monitor_callback(monitor: *ffi::GLFWmonitor, event: c_int) {
    do local_data::get(monitor_fun_tls_key) |data|
    {
      do data.map |& &@cb| {
        cb(&Monitor { ptr: monitor }, event)
      };
    }
}

pub fn set_monitor_fun(cbfun: MonitorFun, f: &fn(ffi::GLFWmonitorfun) ) {
    local_data::set(monitor_fun_tls_key, @cbfun);
    f(monitor_callback);
}

// External window callbacks

macro_rules! window_callback(
    (fn $name:ident () => $field:ident()) => (
        pub extern "C" fn $name(window: *ffi::GLFWwindow) {
            let window_ = Window { ptr: window };
            do window_.get_local_data().$field.map |&cb| {
                cb(&window_)
            };
            unsafe { cast::forget(window_); }
        }
    );
    (fn $name:ident ($($ext_arg:ident: $ext_arg_ty:ty),*) => $field:ident($($arg_conv:expr),*)) => (
        pub extern "C" fn $name(window: *ffi::GLFWwindow $(, $ext_arg: $ext_arg_ty)*) {
            let window_ = Window { ptr: window };
            do window_.get_local_data().$field.map |&cb| {
                cb(&window_ $(, $arg_conv)*)
            };
            unsafe { cast::forget(window_); }
        }
    );
)

window_callback!(fn window_pos_callback(xpos: c_int, ypos: c_int)                           => pos_fun(xpos as int, ypos as int))
window_callback!(fn window_size_callback(width: c_int, height: c_int)                       => size_fun(width as int, height as int))
window_callback!(fn window_close_callback()                                                 => close_fun())
window_callback!(fn window_refresh_callback()                                               => refresh_fun())
window_callback!(fn window_focus_callback(focused: c_int)                                   => focus_fun(focused as bool))
window_callback!(fn window_iconify_callback(iconified: c_int)                               => iconify_fun(iconified as bool))
window_callback!(fn framebuffer_size_callback(width: c_int, height: c_int)                  => framebuffer_size_fun(width as int, height as int))
window_callback!(fn mouse_button_callback(button: c_int, action: c_int, mods: c_int)        => mouse_button_fun(button, action, mods))
window_callback!(fn cursor_pos_callback(xpos: c_double, ypos: c_double)                     => cursor_pos_fun(xpos as float, ypos as float))
window_callback!(fn cursor_enter_callback(entered: c_int)                                   => cursor_enter_fun(entered as bool))
window_callback!(fn scroll_callback(xpos: c_double, ypos: c_double)                         => scroll_fun(xpos as float, ypos as float))
window_callback!(fn key_callback(key: c_int, scancode: c_int, action: c_int, mods: c_int)   => key_fun(key, scancode, action, mods))
window_callback!(fn char_callback(character: c_uint)                                        => char_fun(character as char))
<|endoftext|>


<commit_before><commit_msg>Making GetCart multithreaded<commit_after><|endoftext|>


<commit_before><commit_msg>Implement obj group tracking<commit_after><|endoftext|>


<commit_before><commit_msg>sensors: cleanup help documentation for sensors example<commit_after><|endoftext|>


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


<commit_before><commit_msg>Add HTTPS example.<commit_after>// This requires running with:
//
// ```bash
// cargo run --example https --features ssl
// ```
//
// Generate a key and certificate like so:
//
// ```bash
// openssl genrsa -out localhost.key 4096
// openssl req -key localhost.key -x509 -new -days 3650 -out localhost.crt
// ```

extern crate iron;

#[cfg(feature = "ssl")]
fn main() {
    // Avoid unused errors due to conditional compilation ('ssl' feature is not default)
    use iron::status;
    use iron::{Iron, Request, Response};
    use std::path::{Path};
    use std::result::{Result};

    // openssl genrsa -out localhost.key 4096
    let key = Path::new("localhost.key").to_path_buf();
    // openssl req -key localhost.key -x509 -new -days 3650 -out localhost.crt
    let cert = Path::new("localhost.crt").to_path_buf();

    match Iron::new(|_: &mut Request| {
        Ok(Response::with((status::Ok, "Hello world!")))
    }).https("127.0.0.1:3000", cert, key) {
        Result::Ok(listening) => println!("{:?}", listening),
        Result::Err(err) => println!("{:?}", err),
    }
    // curl -vvvv https://127.0.0.1:3000/ -k
}

#[cfg(not(feature = "ssl"))]
fn main() {
    // We need to do this to make sure `cargo test` passes.
}
<|endoftext|>


<commit_before><commit_msg>Horizontally center layout elements<commit_after><|endoftext|>


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

enum E {
    S0 { s: ~str },
    S1 { u: uint }
}

const C: E = S1 { u: 23 };

fn main() {
    match C {
        S0 { _ } => fail!(),
        S1 { u } => assert u == 23
    }
}
<|endoftext|>


<commit_before><commit_msg>Test exploring the interactions between all of the different kinds of method collisions I could imagine.<commit_after>// ignore-tidy-linelength

// run-pass

// There are five cfg's below. I explored the set of all non-empty combinations
// of the below five cfg's, which is 2^5 - 1 = 31 combinations.
//
// Of the 31, 11 resulted in ambiguous method resolutions; while it may be good
// to have a test for all of the eleven variations of that error, I am not sure
// this particular test is the best way to encode it. So they are skipped in
// this revisions list (but not in the expansion mapping the binary encoding to
// the corresponding cfg flags).
//
// Notable, here are the cases that will be incompatible if something does not override them first:
// {bar_for_foo, valbar_for_et_foo}: these are higher precedent than the `&mut self` method on `Foo`, and so no case matching bx1x1x is included.
// {mutbar_for_foo, valbar_for_etmut_foo} (which are lower precedent than the inherent `&mut self` method on `Foo`; e.g. b10101 *is* included.

// revisions: b00001 b00010 b00011 b00100 b00101 b00110 b00111 b01000 b01001 b01100 b01101 b10000 b10001 b10010 b10011 b10101 b10111 b11000 b11001 b11101

//[b00001]compile-flags:  --cfg inherent_mut
//[b00010]compile-flags:                     --cfg bar_for_foo
//[b00011]compile-flags:  --cfg inherent_mut --cfg bar_for_foo
//[b00100]compile-flags:                                       --cfg mutbar_for_foo
//[b00101]compile-flags:  --cfg inherent_mut                   --cfg mutbar_for_foo
//[b00110]compile-flags:                     --cfg bar_for_foo --cfg mutbar_for_foo
//[b00111]compile-flags:  --cfg inherent_mut --cfg bar_for_foo --cfg mutbar_for_foo
//[b01000]compile-flags:                                                            --cfg valbar_for_et_foo
//[b01001]compile-flags:  --cfg inherent_mut                                        --cfg valbar_for_et_foo
//[b01010]compile-flags:                     --cfg bar_for_foo                      --cfg valbar_for_et_foo
//[b01011]compile-flags:  --cfg inherent_mut --cfg bar_for_foo                      --cfg valbar_for_et_foo
//[b01100]compile-flags:                                       --cfg mutbar_for_foo --cfg valbar_for_et_foo
//[b01101]compile-flags:  --cfg inherent_mut                   --cfg mutbar_for_foo --cfg valbar_for_et_foo
//[b01110]compile-flags:                     --cfg bar_for_foo --cfg mutbar_for_foo --cfg valbar_for_et_foo
//[b01111]compile-flags:  --cfg inherent_mut --cfg bar_for_foo --cfg mutbar_for_foo --cfg valbar_for_et_foo
//[b10000]compile-flags:                                                                                --cfg valbar_for_etmut_foo
//[b10001]compile-flags:  --cfg inherent_mut                                                                --cfg valbar_for_etmut_foo
//[b10010]compile-flags:                     --cfg bar_for_foo                                              --cfg valbar_for_etmut_foo
//[b10011]compile-flags:  --cfg inherent_mut --cfg bar_for_foo                                              --cfg valbar_for_etmut_foo
//[b10100]compile-flags:                                       --cfg mutbar_for_foo                         --cfg valbar_for_etmut_foo
//[b10101]compile-flags:  --cfg inherent_mut                   --cfg mutbar_for_foo                         --cfg valbar_for_etmut_foo
//[b10110]compile-flags:                     --cfg bar_for_foo --cfg mutbar_for_foo                         --cfg valbar_for_etmut_foo
//[b10111]compile-flags:  --cfg inherent_mut --cfg bar_for_foo --cfg mutbar_for_foo                         --cfg valbar_for_etmut_foo
//[b11000]compile-flags:                                                            --cfg valbar_for_et_foo --cfg valbar_for_etmut_foo
//[b11001]compile-flags:  --cfg inherent_mut                                        --cfg valbar_for_et_foo --cfg valbar_for_etmut_foo
//[b11010]compile-flags:                     --cfg bar_for_foo                      --cfg valbar_for_et_foo --cfg valbar_for_etmut_foo
//[b11011]compile-flags:  --cfg inherent_mut --cfg bar_for_foo                      --cfg valbar_for_et_foo --cfg valbar_for_etmut_foo
//[b11100]compile-flags:                                       --cfg mutbar_for_foo --cfg valbar_for_et_foo --cfg valbar_for_etmut_foo
//[b11101]compile-flags:  --cfg inherent_mut                   --cfg mutbar_for_foo --cfg valbar_for_et_foo --cfg valbar_for_etmut_foo
//[b11110]compile-flags:                     --cfg bar_for_foo --cfg mutbar_for_foo --cfg valbar_for_et_foo --cfg valbar_for_etmut_foo
//[b11111]compile-flags:  --cfg inherent_mut --cfg bar_for_foo --cfg mutbar_for_foo --cfg valbar_for_et_foo --cfg valbar_for_etmut_foo

struct Foo {}

type S = &'static str;

trait Bar {
    fn bar(&self, _: &str) -> S;
}

trait MutBar {
    fn bar(&mut self, _: &str) -> S;
}

trait ValBar {
    fn bar(self, _: &str) -> S;
}

#[cfg(inherent_mut)]
impl Foo {
    fn bar(&mut self, _: &str) -> S {
        "In struct impl!"
    }
}

#[cfg(bar_for_foo)]
impl Bar for Foo {
    fn bar(&self, _: &str) -> S {
        "In trait &self impl!"
    }
}

#[cfg(mutbar_for_foo)]
impl MutBar for Foo {
    fn bar(&mut self, _: &str) -> S {
        "In trait &mut self impl!"
    }
}

#[cfg(valbar_for_et_foo)]
impl ValBar for &Foo {
    fn bar(self, _: &str) -> S {
        "In trait self impl for &Foo!"
    }
}

#[cfg(valbar_for_etmut_foo)]
impl ValBar for &mut Foo {
    fn bar(self, _: &str) -> S {
        "In trait self impl for &mut Foo!"
    }
}

fn main() {
    #![allow(unused_mut)] // some of the impls above will want it.

    #![allow(unreachable_patterns)] // the cfg-coding pattern below generates unreachable patterns.

    {
        macro_rules! all_variants_on_value {
            ($e:expr) => {
                match $e {
                    #[cfg(bar_for_foo)]
                    x => assert_eq!(x, "In trait &self impl!"),

                    #[cfg(valbar_for_et_foo)]
                    x => assert_eq!(x, "In trait self impl for &Foo!"),

                    #[cfg(inherent_mut)]
                    x => assert_eq!(x, "In struct impl!"),

                    #[cfg(mutbar_for_foo)]
                    x => assert_eq!(x, "In trait &mut self impl!"),

                    #[cfg(valbar_for_etmut_foo)]
                    x => assert_eq!(x, "In trait self impl for &mut Foo!"),
                }
            }
        }

        let mut f = Foo {};
        all_variants_on_value!(f.bar("f.bar"));

        let f_mr = &mut Foo {};
        all_variants_on_value!((*f_mr).bar("(*f_mr).bar"));
    }

    // This is sort of interesting: `&mut Foo` ends up with a significantly
    // different resolution order than what was devised above. Presumably this
    // is because we can get to a `&self` method by first a deref of the given
    // `&mut Foo` and then an autoref, and that is a longer path than a mere
    // auto-ref of a `Foo`.

    {
        let f_mr = &mut Foo {};

        match f_mr.bar("f_mr.bar") {
            #[cfg(inherent_mut)]
            x => assert_eq!(x, "In struct impl!"),

            #[cfg(valbar_for_etmut_foo)]
            x => assert_eq!(x, "In trait self impl for &mut Foo!"),

            #[cfg(mutbar_for_foo)]
            x => assert_eq!(x, "In trait &mut self impl!"),

            #[cfg(valbar_for_et_foo)]
            x => assert_eq!(x, "In trait self impl for &Foo!"),

            #[cfg(bar_for_foo)]
            x => assert_eq!(x, "In trait &self impl!"),
        }
    }

    // Note that this isn't actually testing a resolution order; if both of these are
    // enabled, it yields an ambiguous method resolution error. The test tries to embed
    // that fact by testing *both* orders (and so the only way that can be right is if
    // they are not actually compatible).
    #[cfg(any(bar_for_foo, valbar_for_et_foo))]
    {
        let f_r = &Foo {};

        match f_r.bar("f_r.bar") {
            #[cfg(bar_for_foo)]
            x => assert_eq!(x, "In trait &self impl!"),

            #[cfg(valbar_for_et_foo)]
            x => assert_eq!(x, "In trait self impl for &Foo!"),
        }

        match f_r.bar("f_r.bar") {
            #[cfg(valbar_for_et_foo)]
            x => assert_eq!(x, "In trait self impl for &Foo!"),

            #[cfg(bar_for_foo)]
            x => assert_eq!(x, "In trait &self impl!"),
        }
    }

}
<|endoftext|>


<commit_before>use std::cell::RefCell;
use std::iter::Iterator;
use std::rc::Rc;
use std::ops::Deref;

use storage::file::File;

pub trait FilePrinter {

    fn new(verbose: bool, debug: bool) -> Self;

    /*
     * Print a single file
     */
    fn print_file(&self, Rc<RefCell<File>>);

    /*
     * Print a list of files
     */
    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        for file in files {
            self.print_file(file);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> String
    {
        info!("{}", f(file));
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> String
    {
        for file in files {
            self.print_file_custom(file, f);
        }
    }

}

struct DebugPrinter {
    debug: bool,
}

impl FilePrinter for DebugPrinter {

    fn new(_: bool, debug: bool) -> DebugPrinter {
        DebugPrinter {
            debug: debug,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> String
    {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f(file));
        }
    }

}

struct SimplePrinter {
    verbose:    bool,
    debug:      bool,
}

impl FilePrinter for SimplePrinter {

    fn new(verbose: bool, debug: bool) -> SimplePrinter {
        SimplePrinter {
            debug:      debug,
            verbose:    verbose,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("{:?}", f);
        } else if self.verbose {
            info!("{}", &*f.deref().borrow());
        } else {
            info!("[File]: {}", f.deref().borrow().id());
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> String
    {
        let s = f(file);
        if self.debug {
            debug!("{:?}", s);
        } else if self.verbose {
            info!("{}", s);
        } else {
            info!("[File]: {}", s);
        }
    }

}

pub struct TablePrinter {
    verbose:    bool,
    debug:      bool,
    sp:         SimplePrinter,
}

impl FilePrinter for TablePrinter {

    fn new(verbose: bool, debug: bool) -> TablePrinter {
        TablePrinter {
            debug:      debug,
            verbose:    verbose,
            sp:         SimplePrinter::new(verbose, debug),
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        self.sp.print_file(f);
    }

    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID"];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);
            let row = Row::new(vec![cell_i, cell_o, cell_id]);
            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

}
<commit_msg>Impl FilePrinter for TablePrinter ::print_files_custom()<commit_after>use std::cell::RefCell;
use std::iter::Iterator;
use std::rc::Rc;
use std::ops::Deref;

use storage::file::File;

pub trait FilePrinter {

    fn new(verbose: bool, debug: bool) -> Self;

    /*
     * Print a single file
     */
    fn print_file(&self, Rc<RefCell<File>>);

    /*
     * Print a list of files
     */
    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        for file in files {
            self.print_file(file);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> String
    {
        info!("{}", f(file));
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> String
    {
        for file in files {
            self.print_file_custom(file, f);
        }
    }

}

struct DebugPrinter {
    debug: bool,
}

impl FilePrinter for DebugPrinter {

    fn new(_: bool, debug: bool) -> DebugPrinter {
        DebugPrinter {
            debug: debug,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> String
    {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f(file));
        }
    }

}

struct SimplePrinter {
    verbose:    bool,
    debug:      bool,
}

impl FilePrinter for SimplePrinter {

    fn new(verbose: bool, debug: bool) -> SimplePrinter {
        SimplePrinter {
            debug:      debug,
            verbose:    verbose,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("{:?}", f);
        } else if self.verbose {
            info!("{}", &*f.deref().borrow());
        } else {
            info!("[File]: {}", f.deref().borrow().id());
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> String
    {
        let s = f(file);
        if self.debug {
            debug!("{:?}", s);
        } else if self.verbose {
            info!("{}", s);
        } else {
            info!("[File]: {}", s);
        }
    }

}

pub struct TablePrinter {
    verbose:    bool,
    debug:      bool,
    sp:         SimplePrinter,
}

impl FilePrinter for TablePrinter {

    fn new(verbose: bool, debug: bool) -> TablePrinter {
        TablePrinter {
            debug:      debug,
            verbose:    verbose,
            sp:         SimplePrinter::new(verbose, debug),
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        self.sp.print_file(f);
    }

    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID"];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);
            let row = Row::new(vec![cell_i, cell_o, cell_id]);
            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> String
    {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID", "..."];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);

            let cell_extra = Cell::new(&f(file)[..]);

            let row = Row::new(vec![cell_i, cell_o, cell_id, cell_extra]);
            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>refactor<commit_after><|endoftext|>


<commit_before><commit_msg>11 - functions<commit_after>// Unlike C/C++, there's no restriction on the order of function definitions
fn main() {
    // We can use this function here, and define it somewhere later
    fizzbuzz_to(100);
}

// Function that returns a boolean value
fn is_divisible_by(lhs: uint, rhs: uint) -> bool {
    // Corner case, early return
    if rhs == 0 {
        return false;
    }

    // This is an expression, the `return` keyword is not necessary here
    lhs % rhs == 0
}

// Functions that "don't" return a value, actually return the unit type `()`
fn fizzbuzz(n: uint) -> () {
    if is_divisible_by(n, 15) {
        println!("fizzbuzz");
    } else if is_divisible_by(n, 3) {
        println!("fizz");
    } else if is_divisible_by(n, 5) {
        println!("buzz");
    } else {
        println!("{}", n);
    }
}

// When a function returns `()`, the return type can be omitted from the
// signature
fn fizzbuzz_to(n: uint) {
    for n in range(1, n + 1) {
        fizzbuzz(n);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add ICH test case for statics<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.

// This test case tests the incremental compilation hash (ICH) implementation
// for statics.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

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

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

// Change static visibility ---------------------------------------------------
#[cfg(cfail1)]
static STATIC_VISIBILITY: u8 = 0;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub static STATIC_VISIBILITY: u8 = 0;

// Change static mutability ---------------------------------------------------
#[cfg(cfail1)]
static STATIC_MUTABILITY: u8 = 0;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
static mut STATIC_MUTABILITY: u8 = 0;

// Add linkage attribute ------------------------------------------------------
#[cfg(cfail1)]
static STATIC_LINKAGE: u8 = 0;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[linkage="weak_odr"]
static STATIC_LINKAGE: u8 = 0;

// Add no_mangle attribute ----------------------------------------------------
#[cfg(cfail1)]
static STATIC_NO_MANGLE: u8 = 0;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[no_mangle]
static STATIC_NO_MANGLE: u8 = 0;

// Add thread_local attribute -------------------------------------------------
#[cfg(cfail1)]
static STATIC_THREAD_LOCAL: u8 = 0;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[thread_local]
static STATIC_THREAD_LOCAL: u8 = 0;

// Change type from i16 to u64 ------------------------------------------------
#[cfg(cfail1)]
static STATIC_CHANGE_TYPE_1: i16 = 0;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
static STATIC_CHANGE_TYPE_1: u64 = 0;

// Change type from Option<i8> to Option<u16> ---------------------------------
#[cfg(cfail1)]
static STATIC_CHANGE_TYPE_2: Option<i8> = None;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
static STATIC_CHANGE_TYPE_2: Option<u16> = None;

// Change value between simple literals ---------------------------------------
#[cfg(cfail1)]
static STATIC_CHANGE_VALUE_1: i16 = 1;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
static STATIC_CHANGE_VALUE_1: i16 = 2;

// Change value between expressions -------------------------------------------
#[cfg(cfail1)]
static STATIC_CHANGE_VALUE_2: i16 = 1 + 1;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
static STATIC_CHANGE_VALUE_2: i16 = 1 + 2;

#[cfg(cfail1)]
static STATIC_CHANGE_VALUE_3: i16 = 2 + 3;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
static STATIC_CHANGE_VALUE_3: i16 = 2 * 3;

#[cfg(cfail1)]
static STATIC_CHANGE_VALUE_4: i16 = 1 + 2 * 3;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
static STATIC_CHANGE_VALUE_4: i16 = 1 + 2 * 4;

// Change type indirectly -----------------------------------------------------
struct ReferencedType1;
struct ReferencedType2;

mod static_change_type_indirectly {
    #[cfg(cfail1)]
    use super::ReferencedType1 as Type;

    #[cfg(not(cfail1))]
    use super::ReferencedType2 as Type;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    static STATIC_CHANGE_TYPE_INDIRECTLY_1: Type = Type;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    static STATIC_CHANGE_TYPE_INDIRECTLY_2: Option<Type> = None;
}
<|endoftext|>


<commit_before><commit_msg>Don't use experimental slicing_syntax feature<commit_after><|endoftext|>


<commit_before><commit_msg>Factor custom flags management to one function<commit_after><|endoftext|>


<commit_before><commit_msg>Create a persistent singly linked list data structure (initial attempt)<commit_after>
// language: Rust master branch

use persistent::list::List;

pub mod persistent {
pub mod list {

// Is reference-counting the best choice for the shared immutable data?
use std::rc::Rc;

// Rc's Eq/Ord compares the contained data, not the pointer.
#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd)]
pub struct List<T> {
  priv node : Rc<Node<T>>
}

#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd)]
pub enum Node<T> {
  Nil,
  Cons(T, List<T>)
}

impl<'self, T> Iterator<&'self T> for &'self List<T> {
  fn next(&mut self) -> Option<&'self T> {
    match *self.node.borrow() {
      Nil => None,
      Cons(ref x, ref xs) => {
        *self = xs;
        Some(x)
      }
    }
  }
}

impl<T> List<T> {
  pub fn iter<'t>(&'t self) -> &'t List<T> {
    self
  }
  pub fn node<'t>(&'t self) -> &'t Node<T> {
    self.node.borrow()
  }
}

// Ought Freeze really be required for members of persistent lists?
// Generally, yes, because there's shared data; but what if you want
// a list of Cells or RefCells that deliberately have shared mutable identity?
// Freeze is forced by Rc.
impl<T: Freeze> List<T> {
  pub fn new(node: Node<T>) -> List<T> {
    List{node: Rc::new(node)}
  }
  pub fn nil() -> List<T> {
    List::new(Nil)
  }
  pub fn cons(x:T, xs:List<T>) -> List<T> {
    List::new(Cons(x, xs))
  }
}
impl<T: Clone+Freeze> List<T> {
  fn reverse_impl(&self, acc : List<T>) -> List<T> {
    match *self.node.borrow() {
      Nil => acc,
      Cons(ref x, ref xs) => xs.reverse_impl(List::cons(x.clone(), acc))
    }
  }
  pub fn reverse(&self) -> List<T> {
    self.reverse_impl(List::nil())
  }
}

impl<T> Container for List<T> {
  fn len(&self) -> uint {
    let mut result = 0;
    for _ in self.iter() { result += 1; }
    result
  }
  fn is_empty(&self) -> bool {
    match *self.node.borrow() {
      Nil => true,
      Cons(_, _) => false
    }
  }
}

impl<T: Freeze> Default for List<T> {
  fn default() -> List<T> {
    List::nil()
  }
}

/* Does this even make sense for an immutable container?
impl<A> Extendable<A> for List<A> {
  fn extend<T: Iterator<A>>(&mut self, iter: &mut T) {
  }
}
*/

impl<A: Freeze> FromIterator<A> for List<A> {
  // Is it possible to write this function without a
  // stack (implicit via recursion, or explicit),
  // and without 'unsafe' code?
  fn from_iterator<T: Iterator<A>>(iter: &mut T) -> List<A> {
    match iter.next() {
      None => List::nil(),
      Some(a) => List::cons(a, FromIterator::from_iterator(iter))
    }
  }
}

#[cfg(test)]
mod test {
use super::List;
//use std::cell::RefCell;
#[test]
fn test() {
  let p0 = List::nil();
  let p1 : List<int> = List::cons(1, p0.clone());
  let p2a = List::cons(2, p1.clone());
  let p2b = List::cons(2, p1.clone());
  let p2c = List::cons(3, p1.clone());
  assert!(p0 == p0);
  assert!(p1 == p1);
  assert!(p0 != p1);
  assert!(p2a == p2b);
  assert!(p2a < p2c);
  assert!(p1 < p2c);
  assert!(p0 == p0.reverse());
  assert!(p1 == p1.reverse());
  assert!(p2a > p2a.reverse());
  assert!(p2a == p2a.reverse().reverse());
  let mut sum = 0;
  for i in p2c.iter() {
    sum += *i;
  }
  assert!(sum == 4);
  let seq = ~[1,3,2]; //why did I have to allocate here in order to get .move_iter()?
  let mut digits = 0;
  let seql : List<int> = seq.move_iter().collect();
  for i in seql.iter() {
    digits = digits * 10 + *i;
  }
  assert!(digits == 132);
  assert!(p0 == Default::default());
  // doesn't meet Freeze requirement:
  //let sdf : List<RefCell<int>> = List::nil();
}
}

}
}

fn main() {
  // Trying out printing some stuff
  let p0 = List::nil();
  let p1 : List<int> = List::cons(1, p0);
  let p2 = List::cons(2, p1.clone());
  let p2a = List::cons(2, p1.clone());
  let p2b = List::cons(3, p1.clone());
  println(format!("Successyays:\n{}, {}", p2 == p2a, p2 == p2b));
  for i in p2b.iter() {
    println(format!("{}", *i))
  }
  // Is there a way not to use the temporary var name here?
  // "for i in p2b.reverse().iter()" didn't work (I guess the
  // lifetime of p2b.reverse() there didn't include the body of the
  // for loop).
  let x = p2b.reverse();
  for i in x.iter() {
    println(format!("{}", *i))
  }
}

<|endoftext|>


<commit_before><commit_msg>never_type: test interaction with auto traits<commit_after>// check-pass

#![feature(optin_builtin_traits)]

fn main() {
    enum Void {}

    auto trait Auto {}
    fn assert_auto<T: Auto>() {}
    assert_auto::<Void>();
    assert_auto::<!>();

    fn assert_send<T: Send>() {}
    assert_send::<Void>();
    assert_send::<!>();
}
<|endoftext|>


<commit_before><commit_msg>More solutions<commit_after>// https://leetcode.com/problems/daily-temperatures/

pub struct Solution;

impl Solution {
    pub fn daily_temperatures(temperatures: Vec<i32>) -> Vec<i32> {
        let mut result = vec![0; temperatures.len()];

        let mut temperature_stack = Vec::new();
        let mut idx_stack = Vec::new();
        for (idx, temperature) in temperatures.into_iter().enumerate() {
            while !temperature_stack.is_empty() && *temperature_stack.last().unwrap() < temperature
            {
                temperature_stack.pop().unwrap();
                let last_idx = idx_stack.pop().unwrap();
                result[last_idx] = (idx - last_idx) as i32;
            }
            temperature_stack.push(temperature);
            idx_stack.push(idx);
        }

        return result;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_1() {
        assert_eq!(
            Solution::daily_temperatures(vec![73, 74, 75, 71, 69, 72, 76, 73]),
            vec![1, 1, 4, 2, 1, 1, 0, 0]
        );
    }

    #[test]
    fn test_2() {
        assert_eq!(
            Solution::daily_temperatures(vec![30, 40, 50, 60]),
            vec![1, 1, 1, 0]
        );
    }

    #[test]
    fn test_3() {
        assert_eq!(
            Solution::daily_temperatures(vec![30, 60, 90]),
            vec![1, 1, 0]
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>updated avatar<commit_after><|endoftext|>


<commit_before><commit_msg>[Back] Add missing file.<commit_after>// Copyright 2016 Pierre Talbot (IRCAM)

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

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

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

pub struct Context<'a>
{
  grammar: &'a TGrammar<'a>,
  variables: Vec<Ident>,
  continuation_success: Box<CompileCombinator>,
  continuation_failure: Box<CompileCombinator>
}

pub trait CompileCombinator
{
  fn compile_combinator<'a>(self, context: Context<'a>) -> RExpr;
}

struct Sequence
{
  grammar: TGrammar,
  sequence: Vec<usize>
}

impl CompileCombinator for Sequence
{
  fn compile_combinator<'a>(self, mut success_cont: RExpr, failure_cont: RExpr, ident: &mut Vec<Ident>) -> RExpr {
    for idx in self.seq.rev() {
      success_cont = compile_combinator(idx, success_cont, failure_cont.clone(), ident);
    }
    success_cont
  }
}

struct Choice
{
  grammar: TGrammar,
  choice: Vec<usize>
}

impl CompileCombinator for Choice
{
  fn compile_combinator<'a>(self, mut success_cont: RExpr, failure_cont: RExpr, ident: &mut Vec<Ident>) -> RExpr {
    let mark = self.gen_mark_name();
    for idx in self.choice.rev() {
      failure_cont = quote_expr!(self.cx,
        state.restore($mark);
        $failure_cont
      );
      failure_cont = compile_combinator(idx, success_cont, failure_cont, &mut ident.clone());
    }
    quote_expr!(self.cx,
      let $mark = state.mark();
      $failure_cont
    )
  }
}
<|endoftext|>