<commit_before>use error::MioResult;
use io::IoHandle;
use os;
use os::token::Token;
use os::event;

pub struct Poll {
    selector: os::Selector,
    events: os::Events
}

impl Poll {
    pub fn new() -> MioResult<Poll> {
        Ok(Poll {
            selector: try!(os::Selector::new()),
            events: os::Events::new()
        })
    }

    pub fn register<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
        debug!("registering  with poller");

        // Register interests for this socket
        try!(self.selector.register(io.desc(), token.as_uint(), interest, opts));

        Ok(())
    }

    pub fn reregister<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
        debug!("registering  with poller");

        // Register interests for this socket
        try!(self.selector.reregister(io.desc(), token.as_uint(), interest, opts));

        Ok(())
    }

    pub fn deregister<H: IoHandle>(&mut self, io: &H) -> MioResult<()> {
        debug!("deregistering IO with poller");

        // Deregister interests for this socket
        try!(self.selector.deregister(io.desc()));

        Ok(())
    }

    pub fn poll(&mut self, timeout_ms: uint) -> MioResult<uint> {
        try!(self.selector.select(&mut self.events, timeout_ms));
        Ok(self.events.len())
    }

    pub fn event(&self, idx: uint) -> event::IoEvent {
        self.events.get(idx)
    }
}
<commit_msg>Iterator for Poller<commit_after>use error::MioResult;
use io::IoHandle;
use os;
use os::token::Token;
use os::event;

pub struct Poll {
    selector: os::Selector,
    events: os::Events
}

impl Poll {
    pub fn new() -> MioResult<Poll> {
        Ok(Poll {
            selector: try!(os::Selector::new()),
            events: os::Events::new()
        })
    }

    pub fn register<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
        debug!("registering  with poller");

        // Register interests for this socket
        try!(self.selector.register(io.desc(), token.as_uint(), interest, opts));

        Ok(())
    }

    pub fn reregister<H: IoHandle>(&mut self, io: &H, token: Token, interest: event::Interest, opts: event::PollOpt) -> MioResult<()> {
        debug!("registering  with poller");

        // Register interests for this socket
        try!(self.selector.reregister(io.desc(), token.as_uint(), interest, opts));

        Ok(())
    }

    pub fn deregister<H: IoHandle>(&mut self, io: &H) -> MioResult<()> {
        debug!("deregistering IO with poller");

        // Deregister interests for this socket
        try!(self.selector.deregister(io.desc()));

        Ok(())
    }

    pub fn poll(&mut self, timeout_ms: uint) -> MioResult<uint> {
        try!(self.selector.select(&mut self.events, timeout_ms));
        Ok(self.events.len())
    }

    pub fn event(&self, idx: uint) -> event::IoEvent {
        self.events.get(idx)
    }

    pub fn iter(&self) -> EventsIterator {
        EventsIterator { events: &self.events, index: 0 }
    }
}

pub struct EventsIterator<'a> {
    events: &'a os::Events,
    index: uint
}

impl<'a> Iterator for EventsIterator<'a> {
    type Item = event::IoEvent;

    fn next(&mut self) -> Option<event::IoEvent> {
        if self.index == self.events.len() {
            None
        } else {
            self.index += 1;
            Some(self.events.get(self.index - 1))
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>static view of new-game is set<commit_after><|endoftext|>


<commit_before><commit_msg>start work on border modifier and center text alignment<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test case for inlining the docs of a macro reexport<commit_after><|endoftext|>


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

// Coroutines represent nothing more than a context and a stack
// segment.

use std::default::Default;
use std::rt::util::min_stack;
use std::thunk::Thunk;
use std::mem::transmute;
use std::rt::unwind::try;
use std::boxed::BoxAny;
use std::ops::{Deref, DerefMut};
use std::ptr;

use context::Context;
use stack::{StackPool, Stack};

/// A coroutine is nothing more than a (register context, stack) pair.
#[allow(raw_pointer_derive)]
#[derive(Debug)]
pub struct Coroutine {
    /// The segment of stack on which the task is currently running or
    /// if the task is blocked, on which the task will resume
    /// execution.
    current_stack_segment: Stack,

    /// Always valid if the task is alive and not running.
    saved_context: Context,

    /// Parent coroutine, may always be valid.
    parent: *mut Coroutine,
}

/// Coroutine spawn options
#[derive(Debug)]
pub struct Options {
    stack_size: usize,
}

impl Default for Options {
    fn default() -> Options {
        Options {
            stack_size: min_stack(),
        }
    }
}

/// Initialization function for make context
extern "C" fn coroutine_initialize(arg: usize, f: *mut ()) -> ! {
    let func: Box<Thunk<&mut Environment, _>> = unsafe { transmute(f) };
    let environment: &mut Environment = unsafe { transmute(arg) };

    let env_mov = unsafe { transmute(arg) };

    if let Err(cause) = unsafe { try(move|| func.invoke(env_mov)) } {
        error!("Panicked inside: {:?}", cause.downcast::<&str>());
    }

    loop {
        // coro.yield_now();
        environment.yield_now();
    }
}

impl Coroutine {
    pub fn empty() -> Box<Coroutine> {
        Box::new(Coroutine {
            current_stack_segment: unsafe { Stack::dummy_stack() },
            saved_context: Context::empty(),
            parent: ptr::null_mut(),
        })
    }

    /// Destroy coroutine and try to reuse std::stack segment.
    pub fn recycle(self, stack_pool: &mut StackPool) {
        let Coroutine { current_stack_segment, .. } = self;
        stack_pool.give_stack(current_stack_segment);
    }
}

/// Coroutine managing environment
#[allow(raw_pointer_derive)]
#[derive(Debug)]
pub struct Environment {
    stack_pool: StackPool,
    current_running: *mut Coroutine,
    main_coroutine: Box<Coroutine>,
}

impl Environment {
    /// Initialize a new environment
    pub fn new() -> Box<Environment> {
        let mut env = box Environment {
            stack_pool: StackPool::new(),
            current_running: ptr::null_mut(),
            main_coroutine: Coroutine::empty(),
        };

        env.current_running = unsafe { transmute(env.main_coroutine.deref()) };
        env
    }

    /// Spawn a new coroutine with options
    pub fn spawn_opts<F>(&mut self, f: F, opts: Options) -> Box<Coroutine>
            where F: FnOnce(&mut Environment) + Send + 'static {

        let mut coro = box Coroutine {
            current_stack_segment: self.stack_pool.take_stack(opts.stack_size),
            saved_context: Context::empty(),
            parent: ptr::null_mut(),
        };

        let ptr_self = unsafe { transmute(self) };
        let ctx = Context::new(coroutine_initialize,
                               ptr_self,
                               f,
                               &mut coro.current_stack_segment);
        coro.saved_context = ctx;

        // FIXME: To make the compiler happy
        let me: &mut Environment = unsafe { transmute(ptr_self) };
        me.resume(&mut coro);
        coro
    }

    /// Spawn a coroutine with default options
    pub fn spawn<F>(&mut self, f: F) -> Box<Coroutine>
            where F: FnOnce(&mut Environment) + Send + 'static {
        self.spawn_opts(f, Default::default())
    }

    /// Yield the current running coroutine
    pub fn yield_now(&mut self) {
        let mut current_running: &mut Coroutine = unsafe { transmute(self.current_running) };
        self.current_running = current_running.parent;
        let parent: &mut Coroutine = unsafe { transmute(self.current_running) };
        Context::swap(&mut current_running.saved_context, &parent.saved_context);
    }

    /// Suspend the current coroutine and resume the `coro` now
    pub fn resume(&mut self, coro: &mut Box<Coroutine>) {
        coro.parent = self.current_running;
        self.current_running = unsafe { transmute(coro.deref_mut()) };

        let coro: &mut Coroutine = unsafe { transmute(self.current_running) };
        let mut parent: &mut Coroutine = unsafe { transmute(coro.parent) };
        Context::swap(&mut parent.saved_context, &coro.saved_context);
    }

    /// Destroy the coroutine
    pub fn recycle(&mut self, coro: Box<Coroutine>) {
        coro.recycle(&mut self.stack_pool)
    }
}

#[cfg(test)]
mod test {
    use std::sync::mpsc::channel;

    use coroutine::Environment;

    #[test]
    fn test_coroutine_basic() {
        let mut env = Environment::new();

        let (tx, rx) = channel();
        let coro = env.spawn(move|_| {
            tx.send(1).unwrap();
        });

        assert_eq!(rx.recv().unwrap(), 1);

        env.recycle(coro);
    }

    #[test]
    fn test_coroutine_yield() {
        let mut env = Environment::new();

        let (tx, rx) = channel();
        let mut coro = env.spawn(move|env| {
            tx.send(1).unwrap();

            env.yield_now();

            tx.send(2).unwrap();
        });

        assert_eq!(rx.recv().unwrap(), 1);
        assert!(rx.try_recv().is_err());

        env.resume(&mut coro);

        assert_eq!(rx.recv().unwrap(), 2);

        env.recycle(coro);
    }

    #[test]
    fn test_coroutine_spawn_inside() {
        let mut env = Environment::new();

        let (tx, rx) = channel();
        let coro = env.spawn(move|env| {
            tx.send(1).unwrap();

            let subcoro = env.spawn(move|_| {
                tx.send(2).unwrap();
            });

            env.recycle(subcoro);
        });

        assert_eq!(rx.recv().unwrap(), 1);
        assert_eq!(rx.recv().unwrap(), 2);

        env.recycle(coro);
    }
}
<commit_msg>add more tests<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.

// Coroutines represent nothing more than a context and a stack
// segment.

use std::default::Default;
use std::rt::util::min_stack;
use std::thunk::Thunk;
use std::mem::transmute;
use std::rt::unwind::try;
use std::boxed::BoxAny;
use std::ops::{Deref, DerefMut};
use std::ptr;

use context::Context;
use stack::{StackPool, Stack};

/// A coroutine is nothing more than a (register context, stack) pair.
#[allow(raw_pointer_derive)]
#[derive(Debug)]
pub struct Coroutine {
    /// The segment of stack on which the task is currently running or
    /// if the task is blocked, on which the task will resume
    /// execution.
    current_stack_segment: Stack,

    /// Always valid if the task is alive and not running.
    saved_context: Context,

    /// Parent coroutine, may always be valid.
    parent: *mut Coroutine,
}

/// Coroutine spawn options
#[derive(Debug)]
pub struct Options {
    stack_size: usize,
}

impl Default for Options {
    fn default() -> Options {
        Options {
            stack_size: min_stack(),
        }
    }
}

/// Initialization function for make context
extern "C" fn coroutine_initialize(arg: usize, f: *mut ()) -> ! {
    let func: Box<Thunk<&mut Environment, _>> = unsafe { transmute(f) };
    let environment: &mut Environment = unsafe { transmute(arg) };

    let env_mov = unsafe { transmute(arg) };

    if let Err(cause) = unsafe { try(move|| func.invoke(env_mov)) } {
        error!("Panicked inside: {:?}", cause.downcast::<&str>());
    }

    loop {
        // coro.yield_now();
        environment.yield_now();
    }
}

impl Coroutine {
    pub fn empty() -> Box<Coroutine> {
        Box::new(Coroutine {
            current_stack_segment: unsafe { Stack::dummy_stack() },
            saved_context: Context::empty(),
            parent: ptr::null_mut(),
        })
    }

