<commit_before>// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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.

#[doc(hidden)]
#[macro_export]
macro_rules! as_item { ($i:item) => {$i} }

// Inserts a placeholder doc comment for the module if it's missing
#[doc(hidden)]
#[macro_export]
macro_rules! add_mod_doc {
    // If nothing left, return
    (
        @rec
        { $(#[$done:meta])* }
        { }
        $i:item
    ) => {
        $(#[$done])*
        #[doc="A module containing an rpc service and client stub."]
        $i
    };

    // If we find a doc attribute, return
    (
        @rec
        { $(#[$done:meta])* }
        {
            #[doc=$doc:expr]
            $(#[$rest:meta])*
        }
        $i:item
    ) => {
        $(#[$done])*
        #[doc=$doc]
        $(#[$rest])*
        $i
    };

    // If we don't find a doc attribute, keep going
    (
        @rec
        { $(#[$($done:tt)*])* }
        {
            #[$($attr:tt)*]
            $($rest:tt)*
        }
        $i:item
    ) => {
        add_mod_doc! {
            @rec
            { $(#[$($done)*])* #[$($attr)*] }
            { $($rest)* }
            $i
        }
    };

    // Entry
    (
        { $(#[$($attr:tt)*])* }
        $i:item
    ) => {
        add_mod_doc! {
            @rec
            {}
            { $(#[$($attr)*])* }
            $i
        }
    };
}

// Required because if-let can't be used with irrefutable patterns, so it needs
// to be special cased.
#[doc(hidden)]
#[macro_export]
macro_rules! client_methods {
    (
        { $(#[$attr:meta])* }
        $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty
    ) => (
        $(#[$attr])*
        pub fn $fn_name(&self, $($arg: $in_),*) -> $crate::Result<$out> {
            let reply = try!((self.0).rpc(&request_variant!($fn_name $($arg),*)));
            let __Reply::$fn_name(reply) = reply;
            Ok(reply)
        }
    );
    ($(
            { $(#[$attr:meta])* }
            $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty
    )*) => ( $(
        $(#[$attr])*
        pub fn $fn_name(&self, $($arg: $in_),*) -> $crate::Result<$out> {
            let reply = try!((self.0).rpc(&request_variant!($fn_name $($arg),*)));
            if let __Reply::$fn_name(reply) = reply {
                Ok(reply)
            } else {
                panic!("Incorrect reply variant returned from protocol::Clientrpc; expected `{}`, but got {:?}", stringify!($fn_name), reply);
            }
        }
    )*);
}

// Required because if-let can't be used with irrefutable patterns, so it needs
// to be special cased.
#[doc(hidden)]
#[macro_export]
macro_rules! async_client_methods {
    (
        { $(#[$attr:meta])* }
        $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty
    ) => (
        $(#[$attr])*
        pub fn $fn_name(&self, $($arg: $in_),*) -> Future<$out> {
            fn mapper(reply: __Reply) -> $out {
                let __Reply::$fn_name(reply) = reply;
                reply
            }
            let reply = (self.0).rpc_async(&request_variant!($fn_name $($arg),*));
            Future {
                future: reply,
                mapper: mapper,
            }
        }
    );
    ($(
            { $(#[$attr:meta])* }
            $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty
    )*) => ( $(
        $(#[$attr])*
        pub fn $fn_name(&self, $($arg: $in_),*) -> Future<$out> {
            fn mapper(reply: __Reply) -> $out {
                if let __Reply::$fn_name(reply) = reply {
                    reply
                } else {
                    panic!("Incorrect reply variant returned from protocol::Clientrpc; expected `{}`, but got {:?}", stringify!($fn_name), reply);
                }
            }
            let reply = (self.0).rpc_async(&request_variant!($fn_name $($arg),*));
            Future {
                future: reply,
                mapper: mapper,
            }
        }
    )*);
}

// Required because enum variants with no fields can't be suffixed by parens
#[doc(hidden)]
#[macro_export]
macro_rules! define_request {
    ($(@($($finished:tt)*))* --) => (as_item!(
            #[allow(non_camel_case_types)]
            #[derive(Debug, Serialize, Deserialize)]
            enum __Request { $($($finished)*),* }
    ););
    ($(@$finished:tt)* -- $name:ident() $($req:tt)*) =>
        (define_request!($(@$finished)* @($name) -- $($req)*););
    ($(@$finished:tt)* -- $name:ident $args: tt $($req:tt)*) =>
        (define_request!($(@$finished)* @($name $args) -- $($req)*););
    ($($started:tt)*) => (define_request!(-- $($started)*););
}

// Required because enum variants with no fields can't be suffixed by parens
#[doc(hidden)]
#[macro_export]
macro_rules! request_variant {
    ($x:ident) => (__Request::$x);
    ($x:ident $($y:ident),+) => (__Request::$x($($y),+));
}

// The main macro that creates RPC services.
#[macro_export]
macro_rules! rpc {
    (
        $(#[$($service_attr:tt)*])*
        mod $server:ident {

            service {
                $(
                    $(#[$attr:meta])*
                    rpc $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty;
                )*
            }
        }
    ) => {
        rpc! {
            $(#[$($service_attr)*])*
            mod $server {

                items { }

                service {
                    $(
                        $(#[$attr])*
                        rpc $fn_name($($arg: $in_),*) -> $out;
                    )*
                }
            }
        }
    };

    (
        // Names the service
        $(#[$($service_attr:tt)*])*
        mod $server:ident {

            // Include any desired or required items. Conflicts can arise with the following names:
            // 1. Service
            // 2. Client
            // 3. serve
            // 4. __Reply
            // 5. __Request
            items { $($i:item)* }

            // List any rpc methods: rpc foo(arg1: Arg1, ..., argN: ArgN) -> Out
            service {
                $(
                    $(#[$attr:meta])*
                    rpc $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty;
                )*
            }
        }
    ) => {

        add_mod_doc! {
            { $(#[$($service_attr)*])* }
            pub mod $server {

                $($i)*

                #[doc="The provided RPC service."]
                pub trait Service: Send + Sync {
                    $(
                        $(#[$attr])*
                        fn $fn_name(&self, $($arg:$in_),*) -> $out;
                    )*
                }

                impl<P, S> Service for P
                    where P: Send + Sync + ::std::ops::Deref<Target=S>,
                          S: Service
                {
                    $(
                        $(#[$attr])*
                        fn $fn_name(&self, $($arg:$in_),*) -> $out {
                            Service::$fn_name(&**self, $($arg),*)
                        }
                    )*
                }

                define_request!($($fn_name($($in_),*))*);

                #[allow(non_camel_case_types)]
                #[derive(Debug, Serialize, Deserialize)]
                enum __Reply {
                    $(
                        $fn_name($out),
                    )*
                }

                /// An asynchronous RPC call
                pub struct Future<T> {
                    future: $crate::protocol::Future<__Reply>,
                    mapper: fn(__Reply) -> T,
                }

                impl<T> Future<T> {
                    /// Block until the result of the RPC call is available
                    pub fn get(self) -> $crate::Result<T> {
                        self.future.get().map(self.mapper)
                    }
                }

                #[doc="The client stub that makes RPC calls to the server."]
                pub struct Client($crate::protocol::Client<__Request, __Reply>);

                impl Client {
                    #[doc="Create a new client that connects to the given address."]
                    pub fn new<A>(addr: A, timeout: ::std::option::Option<::std::time::Duration>)
                        -> $crate::Result<Self>
                        where A: ::std::net::ToSocketAddrs,
                    {
                        let inner = try!($crate::protocol::Client::new(addr, timeout));
                        Ok(Client(inner))
                    }

                    client_methods!(
                        $(
                            { $(#[$attr])* }
                            $fn_name($($arg: $in_),*) -> $out
                        )*
                    );
                }

                #[doc="The client stub that makes asynchronous RPC calls to the server."]
                pub struct AsyncClient($crate::protocol::Client<__Request, __Reply>);

                impl AsyncClient {
                    #[doc="Create a new asynchronous client that connects to the given address."]
                    pub fn new<A>(addr: A, timeout: ::std::option::Option<::std::time::Duration>)
                        -> $crate::Result<Self>
                        where A: ::std::net::ToSocketAddrs,
                    {
                        let inner = try!($crate::protocol::Client::new(addr, timeout));
                        Ok(AsyncClient(inner))
                    }

                    async_client_methods!(
                        $(
                            { $(#[$attr])* }
                            $fn_name($($arg: $in_),*) -> $out
                        )*
                    );
                }

                struct __Server<S: 'static + Service>(S);

                impl<S> $crate::protocol::Serve for __Server<S>
                    where S: 'static + Service
                {
                    type Request = __Request;
                    type Reply = __Reply;
                    fn serve(&self, request: __Request) -> __Reply {
                        match request {
                            $(
                                request_variant!($fn_name $($arg),*) =>
                                    __Reply::$fn_name((self.0).$fn_name($($arg),*)),
                             )*
                        }
                    }
                }

                #[doc="Start a running service."]
                pub fn serve<A, S>(addr: A,
                                   service: S,
                                   read_timeout: ::std::option::Option<::std::time::Duration>)
                    -> $crate::Result<$crate::protocol::ServeHandle>
                    where A: ::std::net::ToSocketAddrs,
                          S: 'static + Service
                {
                    let server = ::std::sync::Arc::new(__Server(service));
                    Ok(try!($crate::protocol::serve_async(addr, server, read_timeout)))
                }
            }
        }
    }
}

#[cfg(test)]
#[allow(dead_code)]
mod test {
    extern crate env_logger;
    use std::time::Duration;
    use test::Bencher;

    fn test_timeout() -> Option<Duration> {
        Some(Duration::from_secs(5))
    }

    rpc! {
        #[deny(missing_docs)]
        #[doc="Hello"]
        mod my_server {
            items {
                #[derive(PartialEq, Debug, Serialize, Deserialize)]
                pub struct Foo {
                    pub message: String
                }
            }

            service {
                rpc hello(foo: Foo) -> Foo;
                rpc add(x: i32, y: i32) -> i32;
            }
        }
    }

    use self::my_server::*;

    struct Server;
    impl Service for Server {
        fn hello(&self, s: Foo) -> Foo {
            Foo { message: format!("Hello, {}", &s.message) }
        }

        fn add(&self, x: i32, y: i32) -> i32 {
            x + y
        }
    }

    #[test]
    fn serve_arc_server() {
        serve("localhost:0", ::std::sync::Arc::new(Server), None)
            .unwrap()
            .shutdown();
    }

    #[test]
    fn simple_test() {
        println!("Starting");
        let addr = "127.0.0.1:9000";
        let shutdown = my_server::serve(addr, Server, test_timeout()).unwrap();
        let client = Client::new(addr, None).unwrap();
        assert_eq!(3, client.add(1, 2).unwrap());
        let foo = Foo { message: "Adam".into() };
        let want = Foo { message: format!("Hello, {}", &foo.message) };
        assert_eq!(want, client.hello(Foo { message: "Adam".into() }).unwrap());
        drop(client);
        shutdown.shutdown();
    }

    // Tests a service definition with a fn that takes no args
    rpc! {
        mod qux {
            service {
                rpc hello() -> String;
            }
        }
    }

    // Tests a service definition with an import
    rpc! {
        mod foo {
            items {
                use std::collections::HashMap;
            }

            service {
                #[doc="Hello bob"]
                #[inline(always)]
                rpc baz(s: String) -> HashMap<String, String>;
            }
        }
    }

    // Tests a service definition with an attribute but no doc comment
    rpc! {
        #[deny(missing_docs)]
        mod bar {
            items {
                use std::collections::HashMap;
            }

            service {
                #[inline(always)]
                rpc baz(s: String) -> HashMap<String, String>;
            }
        }
    }

    // Tests a service definition with an attribute and a doc comment
    rpc! {
        #[deny(missing_docs)]
        #[doc="Hello bob"]
        #[allow(unused)]
        mod baz {
            items {
                use std::collections::HashMap;

                #[derive(Debug)]
                pub struct Debuggable;
            }

            service {
                #[doc="Hello bob"]
                #[inline(always)]
                rpc baz(s: String) -> HashMap<String, String>;
            }
        }
    }

    #[test]
    fn debug() {
        println!("{:?}", baz::Debuggable);
    }

    rpc! {
        mod hello {
            service {
                rpc hello(s: String) -> String;
            }
        }
    }

    struct HelloServer;
    impl hello::Service for HelloServer {
        fn hello(&self, s: String) -> String {
            format!("Hello, {}!", s)
        }
    }

    #[bench]
    fn hello(bencher: &mut Bencher) {
        let _ = env_logger::init();
        let handle = hello::serve("localhost:0", HelloServer, None).unwrap();
        let client = hello::AsyncClient::new(handle.local_addr(), None).unwrap();
        let mut rpcs = Vec::with_capacity(100);
        bencher.iter(|| {
            for _ in 0..1000 {
                rpcs.push(client.hello("Bob".into()));
            }
            for _ in 0..1000 {
                rpcs.pop().unwrap().get().unwrap();
            }
        });
        drop(client);
        handle.shutdown();
    }
}
<commit_msg>clean up benchmark<commit_after>// Copyright 2016 Google Inc. All Rights Reserved.
//
// 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.

#[doc(hidden)]
#[macro_export]
macro_rules! as_item { ($i:item) => {$i} }

// Inserts a placeholder doc comment for the module if it's missing
#[doc(hidden)]
#[macro_export]
macro_rules! add_mod_doc {
    // If nothing left, return
    (
        @rec
        { $(#[$done:meta])* }
        { }
        $i:item
    ) => {
        $(#[$done])*
        #[doc="A module containing an rpc service and client stub."]
        $i
    };

    // If we find a doc attribute, return
    (
        @rec
        { $(#[$done:meta])* }
        {
            #[doc=$doc:expr]
            $(#[$rest:meta])*
        }
        $i:item
    ) => {
        $(#[$done])*
        #[doc=$doc]
        $(#[$rest])*
        $i
    };

    // If we don't find a doc attribute, keep going
    (
        @rec
        { $(#[$($done:tt)*])* }
        {
            #[$($attr:tt)*]
            $($rest:tt)*
        }
        $i:item
    ) => {
        add_mod_doc! {
            @rec
            { $(#[$($done)*])* #[$($attr)*] }
            { $($rest)* }
            $i
        }
    };

    // Entry
    (
        { $(#[$($attr:tt)*])* }
        $i:item
    ) => {
        add_mod_doc! {
            @rec
            {}
            { $(#[$($attr)*])* }
            $i
        }
    };
}

// Required because if-let can't be used with irrefutable patterns, so it needs
// to be special cased.
#[doc(hidden)]
#[macro_export]
macro_rules! client_methods {
    (
        { $(#[$attr:meta])* }
        $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty
    ) => (
        $(#[$attr])*
        pub fn $fn_name(&self, $($arg: $in_),*) -> $crate::Result<$out> {
            let reply = try!((self.0).rpc(&request_variant!($fn_name $($arg),*)));
            let __Reply::$fn_name(reply) = reply;
            Ok(reply)
        }
    );
    ($(
            { $(#[$attr:meta])* }
            $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty
    )*) => ( $(
        $(#[$attr])*
        pub fn $fn_name(&self, $($arg: $in_),*) -> $crate::Result<$out> {
            let reply = try!((self.0).rpc(&request_variant!($fn_name $($arg),*)));
            if let __Reply::$fn_name(reply) = reply {
                Ok(reply)
            } else {
                panic!("Incorrect reply variant returned from protocol::Clientrpc; expected `{}`, but got {:?}", stringify!($fn_name), reply);
            }
        }
    )*);
}

// Required because if-let can't be used with irrefutable patterns, so it needs
// to be special cased.
#[doc(hidden)]
#[macro_export]
macro_rules! async_client_methods {
    (
        { $(#[$attr:meta])* }
        $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty
    ) => (
        $(#[$attr])*
        pub fn $fn_name(&self, $($arg: $in_),*) -> Future<$out> {
            fn mapper(reply: __Reply) -> $out {
                let __Reply::$fn_name(reply) = reply;
                reply
            }
            let reply = (self.0).rpc_async(&request_variant!($fn_name $($arg),*));
            Future {
                future: reply,
                mapper: mapper,
            }
        }
    );
    ($(
            { $(#[$attr:meta])* }
            $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty
    )*) => ( $(
        $(#[$attr])*
        pub fn $fn_name(&self, $($arg: $in_),*) -> Future<$out> {
            fn mapper(reply: __Reply) -> $out {
                if let __Reply::$fn_name(reply) = reply {
                    reply
                } else {
                    panic!("Incorrect reply variant returned from protocol::Clientrpc; expected `{}`, but got {:?}", stringify!($fn_name), reply);
                }
            }
            let reply = (self.0).rpc_async(&request_variant!($fn_name $($arg),*));
            Future {
                future: reply,
                mapper: mapper,
            }
        }
    )*);
}

// Required because enum variants with no fields can't be suffixed by parens
#[doc(hidden)]
#[macro_export]
macro_rules! define_request {
    ($(@($($finished:tt)*))* --) => (as_item!(
            #[allow(non_camel_case_types)]
            #[derive(Debug, Serialize, Deserialize)]
            enum __Request { $($($finished)*),* }
    ););
    ($(@$finished:tt)* -- $name:ident() $($req:tt)*) =>
        (define_request!($(@$finished)* @($name) -- $($req)*););
    ($(@$finished:tt)* -- $name:ident $args: tt $($req:tt)*) =>
        (define_request!($(@$finished)* @($name $args) -- $($req)*););
    ($($started:tt)*) => (define_request!(-- $($started)*););
}

// Required because enum variants with no fields can't be suffixed by parens
#[doc(hidden)]
#[macro_export]
macro_rules! request_variant {
    ($x:ident) => (__Request::$x);
    ($x:ident $($y:ident),+) => (__Request::$x($($y),+));
}

// The main macro that creates RPC services.
#[macro_export]
macro_rules! rpc {
    (
        $(#[$($service_attr:tt)*])*
        mod $server:ident {

            service {
                $(
                    $(#[$attr:meta])*
                    rpc $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty;
                )*
            }
        }
    ) => {
        rpc! {
            $(#[$($service_attr)*])*
            mod $server {

                items { }

                service {
                    $(
                        $(#[$attr])*
                        rpc $fn_name($($arg: $in_),*) -> $out;
                    )*
                }
            }
        }
    };

    (
        // Names the service
        $(#[$($service_attr:tt)*])*
        mod $server:ident {

            // Include any desired or required items. Conflicts can arise with the following names:
            // 1. Service
            // 2. Client
            // 3. serve
            // 4. __Reply
            // 5. __Request
            items { $($i:item)* }

            // List any rpc methods: rpc foo(arg1: Arg1, ..., argN: ArgN) -> Out
            service {
                $(
                    $(#[$attr:meta])*
                    rpc $fn_name:ident( $( $arg:ident : $in_:ty ),* ) -> $out:ty;
                )*
            }
        }
    ) => {

        add_mod_doc! {
            { $(#[$($service_attr)*])* }
            pub mod $server {

                $($i)*

                #[doc="The provided RPC service."]
                pub trait Service: Send + Sync {
                    $(
                        $(#[$attr])*
                        fn $fn_name(&self, $($arg:$in_),*) -> $out;
                    )*
                }

                impl<P, S> Service for P
                    where P: Send + Sync + ::std::ops::Deref<Target=S>,
                          S: Service
                {
                    $(
                        $(#[$attr])*
                        fn $fn_name(&self, $($arg:$in_),*) -> $out {
                            Service::$fn_name(&**self, $($arg),*)
                        }
                    )*
                }

                define_request!($($fn_name($($in_),*))*);

                #[allow(non_camel_case_types)]
                #[derive(Debug, Serialize, Deserialize)]
                enum __Reply {
                    $(
                        $fn_name($out),
                    )*
                }

                /// An asynchronous RPC call
                pub struct Future<T> {
                    future: $crate::protocol::Future<__Reply>,
                    mapper: fn(__Reply) -> T,
                }

                impl<T> Future<T> {
                    /// Block until the result of the RPC call is available
                    pub fn get(self) -> $crate::Result<T> {
                        self.future.get().map(self.mapper)
                    }
                }

                #[doc="The client stub that makes RPC calls to the server."]
                pub struct Client($crate::protocol::Client<__Request, __Reply>);

                impl Client {
                    #[doc="Create a new client that connects to the given address."]
                    pub fn new<A>(addr: A, timeout: ::std::option::Option<::std::time::Duration>)
                        -> $crate::Result<Self>
                        where A: ::std::net::ToSocketAddrs,
                    {
                        let inner = try!($crate::protocol::Client::new(addr, timeout));
                        Ok(Client(inner))
                    }

                    client_methods!(
                        $(
                            { $(#[$attr])* }
                            $fn_name($($arg: $in_),*) -> $out
                        )*
                    );
                }

                #[doc="The client stub that makes asynchronous RPC calls to the server."]
                pub struct AsyncClient($crate::protocol::Client<__Request, __Reply>);

                impl AsyncClient {
                    #[doc="Create a new asynchronous client that connects to the given address."]
                    pub fn new<A>(addr: A, timeout: ::std::option::Option<::std::time::Duration>)
                        -> $crate::Result<Self>
                        where A: ::std::net::ToSocketAddrs,
                    {
                        let inner = try!($crate::protocol::Client::new(addr, timeout));
                        Ok(AsyncClient(inner))
                    }

                    async_client_methods!(
                        $(
                            { $(#[$attr])* }
                            $fn_name($($arg: $in_),*) -> $out
                        )*
                    );
                }

                struct __Server<S: 'static + Service>(S);

                impl<S> $crate::protocol::Serve for __Server<S>
                    where S: 'static + Service
                {
                    type Request = __Request;
                    type Reply = __Reply;
                    fn serve(&self, request: __Request) -> __Reply {
                        match request {
                            $(
                                request_variant!($fn_name $($arg),*) =>
                                    __Reply::$fn_name((self.0).$fn_name($($arg),*)),
                             )*
                        }
                    }
                }

                #[doc="Start a running service."]
                pub fn serve<A, S>(addr: A,
                                   service: S,
                                   read_timeout: ::std::option::Option<::std::time::Duration>)
                    -> $crate::Result<$crate::protocol::ServeHandle>
                    where A: ::std::net::ToSocketAddrs,
                          S: 'static + Service
                {
                    let server = ::std::sync::Arc::new(__Server(service));
                    Ok(try!($crate::protocol::serve_async(addr, server, read_timeout)))
                }
            }
        }
    }
}

#[cfg(test)]
#[allow(dead_code)]
mod test {
    extern crate env_logger;
    use std::time::Duration;
    use test::Bencher;

    fn test_timeout() -> Option<Duration> {
        Some(Duration::from_secs(5))
    }

    rpc! {
        #[deny(missing_docs)]
        #[doc="Hello"]
        mod my_server {
            items {
                #[derive(PartialEq, Debug, Serialize, Deserialize)]
                pub struct Foo {
                    pub message: String
                }
            }

            service {
                rpc hello(foo: Foo) -> Foo;
                rpc add(x: i32, y: i32) -> i32;
            }
        }
    }

    use self::my_server::*;

    struct Server;
    impl Service for Server {
        fn hello(&self, s: Foo) -> Foo {
            Foo { message: format!("Hello, {}", &s.message) }
        }

        fn add(&self, x: i32, y: i32) -> i32 {
            x + y
        }
    }

    #[test]
    fn serve_arc_server() {
        serve("localhost:0", ::std::sync::Arc::new(Server), None)
            .unwrap()
            .shutdown();
    }

    #[test]
    fn simple_test() {
        println!("Starting");
        let addr = "127.0.0.1:9000";
        let shutdown = my_server::serve(addr, Server, test_timeout()).unwrap();
        let client = Client::new(addr, None).unwrap();
        assert_eq!(3, client.add(1, 2).unwrap());
        let foo = Foo { message: "Adam".into() };
        let want = Foo { message: format!("Hello, {}", &foo.message) };
        assert_eq!(want, client.hello(Foo { message: "Adam".into() }).unwrap());
        drop(client);
        shutdown.shutdown();
    }

    // Tests a service definition with a fn that takes no args
    rpc! {
        mod qux {
            service {
                rpc hello() -> String;
            }
        }
    }

    // Tests a service definition with an import
    rpc! {
        mod foo {
            items {
                use std::collections::HashMap;
            }

            service {
                #[doc="Hello bob"]
                #[inline(always)]
                rpc baz(s: String) -> HashMap<String, String>;
            }
        }
    }

    // Tests a service definition with an attribute but no doc comment
    rpc! {
        #[deny(missing_docs)]
        mod bar {
            items {
                use std::collections::HashMap;
            }

            service {
                #[inline(always)]
                rpc baz(s: String) -> HashMap<String, String>;
            }
        }
    }

    // Tests a service definition with an attribute and a doc comment
    rpc! {
        #[deny(missing_docs)]
        #[doc="Hello bob"]
        #[allow(unused)]
        mod baz {
            items {
                use std::collections::HashMap;

                #[derive(Debug)]
                pub struct Debuggable;
            }

            service {
                #[doc="Hello bob"]
                #[inline(always)]
                rpc baz(s: String) -> HashMap<String, String>;
            }
        }
    }

    #[test]
    fn debug() {
        println!("{:?}", baz::Debuggable);
    }

    rpc! {
        mod hello {
            service {
                rpc hello(s: String) -> String;
            }
        }
    }

    struct HelloServer;
    impl hello::Service for HelloServer {
        fn hello(&self, s: String) -> String {
            format!("Hello, {}!", s)
        }
    }

    #[bench]
    fn hello(bencher: &mut Bencher) {
        let _ = env_logger::init();
        let handle = hello::serve("localhost:0", HelloServer, None).unwrap();
        let client = hello::AsyncClient::new(handle.local_addr(), None).unwrap();
        let concurrency = 100;
        let mut rpcs = Vec::with_capacity(concurrency);
        bencher.iter(|| {
            for _ in 0..concurrency {
                rpcs.push(client.hello("Bob".into()));
            }
            for _ in 0..concurrency {
                rpcs.pop().unwrap().get().unwrap();
            }
        });
        drop(client);
        handle.shutdown();
    }
}
<|endoftext|>


<commit_before>//! Test cases for new rustup UI

extern crate multirust_dist;
extern crate multirust_utils;
extern crate multirust_mock;
extern crate tempdir;

use multirust_mock::clitools::{self, Config, Scenario,
                               expect_ok, expect_ok_ex,
                               expect_stdout_ok,
                               expect_err_ex,
                               set_current_dist_date,
                               this_host_triple};

macro_rules! for_host { ($s: expr) => (&format!($s, this_host_triple())) }

pub fn setup(f: &Fn(&Config)) {
    clitools::setup(Scenario::ArchivesV2, &|config| {
        f(config);
    });
}

#[test]
fn rustup_stable() {
    setup(&|config| {
        set_current_dist_date(config, "2015-01-01");
        expect_ok(config, &["rustup", "update", "stable"]);
        set_current_dist_date(config, "2015-01-02");
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
for_host!(r"
  stable-{0} updated - 1.1.0 (hash-s-2)

"),
for_host!(r"info: syncing channel updates for 'stable-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
"));
    });
}

#[test]
fn rustup_stable_no_change() {
    setup(&|config| {
        set_current_dist_date(config, "2015-01-01");
        expect_ok(config, &["rustup", "update", "stable"]);
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
for_host!(r"
  stable-{0} unchanged - 1.0.0 (hash-s-1)

"),
for_host!(r"info: syncing channel updates for 'stable-{0}'
"));
    });
}

#[test]
fn rustup_all_channels() {
    setup(&|config| {
        set_current_dist_date(config, "2015-01-01");
        expect_ok(config, &["rustup", "update", "stable"]);
        expect_ok(config, &["multirust", "update", "beta"]);
        expect_ok(config, &["multirust", "update", "nightly"]);
        set_current_dist_date(config, "2015-01-02");
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
for_host!(r"
   stable-{0} updated - 1.1.0 (hash-s-2)
     beta-{0} updated - 1.2.0 (hash-b-2)
  nightly-{0} updated - 1.3.0 (hash-n-2)

"),
for_host!(r"info: syncing channel updates for 'stable-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: syncing channel updates for 'beta-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: syncing channel updates for 'nightly-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
"));
    })
}

#[test]
fn rustup_some_channels_up_to_date() {
    setup(&|config| {
        set_current_dist_date(config, "2015-01-01");
        expect_ok(config, &["rustup", "update", "stable"]);
        expect_ok(config, &["multirust", "update", "beta"]);
        expect_ok(config, &["multirust", "update", "nightly"]);
        set_current_dist_date(config, "2015-01-02");
        expect_ok(config, &["multirust", "update", "beta"]);
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
for_host!(r"
   stable-{0} updated - 1.1.0 (hash-s-2)
   beta-{0} unchanged - 1.2.0 (hash-b-2)
  nightly-{0} updated - 1.3.0 (hash-n-2)

"),
for_host!(r"info: syncing channel updates for 'stable-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: syncing channel updates for 'beta-{0}'
info: syncing channel updates for 'nightly-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
"));
    })
}

#[test]
fn rustup_no_channels() {
    setup(&|config| {
        expect_ok(config, &["rustup", "update", "stable"]);
        expect_ok(config, &["multirust", "remove-toolchain", "stable"]);
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
r"",
r"info: no updatable toolchains installed
");
    })
}

#[test]
fn default() {
    setup(&|config| {
        expect_ok_ex(config, &["rustup", "default", "nightly"],
for_host!(r"
  nightly-{0} installed - 1.3.0 (hash-n-2)

"),
for_host!(r"info: syncing channel updates for 'nightly-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: default toolchain set to 'nightly-{0}'
"));
    });
}

#[test]
fn add_target() {
    setup(&|config| {
        let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib",
                           &this_host_triple(), clitools::CROSS_ARCH1);
        expect_ok(config, &["rustup", "default", "nightly"]);
        expect_ok(config, &["rustup", "target", "add",
                            clitools::CROSS_ARCH1]);
        assert!(config.rustupdir.join(path).exists());
    });
}

#[test]
fn remove_target() {
    setup(&|config| {
        let ref path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib",
                               &this_host_triple(), clitools::CROSS_ARCH1);
        expect_ok(config, &["rustup", "default", "nightly"]);
        expect_ok(config, &["rustup", "target", "add",
                            clitools::CROSS_ARCH1]);
        assert!(config.rustupdir.join(path).exists());
        expect_ok(config, &["rustup", "target", "remove",
                            clitools::CROSS_ARCH1]);
        assert!(!config.rustupdir.join(path).exists());
    });
}

#[test]
fn list_targets() {
    setup(&|config| {
        expect_ok(config, &["rustup", "default", "nightly"]);
        expect_stdout_ok(config, &["rustup", "target", "list"],
                         clitools::CROSS_ARCH1);
    });
}

#[test]
fn add_target_explicit() {
    setup(&|config| {
        let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib",
                           &this_host_triple(), clitools::CROSS_ARCH1);
        expect_ok(config, &["rustup", "update", "nightly"]);
        expect_ok(config, &["rustup", "target", "add", "--toolchain", "nightly",
                            clitools::CROSS_ARCH1]);
        assert!(config.rustupdir.join(path).exists());
    });
}

#[test]
fn remove_target_explicit() {
    setup(&|config| {
        let ref path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib",
                               &this_host_triple(), clitools::CROSS_ARCH1);
        expect_ok(config, &["rustup", "update", "nightly"]);
        expect_ok(config, &["rustup", "target", "add", "--toolchain", "nightly",
                            clitools::CROSS_ARCH1]);
        assert!(config.rustupdir.join(path).exists());
        expect_ok(config, &["rustup", "target", "remove", "--toolchain", "nightly",
                            clitools::CROSS_ARCH1]);
        assert!(!config.rustupdir.join(path).exists());
    });
}

#[test]
fn list_targets_explicit() {
    setup(&|config| {
        expect_ok(config, &["rustup", "update", "nightly"]);
        expect_stdout_ok(config, &["rustup", "target", "list", "--toolchain", "nightly"],
                         clitools::CROSS_ARCH1);
    });
}

#[test]
fn link() {
    setup(&|config| {
        let path = config.customdir.join("custom-1");
        let path = path.to_string_lossy();
        expect_ok(config, &["rustup", "toolchain", "link", "custom",
                            &path]);
        expect_ok(config, &["rustup", "default", "custom"]);
        expect_stdout_ok(config, &["rustc", "--version"],
                         "hash-c-1");
    });
}

#[test]
fn show_toolchain_none() {
    setup(&|config| {
        expect_ok_ex(config, &["rustup", "show"],
r"no active toolchain
",
r"");
    });
}

#[test]
fn show_toolchain_default() {
    setup(&|config| {
        expect_ok(config, &["rustup", "default", "nightly"]);
        expect_ok_ex(config, &["rustup", "show"],
for_host!(r"nightly-{0} (default toolchain)
"),
r"");
    });
}

#[test]
#[ignore(windows)] // FIXME rustup displays UNC paths
fn show_toolchain_override() {
    setup(&|config| {
        let cwd = ::std::env::current_dir().unwrap();
        expect_ok(config, &["rustup", "override", "add", "nightly"]);
        expect_ok_ex(config, &["rustup", "show"],
&format!(r"nightly (directory override for '{}')
", cwd.display()),
r"");
    });
}

#[test]
fn show_toolchain_override_not_installed() {
    setup(&|config| {
        expect_ok(config, &["rustup", "override", "add", "nightly"]);
        expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]);
        // I'm not sure this should really be erroring when the toolchain
        // is not installed; just capturing the behavior.
        expect_err_ex(config, &["rustup", "show"],
r"",
for_host!(r"error: toolchain 'nightly-{0}' is not installed
"));
    });
}

#[test]
fn show_toolchain_env() {
    setup(&|config| {
        expect_ok(config, &["rustup", "default", "nightly"]);
        let mut cmd = clitools::cmd(config, "rustup", &["show"]);
        clitools::env(config, &mut cmd);
        cmd.env("RUSTUP_TOOLCHAIN", "nightly");
        let out = cmd.output().unwrap();
        assert!(out.status.success());
        let stdout = String::from_utf8(out.stdout).unwrap();
        assert!(&stdout == for_host!("nightly-{0} (environment override by RUSTUP_TOOLCHAIN)\n"));
    });
}

#[test]
fn show_toolchain_env_not_installed() {
    setup(&|config| {
        let mut cmd = clitools::cmd(config, "rustup", &["show"]);
        clitools::env(config, &mut cmd);
        cmd.env("RUSTUP_TOOLCHAIN", "nightly");
        let out = cmd.output().unwrap();
        // I'm not sure this should really be erroring when the toolchain
        // is not installed; just capturing the behavior.
        assert!(!out.status.success());
        let stderr = String::from_utf8(out.stderr).unwrap();
        assert!(stderr == "error: toolchain 'nightly' is not installed\n");
    });
}
<commit_msg>adds test for 'rustup toolchain list' displaying default<commit_after>//! Test cases for new rustup UI

extern crate multirust_dist;
extern crate multirust_utils;
extern crate multirust_mock;
extern crate tempdir;

use multirust_mock::clitools::{self, Config, Scenario,
                               expect_ok, expect_ok_ex,
                               expect_stdout_ok,
                               expect_err_ex,
                               set_current_dist_date,
                               this_host_triple};

macro_rules! for_host { ($s: expr) => (&format!($s, this_host_triple())) }

pub fn setup(f: &Fn(&Config)) {
    clitools::setup(Scenario::ArchivesV2, &|config| {
        f(config);
    });
}

#[test]
fn rustup_stable() {
    setup(&|config| {
        set_current_dist_date(config, "2015-01-01");
        expect_ok(config, &["rustup", "update", "stable"]);
        set_current_dist_date(config, "2015-01-02");
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
for_host!(r"
  stable-{0} updated - 1.1.0 (hash-s-2)

"),
for_host!(r"info: syncing channel updates for 'stable-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
"));
    });
}

#[test]
fn rustup_stable_no_change() {
    setup(&|config| {
        set_current_dist_date(config, "2015-01-01");
        expect_ok(config, &["rustup", "update", "stable"]);
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
for_host!(r"
  stable-{0} unchanged - 1.0.0 (hash-s-1)

"),
for_host!(r"info: syncing channel updates for 'stable-{0}'
"));
    });
}

#[test]
fn rustup_all_channels() {
    setup(&|config| {
        set_current_dist_date(config, "2015-01-01");
        expect_ok(config, &["rustup", "update", "stable"]);
        expect_ok(config, &["multirust", "update", "beta"]);
        expect_ok(config, &["multirust", "update", "nightly"]);
        set_current_dist_date(config, "2015-01-02");
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
for_host!(r"
   stable-{0} updated - 1.1.0 (hash-s-2)
     beta-{0} updated - 1.2.0 (hash-b-2)
  nightly-{0} updated - 1.3.0 (hash-n-2)

"),
for_host!(r"info: syncing channel updates for 'stable-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: syncing channel updates for 'beta-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: syncing channel updates for 'nightly-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
"));
    })
}

#[test]
fn rustup_some_channels_up_to_date() {
    setup(&|config| {
        set_current_dist_date(config, "2015-01-01");
        expect_ok(config, &["rustup", "update", "stable"]);
        expect_ok(config, &["multirust", "update", "beta"]);
        expect_ok(config, &["multirust", "update", "nightly"]);
        set_current_dist_date(config, "2015-01-02");
        expect_ok(config, &["multirust", "update", "beta"]);
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
for_host!(r"
   stable-{0} updated - 1.1.0 (hash-s-2)
   beta-{0} unchanged - 1.2.0 (hash-b-2)
  nightly-{0} updated - 1.3.0 (hash-n-2)

"),
for_host!(r"info: syncing channel updates for 'stable-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: syncing channel updates for 'beta-{0}'
info: syncing channel updates for 'nightly-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
"));
    })
}

#[test]
fn rustup_no_channels() {
    setup(&|config| {
        expect_ok(config, &["rustup", "update", "stable"]);
        expect_ok(config, &["multirust", "remove-toolchain", "stable"]);
        expect_ok_ex(config, &["rustup", "update", "--no-self-update"],
r"",
r"info: no updatable toolchains installed
");
    })
}

#[test]
fn default() {
    setup(&|config| {
        expect_ok_ex(config, &["rustup", "default", "nightly"],
for_host!(r"
  nightly-{0} installed - 1.3.0 (hash-n-2)

"),
for_host!(r"info: syncing channel updates for 'nightly-{0}'
info: downloading component 'rust-std'
info: downloading component 'rustc'
info: downloading component 'cargo'
info: downloading component 'rust-docs'
info: installing component 'rust-std'
info: installing component 'rustc'
info: installing component 'cargo'
info: installing component 'rust-docs'
info: default toolchain set to 'nightly-{0}'
"));
    });
}

#[test]
fn add_target() {
    setup(&|config| {
        let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib",
                           &this_host_triple(), clitools::CROSS_ARCH1);
        expect_ok(config, &["rustup", "default", "nightly"]);
        expect_ok(config, &["rustup", "target", "add",
                            clitools::CROSS_ARCH1]);
        assert!(config.rustupdir.join(path).exists());
    });
}

#[test]
fn remove_target() {
    setup(&|config| {
        let ref path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib",
                               &this_host_triple(), clitools::CROSS_ARCH1);
        expect_ok(config, &["rustup", "default", "nightly"]);
        expect_ok(config, &["rustup", "target", "add",
                            clitools::CROSS_ARCH1]);
        assert!(config.rustupdir.join(path).exists());
        expect_ok(config, &["rustup", "target", "remove",
                            clitools::CROSS_ARCH1]);
        assert!(!config.rustupdir.join(path).exists());
    });
}

#[test]
fn list_targets() {
    setup(&|config| {
        expect_ok(config, &["rustup", "default", "nightly"]);
        expect_stdout_ok(config, &["rustup", "target", "list"],
                         clitools::CROSS_ARCH1);
    });
}

#[test]
fn add_target_explicit() {
    setup(&|config| {
        let path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib",
                           &this_host_triple(), clitools::CROSS_ARCH1);
        expect_ok(config, &["rustup", "update", "nightly"]);
        expect_ok(config, &["rustup", "target", "add", "--toolchain", "nightly",
                            clitools::CROSS_ARCH1]);
        assert!(config.rustupdir.join(path).exists());
    });
}

#[test]
fn remove_target_explicit() {
    setup(&|config| {
        let ref path = format!("toolchains/nightly-{}/lib/rustlib/{}/lib/libstd.rlib",
                               &this_host_triple(), clitools::CROSS_ARCH1);
        expect_ok(config, &["rustup", "update", "nightly"]);
        expect_ok(config, &["rustup", "target", "add", "--toolchain", "nightly",
                            clitools::CROSS_ARCH1]);
        assert!(config.rustupdir.join(path).exists());
        expect_ok(config, &["rustup", "target", "remove", "--toolchain", "nightly",
                            clitools::CROSS_ARCH1]);
        assert!(!config.rustupdir.join(path).exists());
    });
}

#[test]
fn list_targets_explicit() {
    setup(&|config| {
        expect_ok(config, &["rustup", "update", "nightly"]);
        expect_stdout_ok(config, &["rustup", "target", "list", "--toolchain", "nightly"],
                         clitools::CROSS_ARCH1);
    });
}

#[test]
fn link() {
    setup(&|config| {
        let path = config.customdir.join("custom-1");
        let path = path.to_string_lossy();
        expect_ok(config, &["rustup", "toolchain", "link", "custom",
                            &path]);
        expect_ok(config, &["rustup", "default", "custom"]);
        expect_stdout_ok(config, &["rustc", "--version"],
                         "hash-c-1");
    });
}

#[test]
fn show_toolchain_none() {
    setup(&|config| {
        expect_ok_ex(config, &["rustup", "show"],
r"no active toolchain
",
r"");
    });
}

#[test]
fn show_toolchain_default() {
    setup(&|config| {
        expect_ok(config, &["rustup", "default", "nightly"]);
        expect_ok_ex(config, &["rustup", "show"],
for_host!(r"nightly-{0} (default toolchain)
"),
r"");
    });
}

#[test]
fn list_default_toolchain() {
    setup(&|config| {
        expect_ok(config, &["rustup", "default", "nightly"]);
        expect_ok_ex(config, &["rustup", "toolchain", "list"],
for_host!(r"nightly-{0} (default)
"),
r"");
    });
}

#[test]
#[ignore(windows)] // FIXME rustup displays UNC paths
fn show_toolchain_override() {
    setup(&|config| {
        let cwd = ::std::env::current_dir().unwrap();
        expect_ok(config, &["rustup", "override", "add", "nightly"]);
        expect_ok_ex(config, &["rustup", "show"],
&format!(r"nightly (directory override for '{}')
", cwd.display()),
r"");
    });
}

#[test]
fn show_toolchain_override_not_installed() {
    setup(&|config| {
        expect_ok(config, &["rustup", "override", "add", "nightly"]);
        expect_ok(config, &["rustup", "toolchain", "remove", "nightly"]);
        // I'm not sure this should really be erroring when the toolchain
        // is not installed; just capturing the behavior.
        expect_err_ex(config, &["rustup", "show"],
r"",
for_host!(r"error: toolchain 'nightly-{0}' is not installed
"));
    });
}

#[test]
fn show_toolchain_env() {
    setup(&|config| {
        expect_ok(config, &["rustup", "default", "nightly"]);
        let mut cmd = clitools::cmd(config, "rustup", &["show"]);
        clitools::env(config, &mut cmd);
        cmd.env("RUSTUP_TOOLCHAIN", "nightly");
        let out = cmd.output().unwrap();
        assert!(out.status.success());
        let stdout = String::from_utf8(out.stdout).unwrap();
        assert!(&stdout == for_host!("nightly-{0} (environment override by RUSTUP_TOOLCHAIN)\n"));
    });
}

#[test]
fn show_toolchain_env_not_installed() {
    setup(&|config| {
        let mut cmd = clitools::cmd(config, "rustup", &["show"]);
        clitools::env(config, &mut cmd);
        cmd.env("RUSTUP_TOOLCHAIN", "nightly");
        let out = cmd.output().unwrap();
        // I'm not sure this should really be erroring when the toolchain
        // is not installed; just capturing the behavior.
        assert!(!out.status.success());
        let stderr = String::from_utf8(out.stderr).unwrap();
        assert!(stderr == "error: toolchain 'nightly' is not installed\n");
    });
}
<|endoftext|>


<commit_before>extern crate lapin;
#[macro_use] extern crate nom;

use std::net::TcpStream;
use std::iter::repeat;
use std::io::{Read,Write,Error};

use nom::HexDisplay;

use lapin::connection::*;
use lapin::method::*;
use lapin::frame::*;

#[test]
fn connection() {
      let mut stream = TcpStream::connect("127.0.0.1:5672").unwrap();

      let capacity = 4096;
      let mut send_buffer: Vec<u8> = Vec::with_capacity(capacity);
      send_buffer.extend(repeat(0).take(capacity));
      let mut receive_buffer: Vec<u8> = Vec::with_capacity(capacity);
      receive_buffer.extend(repeat(0).take(capacity));

      //let (sl, bytes_written) = gen_protocol_header((&mut send_buffer, 0)).unwrap();
      //assert_eq!(stream.write(&sl[..bytes_written]).unwrap(), bytes_written);

      let mut conn: Connection = Connection::new();
      assert_eq!(conn.connect(&mut stream).unwrap(), ConnectionState::Connecting(ConnectingState::SentProtocolHeader));

      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      //now connected

      //send channel
      conn.channel_open(1, "".to_string());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      //receive channel
      conn.channel_open(2, "".to_string());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      conn.basic_publish(1, 0, "".to_string(), "".to_string(), false, false);
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      panic!();
}
<commit_msg>declare queues, receive messages<commit_after>extern crate lapin;
#[macro_use] extern crate nom;

use std::net::TcpStream;
use std::iter::repeat;
use std::io::{Read,Write,Error};
use std::collections::HashMap;

use nom::HexDisplay;

use lapin::connection::*;
use lapin::method::*;
use lapin::frame::*;

#[test]
fn connection() {
      let mut stream = TcpStream::connect("127.0.0.1:5672").unwrap();

      let capacity = 4096;
      let mut send_buffer: Vec<u8> = Vec::with_capacity(capacity);
      send_buffer.extend(repeat(0).take(capacity));
      let mut receive_buffer: Vec<u8> = Vec::with_capacity(capacity);
      receive_buffer.extend(repeat(0).take(capacity));

      //let (sl, bytes_written) = gen_protocol_header((&mut send_buffer, 0)).unwrap();
      //assert_eq!(stream.write(&sl[..bytes_written]).unwrap(), bytes_written);

      let mut conn: Connection = Connection::new();
      assert_eq!(conn.connect(&mut stream).unwrap(), ConnectionState::Connecting(ConnectingState::SentProtocolHeader));

      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      //now connected

      //send channel
      conn.channel_open(1, "".to_string());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      //receive channel
      conn.channel_open(2, "".to_string());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      //create the hello queue
      conn.queue_declare(1, 0, "hello".to_string(), false, false, false, false, false, HashMap::new());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      conn.queue_declare(2, 0, "hello".to_string(), false, false, false, false, false, HashMap::new());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      println!("will consume");
      conn.basic_consume(2, 0, "hello".to_string(), "".to_string(), false, true, false, false, HashMap::new());
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());

      println!("will publish");
      conn.basic_publish(1, 0, "".to_string(), "hello".to_string(), false, false);
      let payload = b"Hello world!";
      conn.send_content_frames(1, 60, payload);
      println!("[{}] state: {:?}", line!(), conn.write(&mut stream).unwrap());
      println!("[{}] state: {:?}", line!(), conn.read(&mut stream).unwrap());
      panic!();
}
<|endoftext|>


<commit_before><commit_msg>Add expected data param to test fn check_archive_file<commit_after><|endoftext|>


<commit_before>use anyhow::{anyhow, Chain, Error};

fn error() -> Error {
    anyhow!(0).context(1).context(2).context(3)
}

#[test]
fn test_iter() {
    let e = error();
    let mut chain = e.chain();
    assert_eq!("3", chain.next().unwrap().to_string());
    assert_eq!("2", chain.next().unwrap().to_string());
    assert_eq!("1", chain.next().unwrap().to_string());
    assert_eq!("0", chain.next().unwrap().to_string());
    assert!(chain.next().is_none());
    assert!(chain.next_back().is_none());
}

#[test]
fn test_rev() {
    let e = error();
    let mut chain = e.chain().rev();
    assert_eq!("0", chain.next().unwrap().to_string());
    assert_eq!("1", chain.next().unwrap().to_string());
    assert_eq!("2", chain.next().unwrap().to_string());
    assert_eq!("3", chain.next().unwrap().to_string());
    assert!(chain.next().is_none());
    assert!(chain.next_back().is_none());
}

#[test]
fn test_len() {
    let e = error();
    let mut chain = e.chain();
    assert_eq!(4, chain.len());
    assert_eq!((4, Some(4)), chain.size_hint());
    assert_eq!("3", chain.next().unwrap().to_string());
    assert_eq!(3, chain.len());
    assert_eq!((3, Some(3)), chain.size_hint());
    assert_eq!("0", chain.next_back().unwrap().to_string());
    assert_eq!(2, chain.len());
    assert_eq!((2, Some(2)), chain.size_hint());
    assert_eq!("2", chain.next().unwrap().to_string());
    assert_eq!(1, chain.len());
    assert_eq!((1, Some(1)), chain.size_hint());
    assert_eq!("1", chain.next_back().unwrap().to_string());
    assert_eq!(0, chain.len());
    assert_eq!((0, Some(0)), chain.size_hint());
    assert!(chain.next().is_none());
}

#[test]
fn test_default() {
    let mut c = Chain::default();
    assert!(c.next().is_none());
}

#[test]
fn test_clone() {
    let e = error();
    let mut chain = e.chain().clone();
    assert_eq!("3", chain.next().unwrap().to_string());
    assert_eq!("2", chain.next().unwrap().to_string());
    assert_eq!("1", chain.next().unwrap().to_string());
    assert_eq!("0", chain.next().unwrap().to_string());
    assert!(chain.next().is_none());
    assert!(chain.next_back().is_none());
}
<commit_msg>Turn non-string literal macro arg in test suite into expr<commit_after>use anyhow::{anyhow, Chain, Error};

fn error() -> Error {
    anyhow!({ 0 }).context(1).context(2).context(3)
}

#[test]
fn test_iter() {
    let e = error();
    let mut chain = e.chain();
    assert_eq!("3", chain.next().unwrap().to_string());
    assert_eq!("2", chain.next().unwrap().to_string());
    assert_eq!("1", chain.next().unwrap().to_string());
    assert_eq!("0", chain.next().unwrap().to_string());
    assert!(chain.next().is_none());
    assert!(chain.next_back().is_none());
}

#[test]
fn test_rev() {
    let e = error();
    let mut chain = e.chain().rev();
    assert_eq!("0", chain.next().unwrap().to_string());
    assert_eq!("1", chain.next().unwrap().to_string());
    assert_eq!("2", chain.next().unwrap().to_string());
    assert_eq!("3", chain.next().unwrap().to_string());
    assert!(chain.next().is_none());
    assert!(chain.next_back().is_none());
}

#[test]
fn test_len() {
    let e = error();
    let mut chain = e.chain();
    assert_eq!(4, chain.len());
    assert_eq!((4, Some(4)), chain.size_hint());
    assert_eq!("3", chain.next().unwrap().to_string());
    assert_eq!(3, chain.len());
    assert_eq!((3, Some(3)), chain.size_hint());
    assert_eq!("0", chain.next_back().unwrap().to_string());
    assert_eq!(2, chain.len());
    assert_eq!((2, Some(2)), chain.size_hint());
    assert_eq!("2", chain.next().unwrap().to_string());
    assert_eq!(1, chain.len());
    assert_eq!((1, Some(1)), chain.size_hint());
    assert_eq!("1", chain.next_back().unwrap().to_string());
    assert_eq!(0, chain.len());
    assert_eq!((0, Some(0)), chain.size_hint());
    assert!(chain.next().is_none());
}

#[test]
fn test_default() {
    let mut c = Chain::default();
    assert!(c.next().is_none());
}

#[test]
fn test_clone() {
    let e = error();
    let mut chain = e.chain().clone();
    assert_eq!("3", chain.next().unwrap().to_string());
    assert_eq!("2", chain.next().unwrap().to_string());
    assert_eq!("1", chain.next().unwrap().to_string());
    assert_eq!("0", chain.next().unwrap().to_string());
    assert!(chain.next().is_none());
    assert!(chain.next_back().is_none());
}
<|endoftext|>


<commit_before>extern crate glutin;
#[macro_use] extern crate glium;
extern crate cgmath;
extern crate libc;
extern crate rovr;

use std::string;
use cgmath::{ToMatrix4, Matrix, Point, FixedArray, Vector};

fn main() {
    use glium::DisplayBuild;

    let context = rovr::Context::new().unwrap();
    let hmd = context.build_hmd()
        .allow_debug()
        .track(&rovr::TrackingOptions::with_all())
        .build()
        .ok().expect("Unable to build HMD");

    let monitor = rovr::target::find_glutin_monitor(&hmd.get_display());
    let builder = match monitor {
        Some(id) => glutin::WindowBuilder::new().with_fullscreen(id),
        None => {
            let (w, h) = hmd.resolution();
            glutin::WindowBuilder::new().with_dimensions(w, h)
        }
    };
    let display = builder
        .with_title(string::String::from("Cube"))
        .with_vsync()
        .with_gl_version((4, 1))
        .build_glium()
        .ok().expect("Unable to build Window");

    // NOTE: keeping this window around will cause rebuild to panic; not sure there's a way around
    // this with the current glium mutability/rebuild design
    let window = display.get_window().unwrap();
    let target = rovr::target::GlutinRenderTarget::new(&window, 1);
    let render = hmd.render_to(&target).unwrap();

    let program = basic_shader::compile(&display);
    let (vertex_buffer, index_buffer) = basic_shader::cube(&display);

    let attachments = glium_oculus::Attachments::new(&display, &render);
    let mut surfaces = glium_oculus::Surfaces::new(&display, &attachments);

    display_loop(&display, &attachments, &mut surfaces, |m, surface| {
        use glium::Surface;
        use cgmath::FixedArray;

        let uniforms = uniform! {
            uViewProjectionMatrix: *m.as_fixed()
        };

        let params = glium::DrawParameters {
            backface_culling: glium::BackfaceCullingMode::CullClockWise,
            depth_test: glium::DepthTest::IfLess,
            depth_write: true,
            .. std::default::Default::default()
        };

        surface.clear_color(0f32, 0f32, 0f32, 1f32);
        surface.clear_depth(1f32);
        surface.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &params).unwrap();
    });
}

fn display_loop<'a, F: Fn(&cgmath::Matrix4<f32>, &mut glium::framebuffer::SimpleFrameBuffer)>(
    display: &glium::Display,
    attachments: &'a glium_oculus::Attachments,
    surfaces: &'a mut glium_oculus::Surfaces<'a>,
    draw: F) {
    use cgmath::Matrix;

    let mut frame_index = 0u32;
    let (proj_left, proj_right) = {
        let projections: Vec<_> = [rovr::Eye::Left, rovr::Eye::Right].iter().map(|eye| {
            attachments.get_render_context().projection_matrix(&eye, 0.2f32, 10f32)
        }).collect();
        (projections[0], projections[1])
    };
    loop {
        {
            let frame = attachments.start_frame();
            for pose in frame.eye_poses() {
                let projection = match pose.eye {
                    rovr::Eye::Left => proj_left,
                    rovr::Eye::Right => proj_right
                };
                let fixed = cgmath::Vector3::new(0f32, 1f32, 2f32);
                let direction = cgmath::Vector3::new(0f32, 0f32, -1f32);
                let up = cgmath::Vector3::new(0f32, 1f32, 0f32);

                let camera_position = fixed.add_v(cgmath::Vector3::from_fixed_ref(&pose.position));
                let center = cgmath::Point3::from_vec(&camera_position.add_v(&direction));

                let orientation_mat = {
                    let (orientation_s, ref orientation_v) = pose.orientation;
                    cgmath::Quaternion::from_sv(orientation_s,
                                                *cgmath::Vector3::from_fixed_ref(orientation_v))
                        .to_matrix4()
                        .invert().unwrap()
                };
                let eye_transform = *cgmath::Matrix4::from_fixed_ref(&projection) *
                    orientation_mat *
                    cgmath::Matrix4::look_at(&cgmath::Point::from_vec(&camera_position),
                                             &center,
                                             &up);

                draw(&eye_transform, surfaces.surface_for_eye(&pose.eye));
            }
        }

        for event in display.poll_events() {
            match event {
                glutin::Event::Closed => return,
                glutin::Event::KeyboardInput(_, _, key) => {
                    attachments.get_render_context().dismiss_hsw();
                    match key {
                        Some(glutin::VirtualKeyCode::Escape) => return,
                        Some(glutin::VirtualKeyCode::R) =>
                            attachments.get_render_context().recenter_pose(),
                        _ => {}
                    }
                },
                _ => {}
            }
        }
        frame_index = frame_index + 1;
    }
}

mod glium_oculus {
    use rovr;
    use glium;
    use glium::texture::{Texture2d, DepthTexture2d};
    use glium::framebuffer::SimpleFrameBuffer;

    pub struct Attachments<'a> {
        render_context: &'a rovr::render::RenderContext<'a>,
        left: PerEyeAttachments,
        right: PerEyeAttachments,
        binding: rovr::render::TextureBinding,
    }

    struct PerEyeAttachments {
        color: Texture2d,
        depth: DepthTexture2d,
    }

    impl<'a> Attachments<'a> {
        pub fn new(display: &glium::Display,
                   render_context: &'a rovr::render::RenderContext) -> Attachments<'a> {
            use glium::GlObject;

            let left = Attachments::create_attachment(display, render_context, rovr::Eye::Left);
            let right = Attachments::create_attachment(display, render_context, rovr::Eye::Right);
            let binding = render_context.create_binding(left.color.get_id(), right.color.get_id());

            Attachments {
                render_context: render_context,
                left: left,
                right: right,
                binding: binding,
            }
        }

        pub fn start_frame(&self) -> rovr::render::Frame {
            rovr::render::Frame::new(self.render_context, &self.binding)
        }

        pub fn get_render_context(&'a self) -> &'a rovr::render::RenderContext {
            self.render_context
        }

        fn create_attachment(display: &glium::Display,
                             render_context: &rovr::render::RenderContext,
                             eye: rovr::Eye) -> PerEyeAttachments {
            let (w, h) = render_context.target_texture_size(&eye);
            let color: Texture2d = Texture2d::empty(display, w, h);
            let depth = DepthTexture2d::empty(display, w, h);

            PerEyeAttachments {
                color: color,
                depth: depth
            }
        }
    }

    pub struct Surfaces<'a> {
        left: SimpleFrameBuffer<'a>,
        right: SimpleFrameBuffer<'a>
    }

    impl<'a> Surfaces<'a> {
        pub fn new(display: &glium::Display, attachments: &'a Attachments) -> Surfaces<'a> {
            let left = SimpleFrameBuffer::with_depth_buffer(display,
                                                            &attachments.left.color,
                                                            &attachments.left.depth);
            let right = SimpleFrameBuffer::with_depth_buffer(display,
                                                             &attachments.right.color,
                                                             &attachments.right.depth);

            Surfaces {
                left: left,
                right: right
            }
        }

        pub fn surface_for_eye<'b>(&'b mut self, eye: &rovr::Eye)
            -> &'b mut SimpleFrameBuffer<'a> where 'a: 'b {
            match eye {
                &rovr::Eye::Left => &mut self.left,
                &rovr::Eye::Right => &mut self.right
            }
        }
    }
}

mod basic_shader {
    extern crate glium;

    #[derive(Copy, Clone)]
    #[allow(non_snake_case)]
    struct Vertex {
        aPosition: [f32; 3],
        aColor: [f32; 3]
    }

    implement_vertex!(Vertex, aPosition, aColor);

    impl Vertex {
        fn new(position: [f32; 3], color: [f32; 3]) -> Vertex {
            Vertex { aPosition: position, aColor: color }
        }
    }

    pub fn compile(display: &glium::Display) -> glium::Program {
        static VERTEX: &'static str = "
            #version 410

            uniform mat4 uViewProjectionMatrix;

            in vec3 aPosition;
            in vec3 aColor;

            out vec3 vColor;

            void main() {
                gl_Position = uViewProjectionMatrix * vec4(aPosition, 1);
                vColor = aColor;
            }
        ";

        static FRAGMENT: &'static str = "
            #version 410

            in vec3 vColor;
            out vec4 outColor;

            void main() {
                outColor = vec4(vColor, 1);
            }
        ";

        glium::Program::from_source(display, VERTEX, FRAGMENT, None).unwrap()
    }

    pub fn cube(display: &glium::Display) -> (glium::vertex::VertexBufferAny, glium::IndexBuffer) {
        let vertex_buffer = {
            let blue = [0f32, 0f32, 1f32];
            let green = [0f32, 1f32, 0f32];
            let red = [1f32, 0f32, 0f32];
            glium::VertexBuffer::new(display,
                                     vec![
                                        Vertex::new([-0.5f32, -0.5f32,  0.5f32], blue),
                                        Vertex::new([-0.5f32,  0.5f32,  0.5f32], red),
                                        Vertex::new([ 0.5f32, -0.5f32,  0.5f32], green),
                                        Vertex::new([ 0.5f32,  0.5f32,  0.5f32], blue),
                                        Vertex::new([-0.5f32,  0.5f32, -0.5f32], blue),
                                        Vertex::new([ 0.5f32,  0.5f32, -0.5f32], red),
                                        Vertex::new([-0.5f32, -0.5f32, -0.5f32], green),
                                        Vertex::new([ 0.5f32, -0.5f32, -0.5f32], blue)
                                     ]).into_vertex_buffer_any()
        };

        let index_buffer = {
            let triangles = vec![
                // front
                1u32, 0u32, 2u32,
                2u32, 3u32, 1u32,

                // top
                1u32, 3u32, 4u32,
                4u32, 3u32, 5u32,

                // right
                2u32, 7u32, 3u32,
                3u32, 7u32, 5u32,

                // left
                6u32, 0u32, 4u32,
                0u32, 1u32, 4u32,

                // bottom
                7u32, 0u32, 6u32,
                2u32, 0u32, 7u32,

                // back
                7u32, 6u32, 5u32,
                5u32, 6u32, 4u32
            ];
            glium::IndexBuffer::new(display, glium::index::TrianglesList(triangles))
        };

        (vertex_buffer, index_buffer)
    }
}

<commit_msg>updated example scene code for cgmath and glutin changes<commit_after>extern crate glutin;
#[macro_use] extern crate glium;
extern crate cgmath;
extern crate libc;
extern crate rovr;

use std::string;
use cgmath::{Matrix, Point, FixedArray, Vector};

fn main() {
    use glium::DisplayBuild;

    let context = rovr::Context::new().unwrap();
    let hmd = context.build_hmd()
        .allow_debug()
        .track(&rovr::TrackingOptions::with_all())
        .build()
        .ok().expect("Unable to build HMD");

    let monitor = rovr::target::find_glutin_monitor(&hmd.get_display());
    let builder = match monitor {
        Some(id) => glutin::WindowBuilder::new().with_fullscreen(id),
        None => {
            let (w, h) = hmd.resolution();
            glutin::WindowBuilder::new().with_dimensions(w, h)
        }
    };
    let display = builder
        .with_title(string::String::from("Cube"))
        .with_vsync()
        .with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (4, 1)))
        .build_glium()
        .ok().expect("Unable to build Window");

    // NOTE: keeping this window around will cause rebuild to panic; not sure there's a way around
    // this with the current glium mutability/rebuild design
    let window = display.get_window().unwrap();
    let target = rovr::target::GlutinRenderTarget::new(&window, 1);
    let render = hmd.render_to(&target).unwrap();

    let program = basic_shader::compile(&display);
    let (vertex_buffer, index_buffer) = basic_shader::cube(&display);

    let attachments = glium_oculus::Attachments::new(&display, &render);
    let mut surfaces = glium_oculus::Surfaces::new(&display, &attachments);

    display_loop(&display, &attachments, &mut surfaces, |m, surface| {
        use glium::Surface;
        use cgmath::FixedArray;

        let uniforms = uniform! {
            uViewProjectionMatrix: *m.as_fixed()
        };

        let params = glium::DrawParameters {
            backface_culling: glium::BackfaceCullingMode::CullClockWise,
            depth_test: glium::DepthTest::IfLess,
            depth_write: true,
            .. std::default::Default::default()
        };

        surface.clear_color(0f32, 0f32, 0f32, 1f32);
        surface.clear_depth(1f32);
        surface.draw(&vertex_buffer, &index_buffer, &program, &uniforms, &params).unwrap();
    });
}

fn display_loop<'a, F: Fn(&cgmath::Matrix4<f32>, &mut glium::framebuffer::SimpleFrameBuffer)>(
    display: &glium::Display,
    attachments: &'a glium_oculus::Attachments,
    surfaces: &'a mut glium_oculus::Surfaces<'a>,
    draw: F) {
    use cgmath::Matrix;

    let mut frame_index = 0u32;
    let (proj_left, proj_right) = {
        let projections: Vec<_> = [rovr::Eye::Left, rovr::Eye::Right].iter().map(|eye| {
            attachments.get_render_context().projection_matrix(&eye, 0.2f32, 10f32)
        }).collect();
        (projections[0], projections[1])
    };
    loop {
        {
            let frame = attachments.start_frame();
            for pose in frame.eye_poses() {
                let projection = match pose.eye {
                    rovr::Eye::Left => proj_left,
                    rovr::Eye::Right => proj_right
                };
                let fixed = cgmath::Vector3::new(0f32, 1f32, 2f32);
                let direction = cgmath::Vector3::new(0f32, 0f32, -1f32);
                let up = cgmath::Vector3::new(0f32, 1f32, 0f32);

                let camera_position = fixed.add_v(cgmath::Vector3::from_fixed_ref(&pose.position));
                let center = cgmath::Point3::from_vec(&camera_position.add_v(&direction));

                let orientation_mat = {
                    let mat: cgmath::Matrix4<_> = {
                        let (orientation_s, ref orientation_v) = pose.orientation;
                        cgmath::Quaternion::from_sv(orientation_s,
                            *cgmath::Vector3::from_fixed_ref(orientation_v))
                    }.into();
                    mat.invert().unwrap()
                };

                let eye_transform = *cgmath::Matrix4::from_fixed_ref(&projection) *
                    orientation_mat *
                    cgmath::Matrix4::look_at(&cgmath::Point::from_vec(&camera_position),
                                             &center,
                                             &up);

                draw(&eye_transform, surfaces.surface_for_eye(&pose.eye));
            }
        }

        for event in display.poll_events() {
            match event {
                glutin::Event::Closed => return,
                glutin::Event::KeyboardInput(_, _, key) => {
                    attachments.get_render_context().dismiss_hsw();
                    match key {
                        Some(glutin::VirtualKeyCode::Escape) => return,
                        Some(glutin::VirtualKeyCode::R) =>
                            attachments.get_render_context().recenter_pose(),
                        _ => {}
                    }
                },
                _ => {}
            }
        }
        frame_index = frame_index + 1;
    }
}

mod glium_oculus {
    use rovr;
    use glium;
    use glium::texture::{Texture2d, DepthTexture2d};
    use glium::framebuffer::SimpleFrameBuffer;

    pub struct Attachments<'a> {
        render_context: &'a rovr::render::RenderContext<'a>,
        left: PerEyeAttachments,
        right: PerEyeAttachments,
        binding: rovr::render::TextureBinding,
    }

    struct PerEyeAttachments {
        color: Texture2d,
        depth: DepthTexture2d,
    }

    impl<'a> Attachments<'a> {
        pub fn new(display: &glium::Display,
                   render_context: &'a rovr::render::RenderContext) -> Attachments<'a> {
            use glium::GlObject;

            let left = Attachments::create_attachment(display, render_context, rovr::Eye::Left);
            let right = Attachments::create_attachment(display, render_context, rovr::Eye::Right);
            let binding = render_context.create_binding(left.color.get_id(), right.color.get_id());

            Attachments {
                render_context: render_context,
                left: left,
                right: right,
                binding: binding,
            }
        }

        pub fn start_frame(&self) -> rovr::render::Frame {
            rovr::render::Frame::new(self.render_context, &self.binding)
        }

        pub fn get_render_context(&'a self) -> &'a rovr::render::RenderContext {
            self.render_context
        }

        fn create_attachment(display: &glium::Display,
                             render_context: &rovr::render::RenderContext,
                             eye: rovr::Eye) -> PerEyeAttachments {
            let (w, h) = render_context.target_texture_size(&eye);
            let color: Texture2d = Texture2d::empty(display, w, h);
            let depth = DepthTexture2d::empty(display, w, h);

            PerEyeAttachments {
                color: color,
                depth: depth
            }
        }
    }

    pub struct Surfaces<'a> {
        left: SimpleFrameBuffer<'a>,
        right: SimpleFrameBuffer<'a>
    }

    impl<'a> Surfaces<'a> {
        pub fn new(display: &glium::Display, attachments: &'a Attachments) -> Surfaces<'a> {
            let left = SimpleFrameBuffer::with_depth_buffer(display,
                                                            &attachments.left.color,
                                                            &attachments.left.depth);
            let right = SimpleFrameBuffer::with_depth_buffer(display,
                                                             &attachments.right.color,
                                                             &attachments.right.depth);

            Surfaces {
                left: left,
                right: right
            }
        }

        pub fn surface_for_eye<'b>(&'b mut self, eye: &rovr::Eye)
            -> &'b mut SimpleFrameBuffer<'a> where 'a: 'b {
            match eye {
                &rovr::Eye::Left => &mut self.left,
                &rovr::Eye::Right => &mut self.right
            }
        }
    }
}

mod basic_shader {
    extern crate glium;

    #[derive(Copy, Clone)]
    #[allow(non_snake_case)]
    struct Vertex {
        aPosition: [f32; 3],
        aColor: [f32; 3]
    }

    implement_vertex!(Vertex, aPosition, aColor);

    impl Vertex {
        fn new(position: [f32; 3], color: [f32; 3]) -> Vertex {
            Vertex { aPosition: position, aColor: color }
        }
    }

    pub fn compile(display: &glium::Display) -> glium::Program {
        static VERTEX: &'static str = "
            #version 410

            uniform mat4 uViewProjectionMatrix;

            in vec3 aPosition;
            in vec3 aColor;

            out vec3 vColor;

            void main() {
                gl_Position = uViewProjectionMatrix * vec4(aPosition, 1);
                vColor = aColor;
            }
        ";

        static FRAGMENT: &'static str = "
            #version 410

            in vec3 vColor;
            out vec4 outColor;

            void main() {
                outColor = vec4(vColor, 1);
            }
        ";

        glium::Program::from_source(display, VERTEX, FRAGMENT, None).unwrap()
    }

    pub fn cube(display: &glium::Display) -> (glium::vertex::VertexBufferAny, glium::IndexBuffer) {
        let vertex_buffer = {
            let blue = [0f32, 0f32, 1f32];
            let green = [0f32, 1f32, 0f32];
            let red = [1f32, 0f32, 0f32];
            glium::VertexBuffer::new(display,
                                     vec![
                                        Vertex::new([-0.5f32, -0.5f32,  0.5f32], blue),
                                        Vertex::new([-0.5f32,  0.5f32,  0.5f32], red),
                                        Vertex::new([ 0.5f32, -0.5f32,  0.5f32], green),
                                        Vertex::new([ 0.5f32,  0.5f32,  0.5f32], blue),
                                        Vertex::new([-0.5f32,  0.5f32, -0.5f32], blue),
                                        Vertex::new([ 0.5f32,  0.5f32, -0.5f32], red),
                                        Vertex::new([-0.5f32, -0.5f32, -0.5f32], green),
                                        Vertex::new([ 0.5f32, -0.5f32, -0.5f32], blue)
                                     ]).into_vertex_buffer_any()
        };

        let index_buffer = {
            let triangles = vec![
                // front
                1u32, 0u32, 2u32,
                2u32, 3u32, 1u32,

                // top
                1u32, 3u32, 4u32,
                4u32, 3u32, 5u32,

                // right
                2u32, 7u32, 3u32,
                3u32, 7u32, 5u32,

                // left
                6u32, 0u32, 4u32,
                0u32, 1u32, 4u32,

                // bottom
                7u32, 0u32, 6u32,
                2u32, 0u32, 7u32,

                // back
                7u32, 6u32, 5u32,
                5u32, 6u32, 4u32
            ];
            glium::IndexBuffer::new(display, glium::index::TrianglesList(triangles))
        };

        (vertex_buffer, index_buffer)
    }
}

<|endoftext|>


<commit_before>#![feature(unboxed_closures)]

extern crate monad;

use monad::monad::state;
use monad::monad::state::{
    State,
};

#[inline(always)]
pub fn incr<'a>() -> State<'a,int,()> {
    state::get().bind(|:a: int| {
    state::put(a + 1i)
    })
}

#[inline(always)]
pub fn decr<'a>() -> State<'a,int,()> {
    state::get().bind(|:a: int| {
    state::put(a - 1i)
    })
}

#[allow(dead_code)]
fn main() {
    let mut mon = state::point(());
    for _ in range(0u, 5000u) {
        mon = mon.seq(incr())
    }
    for _ in range(0u, 5000u) {
        mon = mon.seq(decr())
    }
    let fst = 42i;
    let res = mon.run(fst);
    println!("{} == {} is {}", fst, res.1, fst == res.1);
}
<commit_msg>Formatting<commit_after>#![feature(unboxed_closures)]

extern crate monad;

use monad::monad::state::{
    State,
    get,
    point,
    put,
};

#[inline(always)]
pub fn incr<'a>() -> State<'a, int, ()> {
    get().bind(|:a: int| {
    put(a + 1i)
    })
}

#[inline(always)]
pub fn decr<'a>() -> State<'a, int, ()> {
    get().bind(|:a: int| {
    put(a - 1i)
    })
}

#[allow(dead_code)]
fn main() {
    let mut mon = point(());
    for _ in range(0u, 5000u) {
        mon = mon.seq(incr())
    }
    for _ in range(0u, 5000u) {
        mon = mon.seq(decr())
    }
    let fst = 42i;
    let res = mon.run(fst);
    println!("{} == {} is {}", fst, res.1, fst == res.1);
}
<|endoftext|>


<commit_before>#![warn(bad_style,
        unused, unused_extern_crates, unused_import_braces,
        unused_qualifications, unused_results)]

extern crate twitter_api as twitter;
extern crate rustc_serialize as rustc_serialize;
extern crate oauth_client as oauth;

use std::io;
use std::io::prelude::*;
use std::env;
use std::fs::{File, OpenOptions};
use std::path::Path;
use std::path::PathBuf;
use rustc_serialize::Decodable;
use rustc_serialize::json::{self, Json};
use oauth::Token;

const TWITTER_CONF_FILENAME: &'static str = ".twitter.conf";

fn get_home_dir() -> PathBuf{
    match env::home_dir() {
        Some(p) => p,
        None => {
            panic!("Impossible to get your home dir!");
        }
    }
}

#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct Config {
    pub consumer_key: String,
    pub consumer_secret: String,
    pub access_key: String,
    pub access_secret: String
}

impl Config {
    pub fn read(path_file : &Path) -> Option<Config> {
        let mut file = match File::open(path_file) {
            Ok(f) => f,
            Err(_) => return None
        };
        let conf = Json::from_reader(&mut file).unwrap();
        Decodable::decode(&mut json::Decoder::new(conf)).ok()
    }

    pub fn write(&self, path_file : &Path) {
        let mut file = match OpenOptions::new().write(true).open(path_file) {
            Ok(f) => f,
            Err(e) => panic!("{}", e)
        };
        let _ = write!(&mut file, "{}\n", &json::encode(self).unwrap());
    }

    pub fn create(path_file : &Path) {
        match File::create(path_file) {
            Ok(_) => println!("File created!"),
            Err(_) => panic!("Problem to create the file...\nProgram aborted!")
        }
    }
}

fn console_input(prompt: &str) -> String {
    println!("{} : ", prompt);
    let mut line = String::new();
    let _ = io::stdin().read_line(&mut line).unwrap();
    line.trim().to_string()
}

fn main() {
    //Get the full path of the Twitter configuration path
    let mut twitter_conf_file_path : PathBuf = get_home_dir();
    twitter_conf_file_path.push(Path::new(TWITTER_CONF_FILENAME));

    let conf = match Config::read(&twitter_conf_file_path) {
        Some(c) => c,
        None => {

            Config::create(&twitter_conf_file_path);

            let consumer_key    = console_input("input your consumer key:");
            let consumer_secret = console_input("input your consumer secret:");
            let consumer = Token::new(consumer_key, consumer_secret);

            let request = twitter::get_request_token(&consumer);
            println!("open the following url:");
            println!("\t{}", twitter::get_authorize_url(&request));
            let pin = console_input("input pin:");
            let access = twitter::get_access_token(&consumer, &request, &pin);

            let c = Config {
                consumer_key: consumer.key.to_string(),
                consumer_secret: consumer.secret.to_string(),
                access_key: access.key.to_string(),
                access_secret: access.secret.to_string()
            };

            c.write(&twitter_conf_file_path);
            c
        }
    };

    let consumer = Token::new(conf.consumer_key, conf.consumer_secret);
    let access = Token::new(conf.access_key, conf.access_secret);

    loop {
        let make_your_choice = console_input("What do you want to do?");

        match make_your_choice.as_ref() {
            "update status" => {
                let status = console_input("What's happening?");
                twitter::update_status(&consumer, &access, &status);
            },
            "get timeline" => {
                twitter::get_last_tweets(&consumer, &access);
            },
            _ => break
        }
    }
}
<commit_msg>examples/tweet.rs : Importation of AsRef to match Strings<commit_after>#![warn(bad_style,
        unused, unused_extern_crates, unused_import_braces,
        unused_qualifications, unused_results)]

extern crate twitter_api as twitter;
extern crate rustc_serialize as rustc_serialize;
extern crate oauth_client as oauth;

use std::convert::AsRef;
use std::io;
use std::io::prelude::*;
use std::env;
use std::fs::{File, OpenOptions};
use std::path::Path;
use std::path::PathBuf;
use rustc_serialize::Decodable;
use rustc_serialize::json::{self, Json};
use oauth::Token;

const TWITTER_CONF_FILENAME: &'static str = ".twitter.conf";

fn get_home_dir() -> PathBuf{
    match env::home_dir() {
        Some(p) => p,
        None => {
            panic!("Impossible to get your home dir!");
        }
    }
}

#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct Config {
    pub consumer_key: String,
    pub consumer_secret: String,
    pub access_key: String,
    pub access_secret: String
}

impl Config {
    pub fn read(path_file : &Path) -> Option<Config> {
        let mut file = match File::open(path_file) {
            Ok(f) => f,
            Err(_) => return None
        };
        let conf = Json::from_reader(&mut file).unwrap();
        Decodable::decode(&mut json::Decoder::new(conf)).ok()
    }

    pub fn write(&self, path_file : &Path) {
        let mut file = match OpenOptions::new().write(true).open(path_file) {
            Ok(f) => f,
            Err(e) => panic!("{}", e)
        };
        let _ = write!(&mut file, "{}\n", &json::encode(self).unwrap());
    }

    pub fn create(path_file : &Path) {
        match File::create(path_file) {
            Ok(_) => println!("File created!"),
            Err(_) => panic!("Problem to create the file...\nProgram aborted!")
        }
    }
}

fn console_input(prompt: &str) -> String {
    println!("{} : ", prompt);
    let mut line = String::new();
    let _ = io::stdin().read_line(&mut line).unwrap();
    line.trim().to_string()
}

fn main() {
    //Get the full path of the Twitter configuration path
    let mut twitter_conf_file_path : PathBuf = get_home_dir();
    twitter_conf_file_path.push(Path::new(TWITTER_CONF_FILENAME));

    let conf = match Config::read(&twitter_conf_file_path) {
        Some(c) => c,
        None => {

            Config::create(&twitter_conf_file_path);

            let consumer_key    = console_input("input your consumer key:");
            let consumer_secret = console_input("input your consumer secret:");
            let consumer = Token::new(consumer_key, consumer_secret);

            let request = twitter::get_request_token(&consumer);
            println!("open the following url:");
            println!("\t{}", twitter::get_authorize_url(&request));
            let pin = console_input("input pin:");
            let access = twitter::get_access_token(&consumer, &request, &pin);

            let c = Config {
                consumer_key: consumer.key.to_string(),
                consumer_secret: consumer.secret.to_string(),
                access_key: access.key.to_string(),
                access_secret: access.secret.to_string()
            };

            c.write(&twitter_conf_file_path);
            c
        }
    };

    let consumer = Token::new(conf.consumer_key, conf.consumer_secret);
    let access = Token::new(conf.access_key, conf.access_secret);

    loop {
        let make_your_choice = console_input("What do you want to do?");

        match make_your_choice.as_ref() {
            "update status" => {
                let status = console_input("What's happening?");
                twitter::update_status(&consumer, &access, &status);
            },
            "get timeline" => {
                twitter::get_last_tweets(&consumer, &access);
            },
            _ => break
        }
    }
}
<|endoftext|>