    /// Destroy coroutine and try to reuse std::stack segment.
    pub fn recycle(self, stack_pool: &mut StackPool) {
        let Coroutine { current_stack_segment, .. } = self;
        stack_pool.give_stack(current_stack_segment);
    }
}

/// Coroutine managing environment
#[allow(raw_pointer_derive)]
#[derive(Debug)]
pub struct Environment {
    stack_pool: StackPool,
    current_running: *mut Coroutine,
    main_coroutine: Box<Coroutine>,
}

impl Environment {
    /// Initialize a new environment
    pub fn new() -> Box<Environment> {
        let mut env = box Environment {
            stack_pool: StackPool::new(),
            current_running: ptr::null_mut(),
            main_coroutine: Coroutine::empty(),
        };

        env.current_running = unsafe { transmute(env.main_coroutine.deref()) };
        env
    }

    /// Spawn a new coroutine with options
    pub fn spawn_opts<F>(&mut self, f: F, opts: Options) -> Box<Coroutine>
            where F: FnOnce(&mut Environment) + Send + 'static {

        let mut coro = box Coroutine {
            current_stack_segment: self.stack_pool.take_stack(opts.stack_size),
            saved_context: Context::empty(),
            parent: ptr::null_mut(),
        };

        let ptr_self = unsafe { transmute(self) };
        let ctx = Context::new(coroutine_initialize,
                               ptr_self,
                               f,
                               &mut coro.current_stack_segment);
        coro.saved_context = ctx;

        // FIXME: To make the compiler happy
        let me: &mut Environment = unsafe { transmute(ptr_self) };
        me.resume(&mut coro);
        coro
    }

    /// Spawn a coroutine with default options
    pub fn spawn<F>(&mut self, f: F) -> Box<Coroutine>
            where F: FnOnce(&mut Environment) + Send + 'static {
        self.spawn_opts(f, Default::default())
    }

    /// Yield the current running coroutine
    pub fn yield_now(&mut self) {
        let mut current_running: &mut Coroutine = unsafe { transmute(self.current_running) };
        self.current_running = current_running.parent;
        let parent: &mut Coroutine = unsafe { transmute(self.current_running) };
        Context::swap(&mut current_running.saved_context, &parent.saved_context);
    }

    /// Suspend the current coroutine and resume the `coro` now
    pub fn resume(&mut self, coro: &mut Box<Coroutine>) {
        coro.parent = self.current_running;
        self.current_running = unsafe { transmute(coro.deref_mut()) };

        let coro: &mut Coroutine = unsafe { transmute(self.current_running) };
        let mut parent: &mut Coroutine = unsafe { transmute(coro.parent) };
        Context::swap(&mut parent.saved_context, &coro.saved_context);
    }

    /// Destroy the coroutine
    pub fn recycle(&mut self, coro: Box<Coroutine>) {
        coro.recycle(&mut self.stack_pool)
    }
}

#[cfg(test)]
mod test {
    use std::sync::mpsc::channel;

    use coroutine::Environment;

    #[test]
    fn test_coroutine_basic() {
        let mut env = Environment::new();

        let (tx, rx) = channel();
        let coro = env.spawn(move|_| {
            tx.send(1).unwrap();
        });

        assert_eq!(rx.recv().unwrap(), 1);

        env.recycle(coro);
    }

    #[test]
    fn test_coroutine_yield() {
        let mut env = Environment::new();

        let (tx, rx) = channel();
        let mut coro = env.spawn(move|env| {
            tx.send(1).unwrap();

            env.yield_now();

            tx.send(2).unwrap();
        });

        assert_eq!(rx.recv().unwrap(), 1);
        assert!(rx.try_recv().is_err());

        env.resume(&mut coro);

        assert_eq!(rx.recv().unwrap(), 2);

        env.recycle(coro);
    }

    #[test]
    fn test_coroutine_spawn_inside() {
        let mut env = Environment::new();

        let (tx, rx) = channel();
        let coro = env.spawn(move|env| {
            tx.send(1).unwrap();

            let subcoro = env.spawn(move|_| {
                tx.send(2).unwrap();
            });

            env.recycle(subcoro);
        });

        assert_eq!(rx.recv().unwrap(), 1);
        assert_eq!(rx.recv().unwrap(), 2);

        env.recycle(coro);
    }

    #[test]
    #[should_fail]
    fn test_coroutine_panic() {
        let mut env = Environment::new();

        env.spawn(move|_| {
            panic!("Panic inside a coroutine!!");
        });

        unreachable!();
    }

    #[test]
    #[should_fail]
    fn test_coroutine_child_panic() {
        let mut env = Environment::new();

        env.spawn(move|env| {

            env.spawn(move|_| {
                panic!("Panic inside a coroutine's child!!");
            });

        });

        unreachable!();
    }
}
<|endoftext|>


<commit_before>use bytes::Bytes;
use futures::{Poll, Stream};
use futures::sync::mpsc;
use tokio_proto;

use http::Chunk;

pub type TokioBody = tokio_proto::streaming::Body<Chunk, ::Error>;

/// A `Stream` for `Chunk`s used in requests and responses.
#[derive(Debug)]
pub struct Body(TokioBody);

impl Body {
    /// Return an empty body stream
    #[inline]
    pub fn empty() -> Body {
        Body(TokioBody::empty())
    }

    /// Return a body stream with an associated sender half
    #[inline]
    pub fn pair() -> (mpsc::Sender<Result<Chunk, ::Error>>, Body) {
        let (tx, rx) = TokioBody::pair();
        let rx = Body(rx);
        (tx, rx)
    }
}

impl Default for Body {
    #[inline]
    fn default() -> Body {
        Body::empty()
    }
}

impl Stream for Body {
    type Item = Chunk;
    type Error = ::Error;

    #[inline]
    fn poll(&mut self) -> Poll<Option<Chunk>, ::Error> {
        self.0.poll()
    }
}

impl From<Body> for tokio_proto::streaming::Body<Chunk, ::Error> {
    #[inline]
    fn from(b: Body) -> tokio_proto::streaming::Body<Chunk, ::Error> {
        b.0
    }
}

impl From<tokio_proto::streaming::Body<Chunk, ::Error>> for Body {
    #[inline]
    fn from(tokio_body: tokio_proto::streaming::Body<Chunk, ::Error>) -> Body {
        Body(tokio_body)
    }
}

impl From<mpsc::Receiver<Result<Chunk, ::Error>>> for Body {
    #[inline]
    fn from(src: mpsc::Receiver<Result<Chunk, ::Error>>) -> Body {
        Body(src.into())
    }
}

impl From<Chunk> for Body {
    #[inline]
    fn from (chunk: Chunk) -> Body {
        Body(TokioBody::from(chunk))
    }
}

impl From<Bytes> for Body {
    #[inline]
    fn from (bytes: Bytes) -> Body {
        Body(TokioBody::from(Chunk::from(bytes)))
    }
}

impl From<Vec<u8>> for Body {
    #[inline]
    fn from (vec: Vec<u8>) -> Body {
        Body(TokioBody::from(Chunk::from(vec)))
    }
}

impl From<&'static [u8]> for Body {
    #[inline]
    fn from (slice: &'static [u8]) -> Body {
        Body(TokioBody::from(Chunk::from(slice)))
    }
}

impl From<String> for Body {
    #[inline]
    fn from (s: String) -> Body {
        Body(TokioBody::from(Chunk::from(s.into_bytes())))
    }
}

impl From<&'static str> for Body {
    #[inline]
    fn from (slice: &'static str) -> Body {
        Body(TokioBody::from(Chunk::from(slice.as_bytes())))
    }
}

fn _assert_send_sync() {
    fn _assert_send<T: Send>() {}
    fn _assert_sync<T: Sync>() {}

    _assert_send::<Body>();
    _assert_send::<Chunk>();
    _assert_sync::<Chunk>();
}

#[test]
fn test_body_stream_concat() {
    use futures::{Sink, Stream, Future};
    let (tx, body) = Body::pair();

    ::std::thread::spawn(move || {
        let tx = tx.send(Ok("hello ".into())).wait().unwrap();
        tx.send(Ok("world".into())).wait().unwrap();
    });

    let total = body.concat().wait().unwrap();
    assert_eq!(total.as_ref(), b"hello world");

}
<commit_msg>feat(http): add Default trait to Body<commit_after>use bytes::Bytes;
use futures::{Poll, Stream};
use futures::sync::mpsc;
use tokio_proto;

use http::Chunk;

pub type TokioBody = tokio_proto::streaming::Body<Chunk, ::Error>;

/// A `Stream` for `Chunk`s used in requests and responses.
#[derive(Debug)]
pub struct Body(TokioBody);

impl Body {
    /// Return an empty body stream
    #[inline]
    pub fn empty() -> Body {
        Body(TokioBody::empty())
    }

    /// Return a body stream with an associated sender half
    #[inline]
    pub fn pair() -> (mpsc::Sender<Result<Chunk, ::Error>>, Body) {
        let (tx, rx) = TokioBody::pair();
        let rx = Body(rx);
        (tx, rx)
    }
}

impl Default for Body {
    #[inline]
    fn default() -> Body {
        Body::empty()
    }
}

impl Default for Body {
    fn default() -> Body {
        Body::empty()
    }
}

impl Stream for Body {
    type Item = Chunk;
    type Error = ::Error;

    #[inline]
    fn poll(&mut self) -> Poll<Option<Chunk>, ::Error> {
        self.0.poll()
    }
}

impl From<Body> for tokio_proto::streaming::Body<Chunk, ::Error> {
    #[inline]
    fn from(b: Body) -> tokio_proto::streaming::Body<Chunk, ::Error> {
        b.0
    }
}

impl From<tokio_proto::streaming::Body<Chunk, ::Error>> for Body {
    #[inline]
    fn from(tokio_body: tokio_proto::streaming::Body<Chunk, ::Error>) -> Body {
        Body(tokio_body)
    }
}

impl From<mpsc::Receiver<Result<Chunk, ::Error>>> for Body {
    #[inline]
    fn from(src: mpsc::Receiver<Result<Chunk, ::Error>>) -> Body {
        Body(src.into())
    }
}

impl From<Chunk> for Body {
    #[inline]
    fn from (chunk: Chunk) -> Body {
        Body(TokioBody::from(chunk))
    }
}

impl From<Bytes> for Body {
    #[inline]
    fn from (bytes: Bytes) -> Body {
        Body(TokioBody::from(Chunk::from(bytes)))
    }
}

impl From<Vec<u8>> for Body {
    #[inline]
    fn from (vec: Vec<u8>) -> Body {
        Body(TokioBody::from(Chunk::from(vec)))
    }
}

impl From<&'static [u8]> for Body {
    #[inline]
    fn from (slice: &'static [u8]) -> Body {
        Body(TokioBody::from(Chunk::from(slice)))
    }
}

impl From<String> for Body {
    #[inline]
    fn from (s: String) -> Body {
        Body(TokioBody::from(Chunk::from(s.into_bytes())))
    }
}

impl From<&'static str> for Body {
    #[inline]
    fn from (slice: &'static str) -> Body {
        Body(TokioBody::from(Chunk::from(slice.as_bytes())))
    }
}

impl From<Option<Body>> for Body {
    fn from (body: Option<Body>) -> Body {
        body.unwrap_or_default()
    }
}

fn _assert_send_sync() {
    fn _assert_send<T: Send>() {}
    fn _assert_sync<T: Sync>() {}

    _assert_send::<Body>();
    _assert_send::<Chunk>();
    _assert_sync::<Chunk>();
}

#[test]
fn test_body_stream_concat() {
    use futures::{Sink, Stream, Future};
    let (tx, body) = Body::pair();

    ::std::thread::spawn(move || {
        let tx = tx.send(Ok("hello ".into())).wait().unwrap();
        tx.send(Ok("world".into())).wait().unwrap();
    });

    let total = body.concat().wait().unwrap();
    assert_eq!(total.as_ref(), b"hello world");

}
<|endoftext|>


<commit_before><commit_msg>[ExecContainer] Add example for exec command<commit_after>extern crate shiplift;

use shiplift::{Docker, ExecContainerOptions};
use std::env;

fn main() {
    let docker = Docker::new();
    let options = ExecContainerOptions::builder().cmd(vec!["ls"]).build();
    if let Some(id) = env::args().nth(1) {
        let container = docker.containers()
            .get(&id)
            .exec(&options)
            .unwrap();
        println!("{:?}", container);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test case for type aliasing `impl Sized`<commit_after>// check-pass

#![feature(type_alias_impl_trait)]

type A = impl Sized;
fn f1() -> A { 0 }

type B = impl ?Sized;
fn f2() -> &'static B { &[0] }

type C = impl ?Sized + 'static;
fn f3() -> &'static C { &[0] }

type D = impl ?Sized;
fn f4() -> &'static D { &1 }

fn main() {}
<|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


<commit_before><commit_msg>#24468 add a update_entry method to Performance<commit_after><|endoftext|>


<commit_before><commit_msg>unionfind example<commit_after>extern crate time;
extern crate rand;
extern crate timely;
extern crate timely_sort;

use std::cmp::Ordering;

use rand::{Rng, SeedableRng, StdRng};

use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::dataflow::channels::pact::Pipeline;

fn main() {

    // command-line args: numbers of nodes and edges in the random graph.
    let nodes: usize = std::env::args().nth(1).unwrap().parse().unwrap();
    let edges: usize = std::env::args().nth(2).unwrap().parse().unwrap();
    let batch: usize = std::env::args().nth(3).unwrap().parse().unwrap();

    timely::execute_from_args(std::env::args().skip(4), move |root| {

        let index = root.index();
        let peers = root.peers();

        let (mut input, probe) = root.scoped(move |scope| {

            let (handle, stream) = scope.new_input();

            let probe = stream//.exchange(move |x: &(usize, usize)| (x.0 % (peers - 1)) as u64 + 1)
                              .union_find()
                              .exchange(|_| 0)
                              .union_find()
                              .probe().0;

            (handle, probe)
        });

        let seed: &[_] = &[1, 2, 3, index];
        let mut rng: StdRng = SeedableRng::from_seed(seed);

        for edge in 0..(edges / peers) {
            input.send((rng.gen_range(0, nodes), rng.gen_range(0, nodes)));
            if edge % batch == (batch - 1) {
                let next = input.epoch() + 1;
                input.advance_to(next);
                while probe.lt(input.time()) {
                    root.step();
                }
            }
        }

    }).unwrap(); // asserts error-free execution;
}

trait UnionFind {
    fn union_find(&self) -> Self;
}

impl<G: Scope> UnionFind for Stream<G, (usize, usize)> {
    fn union_find(&self) -> Stream<G, (usize, usize)> {

        let mut roots = vec![];  // u32 works, and is smaller than uint/u64
        let mut ranks = vec![];  // u8 should be large enough (n < 2^256)

        self.unary_stream(Pipeline, "UnionFind", move |input, output| {

            while let Some((time, data)) = input.next() {

                let mut session = output.session(&time);
                for &(mut x, mut y) in data.iter() {

                    // grow arrays if required.
                    let m = ::std::cmp::max(x, y);
                    for i in roots.len() .. (m + 1) {
                        roots.push(i as u32);
                        ranks.push(0);
                    }

                    // look up roots for `x` and `y`.
                    // while x != roots[x] { x = roots[x]; }
                    // while y != roots[y] { y = roots[y]; }

                    unsafe { while x != *roots.get_unchecked(x) as usize { x = *roots.get_unchecked(x) as usize; } }
                    unsafe { while y != *roots.get_unchecked(y) as usize { y = *roots.get_unchecked(y) as usize; } }

                    if x != y {
                        session.give((x, y));
                        match ranks[x].cmp(&ranks[y]) {
                            Ordering::Less    => { roots[x] = y as u32 },
                            Ordering::Greater => { roots[y] = x as u32 },
                            Ordering::Equal   => { roots[y] = x as u32; ranks[x] += 1 },
                        }
                    }
                }
            }
        })
    }
}<|endoftext|>


<commit_before><commit_msg>Implement lexing of raw quotes.<commit_after><|endoftext|>


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

//! An interface for numeric types
use cmp::{Eq, Ord};
use ops::{Neg, Add, Sub, Mul, Div, Modulo};
use option::Option;
use kinds::Copy;

pub mod strconv;

pub trait Num: Eq + Zero + One
             + Neg<Self>
             + Add<Self,Self>
             + Sub<Self,Self>
             + Mul<Self,Self>
             + Div<Self,Self>
             + Modulo<Self,Self> {}

impl Num for u8 {}
impl Num for u16 {}
impl Num for u32 {}
impl Num for u64 {}
impl Num for uint {}
impl Num for i8 {}
impl Num for i16 {}
impl Num for i32 {}
impl Num for i64 {}
impl Num for int {}
impl Num for f32 {}
impl Num for f64 {}
impl Num for float {}

pub trait IntConvertible {
    fn to_int(&self) -> int;
    fn from_int(n: int) -> Self;
}

pub trait Zero {
    fn zero() -> Self;
}

pub trait One {
    fn one() -> Self;
}

pub fn abs<T:Ord + Zero + Neg<T>>(v: T) -> T {
    if v < Zero::zero() { v.neg() } else { v }
}

pub trait Round {
    fn round(&self, mode: RoundMode) -> Self;

    fn floor(&self) -> Self;
    fn ceil(&self)  -> Self;
    fn fract(&self) -> Self;
}

pub enum RoundMode {
    RoundDown,
    RoundUp,
    RoundToZero,
    RoundFromZero
}

/**
 * Cast from one machine scalar to another
 *
 * # Example
 *
 * ~~~
 * let twenty: f32 = num::cast(0x14);
 * assert!(twenty == 20f32);
 * ~~~
 */
#[inline(always)]
pub fn cast<T:NumCast,U:NumCast>(n: T) -> U {
    NumCast::from(n)
}

/**
 * An interface for casting between machine scalars
 */
pub trait NumCast {
    fn from<T:NumCast>(n: T) -> Self;

    fn to_u8(&self) -> u8;
    fn to_u16(&self) -> u16;
    fn to_u32(&self) -> u32;
    fn to_u64(&self) -> u64;
    fn to_uint(&self) -> uint;

    fn to_i8(&self) -> i8;
    fn to_i16(&self) -> i16;
    fn to_i32(&self) -> i32;
    fn to_i64(&self) -> i64;
    fn to_int(&self) -> int;

    fn to_f32(&self) -> f32;
    fn to_f64(&self) -> f64;
    fn to_float(&self) -> float;
}

macro_rules! impl_num_cast(
    ($T:ty, $conv:ident) => (
        // FIXME #4375: This enclosing module is necessary because
        // of a bug with macros expanding into multiple items
        pub mod $conv {
            use num::NumCast;

            #[cfg(notest)]
            impl NumCast for $T {
                #[doc = "Cast `n` to a `$T`"]
                #[inline(always)]
                fn from<N:NumCast>(n: N) -> $T {
                    // `$conv` could be generated using `concat_idents!`, but that
                    // macro seems to be broken at the moment
                    n.$conv()
                }

                #[inline(always)] fn to_u8(&self)    -> u8    { *self as u8    }
                #[inline(always)] fn to_u16(&self)   -> u16   { *self as u16   }
                #[inline(always)] fn to_u32(&self)   -> u32   { *self as u32   }
                #[inline(always)] fn to_u64(&self)   -> u64   { *self as u64   }
                #[inline(always)] fn to_uint(&self)  -> uint  { *self as uint  }

                #[inline(always)] fn to_i8(&self)    -> i8    { *self as i8    }
                #[inline(always)] fn to_i16(&self)   -> i16   { *self as i16   }
                #[inline(always)] fn to_i32(&self)   -> i32   { *self as i32   }
                #[inline(always)] fn to_i64(&self)   -> i64   { *self as i64   }
                #[inline(always)] fn to_int(&self)   -> int   { *self as int   }

                #[inline(always)] fn to_f32(&self)   -> f32   { *self as f32   }
                #[inline(always)] fn to_f64(&self)   -> f64   { *self as f64   }
                #[inline(always)] fn to_float(&self) -> float { *self as float }
            }
        }
    )
)

impl_num_cast!(u8,    to_u8)
impl_num_cast!(u16,   to_u16)
impl_num_cast!(u32,   to_u32)
impl_num_cast!(u64,   to_u64)
impl_num_cast!(uint,  to_uint)
impl_num_cast!(i8,    to_i8)
impl_num_cast!(i16,   to_i16)
impl_num_cast!(i32,   to_i32)
impl_num_cast!(i64,   to_i64)
impl_num_cast!(int,   to_int)
impl_num_cast!(f32,   to_f32)
impl_num_cast!(f64,   to_f64)
impl_num_cast!(float, to_float)

pub trait ToStrRadix {
    pub fn to_str_radix(&self, radix: uint) -> ~str;
}

pub trait FromStrRadix {
    pub fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
}

// Generic math functions:

/**
 * Calculates a power to a given radix, optimized for uint `pow` and `radix`.
 *
 * Returns `radix^pow` as `T`.
 *
 * Note:
 * Also returns `1` for `0^0`, despite that technically being an
 * undefined number. The reason for this is twofold:
 * - If code written to use this function cares about that special case, it's
 *   probably going to catch it before making the call.
 * - If code written to use this function doesn't care about it, it's
 *   probably assuming that `x^0` always equals `1`.
 */
pub fn pow_with_uint<T:NumCast+One+Zero+Copy+Div<T,T>+Mul<T,T>>(
    radix: uint, pow: uint) -> T {
    let _0: T = Zero::zero();
    let _1: T = One::one();

    if pow   == 0u { return _1; }
    if radix == 0u { return _0; }
    let mut my_pow     = pow;
    let mut total      = _1;
    let mut multiplier = cast(radix as int);
    while (my_pow > 0u) {
        if my_pow % 2u == 1u {
            total *= multiplier;
        }
        my_pow     /= 2u;
        multiplier *= multiplier;
    }
    total
}

#[cfg(test)]
fn test_num<T:Num + NumCast>(ten: T, two: T) {
    assert!(ten.add(&two)    == cast(12));
    assert!(ten.sub(&two)    == cast(8));
    assert!(ten.mul(&two)    == cast(20));
    assert!(ten.div(&two)    == cast(5));
    assert!(ten.modulo(&two) == cast(0));

    assert!(ten.add(&two)    == ten + two);
    assert!(ten.sub(&two)    == ten - two);
    assert!(ten.mul(&two)    == ten * two);
    assert!(ten.div(&two)    == ten / two);
    assert!(ten.modulo(&two) == ten % two);
}

#[test] fn test_u8_num()    { test_num(10u8,  2u8)  }
#[test] fn test_u16_num()   { test_num(10u16, 2u16) }
#[test] fn test_u32_num()   { test_num(10u32, 2u32) }
#[test] fn test_u64_num()   { test_num(10u64, 2u64) }
#[test] fn test_uint_num()  { test_num(10u,   2u)   }
#[test] fn test_i8_num()    { test_num(10i8,  2i8)  }
#[test] fn test_i16_num()   { test_num(10i16, 2i16) }
#[test] fn test_i32_num()   { test_num(10i32, 2i32) }
#[test] fn test_i64_num()   { test_num(10i64, 2i64) }
#[test] fn test_int_num()   { test_num(10i,   2i)   }
#[test] fn test_f32_num()   { test_num(10f32, 2f32) }
#[test] fn test_f64_num()   { test_num(10f64, 2f64) }
#[test] fn test_float_num() { test_num(10f,   2f)   }

macro_rules! test_cast_20(
    ($_20:expr) => ({
        let _20 = $_20;

        assert!(20u   == _20.to_uint());
        assert!(20u8  == _20.to_u8());
        assert!(20u16 == _20.to_u16());
        assert!(20u32 == _20.to_u32());
        assert!(20u64 == _20.to_u64());
        assert!(20i   == _20.to_int());
        assert!(20i8  == _20.to_i8());
        assert!(20i16 == _20.to_i16());
        assert!(20i32 == _20.to_i32());
        assert!(20i64 == _20.to_i64());
        assert!(20f   == _20.to_float());
        assert!(20f32 == _20.to_f32());
        assert!(20f64 == _20.to_f64());

        assert!(_20 == NumCast::from(20u));
        assert!(_20 == NumCast::from(20u8));
        assert!(_20 == NumCast::from(20u16));
        assert!(_20 == NumCast::from(20u32));
        assert!(_20 == NumCast::from(20u64));
        assert!(_20 == NumCast::from(20i));
        assert!(_20 == NumCast::from(20i8));
        assert!(_20 == NumCast::from(20i16));
        assert!(_20 == NumCast::from(20i32));
        assert!(_20 == NumCast::from(20i64));
        assert!(_20 == NumCast::from(20f));
        assert!(_20 == NumCast::from(20f32));
        assert!(_20 == NumCast::from(20f64));

        assert!(_20 == cast(20u));
        assert!(_20 == cast(20u8));
        assert!(_20 == cast(20u16));
        assert!(_20 == cast(20u32));
        assert!(_20 == cast(20u64));
        assert!(_20 == cast(20i));
        assert!(_20 == cast(20i8));
        assert!(_20 == cast(20i16));
        assert!(_20 == cast(20i32));
        assert!(_20 == cast(20i64));
        assert!(_20 == cast(20f));
        assert!(_20 == cast(20f32));
        assert!(_20 == cast(20f64));
    })
)

#[test] fn test_u8_cast()    { test_cast_20!(20u8)  }
#[test] fn test_u16_cast()   { test_cast_20!(20u16) }
#[test] fn test_u32_cast()   { test_cast_20!(20u32) }
#[test] fn test_u64_cast()   { test_cast_20!(20u64) }
#[test] fn test_uint_cast()  { test_cast_20!(20u)   }
#[test] fn test_i8_cast()    { test_cast_20!(20i8)  }
#[test] fn test_i16_cast()   { test_cast_20!(20i16) }
#[test] fn test_i32_cast()   { test_cast_20!(20i32) }
#[test] fn test_i64_cast()   { test_cast_20!(20i64) }
#[test] fn test_int_cast()   { test_cast_20!(20i)   }
#[test] fn test_f32_cast()   { test_cast_20!(20f32) }
#[test] fn test_f64_cast()   { test_cast_20!(20f64) }
#[test] fn test_float_cast() { test_cast_20!(20f)   }
<commit_msg>Remove unnecessary enclosing modules for NumCast impls<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! An interface for numeric types
use cmp::{Eq, Ord};
use ops::{Neg, Add, Sub, Mul, Div, Modulo};
use option::Option;
use kinds::Copy;

pub mod strconv;

pub trait Num: Eq + Zero + One
             + Neg<Self>
             + Add<Self,Self>
             + Sub<Self,Self>
             + Mul<Self,Self>
             + Div<Self,Self>
             + Modulo<Self,Self> {}

impl Num for u8 {}
impl Num for u16 {}
impl Num for u32 {}
impl Num for u64 {}
impl Num for uint {}
impl Num for i8 {}
impl Num for i16 {}
impl Num for i32 {}
impl Num for i64 {}
impl Num for int {}
impl Num for f32 {}
impl Num for f64 {}
impl Num for float {}

pub trait IntConvertible {
    fn to_int(&self) -> int;
    fn from_int(n: int) -> Self;
}

pub trait Zero {
    fn zero() -> Self;
}

pub trait One {
    fn one() -> Self;
}

pub fn abs<T:Ord + Zero + Neg<T>>(v: T) -> T {
    if v < Zero::zero() { v.neg() } else { v }
}

pub trait Round {
    fn round(&self, mode: RoundMode) -> Self;

    fn floor(&self) -> Self;
    fn ceil(&self)  -> Self;
    fn fract(&self) -> Self;
}

pub enum RoundMode {
    RoundDown,
    RoundUp,
    RoundToZero,
    RoundFromZero
}

/**
 * Cast from one machine scalar to another
 *
 * # Example
 *
 * ~~~
 * let twenty: f32 = num::cast(0x14);
 * assert!(twenty == 20f32);
 * ~~~
 */
#[inline(always)]
pub fn cast<T:NumCast,U:NumCast>(n: T) -> U {
    NumCast::from(n)
}

/**
 * An interface for casting between machine scalars
 */
pub trait NumCast {
    fn from<T:NumCast>(n: T) -> Self;

    fn to_u8(&self) -> u8;
    fn to_u16(&self) -> u16;
    fn to_u32(&self) -> u32;
    fn to_u64(&self) -> u64;
    fn to_uint(&self) -> uint;

    fn to_i8(&self) -> i8;
    fn to_i16(&self) -> i16;
    fn to_i32(&self) -> i32;
    fn to_i64(&self) -> i64;
    fn to_int(&self) -> int;

    fn to_f32(&self) -> f32;
    fn to_f64(&self) -> f64;
    fn to_float(&self) -> float;
}

macro_rules! impl_num_cast(
    ($T:ty, $conv:ident) => (
        impl NumCast for $T {
            #[inline(always)]
            fn from<N:NumCast>(n: N) -> $T {
                // `$conv` could be generated using `concat_idents!`, but that
                // macro seems to be broken at the moment
                n.$conv()
            }

            #[inline(always)] fn to_u8(&self)    -> u8    { *self as u8    }
            #[inline(always)] fn to_u16(&self)   -> u16   { *self as u16   }
            #[inline(always)] fn to_u32(&self)   -> u32   { *self as u32   }
            #[inline(always)] fn to_u64(&self)   -> u64   { *self as u64   }
            #[inline(always)] fn to_uint(&self)  -> uint  { *self as uint  }

            #[inline(always)] fn to_i8(&self)    -> i8    { *self as i8    }
            #[inline(always)] fn to_i16(&self)   -> i16   { *self as i16   }
            #[inline(always)] fn to_i32(&self)   -> i32   { *self as i32   }
            #[inline(always)] fn to_i64(&self)   -> i64   { *self as i64   }
            #[inline(always)] fn to_int(&self)   -> int   { *self as int   }

            #[inline(always)] fn to_f32(&self)   -> f32   { *self as f32   }
            #[inline(always)] fn to_f64(&self)   -> f64   { *self as f64   }
            #[inline(always)] fn to_float(&self) -> float { *self as float }
        }
    )
)

impl_num_cast!(u8,    to_u8)
impl_num_cast!(u16,   to_u16)
impl_num_cast!(u32,   to_u32)
impl_num_cast!(u64,   to_u64)
impl_num_cast!(uint,  to_uint)
impl_num_cast!(i8,    to_i8)
impl_num_cast!(i16,   to_i16)
impl_num_cast!(i32,   to_i32)
impl_num_cast!(i64,   to_i64)
impl_num_cast!(int,   to_int)
impl_num_cast!(f32,   to_f32)
impl_num_cast!(f64,   to_f64)
impl_num_cast!(float, to_float)

pub trait ToStrRadix {
    pub fn to_str_radix(&self, radix: uint) -> ~str;
}

pub trait FromStrRadix {
    pub fn from_str_radix(str: &str, radix: uint) -> Option<Self>;
}

// Generic math functions:

/**
 * Calculates a power to a given radix, optimized for uint `pow` and `radix`.
 *
 * Returns `radix^pow` as `T`.
 *
 * Note:
 * Also returns `1` for `0^0`, despite that technically being an
 * undefined number. The reason for this is twofold:
 * - If code written to use this function cares about that special case, it's
 *   probably going to catch it before making the call.
 * - If code written to use this function doesn't care about it, it's
 *   probably assuming that `x^0` always equals `1`.
 */
pub fn pow_with_uint<T:NumCast+One+Zero+Copy+Div<T,T>+Mul<T,T>>(
    radix: uint, pow: uint) -> T {
    let _0: T = Zero::zero();
    let _1: T = One::one();

    if pow   == 0u { return _1; }
    if radix == 0u { return _0; }
    let mut my_pow     = pow;
    let mut total      = _1;
    let mut multiplier = cast(radix as int);
    while (my_pow > 0u) {
        if my_pow % 2u == 1u {
            total *= multiplier;
        }
        my_pow     /= 2u;
        multiplier *= multiplier;
    }
    total
}

#[cfg(test)]
fn test_num<T:Num + NumCast>(ten: T, two: T) {
    assert!(ten.add(&two)    == cast(12));
    assert!(ten.sub(&two)    == cast(8));
    assert!(ten.mul(&two)    == cast(20));
    assert!(ten.div(&two)    == cast(5));
    assert!(ten.modulo(&two) == cast(0));

    assert!(ten.add(&two)    == ten + two);
    assert!(ten.sub(&two)    == ten - two);
    assert!(ten.mul(&two)    == ten * two);
    assert!(ten.div(&two)    == ten / two);
    assert!(ten.modulo(&two) == ten % two);
}

#[test] fn test_u8_num()    { test_num(10u8,  2u8)  }
#[test] fn test_u16_num()   { test_num(10u16, 2u16) }
#[test] fn test_u32_num()   { test_num(10u32, 2u32) }
#[test] fn test_u64_num()   { test_num(10u64, 2u64) }
#[test] fn test_uint_num()  { test_num(10u,   2u)   }
#[test] fn test_i8_num()    { test_num(10i8,  2i8)  }
#[test] fn test_i16_num()   { test_num(10i16, 2i16) }
#[test] fn test_i32_num()   { test_num(10i32, 2i32) }
#[test] fn test_i64_num()   { test_num(10i64, 2i64) }
#[test] fn test_int_num()   { test_num(10i,   2i)   }
#[test] fn test_f32_num()   { test_num(10f32, 2f32) }
#[test] fn test_f64_num()   { test_num(10f64, 2f64) }
#[test] fn test_float_num() { test_num(10f,   2f)   }

macro_rules! test_cast_20(
    ($_20:expr) => ({
        let _20 = $_20;

        assert!(20u   == _20.to_uint());
        assert!(20u8  == _20.to_u8());
        assert!(20u16 == _20.to_u16());
        assert!(20u32 == _20.to_u32());
        assert!(20u64 == _20.to_u64());
        assert!(20i   == _20.to_int());
        assert!(20i8  == _20.to_i8());
        assert!(20i16 == _20.to_i16());
        assert!(20i32 == _20.to_i32());
        assert!(20i64 == _20.to_i64());
        assert!(20f   == _20.to_float());
        assert!(20f32 == _20.to_f32());
        assert!(20f64 == _20.to_f64());

        assert!(_20 == NumCast::from(20u));
        assert!(_20 == NumCast::from(20u8));
        assert!(_20 == NumCast::from(20u16));
        assert!(_20 == NumCast::from(20u32));
        assert!(_20 == NumCast::from(20u64));
        assert!(_20 == NumCast::from(20i));
        assert!(_20 == NumCast::from(20i8));
        assert!(_20 == NumCast::from(20i16));
        assert!(_20 == NumCast::from(20i32));
        assert!(_20 == NumCast::from(20i64));
        assert!(_20 == NumCast::from(20f));
        assert!(_20 == NumCast::from(20f32));
        assert!(_20 == NumCast::from(20f64));

        assert!(_20 == cast(20u));
        assert!(_20 == cast(20u8));
        assert!(_20 == cast(20u16));
        assert!(_20 == cast(20u32));
        assert!(_20 == cast(20u64));
        assert!(_20 == cast(20i));
        assert!(_20 == cast(20i8));
        assert!(_20 == cast(20i16));
        assert!(_20 == cast(20i32));
        assert!(_20 == cast(20i64));
        assert!(_20 == cast(20f));
        assert!(_20 == cast(20f32));
        assert!(_20 == cast(20f64));
    })
)

#[test] fn test_u8_cast()    { test_cast_20!(20u8)  }
#[test] fn test_u16_cast()   { test_cast_20!(20u16) }
#[test] fn test_u32_cast()   { test_cast_20!(20u32) }
#[test] fn test_u64_cast()   { test_cast_20!(20u64) }
#[test] fn test_uint_cast()  { test_cast_20!(20u)   }
#[test] fn test_i8_cast()    { test_cast_20!(20i8)  }
#[test] fn test_i16_cast()   { test_cast_20!(20i16) }
#[test] fn test_i32_cast()   { test_cast_20!(20i32) }
#[test] fn test_i64_cast()   { test_cast_20!(20i64) }
#[test] fn test_int_cast()   { test_cast_20!(20i)   }
#[test] fn test_f32_cast()   { test_cast_20!(20f32) }
#[test] fn test_f64_cast()   { test_cast_20!(20f64) }
#[test] fn test_float_cast() { test_cast_20!(20f)   }
<|endoftext|>


<commit_before><commit_msg>Add Annotation types for VM<commit_after>use crate::ty::BuiltinType;
use crate::utils::GrowableVec;
use crate::vm::{FileId, TypeParam};
use dora_parser::ast::{AnnotationParam, Modifier};
use dora_parser::interner::Name;
use dora_parser::Position;
use parking_lot::RwLock;
use std::sync::Arc;

#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub struct AnnotationId(usize);

impl AnnotationId {
    pub fn max() -> AnnotationId {
        AnnotationId(usize::max_value())
    }
}

impl From<AnnotationId> for usize {
    fn from(data: AnnotationId) -> usize {
        data.0
    }
}

impl From<usize> for AnnotationId {
    fn from(data: usize) -> AnnotationId {
        AnnotationId(data)
    }
}

impl GrowableVec<RwLock<Annotation>> {
    pub fn idx(&self, index: AnnotationId) -> Arc<RwLock<Annotation>> {
        self.idx_usize(index.0)
    }
}

#[derive(Debug)]
pub struct Annotation {
    pub id: AnnotationId,
    pub file: FileId,
    pub pos: Position,
    pub name: Name,
    pub ty: BuiltinType,
    pub internal: Option<Modifier>,

    pub type_params: Option<Vec<TypeParam>>,
    pub term_params: Option<Vec<AnnotationParam>>,
}
<|endoftext|>


<commit_before><commit_msg>Add test for #34053<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.

#![feature(drop_types_in_const)]

struct A(i32);

impl Drop for A {
    fn drop(&mut self) {}
}

static FOO: A = A(123);

fn main() {
    println!("{}", &FOO.0);
}
<|endoftext|>


<commit_before><commit_msg>primitive types<commit_after>fn main() {
    let x = true;
    let y: bool = false;
    println!("{} {}", x, y);
}
<|endoftext|>


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

use dom::bindings::js::JS;
use dom::bindings::utils::{Reflectable, Reflector};

use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSTRACE_OBJECT};
use js::jsval::JSVal;

use libc;
use std::cast;
use std::cell::{Cell, RefCell};
use serialize::{Encodable, Encoder};

// IMPORTANT: We rely on the fact that we never attempt to encode DOM objects using
//            any encoder but JSTracer. Since we derive trace hooks automatically,
//            we are unfortunately required to use generic types everywhere and
//            unsafely cast to the concrete JSTracer we actually require.

fn get_jstracer<'a, S: Encoder<E>, E>(s: &'a mut S) -> &'a mut JSTracer {
    unsafe {
        cast::transmute(s)
    }
}

impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for JS<T> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        trace_reflector(get_jstracer(s), "", self.reflector());
        Ok(())
    }
}

impl<S: Encoder<E>, E> Encodable<S, E> for Reflector {
    fn encode(&self, _s: &mut S) -> Result<(), E> {
        Ok(())
    }
}

pub trait JSTraceable {
    fn trace(&self, trc: *mut JSTracer);
}

pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) {
    if !val.is_gcthing() {
        return;
    }

    unsafe {
        description.to_c_str().with_ref(|name| {
            (*tracer).debugPrinter = None;
            (*tracer).debugPrintIndex = -1;
            (*tracer).debugPrintArg = name as *libc::c_void;
            debug!("tracing value {:s}", description);
            JS_CallTracer(tracer, val.to_gcthing(), val.trace_kind());
        });
    }
}

pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
    trace_object(tracer, description, reflector.get_jsobject())
}

pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) {
    unsafe {
        description.to_c_str().with_ref(|name| {
            (*tracer).debugPrinter = None;
            (*tracer).debugPrintIndex = -1;
            (*tracer).debugPrintArg = name as *libc::c_void;
            debug!("tracing {:s}", description);
            JS_CallTracer(tracer, obj as *mut libc::c_void, JSTRACE_OBJECT);
        });
    }
}

/// Encapsulates a type that cannot easily have Encodable derived automagically,
/// but also does not need to be made known to the SpiderMonkey garbage collector.
/// Use only with types that are not associated with a JS reflector and do not contain
/// fields of types associated with JS reflectors.
pub struct Untraceable<T> {
    inner: T,
}

impl<T> Untraceable<T> {
    pub fn new(val: T) -> Untraceable<T> {
        Untraceable {
            inner: val
        }
    }
}

impl<S: Encoder<E>, E, T> Encodable<S, E> for Untraceable<T> {
    fn encode(&self, _s: &mut S) -> Result<(), E> {
        Ok(())
    }
}

impl<T> Deref<T> for Untraceable<T> {
    fn deref<'a>(&'a self) -> &'a T {
        &self.inner
    }
}

impl<T> DerefMut<T> for Untraceable<T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        &mut self.inner
    }
}

/// Encapsulates a type that can be traced but is boxed in a type we don't control
/// (such as RefCell). Wrap a field in Traceable and implement the Encodable trait
/// for that new concrete type to achieve magic compiler-derived trace hooks.
#[deriving(Eq, Clone)]
pub struct Traceable<T> {
    inner: T
}

impl<T> Traceable<T> {
    pub fn new(val: T) -> Traceable<T> {
        Traceable {
            inner: val
        }
    }
}

impl<T> Deref<T> for Traceable<T> {
    fn deref<'a>(&'a self) -> &'a T {
        &self.inner
    }
}

impl<T> DerefMut<T> for Traceable<T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        &mut self.inner
    }
}

impl<S: Encoder<E>, E, T: Encodable<S, E>> Encodable<S, E> for Traceable<RefCell<T>> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        self.borrow().encode(s)
    }
}

impl<S: Encoder<E>, E, T: Encodable<S, E>+Copy> Encodable<S, E> for Traceable<Cell<T>> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        self.deref().get().encode(s)
    }
}

impl<S: Encoder<E>, E> Encodable<S, E> for Traceable<*mut JSObject> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        trace_object(get_jstracer(s), "object", **self);
        Ok(())
    }
}

impl<S: Encoder<E>, E> Encodable<S, E> for Traceable<JSVal> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        trace_jsval(get_jstracer(s), "val", **self);
        Ok(())
    }
}

/// for a field which contains DOMType
impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for Cell<JS<T>> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        self.get().encode(s)
    }
}
<commit_msg>Make 'RefCell<Vec<JS<T>>>' traceable.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::js::JS;
use dom::bindings::utils::{Reflectable, Reflector};

use js::jsapi::{JSObject, JSTracer, JS_CallTracer, JSTRACE_OBJECT};
use js::jsval::JSVal;

use libc;
use std::cast;
use std::cell::{Cell, RefCell};
use serialize::{Encodable, Encoder};

// IMPORTANT: We rely on the fact that we never attempt to encode DOM objects using
//            any encoder but JSTracer. Since we derive trace hooks automatically,
//            we are unfortunately required to use generic types everywhere and
//            unsafely cast to the concrete JSTracer we actually require.

fn get_jstracer<'a, S: Encoder<E>, E>(s: &'a mut S) -> &'a mut JSTracer {
    unsafe {
        cast::transmute(s)
    }
}

impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for JS<T> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        trace_reflector(get_jstracer(s), "", self.reflector());
        Ok(())
    }
}

impl<S: Encoder<E>, E> Encodable<S, E> for Reflector {
    fn encode(&self, _s: &mut S) -> Result<(), E> {
        Ok(())
    }
}

pub trait JSTraceable {
    fn trace(&self, trc: *mut JSTracer);
}

pub fn trace_jsval(tracer: *mut JSTracer, description: &str, val: JSVal) {
    if !val.is_gcthing() {
        return;
    }

    unsafe {
        description.to_c_str().with_ref(|name| {
            (*tracer).debugPrinter = None;
            (*tracer).debugPrintIndex = -1;
            (*tracer).debugPrintArg = name as *libc::c_void;
            debug!("tracing value {:s}", description);
            JS_CallTracer(tracer, val.to_gcthing(), val.trace_kind());
        });
    }
}

pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) {
    trace_object(tracer, description, reflector.get_jsobject())
}

pub fn trace_object(tracer: *mut JSTracer, description: &str, obj: *mut JSObject) {
    unsafe {
        description.to_c_str().with_ref(|name| {
            (*tracer).debugPrinter = None;
            (*tracer).debugPrintIndex = -1;
            (*tracer).debugPrintArg = name as *libc::c_void;
            debug!("tracing {:s}", description);
            JS_CallTracer(tracer, obj as *mut libc::c_void, JSTRACE_OBJECT);
        });
    }
}

/// Encapsulates a type that cannot easily have Encodable derived automagically,
/// but also does not need to be made known to the SpiderMonkey garbage collector.
/// Use only with types that are not associated with a JS reflector and do not contain
/// fields of types associated with JS reflectors.
pub struct Untraceable<T> {
    inner: T,
}

impl<T> Untraceable<T> {
    pub fn new(val: T) -> Untraceable<T> {
        Untraceable {
            inner: val
        }
    }
}

impl<S: Encoder<E>, E, T> Encodable<S, E> for Untraceable<T> {
    fn encode(&self, _s: &mut S) -> Result<(), E> {
        Ok(())
    }
}

impl<T> Deref<T> for Untraceable<T> {
    fn deref<'a>(&'a self) -> &'a T {
        &self.inner
    }
}

impl<T> DerefMut<T> for Untraceable<T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        &mut self.inner
    }
}

/// Encapsulates a type that can be traced but is boxed in a type we don't control
/// (such as RefCell). Wrap a field in Traceable and implement the Encodable trait
/// for that new concrete type to achieve magic compiler-derived trace hooks.
#[deriving(Eq, Clone)]
pub struct Traceable<T> {
    inner: T
}

impl<T> Traceable<T> {
    pub fn new(val: T) -> Traceable<T> {
        Traceable {
            inner: val
        }
    }
}

impl<T> Deref<T> for Traceable<T> {
    fn deref<'a>(&'a self) -> &'a T {
        &self.inner
    }
}

impl<T> DerefMut<T> for Traceable<T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        &mut self.inner
    }
}

impl<S: Encoder<E>, E, T: Encodable<S, E>> Encodable<S, E> for Traceable<RefCell<T>> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        self.borrow().encode(s)
    }
}

impl<S: Encoder<E>, E, T: Encodable<S, E>+Copy> Encodable<S, E> for Traceable<Cell<T>> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        self.deref().get().encode(s)
    }
}

impl<S: Encoder<E>, E> Encodable<S, E> for Traceable<*mut JSObject> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        trace_object(get_jstracer(s), "object", **self);
        Ok(())
    }
}

impl<S: Encoder<E>, E> Encodable<S, E> for Traceable<JSVal> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        trace_jsval(get_jstracer(s), "val", **self);
        Ok(())
    }
}

/// for a field which contains DOMType
impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for Cell<JS<T>> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        self.get().encode(s)
    }
}

/// for a field which contains non-POD type contains DOMType
impl<T: Reflectable+Encodable<S, E>, S: Encoder<E>, E> Encodable<S, E> for RefCell<Vec<JS<T>>> {
    fn encode(&self, s: &mut S) -> Result<(), E> {
        self.borrow().encode(s)
    }
}
<|endoftext|>


<commit_before>// -*- rust -*-
use std;
import std::io;
import std::str;
import std::result;

// FIXME (726)
#[test]
#[ignore(cfg(target_os = "macos"))]
fn test_simple() {
    let tmpfile: str = "test/run-pass/lib-io-test-simple.tmp";
    log tmpfile;
    let frood: str = "A hoopy frood who really knows where his towel is.";
    log frood;
    {
        let out: io::writer =
            result::get(io::file_writer(tmpfile, [io::create, io::truncate]));
        out.write_str(frood);
    }
    let inp: io::reader = result::get(io::file_reader(tmpfile));
    let frood2: str = inp.read_c_str();
    log frood2;
    assert (str::eq(frood, frood2));
}

#[test]
fn file_reader_not_exist() {
    alt io::file_reader("not a file") {
      result::err(e) {
        assert e == "error opening not a file";
      }
      result::ok(_) { fail; }
    }
}

#[test]
// FIXME (726)
#[ignore(cfg(target_os = "macos"))]
fn file_buf_writer_bad_name() {
    alt io::file_buf_writer("/?", []) {
      result::err(e) {
        assert e == "error opening /?";
      }
      result::ok(_) { fail; }
    }
}

#[test]
// FIXME (726)
#[ignore(cfg(target_os = "macos"))]
fn buffered_file_buf_writer_bad_name() {
    alt io::buffered_file_buf_writer("/?") {
      result::err(e) {
        assert e == "error opening /?";
      }
      result::ok(_) { fail; }
    }
}
<commit_msg>Fix the filenames used in some IO tests<commit_after>// -*- rust -*-
use std;
import std::io;
import std::str;
import std::result;

// FIXME (726)
#[test]
#[ignore(cfg(target_os = "macos"))]
fn test_simple() {
    let tmpfile: str = "test/run-pass/lib-io-test-simple.tmp";
    log tmpfile;
    let frood: str = "A hoopy frood who really knows where his towel is.";
    log frood;
    {
        let out: io::writer =
            result::get(io::file_writer(tmpfile, [io::create, io::truncate]));
        out.write_str(frood);
    }
    let inp: io::reader = result::get(io::file_reader(tmpfile));
    let frood2: str = inp.read_c_str();
    log frood2;
    assert (str::eq(frood, frood2));
}

#[test]
fn file_reader_not_exist() {
    alt io::file_reader("not a file") {
      result::err(e) {
        assert e == "error opening not a file";
      }
      result::ok(_) { fail; }
    }
}

#[test]
// FIXME (726)
#[ignore(cfg(target_os = "macos"))]
fn file_buf_writer_bad_name() {
    alt io::file_buf_writer("?/?", []) {
      result::err(e) {
        assert e == "error opening ?/?";
      }
      result::ok(_) { fail; }
    }
}

#[test]
// FIXME (726)
#[ignore(cfg(target_os = "macos"))]
fn buffered_file_buf_writer_bad_name() {
    alt io::buffered_file_buf_writer("?/?") {
      result::err(e) {
        assert e == "error opening ?/?";
      }
      result::ok(_) { fail; }
    }
}
<|endoftext|>


<commit_before><commit_msg>Set up tests for the virtual computer.<commit_after>use std::vec::Vec;

pub struct Machine {
    memory: Vec<u32>
}

impl Machine {
    pub fn new() -> Machine {
        Machine {
            memory: vec![0; 2097152]
        }
    }

    pub fn dump(&self) -> &Vec<u32> {
        &self.memory
    }

    pub fn load(&mut self, data: Vec<u32>) {
        self.memory = data;
    }
}

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

    #[test]
    fn it_can_load_data() {
        let mut m = Machine::new();
        assert_eq!(Some(&0), m.dump().first());

        m.load(vec![1]);
        assert_eq!(Some(&1), m.dump().first());
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove unnecessary Error::from() call<commit_after><|endoftext|>


<commit_before><commit_msg>Collapse nested if-else-if<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 {Intrinsic, i, f, v};
use rustc::middle::ty;

macro_rules! p {
    ($name: expr, ($($inputs: tt),*) -> $output: tt) => {
        plain!(concat!("llvm.aarch64.neon.", $name), ($($inputs),*) -> $output)
    }
}
pub fn find<'tcx>(_tcx: &ty::ctxt<'tcx>, name: &str) -> Option<Intrinsic> {
    Some(match name {
        "vmaxvq_u8" => p!("umaxv.i8.v16i8", (i8x16) -> i8),
        "vmaxvq_u16" => p!("umaxv.i16.v8i16", (i16x8) -> i16),
        "vmaxvq_u32" => p!("umaxv.i32.v4i32", (i32x4) -> i32),

        "vmaxvq_s8" => p!("smaxv.i8.v16i8", (i8x16) -> i8),
        "vmaxvq_s16" => p!("smaxv.i16.v8i16", (i16x8) -> i16),
        "vmaxvq_s32" => p!("smaxv.i32.v4i32", (i32x4) -> i32),

        "vminvq_u8" => p!("uminv.i8.v16i8", (i8x16) -> i8),
        "vminvq_u16" => p!("uminv.i16.v8i16", (i16x8) -> i16),
        "vminvq_u32" => p!("uminv.i32.v4i32", (i32x4) -> i32),
        "vminvq_s8" => p!("sminv.i8.v16i8", (i8x16) -> i8),
        "vminvq_s16" => p!("sminv.i16.v8i16", (i16x8) -> i16),
        "vminvq_s32" => p!("sminv.i32.v4i32", (i32x4) -> i32),

        "vsqrtq_f32" => plain!("llvm.sqrt.v4f32", (f32x4) -> f32x4),
        "vsqrtq_f64" => plain!("llvm.sqrt.v2f64", (f64x2) -> f64x2),

        "vrsqrteq_f32" => p!("vrsqrte.v4f32", (f32x4) -> f32x4),
        "vrsqrteq_f64" => p!("vrsqrte.v2f64", (f64x2) -> f64x2),

        "vmaxq_f32" => p!("fmax.v4f32", (f32x4, f32x4) -> f32x4),
        "vmaxq_f64" => p!("fmax.v2f64", (f64x2, f64x2) -> f64x2),

        "vminq_f32" => p!("fmin.v4f32", (f32x4, f32x4) -> f32x4),
        "vminq_f64" => p!("fmin.v2f64", (f64x2, f64x2) -> f64x2),
        _ => return None,
    })
}
<commit_msg>Add AArch64 vrecpeq_... intrinsic (necessary for minimal API).<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 {Intrinsic, i, f, v};
use rustc::middle::ty;

macro_rules! p {
    ($name: expr, ($($inputs: tt),*) -> $output: tt) => {
        plain!(concat!("llvm.aarch64.neon.", $name), ($($inputs),*) -> $output)
    }
}
pub fn find<'tcx>(_tcx: &ty::ctxt<'tcx>, name: &str) -> Option<Intrinsic> {
    Some(match name {
        "vmaxvq_u8" => p!("umaxv.i8.v16i8", (i8x16) -> i8),
        "vmaxvq_u16" => p!("umaxv.i16.v8i16", (i16x8) -> i16),
        "vmaxvq_u32" => p!("umaxv.i32.v4i32", (i32x4) -> i32),

        "vmaxvq_s8" => p!("smaxv.i8.v16i8", (i8x16) -> i8),
        "vmaxvq_s16" => p!("smaxv.i16.v8i16", (i16x8) -> i16),
        "vmaxvq_s32" => p!("smaxv.i32.v4i32", (i32x4) -> i32),

        "vminvq_u8" => p!("uminv.i8.v16i8", (i8x16) -> i8),
        "vminvq_u16" => p!("uminv.i16.v8i16", (i16x8) -> i16),
        "vminvq_u32" => p!("uminv.i32.v4i32", (i32x4) -> i32),
        "vminvq_s8" => p!("sminv.i8.v16i8", (i8x16) -> i8),
        "vminvq_s16" => p!("sminv.i16.v8i16", (i16x8) -> i16),
        "vminvq_s32" => p!("sminv.i32.v4i32", (i32x4) -> i32),

        "vsqrtq_f32" => plain!("llvm.sqrt.v4f32", (f32x4) -> f32x4),
        "vsqrtq_f64" => plain!("llvm.sqrt.v2f64", (f64x2) -> f64x2),

        "vrsqrteq_f32" => p!("vrsqrte.v4f32", (f32x4) -> f32x4),
        "vrsqrteq_f64" => p!("vrsqrte.v2f64", (f64x2) -> f64x2),
        "vrecpeq_f32" => p!("vrecpe.v4f32", (f32x4) -> f32x4),
        "vrecpeq_f64" => p!("vrecpe.v2f64", (f64x2) -> f64x2),

        "vmaxq_f32" => p!("fmax.v4f32", (f32x4, f32x4) -> f32x4),
        "vmaxq_f64" => p!("fmax.v2f64", (f64x2, f64x2) -> f64x2),

        "vminq_f32" => p!("fmin.v4f32", (f32x4, f32x4) -> f32x4),
        "vminq_f64" => p!("fmin.v2f64", (f64x2, f64x2) -> f64x2),
        _ => return None,
    })
}
<|endoftext|>


<commit_before><commit_msg>add error-in-impl-trait const generics test<commit_after>// check-pass
// edition:2018
#![feature(min_const_generics)]
trait ValidTrait {}

/// This has docs
pub fn extern_fn<const N: usize>() -> impl Iterator<Item = [u8; N]> {
    loop {}
}

pub trait Trait<const N: usize> {}
impl Trait<1> for u8 {}
impl Trait<2> for u8 {}
impl<const N: usize> Trait<N> for [u8; N] {}

/// This also has docs
pub fn test<const N: usize>() -> impl Trait<N> where u8: Trait<N> {
    loop {}
}

/// Document all the functions
pub async fn a_sink<const N: usize>(v: [u8; N]) -> impl Trait<N> {
    loop {}
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #408 - kali:master, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>algorithms yo<commit_after><|endoftext|>


<commit_before><commit_msg>Added Rust debounce solution (#112)<commit_after>use std::time::{Duration, Instant};

fn debounce<F: FnMut()>(mut f: F, timeout: u64, pass: bool) -> impl FnMut() {
  let dur = Duration::from_millis(timeout);
  let mut active: Option<Instant> = None;
  move || {
    match active {
      Some(inst) if (inst.elapsed() <= dur) && !pass => {
        active = Some(Instant::now());
      }
      Some(_) | None => {
        f();
        active = Some(Instant::now());
      }
    }
  }
}

fn main() {
  let mut debounced = debounce(|| {println!("debounce!");}, 5, false);
  debounced();
}

mod tests {
  use super::debounce;
  use std::time::Duration;
  use std::thread::sleep;

  #[test]
  fn function_is_called_first_time() {
    let mut start = 0;
    {
      let mut debounced = debounce(|| {
      start += 1;
      }, 10, false);
      debounced();
    }
    assert_eq!(1, start);
  }

  #[test]
  fn function_is_not_called_if_timeout_hasnt_elapsed() {
    let mut start = 0;
    {
      let mut debounced = debounce(|| {
      start += 1;
      }, 100, false);
      debounced();
      debounced();
    }
    assert_eq!(1, start);
  }

  #[test]
  fn function_iscalled_after_timeout_has_elapsed() {
    let mut start = 0;
    let dur = 100;
    {
      let mut debounced = debounce(|| {
      start += 1;
      }, dur, false);
      debounced();
      sleep(Duration::from_millis(dur));
      debounced();
    }
    assert_eq!(2, start);
  }

  #[test]
  fn timeout_is_restarted_if_function_is_called_before_timeout_has_elapsed() {
    let mut start = 0;
    let dur = 100;
    {
      let mut debounced = debounce(|| {
      start += 1;
      }, dur, false);
      debounced();
      sleep(Duration::from_millis(dur - 20));
      debounced();
      sleep(Duration::from_millis(20));
      debounced();
    }
    assert_eq!(1, start);
  }

  #[test]
  fn function_is_called_after_timeout_is_restarted() {
    let mut start = 0;
    let dur = 100;
    {
      let mut debounced = debounce(|| {
      start += 1;
      }, dur, false);
      debounced();
      sleep(Duration::from_millis(dur - 20));
      debounced();
      sleep(Duration::from_millis(20));
      debounced();
      sleep(Duration::from_millis(dur));
      debounced();
    }
    assert_eq!(2, start);
  }

  #[test]
  fn function_is_called_is_pass() {
    let mut start = 0;
    let dur = 100;
    {
      let mut debounced = debounce(|| {
      start += 1;
      }, dur, true);
      debounced();
      debounced();
      debounced();
    }
    assert_eq!(3, start);
  }
}
<|endoftext|>


<commit_before><commit_msg>Problem 37<commit_after>use std::iter::MultiplicativeIterator;

fn factors(n: uint) -> ~[(uint, uint)] {
    if n <= 1 {
        return ~[(n, 1)];
    }
    let mut primes = ~[2];
    let mut result = ~[];
    let mut i = 3;
    let mut n = n;
    while n != 1 {
        let &p = primes.last().unwrap();
        let mut j = 0;
        while n % p == 0 {
            j += 1;
            n /= p;
        }
        if j > 0 {
            result.push((p, j));
        }
        while primes.iter().any(|&x| i%x == 0) {
            i += 2;
        }
        primes.push(i);
    }
    result
}

fn phi_improved(n: uint) -> uint {
    factors(n).iter().map(|&(p, m)| (p-1)*std::num::pow(p, m-1)).product()
}

fn main() {
    println!("{:?}", phi_improved(10));
    println!("{:?}", phi_improved(13));
}

<|endoftext|>


<commit_before><commit_msg>More audio output shifts/masks<commit_after><|endoftext|>


<commit_before><commit_msg>added a utils module<commit_after>use std::path::PathBuf;
use std::fs::canonicalize;
use std::io;

pub fn make_absolute(p: PathBuf) -> Result<PathBuf, io::Error> {
    canonicalize(p)
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::sync::mpsc::{Sender, Receiver};
extern crate sdl2;
use self::sdl2::event::Event;
use self::sdl2::keyboard::Keycode;
use self::sdl2::pixels::Color;

use rustboylib::gpu::{SCREEN_W, SCREEN_H};
use super::{EmulatorBackend, BackendMessage};
use config::EmulatorAppConfig;
use input::get_key_bindings;
use emulator::EmulationMessage;

/// The SDL 2 backend, using rust-sdl2.
pub struct BackendSDL2;

impl EmulatorBackend for BackendSDL2 {
    fn run(&mut self,
           config: EmulatorAppConfig,
           tx: Sender<BackendMessage>,
           rx: Receiver<EmulationMessage>) {
        use emulator::EmulationMessage::*;
        use backend::BackendMessage::*;

        info!("starting the main application thread.");

        // Input bindings
        let key_binds = match get_key_bindings::<Keycode>(config.get_keyboard_binding(),
                                                          keycode_from_symbol_hm()) {
            Ok(hm) => hm,
            Err(why) => {
                error!("SDL2 backend input : {}", why);
                return;
            }
        };

        // Window size
        let (scale_h, scale_v) = config.compute_display_scale();
        let w = (SCREEN_W as u32) * (scale_h as u32);
        let h = (SCREEN_H as u32) * (scale_v as u32);
        info!("display scale = ({}, {}).", scale_h, scale_v);

        // SDL 2 initialization
        let sdl_context = sdl2::init().unwrap();
        let video_subsystem = sdl_context.video().unwrap();
        let window = match video_subsystem.window(config.get_title(), w, h)
                                          .position_centered()
                                          .opengl()
                                          .build() {
            Ok(window) => window,
            Err(why) => {
                error!("SDL2 backend failed to create the window : {}", why);
                return;
            }
        };
        let mut renderer = match window.renderer().build() {
            Ok(renderer) => renderer,
            Err(why) => {
                error!("SDL2 backend failed to create the renderer : {}", why);
                return;
            }
        };
        renderer.set_draw_color(Color::RGB(0, 0, 0));
        renderer.present();
        let mut events = sdl_context.event_pump().unwrap();

        // is the emulation paused ?
        let mut paused = false;
        // avoid spamming 'Event::KeyDown' events for the same key
        let mut last_key: Option<Keycode> = None;

        // Main loop
        'ui: loop {
            // Event loop
            for event in events.poll_iter() {
                match event {
                    Event::Quit { .. } => {
                        paused = true;
                        tx.send(Quit).unwrap();
                    }
                    Event::KeyDown { keycode: Some(keycode), .. } => {
                        if !last_key.is_none() && keycode == last_key.unwrap() {
                            continue;
                        }
                        match keycode {
                            // quit
                            Keycode::Escape => {
                                paused = true;
                                tx.send(Quit).unwrap();
                            }
                            // toggle pause
                            Keycode::Return => {
                                tx.send(UpdateRunStatus(paused)).unwrap();
                                paused = !paused;
                            }
                            _ => {
                                if !paused {
                                    match key_binds.get(&keycode) {
                                        Some(keypad_key) => {
                                            tx.send(KeyDown(*keypad_key)).unwrap();
                                        }
                                        _ => {}
                                    }
                                }
                            }
                        }
                        last_key = Some(keycode);
                    }
                    Event::KeyUp { keycode: Some(keycode), .. } if !paused => {
                        match key_binds.get(&keycode) {
                            Some(keypad_key) => {
                                tx.send(KeyUp(*keypad_key)).unwrap();
                            }
                            _ => {}
                        }
                        if !last_key.is_none() && keycode == last_key.unwrap() {
                            last_key = None;
                        }
                    }
                    _ => continue,
                }
            }

            // Signals from the VM
            match rx.try_recv() {
                Ok(emulation_message) => {
                    match emulation_message {
                        Finished => break 'ui,
                    }
                }
                _ => {}
            }
        }

        info!("terminating the main application thread.")
    }
}

pub fn keycode_from_symbol_hm() -> HashMap<String, Keycode> {
    let mut hm = HashMap::new();

    hm.insert("Up".into(), Keycode::Up);
    hm.insert("Down".into(), Keycode::Down);
    hm.insert("Left".into(), Keycode::Left);
    hm.insert("Right".into(), Keycode::Right);
    hm.insert("Numpad0".into(), Keycode::Kp0);
    hm.insert("Numpad1".into(), Keycode::Kp1);
    hm.insert("Numpad2".into(), Keycode::Kp2);
    hm.insert("Numpad3".into(), Keycode::Kp3);
    hm.insert("Numpad4".into(), Keycode::Kp4);
    hm.insert("Numpad5".into(), Keycode::Kp5);
    hm.insert("Numpad6".into(), Keycode::Kp6);
    hm.insert("Numpad7".into(), Keycode::Kp7);
    hm.insert("Numpad8".into(), Keycode::Kp8);
    hm.insert("Numpad9".into(), Keycode::Kp9);
    hm.insert("NumpadPlus".into(), Keycode::KpPlus);
    hm.insert("NumpadMinus".into(), Keycode::KpMinus);
    hm.insert("NumpadMultiply".into(), Keycode::KpMultiply);
    hm.insert("NumpadDivide".into(), Keycode::KpDivide);
    // reference : https://wiki.libsdl.org/SDL_Keycode
    // and : "keycode.rs" from https://github.com/AngryLawyer/rust-sdl2/
    let mut sdl2_key_names = Vec::<String>::new();
    for c in b'A'..b'Z' + 1 {
        sdl2_key_names.push((c as char).to_string());
    }
    for i in 1..13 {
        sdl2_key_names.push(format!("F{}", i));
    } // F0-F12
    for key_name in sdl2_key_names {
        let key_code = match Keycode::from_name(&key_name[..]) {
            Some(code) => code,
            None => panic!("SDL2 backend : invalid keycode \"{}\"", key_name),
        };
        hm.insert(key_name.clone(), key_code);
    }

    hm
}

#[cfg(test)]
mod test {
    use super::sdl2::keyboard::Keycode;
    use rustboylib::joypad::JoypadKey;
    use input::get_key_bindings;
    use input::KeyboardBinding::FromConfigFile;

    #[test]
    fn test_keyboard_hm_from_config() {
        let key_binds = get_key_bindings::<Keycode>(FromConfigFile("tests/backend_input.toml"
                                                                       .into()),
                                                    super::keycode_from_symbol_hm())
                            .unwrap();
        assert_eq!(*key_binds.get(&Keycode::Up).unwrap(), JoypadKey::Up);
        assert_eq!(*key_binds.get(&Keycode::Down).unwrap(), JoypadKey::Down);
        assert_eq!(*key_binds.get(&Keycode::Left).unwrap(), JoypadKey::Left);
        assert_eq!(*key_binds.get(&Keycode::Right).unwrap(), JoypadKey::Right);
        assert_eq!(*key_binds.get(&Keycode::Kp1).unwrap(), JoypadKey::Select);
        assert_eq!(*key_binds.get(&Keycode::Kp3).unwrap(), JoypadKey::Start);
        assert_eq!(*key_binds.get(&Keycode::E).unwrap(), JoypadKey::A);
        assert_eq!(*key_binds.get(&Keycode::T).unwrap(), JoypadKey::B);
    }
}
<commit_msg>Fixed emulation pause behavior<commit_after>use std::collections::HashMap;
use std::sync::mpsc::{Sender, Receiver};
extern crate sdl2;
use self::sdl2::event::Event;
use self::sdl2::keyboard::Keycode;
use self::sdl2::pixels::Color;

use rustboylib::gpu::{SCREEN_W, SCREEN_H};
use super::{EmulatorBackend, BackendMessage};
use config::EmulatorAppConfig;
use input::get_key_bindings;
use emulator::EmulationMessage;

/// The SDL 2 backend, using rust-sdl2.
pub struct BackendSDL2;

impl EmulatorBackend for BackendSDL2 {
    fn run(&mut self,
           config: EmulatorAppConfig,
           tx: Sender<BackendMessage>,
           rx: Receiver<EmulationMessage>) {
        use emulator::EmulationMessage::*;
        use backend::BackendMessage::*;

        info!("starting the main application thread.");

        // Input bindings
        let key_binds = match get_key_bindings::<Keycode>(config.get_keyboard_binding(),
                                                          keycode_from_symbol_hm()) {
            Ok(hm) => hm,
            Err(why) => {
                error!("SDL2 backend input : {}", why);
                return;
            }
        };

        // Window size
        let (scale_h, scale_v) = config.compute_display_scale();
        let w = (SCREEN_W as u32) * (scale_h as u32);
        let h = (SCREEN_H as u32) * (scale_v as u32);
        info!("display scale = ({}, {}).", scale_h, scale_v);

        // SDL 2 initialization
        let sdl_context = sdl2::init().unwrap();
        let video_subsystem = sdl_context.video().unwrap();
        let window = match video_subsystem.window(config.get_title(), w, h)
                                          .position_centered()
                                          .opengl()
                                          .build() {
            Ok(window) => window,
            Err(why) => {
                error!("SDL2 backend failed to create the window : {}", why);
                return;
            }
        };
        let mut renderer = match window.renderer().build() {
            Ok(renderer) => renderer,
            Err(why) => {
                error!("SDL2 backend failed to create the renderer : {}", why);
                return;
            }
        };
        renderer.set_draw_color(Color::RGB(0, 0, 0));
        renderer.present();
        let mut events = sdl_context.event_pump().unwrap();

        // is the emulation paused ?
        let mut paused = false;
        // avoid spamming 'Event::KeyDown' events for the same key
        let mut last_key: Option<Keycode> = None;

        // Main loop
        'ui: loop {
            // Event loop
            for event in events.poll_iter() {
                match event {
                    Event::Quit { .. } => {
                        paused = true;
                        tx.send(Quit).unwrap();
                    }
                    Event::KeyDown { keycode: Some(keycode), .. } => {
                        if !last_key.is_none() && keycode == last_key.unwrap() {
                            continue;
                        }
                        match keycode {
                            // quit
                            Keycode::Escape => {
                                paused = true;
                                tx.send(Quit).unwrap();
                            }
                            // toggle pause
                            Keycode::Return => {
                                paused = !paused;
                                tx.send(UpdateRunStatus(paused)).unwrap();
                            }
                            _ => {
                                if !paused {
                                    match key_binds.get(&keycode) {
                                        Some(keypad_key) => {
                                            tx.send(KeyDown(*keypad_key)).unwrap();
                                        }
                                        _ => {}
                                    }
                                }
                            }
                        }
                        last_key = Some(keycode);
                    }
                    Event::KeyUp { keycode: Some(keycode), .. } if !paused => {
                        match key_binds.get(&keycode) {
                            Some(keypad_key) => {
                                tx.send(KeyUp(*keypad_key)).unwrap();
                            }
                            _ => {}
                        }
                        if !last_key.is_none() && keycode == last_key.unwrap() {
                            last_key = None;
                        }
                    }
                    _ => continue,
                }
            }

            // Signals from the VM
            match rx.try_recv() {
                Ok(emulation_message) => {
                    match emulation_message {
                        Finished => break 'ui,
                    }
                }
                _ => {}
            }
        }

        info!("terminating the main application thread.")
    }
}

pub fn keycode_from_symbol_hm() -> HashMap<String, Keycode> {
    let mut hm = HashMap::new();

    hm.insert("Up".into(), Keycode::Up);
    hm.insert("Down".into(), Keycode::Down);
    hm.insert("Left".into(), Keycode::Left);
    hm.insert("Right".into(), Keycode::Right);
    hm.insert("Numpad0".into(), Keycode::Kp0);
    hm.insert("Numpad1".into(), Keycode::Kp1);
    hm.insert("Numpad2".into(), Keycode::Kp2);
    hm.insert("Numpad3".into(), Keycode::Kp3);
    hm.insert("Numpad4".into(), Keycode::Kp4);
    hm.insert("Numpad5".into(), Keycode::Kp5);
    hm.insert("Numpad6".into(), Keycode::Kp6);
    hm.insert("Numpad7".into(), Keycode::Kp7);
    hm.insert("Numpad8".into(), Keycode::Kp8);
    hm.insert("Numpad9".into(), Keycode::Kp9);
    hm.insert("NumpadPlus".into(), Keycode::KpPlus);
    hm.insert("NumpadMinus".into(), Keycode::KpMinus);
    hm.insert("NumpadMultiply".into(), Keycode::KpMultiply);
    hm.insert("NumpadDivide".into(), Keycode::KpDivide);
    // reference : https://wiki.libsdl.org/SDL_Keycode
    // and : "keycode.rs" from https://github.com/AngryLawyer/rust-sdl2/
    let mut sdl2_key_names = Vec::<String>::new();
    for c in b'A'..b'Z' + 1 {
        sdl2_key_names.push((c as char).to_string());
    }
    for i in 1..13 {
        sdl2_key_names.push(format!("F{}", i));
    } // F0-F12
    for key_name in sdl2_key_names {
        let key_code = match Keycode::from_name(&key_name[..]) {
            Some(code) => code,
            None => panic!("SDL2 backend : invalid keycode \"{}\"", key_name),
        };
        hm.insert(key_name.clone(), key_code);
    }

    hm
}

#[cfg(test)]
mod test {
    use super::sdl2::keyboard::Keycode;
    use rustboylib::joypad::JoypadKey;
    use input::get_key_bindings;
    use input::KeyboardBinding::FromConfigFile;

    #[test]
    fn test_keyboard_hm_from_config() {
        let key_binds = get_key_bindings::<Keycode>(FromConfigFile("tests/backend_input.toml"
                                                                       .into()),
                                                    super::keycode_from_symbol_hm())
                            .unwrap();
        assert_eq!(*key_binds.get(&Keycode::Up).unwrap(), JoypadKey::Up);
        assert_eq!(*key_binds.get(&Keycode::Down).unwrap(), JoypadKey::Down);
        assert_eq!(*key_binds.get(&Keycode::Left).unwrap(), JoypadKey::Left);
        assert_eq!(*key_binds.get(&Keycode::Right).unwrap(), JoypadKey::Right);
        assert_eq!(*key_binds.get(&Keycode::Kp1).unwrap(), JoypadKey::Select);
        assert_eq!(*key_binds.get(&Keycode::Kp3).unwrap(), JoypadKey::Start);
        assert_eq!(*key_binds.get(&Keycode::E).unwrap(), JoypadKey::A);
        assert_eq!(*key_binds.get(&Keycode::T).unwrap(), JoypadKey::B);
    }
}
<|endoftext|>


<commit_before><commit_msg>add example<commit_after>#![feature(box_patterns)]

extern crate query_planner;
use query_planner::rel::*;
use query_planner::schema::*;
use query_planner::csvrelation::*;
use query_planner::exec::*;

fn main() {

    // define schema for data source (csv file)
    let tt = TupleType {
        columns: vec![
            ColumnMeta { name: String::from("id"), data_type: DataType::UnsignedLong, nullable: false },
            ColumnMeta { name: String::from("name"), data_type: DataType::String, nullable: false }
        ]
    };

    // open csv file
    let mut csv = CsvRelation::open(String::from("people.csv"), tt.clone());

    // create simple filter expression for "id = 2"
    let filter_expr = Rex::BinaryExpr {
        left: Box::new(Rex::TupleValue(0)),
        op: Operator::Eq,
        right: Box::new(Rex::Literal(Value::UnsignedLong(2)))
    };

    // get iterator over data
    let mut it = csv.scan();

    // filter out rows matching the predicate
    while let Some(t) = it.next() {
        match evaluate(&t, &tt, &filter_expr) {
            Ok(Value::Boolean(true)) => println!("{:?}", t),
            _ => {}
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>Remove unused imports<commit_after><|endoftext|>