<commit_before>/*!
 * Entity component system
 */

extern crate rustc_serialize;

use std::default::{Default};
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::collections::{HashMap, HashSet};
use std::collections::hash_set;

/// Handle for an entity in the entity component system.
///
/// The internal value is the unique identifier for the entity. No two
/// entities should get the same UID during the lifetime of the ECS.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, RustcDecodable, RustcEncodable)]
pub struct Entity(pub usize);

pub trait AnyComponent {
    /// Remove an entity's component.
    fn remove(&mut self, e: Entity);
}

/// Storage for a single component type.
#[derive(RustcEncodable, RustcDecodable)]
pub struct ComponentData<C> {
    // TODO: Add reused index fields to entities and use VecMap with the
    // index field instead of HashMap with the UID here for more
    // efficient access.
    data: HashMap<usize, C>,
}

impl<C> ComponentData<C> {
    pub fn new() -> ComponentData<C> {
        ComponentData {
            data: HashMap::new()
        }
    }

    /// Insert a component to an entity.
    pub fn insert(&mut self, Entity(uid): Entity, comp: C) {
        self.data.insert(uid, comp);
    }

    /// Return whether an entity contains this component.
    pub fn contains(&self, Entity(uid): Entity) -> bool {
        self.data.contains_key(&uid)
    }
}

impl<C> Index<Entity> for ComponentData<C> {
    type Output = C;

    fn index<'a>(&'a self, Entity(uid): Entity) -> &'a C {
        self.data.get(&uid).unwrap()
    }
}

impl<C> IndexMut<Entity> for ComponentData<C> {
    fn index_mut<'a>(&'a mut self, Entity(uid): Entity) -> &'a mut C {
        self.data.get_mut(&uid).unwrap()
    }
}

impl<C> AnyComponent for ComponentData<C> {
    fn remove(&mut self, Entity(uid): Entity) {
        self.data.remove(&uid);
    }
}

pub trait Store {
    /// Perform an operation for each component container.
    fn for_each_component<F>(&mut self, f: F)
        where F: FnMut(&mut AnyComponent);
}

#[derive(RustcEncodable, RustcDecodable)]
pub struct Ecs<S> {
    next_uid: usize,
    active: HashSet<Entity>,
    store: S,
}

impl<S: Default+Store> Ecs<S> {
    pub fn new() -> Ecs<S> {
        Ecs {
            next_uid: 1,
            active: HashSet::new(),
            store: Default::default(),
        }
    }

    /// Create a new empty entity.
    pub fn make(&mut self) -> Entity {
        let next = self.next_uid;
        self.next_uid += 1;
        let ret = Entity(next);
        self.active.insert(ret);
        ret
    }

    /// Remove an entity from the system and clear its components.
    pub fn remove(&mut self, e: Entity) {
        self.active.remove(&e);
        self.store.for_each_component(|c| c.remove(e));
    }

    /// Return whether the system contains an entity.
    pub fn contains(&self, e: Entity) -> bool {
        self.active.contains(&e)
    }

    pub fn iter(&self) -> hash_set::Iter<Entity> {
        self.active.iter()
    }
}

impl<S> Deref for Ecs<S> {
    type Target = S;

    fn deref(&self) -> &S { &self.store }
}

impl<S> DerefMut for Ecs<S> {
    fn deref_mut(&mut self) -> &mut S {&mut self.store}
}

/// Entity component system builder macro.
///
/// Defines a local `Ecs` type that's parametrized with a custom component
/// store type with the component types you specify. Will also define a trait
/// `Component` which will be implemented for the component types.
#[macro_export]
macro_rules! Ecs {
    {
        // Declare the type of the (plain old data) component and the
        // identifier to use for it in the ECS.
        $($compname:ident: $comptype:ty,)+
    } => {
        mod _ecs_inner {
            // Use the enum to convert components to numbers for component bit masks etc.
            #[allow(non_camel_case_types, dead_code)]
            pub enum ComponentNum {
                $($compname,)+
            }

        }

        pub use self::_ecs_inner::ComponentNum;

#[derive(RustcEncodable, RustcDecodable)]
        pub struct _ComponentStore {
            $(pub $compname: ::calx_ecs::ComponentData<$comptype>),+
        }

        impl ::std::default::Default for _ComponentStore {
            fn default() -> _ComponentStore {
                _ComponentStore {
                    $($compname: ::calx_ecs::ComponentData::new()),+
                }
            }
        }

        impl ::calx_ecs::Store for _ComponentStore {
            fn for_each_component<F>(&mut self, mut f: F)
                where F: FnMut(&mut ::calx_ecs::AnyComponent)
            {
                $(f(&mut self.$compname as &mut ::calx_ecs::AnyComponent);)+
            }
        }

#[allow(dead_code)]
        pub fn matches_mask(ecs: &::calx_ecs::Ecs<_ComponentStore>, e: ::calx_ecs::Entity, mask: u64) -> bool {
            $(if mask & (1 << ComponentNum::$compname as u8) != 0 && !ecs.$compname.contains(e) {
                return false;
            })+
            return true;
        }

        /// Common operations for ECS component value types.
        pub trait Component {
            /// Add a clone of the component value to an entity in an ECS.
            ///
            /// Can't move the component itself since we might be using this
            /// through a trait object.
            fn add_to(&self, ecs: &mut ::calx_ecs::Ecs<_ComponentStore>, e: ::calx_ecs::Entity);
        }

        $(impl Component for $comptype {
            fn add_to(&self, ecs: &mut ::calx_ecs::Ecs<_ComponentStore>, e: ::calx_ecs::Entity) {
                ecs.$compname.insert(e, self.clone());
            }
        })+

        pub type Ecs = ::calx_ecs::Ecs<_ComponentStore>;
    }
}

/// Build a vector of Component trait objects from component values.
///
/// Use to set up prototype templates for entities.
#[macro_export]
macro_rules! loadout {
    [ $($comp:expr),+ ] => {
        vec![
            $(Box::new($comp) as Box<Component>),+
        ]
    }
}

/// Build a component type mask to match component iteration with.
///
/// You must have ComponentNum enum from the Ecs! macro expansion in scope
/// when using this.
#[macro_export]
macro_rules! build_mask {
    ( $($compname:ident),+ ) => {
        0u64 $(| (1u64 << ComponentNum::$compname as u8))+
    }
}
<commit_msg>ECS component iteration and option access<commit_after>/*!
 * Entity component system
 */

extern crate rustc_serialize;

use std::default::{Default};
use std::ops::{Deref, DerefMut, Index, IndexMut};
use std::collections::{hash_map, HashMap, HashSet};
use std::collections::hash_set;

/// Handle for an entity in the entity component system.
///
/// The internal value is the unique identifier for the entity. No two
/// entities should get the same UID during the lifetime of the ECS.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug, RustcDecodable, RustcEncodable)]
pub struct Entity(pub usize);

pub trait AnyComponent {
    /// Remove an entity's component.
    fn remove(&mut self, e: Entity);
}

/// Storage for a single component type.
#[derive(RustcEncodable, RustcDecodable)]
pub struct ComponentData<C> {
    // TODO: Add reused index fields to entities and use VecMap with the
    // index field instead of HashMap with the UID here for more
    // efficient access.
    data: HashMap<Entity, C>,
}

impl<C> ComponentData<C> {
    pub fn new() -> ComponentData<C> {
        ComponentData {
            data: HashMap::new()
        }
    }

    /// Insert a component to an entity.
    pub fn insert(&mut self, e: Entity, comp: C) {
        self.data.insert(e, comp);
    }

    /// Return whether an entity contains this component.
    pub fn contains(&self, e: Entity) -> bool {
        self.data.contains_key(&e)
    }

    /// Get a reference to a component only if it exists for this entity.
    pub fn get(&self, e: Entity) -> Option<&C> {
        self.data.get(&e)
    }

    /// Get a mutable reference to a component only if it exists for this entity.
    pub fn get_mut(&mut self, e: Entity) -> Option<&mut C> {
        self.data.get_mut(&e)
    }

    /// Iterate entity-component pairs for this component.
    pub fn iter(&self) -> hash_map::Iter<Entity, C> {
        self.data.iter()
    }

    /// Iterate mutable entity-component pairs for this component.
    pub fn iter_mut(&mut self) -> hash_map::IterMut<Entity, C> {
        self.data.iter_mut()
    }
}

impl<C> Index<Entity> for ComponentData<C> {
    type Output = C;

    fn index<'a>(&'a self, e: Entity) -> &'a C {
        self.data.get(&e).unwrap()
    }
}

impl<C> IndexMut<Entity> for ComponentData<C> {
    fn index_mut<'a>(&'a mut self, e: Entity) -> &'a mut C {
        self.data.get_mut(&e).unwrap()
    }
}

impl<C> AnyComponent for ComponentData<C> {
    fn remove(&mut self, e: Entity) {
        self.data.remove(&e);
    }
}

pub trait Store {
    /// Perform an operation for each component container.
    fn for_each_component<F>(&mut self, f: F)
        where F: FnMut(&mut AnyComponent);
}

#[derive(RustcEncodable, RustcDecodable)]
pub struct Ecs<S> {
    next_uid: usize,
    active: HashSet<Entity>,
    store: S,
}

impl<S: Default+Store> Ecs<S> {
    pub fn new() -> Ecs<S> {
        Ecs {
            next_uid: 1,
            active: HashSet::new(),
            store: Default::default(),
        }
    }

    /// Create a new empty entity.
    pub fn make(&mut self) -> Entity {
        let next = self.next_uid;
        self.next_uid += 1;
        let ret = Entity(next);
        self.active.insert(ret);
        ret
    }

    /// Remove an entity from the system and clear its components.
    pub fn remove(&mut self, e: Entity) {
        self.active.remove(&e);
        self.store.for_each_component(|c| c.remove(e));
    }

    /// Return whether the system contains an entity.
    pub fn contains(&self, e: Entity) -> bool {
        self.active.contains(&e)
    }

    pub fn iter(&self) -> hash_set::Iter<Entity> {
        self.active.iter()
    }
}

impl<S> Deref for Ecs<S> {
    type Target = S;

    fn deref(&self) -> &S { &self.store }
}

impl<S> DerefMut for Ecs<S> {
    fn deref_mut(&mut self) -> &mut S {&mut self.store}
}

/// Entity component system builder macro.
///
/// Defines a local `Ecs` type that's parametrized with a custom component
/// store type with the component types you specify. Will also define a trait
/// `Component` which will be implemented for the component types.
#[macro_export]
macro_rules! Ecs {
    {
        // Declare the type of the (plain old data) component and the
        // identifier to use for it in the ECS.
        $($compname:ident: $comptype:ty,)+
    } => {
        mod _ecs_inner {
            // Use the enum to convert components to numbers for component bit masks etc.
            #[allow(non_camel_case_types, dead_code)]
            pub enum ComponentNum {
                $($compname,)+
            }

        }

        pub use self::_ecs_inner::ComponentNum;

#[derive(RustcEncodable, RustcDecodable)]
        pub struct _ComponentStore {
            $(pub $compname: ::calx_ecs::ComponentData<$comptype>),+
        }

        impl ::std::default::Default for _ComponentStore {
            fn default() -> _ComponentStore {
                _ComponentStore {
                    $($compname: ::calx_ecs::ComponentData::new()),+
                }
            }
        }

        impl ::calx_ecs::Store for _ComponentStore {
            fn for_each_component<F>(&mut self, mut f: F)
                where F: FnMut(&mut ::calx_ecs::AnyComponent)
            {
                $(f(&mut self.$compname as &mut ::calx_ecs::AnyComponent);)+
            }
        }

#[allow(dead_code)]
        pub fn matches_mask(ecs: &::calx_ecs::Ecs<_ComponentStore>, e: ::calx_ecs::Entity, mask: u64) -> bool {
            $(if mask & (1 << ComponentNum::$compname as u8) != 0 && !ecs.$compname.contains(e) {
                return false;
            })+
            return true;
        }

        /// Common operations for ECS component value types.
        pub trait Component {
            /// Add a clone of the component value to an entity in an ECS.
            ///
            /// Can't move the component itself since we might be using this
            /// through a trait object.
            fn add_to(&self, ecs: &mut ::calx_ecs::Ecs<_ComponentStore>, e: ::calx_ecs::Entity);
        }

        $(impl Component for $comptype {
            fn add_to(&self, ecs: &mut ::calx_ecs::Ecs<_ComponentStore>, e: ::calx_ecs::Entity) {
                ecs.$compname.insert(e, self.clone());
            }
        })+

        pub type Ecs = ::calx_ecs::Ecs<_ComponentStore>;
    }
}

/// Build a vector of Component trait objects from component values.
///
/// Use to set up prototype templates for entities.
#[macro_export]
macro_rules! loadout {
    [ $($comp:expr),+ ] => {
        vec![
            $(Box::new($comp) as Box<Component>),+
        ]
    }
}

/// Build a component type mask to match component iteration with.
///
/// You must have ComponentNum enum from the Ecs! macro expansion in scope
/// when using this.
#[macro_export]
macro_rules! build_mask {
    ( $($compname:ident),+ ) => {
        0u64 $(| (1u64 << ComponentNum::$compname as u8))+
    }
}
<|endoftext|>


<commit_before>//! Algorithm module for managing Algorithmia Data Collections
//!
//! # Examples
//!
//! ```no_run
//! use algorithmia::Service;
//! use std::fs::File;
//!
//! let algo_service = Service::new("111112222233333444445555566");
//! let my_bucket = algo_service.collection("my_user", "my_bucket");
//!
//! my_bucket.create();
//! let mut my_file = File::open("/path/to/file").unwrap();
//! my_bucket.upload_file(&mut my_file);
//!
//! my_bucket.write_file("some_filename", "file_contents".as_bytes());
//! ```

extern crate hyper;

use ::{Service, AlgorithmiaError, ApiErrorResponse, API_BASE_URL};
use hyper::Url;
use rustc_serialize::{json, Decoder};
use std::io::Read;
use std::fs::File;

static COLLECTION_BASE_PATH: &'static str = "data";

/// Algorithmia data collection
pub struct Collection<'a> {
    pub user: &'a str,
    pub name: &'a str,
}

pub type CollectionShowResult = Result<CollectionShow, AlgorithmiaError>;
pub type CollectionCreatedResult = Result<CollectionCreated, AlgorithmiaError>;
pub type CollectionFileAddedResult = Result<CollectionFileAdded, AlgorithmiaError>;

/// Permissions for a data collection
#[derive(RustcDecodable, Debug)]
pub struct CollectionAcl {
    /// Readable by world
    pub read_w: bool,
    /// Readable by group
    pub read_g: bool,
    /// Readable by user
    pub read_u: bool,
    /// Readable by user's algorithms regardless who runs them
    pub read_a: bool,
}

/// Response when creating a new collection
#[derive(RustcDecodable, Debug)]
pub struct CollectionCreated {
    pub collection_id: u32,
    pub object_id: String,
    pub collection_name: String,
    pub username: String,
    pub acl: CollectionAcl,
}

/// Response when querying an existing collection
#[derive(RustcDecodable, Debug)]
pub struct CollectionShow {
    pub username: String,
    pub collection_name: String,
    pub files: Vec<String>,
}

/// Response when adding a file to a collection
#[derive(RustcDecodable, Debug)]
pub struct CollectionFileAdded {
    pub result: String
}

/// Service endpoint for managing Algorithmia data collections
pub struct CollectionService<'a> {
    pub service: Service,
    pub collection: Collection<'a>,
}

impl<'a> Collection<'a> {
    /// Get the API Endpoint URL for a particular collection
    fn to_url(&self) -> Url {
        let url_string = format!("{}/{}/{}/{}", API_BASE_URL, COLLECTION_BASE_PATH, self.user, self.name);
        Url::parse(&*url_string).unwrap()
    }
}

impl<'c> CollectionService<'c> {
    /// Instantiate `CollectionService` directly - alternative to `Service::collection`
    ///
    /// # Examples
    /// ```
    /// # use algorithmia::collection::CollectionService;
    /// let my_bucket = CollectionService::new("111112222233333444445555566", "my_user", "my_bucket");
    /// ```
    pub fn new(api_key: &'c str, user: &'c str, name: &'c str) -> CollectionService<'c> {
        CollectionService {
            service: Service::new(api_key),
            collection: Collection{ user: user, name: name }
        }
    }

    /// Display collection details if it exists
    ///
    /// # Examples
    /// ```no_run
    /// # use algorithmia::Service;
    /// let algo_service = Service::new("111112222233333444445555566");
    /// let my_bucket = algo_service.collection("my_user", "my_bucket");
    /// match my_bucket.show() {
    ///   Ok(bucket) => println!("Files: {}", bucket.files.connect(", ")),
    ///   Err(e) => println!("ERROR: {:?}", e),
    /// };
    /// ```
    pub fn show(&'c self) -> CollectionShowResult {
        let ref mut api_client = self.service.api_client();
        let req = api_client.get(self.collection.to_url());

        let mut res = try!(req.send());
        let mut res_json = String::new();
        try!(res.read_to_string(&mut res_json));

        match json::decode::<CollectionShow>(&*res_json) {
            Ok(result) => Ok(result),
            Err(why) => match json::decode::<ApiErrorResponse>(&*res_json) {
                Ok(api_error) => Err(AlgorithmiaError::ApiError(api_error.error)),
                Err(_) => Err(AlgorithmiaError::DecoderErrorWithContext(why, res_json)),
            }
        }
    }

    /// Create a collection
    ///
    /// # Examples
    /// ```no_run
    /// # use algorithmia::Service;
    /// let algo_service = Service::new("111112222233333444445555566");
    /// let my_bucket = algo_service.collection("my_user", "my_bucket");
    /// match my_bucket.create() {
    ///   Ok(_) => println!("Successfully created collection"),
    ///   Err(e) => println!("ERROR creating collection: {:?}", e),
    /// };
    /// ```
    pub fn create(&'c self) -> CollectionCreatedResult {
        // Construct URL
        let url_string = format!("{}/{}/{}", API_BASE_URL, COLLECTION_BASE_PATH, self.collection.user);
        let url = Url::parse(&*url_string).unwrap();

        // POST request
        let ref mut api_client = self.service.api_client();
        let req = api_client.post(url).body(self.collection.name);

        // Parse response
        let mut res = try!(req.send());
        let mut res_json = String::new();
        try!(res.read_to_string(&mut res_json));

        Service::decode_to_result::<CollectionCreated>(res_json)

    }

    /// Upload a file to an existing collection
    ///
    /// # Examples
    /// ```no_run
    /// # use algorithmia::Service;
    /// # use std::fs::File;
    /// let algo_service = Service::new("111112222233333444445555566");
    /// let my_bucket = algo_service.collection("my_user", "my_bucket");
    ///
    /// let mut my_file = File::open("/path/to/file").unwrap();
    /// match my_bucket.upload_file(&mut my_file) {
    ///   Ok(response) => println!("Successfully uploaded to: {}", response.result),
    ///   Err(e) => println!("ERROR uploading file: {:?}", e),
    /// };
    /// ```
    pub fn upload_file(&'c self, file: &mut File) -> CollectionFileAddedResult {
        let url_string = format!("{}/{}",
            self.collection.to_url(),
            file.path().unwrap().file_name().unwrap().to_str().unwrap()
        );
        let url = Url::parse(&*url_string).unwrap();

        let ref mut api_client = self.service.api_client();
        let req = api_client.post(url).body(file);

        let mut res = try!(req.send());
        let mut res_json = String::new();
        try!(res.read_to_string(&mut res_json));

        Service::decode_to_result::<CollectionFileAdded>(res_json)
    }

    /// Write a file (raw bytes) directly to a data collection
    ///
    /// # Examples
    /// ```no_run
    /// # use algorithmia::Service;
    /// let algo_service = Service::new("111112222233333444445555566");
    /// let my_bucket = algo_service.collection("my_user", "my_bucket");
    ///
    /// match my_bucket.write_file("some_filename", "file_contents".as_bytes()) {
    ///   Ok(response) => println!("Successfully uploaded to: {}", response.result),
    ///   Err(e) => println!("ERROR uploading file: {:?}", e),
    /// };
    /// ```
    pub fn write_file(&'c self, filename: &str, input_data: &[u8]) -> CollectionFileAddedResult {
        let url_string = format!("{}/{}", self.collection.to_url(), filename);
        let url = Url::parse(&*url_string).unwrap();

        let ref mut api_client = self.service.api_client();
        let req = api_client.post(url).body(&*input_data);

        let mut res = try!(req.send());
        let mut res_json = String::new();
        try!(res.read_to_string(&mut res_json));

        Service::decode_to_result::<CollectionFileAdded>(res_json)
    }

}

#[test]
fn test_to_url() {
    let collection = Collection{ user: "anowell", name: "foo" };
    assert_eq!(collection.to_url().serialize(), format!("{}/data/anowell/foo", API_BASE_URL));
}
<commit_msg>Copy-paste typo<commit_after>//! Collection module for managing Algorithmia Data Collections
//!
//! # Examples
//!
//! ```no_run
//! use algorithmia::Service;
//! use std::fs::File;
//!
//! let algo_service = Service::new("111112222233333444445555566");
//! let my_bucket = algo_service.collection("my_user", "my_bucket");
//!
//! my_bucket.create();
//! let mut my_file = File::open("/path/to/file").unwrap();
//! my_bucket.upload_file(&mut my_file);
//!
//! my_bucket.write_file("some_filename", "file_contents".as_bytes());
//! ```

extern crate hyper;

use ::{Service, AlgorithmiaError, ApiErrorResponse, API_BASE_URL};
use hyper::Url;
use rustc_serialize::{json, Decoder};
use std::io::Read;
use std::fs::File;

static COLLECTION_BASE_PATH: &'static str = "data";

/// Algorithmia data collection
pub struct Collection<'a> {
    pub user: &'a str,
    pub name: &'a str,
}

pub type CollectionShowResult = Result<CollectionShow, AlgorithmiaError>;
pub type CollectionCreatedResult = Result<CollectionCreated, AlgorithmiaError>;
pub type CollectionFileAddedResult = Result<CollectionFileAdded, AlgorithmiaError>;

/// Permissions for a data collection
#[derive(RustcDecodable, Debug)]
pub struct CollectionAcl {
    /// Readable by world
    pub read_w: bool,
    /// Readable by group
    pub read_g: bool,
    /// Readable by user
    pub read_u: bool,
    /// Readable by user's algorithms regardless who runs them
    pub read_a: bool,
}

/// Response when creating a new collection
#[derive(RustcDecodable, Debug)]
pub struct CollectionCreated {
    pub collection_id: u32,
    pub object_id: String,
    pub collection_name: String,
    pub username: String,
    pub acl: CollectionAcl,
}

/// Response when querying an existing collection
#[derive(RustcDecodable, Debug)]
pub struct CollectionShow {
    pub username: String,
    pub collection_name: String,
    pub files: Vec<String>,
}

/// Response when adding a file to a collection
#[derive(RustcDecodable, Debug)]
pub struct CollectionFileAdded {
    pub result: String
}

/// Service endpoint for managing Algorithmia data collections
pub struct CollectionService<'a> {
    pub service: Service,
    pub collection: Collection<'a>,
}

impl<'a> Collection<'a> {
    /// Get the API Endpoint URL for a particular collection
    fn to_url(&self) -> Url {
        let url_string = format!("{}/{}/{}/{}", API_BASE_URL, COLLECTION_BASE_PATH, self.user, self.name);
        Url::parse(&*url_string).unwrap()
    }
}

impl<'c> CollectionService<'c> {
    /// Instantiate `CollectionService` directly - alternative to `Service::collection`
    ///
    /// # Examples
    /// ```
    /// # use algorithmia::collection::CollectionService;
    /// let my_bucket = CollectionService::new("111112222233333444445555566", "my_user", "my_bucket");
    /// ```
    pub fn new(api_key: &'c str, user: &'c str, name: &'c str) -> CollectionService<'c> {
        CollectionService {
            service: Service::new(api_key),
            collection: Collection{ user: user, name: name }
        }
    }

    /// Display collection details if it exists
    ///
    /// # Examples
    /// ```no_run
    /// # use algorithmia::Service;
    /// let algo_service = Service::new("111112222233333444445555566");
    /// let my_bucket = algo_service.collection("my_user", "my_bucket");
    /// match my_bucket.show() {
    ///   Ok(bucket) => println!("Files: {}", bucket.files.connect(", ")),
    ///   Err(e) => println!("ERROR: {:?}", e),
    /// };
    /// ```
    pub fn show(&'c self) -> CollectionShowResult {
        let ref mut api_client = self.service.api_client();
        let req = api_client.get(self.collection.to_url());

        let mut res = try!(req.send());
        let mut res_json = String::new();
        try!(res.read_to_string(&mut res_json));

        match json::decode::<CollectionShow>(&*res_json) {
            Ok(result) => Ok(result),
            Err(why) => match json::decode::<ApiErrorResponse>(&*res_json) {
                Ok(api_error) => Err(AlgorithmiaError::ApiError(api_error.error)),
                Err(_) => Err(AlgorithmiaError::DecoderErrorWithContext(why, res_json)),
            }
        }
    }

    /// Create a collection
    ///
    /// # Examples
    /// ```no_run
    /// # use algorithmia::Service;
    /// let algo_service = Service::new("111112222233333444445555566");
    /// let my_bucket = algo_service.collection("my_user", "my_bucket");
    /// match my_bucket.create() {
    ///   Ok(_) => println!("Successfully created collection"),
    ///   Err(e) => println!("ERROR creating collection: {:?}", e),
    /// };
    /// ```
    pub fn create(&'c self) -> CollectionCreatedResult {
        // Construct URL
        let url_string = format!("{}/{}/{}", API_BASE_URL, COLLECTION_BASE_PATH, self.collection.user);
        let url = Url::parse(&*url_string).unwrap();

        // POST request
        let ref mut api_client = self.service.api_client();
        let req = api_client.post(url).body(self.collection.name);

        // Parse response
        let mut res = try!(req.send());
        let mut res_json = String::new();
        try!(res.read_to_string(&mut res_json));

        Service::decode_to_result::<CollectionCreated>(res_json)

    }

    /// Upload a file to an existing collection
    ///
    /// # Examples
    /// ```no_run
    /// # use algorithmia::Service;
    /// # use std::fs::File;
    /// let algo_service = Service::new("111112222233333444445555566");
    /// let my_bucket = algo_service.collection("my_user", "my_bucket");
    ///
    /// let mut my_file = File::open("/path/to/file").unwrap();
    /// match my_bucket.upload_file(&mut my_file) {
    ///   Ok(response) => println!("Successfully uploaded to: {}", response.result),
    ///   Err(e) => println!("ERROR uploading file: {:?}", e),
    /// };
    /// ```
    pub fn upload_file(&'c self, file: &mut File) -> CollectionFileAddedResult {
        let url_string = format!("{}/{}",
            self.collection.to_url(),
            file.path().unwrap().file_name().unwrap().to_str().unwrap()
        );
        let url = Url::parse(&*url_string).unwrap();

        let ref mut api_client = self.service.api_client();
        let req = api_client.post(url).body(file);

        let mut res = try!(req.send());
        let mut res_json = String::new();
        try!(res.read_to_string(&mut res_json));

        Service::decode_to_result::<CollectionFileAdded>(res_json)
    }

    /// Write a file (raw bytes) directly to a data collection
    ///
    /// # Examples
    /// ```no_run
    /// # use algorithmia::Service;
    /// let algo_service = Service::new("111112222233333444445555566");
    /// let my_bucket = algo_service.collection("my_user", "my_bucket");
    ///
    /// match my_bucket.write_file("some_filename", "file_contents".as_bytes()) {
    ///   Ok(response) => println!("Successfully uploaded to: {}", response.result),
    ///   Err(e) => println!("ERROR uploading file: {:?}", e),
    /// };
    /// ```
    pub fn write_file(&'c self, filename: &str, input_data: &[u8]) -> CollectionFileAddedResult {
        let url_string = format!("{}/{}", self.collection.to_url(), filename);
        let url = Url::parse(&*url_string).unwrap();

        let ref mut api_client = self.service.api_client();
        let req = api_client.post(url).body(&*input_data);

        let mut res = try!(req.send());
        let mut res_json = String::new();
        try!(res.read_to_string(&mut res_json));

        Service::decode_to_result::<CollectionFileAdded>(res_json)
    }

}

#[test]
fn test_to_url() {
    let collection = Collection{ user: "anowell", name: "foo" };
    assert_eq!(collection.to_url().serialize(), format!("{}/data/anowell/foo", API_BASE_URL));
}
<|endoftext|>


<commit_before>use uuid::Uuid;

use super::Action;
use super::Conditions;

pub struct Context {
    pub name: Option<String>,
    pub uuid: Uuid,
    pub conditions: Conditions,
    pub actions: Vec<Action>
}

pub struct ContextBuilder {
    name: Option<String>,
    uuid: Uuid,
    conditions: Conditions,
    actions: Vec<Action>
}

impl ContextBuilder {
    pub fn new(uuid: Uuid, conditions: Conditions) -> ContextBuilder {
        ContextBuilder {
            name: None,
            uuid: uuid,
            conditions: conditions,
            actions: Vec::new()
        }
    }

    pub fn actions(&mut self, actions: Vec<Action>) -> &mut ContextBuilder {
        self.actions = actions;
        self
    }

    pub fn build(&self) -> Context {
        Context {
            name: self.name.clone(),
            uuid: self.uuid.clone(),
            conditions: self.conditions.clone(),
            actions: self.actions.clone()
        }
    }
}
<commit_msg>config::Context: derive Debug trait implementation<commit_after>use uuid::Uuid;

use super::Action;
use super::Conditions;

#[derive(Debug)]
pub struct Context {
    pub name: Option<String>,
    pub uuid: Uuid,
    pub conditions: Conditions,
    pub actions: Vec<Action>
}

pub struct ContextBuilder {
    name: Option<String>,
    uuid: Uuid,
    conditions: Conditions,
    actions: Vec<Action>
}

impl ContextBuilder {
    pub fn new(uuid: Uuid, conditions: Conditions) -> ContextBuilder {
        ContextBuilder {
            name: None,
            uuid: uuid,
            conditions: conditions,
            actions: Vec::new()
        }
    }

    pub fn actions(&mut self, actions: Vec<Action>) -> &mut ContextBuilder {
        self.actions = actions;
        self
    }

    pub fn build(&self) -> Context {
        Context {
            name: self.name.clone(),
            uuid: self.uuid.clone(),
            conditions: self.conditions.clone(),
            actions: self.actions.clone()
        }
    }
}
<|endoftext|>


<commit_before>#![feature(test)]

extern crate mazes;
extern crate test;

use mazes::generators;
use mazes::renderers;
use mazes::pathing;
use mazes::squaregrid;

use std::ptr;
use test::Bencher;

extern "C" {
                                            // maybe null function pointer
    pub fn SDL_LogSetOutputFunction(callback: Option<extern fn()>,
                                    userdata: Option<extern fn()>);
}

#[bench]
fn render_grid(b: &mut Bencher) {

    unsafe { SDL_LogSetOutputFunction(None, None); }

    let grid_size = 200;
    let mut maze_grid = squaregrid::SquareGrid::<u32>::new(grid_size);
    let start_coord = squaregrid::GridCoordinate::new(0, 0);
    generators::recursive_backtracker(&mut maze_grid);
    let distances = pathing::DijkstraDistances::<u32>::new(&maze_grid, start_coord);

    let render_options = renderers::RenderOptionsBuilder::new()
             .colour_distances(true)
             .mark_start_end(true)
             .start(Some(start_coord))
             .end(Some(squaregrid::GridCoordinate::new(199, 199)))
             .show_path(true)
             .distances(distances.as_ref())
             .build();

    // Todo - why does SDL_LogCritical get called so much by fill_rect/draw_line?
    // render recursive-backtracker image --mark-start-end --grid-size 2500 --cell-pixels 8 --show-path --image-out=perf-test-maze.png --colour-distances
    // 23% of samples
    // and it does not improve when setting SDL_LogSetOutputFunction to nothing
    b.iter(|| renderers::render_square_grid(&maze_grid, &render_options));
}

// void SDL_LogSetOutputFunction(SDL_LogOutputFunction callback, void *userdata);
// static void SDL_LogOutput(void *userdata,
//                           int category, SDL_LogPriority priority,
//                           const char *message);

// ?
// static void
// debug_print(const char *fmt, ...)
// {
//     va_list ap;
//     va_start(ap, fmt);
//     SDL_LogMessageV(SDL_LOG_CATEGORY_ASSERT, SDL_LOG_PRIORITY_WARN, fmt, ap);
//     va_end(ap);
// }
//
// SDL_SetError if in debug
//
//  #if LOG_WINDOW_EVENTS==1
<commit_msg>Renderers bench update.<commit_after>#![feature(test)]

extern crate mazes;
extern crate test;

use mazes::generators;
use mazes::renderers;
use mazes::pathing;
use mazes::squaregrid;

use test::Bencher;

#[bench]
fn render_grid(b: &mut Bencher) {

    let grid_size = 200;
    let mut maze_grid = squaregrid::SquareGrid::<u32>::new(grid_size);
    let start_coord = squaregrid::GridCoordinate::new(0, 0);
    generators::recursive_backtracker(&mut maze_grid);
    let distances = pathing::DijkstraDistances::<u32>::new(&maze_grid, start_coord);

    let render_options = renderers::RenderOptionsBuilder::new()
             .colour_distances(true)
             .mark_start_end(true)
             .start(Some(start_coord))
             .end(Some(squaregrid::GridCoordinate::new(199, 199)))
             .show_path(true)
             .distances(distances.as_ref())
             .build();

    // Why does SDL_LogCritical get called so much by fill_rect/draw_line? At least according to the CodeXL sampling profiler.
    // render recursive-backtracker image --mark-start-end --grid-size 2500 --cell-pixels 8 --show-path --image-out=perf-test-maze.png --colour-distances
    // 23% of samples and it does not improve when setting SDL_LogSetOutputFunction to nothing:
    // extern "C" {
    //                                         // maybe null function pointer
    // pub fn SDL_LogSetOutputFunction(callback: Option<extern fn()>,
    //                                 userdata: Option<extern fn()>);
    // }
    // unsafe { SDL_LogSetOutputFunction(None, None); }
    // Probably a non-issue:
    // It happens with msvc aswell.
    // It disappears when using a rebuilt from scratch 64bit msvc SDL lib/dll.
    // The runtime is basically the same
    b.iter(|| renderers::render_square_grid(&maze_grid, &render_options));
}
<|endoftext|>


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

#![allow(dead_code)] // not used on all platforms

use collections::BTreeMap;
use ptr;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};

pub type Key = usize;

type Dtor = unsafe extern fn(*mut u8);

static NEXT_KEY: AtomicUsize = ATOMIC_USIZE_INIT;

static mut KEYS: *mut BTreeMap<Key, Option<Dtor>> = ptr::null_mut();

#[thread_local]
static mut LOCALS: *mut BTreeMap<Key, *mut u8> = ptr::null_mut();

unsafe fn keys() -> &'static mut BTreeMap<Key, Option<Dtor>> {
    if KEYS == ptr::null_mut() {
        KEYS = Box::into_raw(Box::new(BTreeMap::new()));
    }
    &mut *KEYS
}

unsafe fn locals() -> &'static mut BTreeMap<Key, *mut u8> {
    if LOCALS == ptr::null_mut() {
        LOCALS = Box::into_raw(Box::new(BTreeMap::new()));
    }
    &mut *LOCALS
}

#[inline]
pub unsafe fn create(dtor: Option<Dtor>) -> Key {
    let key = NEXT_KEY.fetch_add(1, Ordering::SeqCst);
    keys().insert(key, dtor);
    key
}

#[inline]
pub unsafe fn get(key: Key) -> *mut u8 {
    if let Some(&entry) = locals().get(&key) {
        entry
    } else {
        ptr::null_mut()
    }
}

#[inline]
pub unsafe fn set(key: Key, value: *mut u8) {
    locals().insert(key, value);
}

#[inline]
pub unsafe fn destroy(key: Key) {
    keys().remove(&key);
}
<commit_msg>Rollup merge of #42142 - ids1024:redox, r=aturon<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(dead_code)] // not used on all platforms

use collections::BTreeMap;
use ptr;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};

pub type Key = usize;

type Dtor = unsafe extern fn(*mut u8);

static NEXT_KEY: AtomicUsize = ATOMIC_USIZE_INIT;

static mut KEYS: *mut BTreeMap<Key, Option<Dtor>> = ptr::null_mut();

#[thread_local]
static mut LOCALS: *mut BTreeMap<Key, *mut u8> = ptr::null_mut();

unsafe fn keys() -> &'static mut BTreeMap<Key, Option<Dtor>> {
    if KEYS == ptr::null_mut() {
        KEYS = Box::into_raw(Box::new(BTreeMap::new()));
    }
    &mut *KEYS
}

unsafe fn locals() -> &'static mut BTreeMap<Key, *mut u8> {
    if LOCALS == ptr::null_mut() {
        LOCALS = Box::into_raw(Box::new(BTreeMap::new()));
    }
    &mut *LOCALS
}

#[inline]
pub unsafe fn create(dtor: Option<Dtor>) -> Key {
    let key = NEXT_KEY.fetch_add(1, Ordering::SeqCst);
    keys().insert(key, dtor);
    key
}

#[inline]
pub unsafe fn get(key: Key) -> *mut u8 {
    if let Some(&entry) = locals().get(&key) {
        entry
    } else {
        ptr::null_mut()
    }
}

#[inline]
pub unsafe fn set(key: Key, value: *mut u8) {
    locals().insert(key, value);
}

#[inline]
pub unsafe fn destroy(key: Key) {
    keys().remove(&key);
}

#[inline]
pub fn requires_synchronized_create() -> bool {
    false
}
<|endoftext|>


<commit_before>use error::MemcacheError;
use std::io;
use std::io::{Read, Write};
use std::net::TcpStream;
#[cfg(unix)]
use std::os::unix::net::UnixStream;
use std::time::Duration;
use udp_stream::UdpStream;
#[cfg(unix)]
use url::Host;
use url::Url;

enum Stream {
    TcpStream(TcpStream),
    UdpSocket(UdpStream),
    #[cfg(unix)]
    UnixStream(UnixStream),
}

/// a connection to the memcached server
pub struct Connection {
    stream: Stream,
    pub url: String,
}

impl Connection {
    pub fn connect(addr: &str) -> Result<Self, MemcacheError> {
        let addr = match Url::parse(addr) {
            Ok(v) => v,
            Err(_) => return Err(MemcacheError::ClientError("Invalid memcache URL".into())),
        };
        if addr.scheme() != "memcache" {
            return Err(MemcacheError::ClientError(
                "memcache URL should start with 'memcache://'".into(),
            ));
        }

        let is_udp = addr
            .query_pairs()
            .any(|(ref k, ref v)| k == "udp" && v == "true");

        if is_udp {
            let udp_stream = Stream::UdpSocket(UdpStream::new(addr.clone())?);
            return Ok(Connection {
                url: addr.into_string(),
                stream: udp_stream,
            });
        }

        #[cfg(unix)]
        {
            if addr.host() == Some(Host::Domain("")) && addr.port() == None {
                let stream = UnixStream::connect(addr.path())?;
                return Ok(Connection {
                    url: addr.into_string(),
                    stream: Stream::UnixStream(stream),
                });
            }
        }

        let stream = TcpStream::connect(addr.clone())?;
        let tcp_nodelay = addr
            .query_pairs()
            .any(|(ref k, ref v)| k == "tcp_nodelay" && v == "true");
        stream.set_nodelay(tcp_nodelay)?;
        let timeout = addr.query_pairs()
            .find(|&(ref k, ref _v)| k == "timeout")
            .and_then(|(ref _k, ref v)| v.parse::<u64>().ok())
            .map(Duration::from_secs);
        if timeout.is_some() {
            stream.set_read_timeout(timeout)?;
            stream.set_write_timeout(timeout)?;
        }
        return Ok(Connection {
            url: addr.into_string(),
            stream: Stream::TcpStream(stream),
        });
    }

    pub(crate) fn set_read_timeout(&mut self, timeout: Option<Duration>) -> Result<(), MemcacheError> {
        if  let Stream::TcpStream(ref mut conn) =  self.stream {
            conn.set_read_timeout(timeout)?;
        }
        Ok(())
    }

    pub(crate) fn set_write_timeout(&mut self, timeout: Option<Duration>) -> Result<(), MemcacheError> {
        if  let Stream::TcpStream(ref mut conn) =  self.stream {
            conn.set_write_timeout(timeout)?;
        }
        Ok(())
    }
}

impl Read for Connection {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self.stream {
            Stream::TcpStream(ref mut stream) => stream.read(buf),
            Stream::UdpSocket(ref mut stream) => stream.read(buf),
            #[cfg(unix)]
            Stream::UnixStream(ref mut stream) => stream.read(buf),
        }
    }
}

impl Write for Connection {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self.stream {
            Stream::TcpStream(ref mut stream) => stream.write(buf),
            Stream::UdpSocket(ref mut stream) => stream.write(buf),
            #[cfg(unix)]
            Stream::UnixStream(ref mut stream) => stream.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self.stream {
            Stream::TcpStream(ref mut stream) => stream.flush(),
            Stream::UdpSocket(ref mut stream) => stream.flush(),
            #[cfg(unix)]
            Stream::UnixStream(ref mut stream) => stream.flush(),
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn tcp_nodelay() {
        super::Connection::connect("memcache://localhost:12345?tcp_nodelay=true").unwrap();
    }
}
<commit_msg>:zap: enable tcp no nolay by default<commit_after>use error::MemcacheError;
use std::io;
use std::io::{Read, Write};
use std::net::TcpStream;
#[cfg(unix)]
use std::os::unix::net::UnixStream;
use std::time::Duration;
use udp_stream::UdpStream;
#[cfg(unix)]
use url::Host;
use url::Url;

enum Stream {
    TcpStream(TcpStream),
    UdpSocket(UdpStream),
    #[cfg(unix)]
    UnixStream(UnixStream),
}

/// a connection to the memcached server
pub struct Connection {
    stream: Stream,
    pub url: String,
}

impl Connection {
    pub fn connect(addr: &str) -> Result<Self, MemcacheError> {
        let addr = match Url::parse(addr) {
            Ok(v) => v,
            Err(_) => return Err(MemcacheError::ClientError("Invalid memcache URL".into())),
        };
        if addr.scheme() != "memcache" {
            return Err(MemcacheError::ClientError(
                "memcache URL should start with 'memcache://'".into(),
            ));
        }

        let is_udp = addr
            .query_pairs()
            .any(|(ref k, ref v)| k == "udp" && v == "true");

        if is_udp {
            let udp_stream = Stream::UdpSocket(UdpStream::new(addr.clone())?);
            return Ok(Connection {
                url: addr.into_string(),
                stream: udp_stream,
            });
        }

        #[cfg(unix)]
        {
            if addr.host() == Some(Host::Domain("")) && addr.port() == None {
                let stream = UnixStream::connect(addr.path())?;
                return Ok(Connection {
                    url: addr.into_string(),
                    stream: Stream::UnixStream(stream),
                });
            }
        }

        let stream = TcpStream::connect(addr.clone())?;

        let disable_tcp_nodelay = addr
            .query_pairs()
            .any(|(ref k, ref v)| k == "tcp_nodelay" && v == "false");
        if !disable_tcp_nodelay {
            stream.set_nodelay(true)?;
        }
        let timeout = addr.query_pairs()
            .find(|&(ref k, ref _v)| k == "timeout")
            .and_then(|(ref _k, ref v)| v.parse::<u64>().ok())
            .map(Duration::from_secs);
        if timeout.is_some() {
            stream.set_read_timeout(timeout)?;
            stream.set_write_timeout(timeout)?;
        }
        return Ok(Connection {
            url: addr.into_string(),
            stream: Stream::TcpStream(stream),
        });
    }

    pub(crate) fn set_read_timeout(&mut self, timeout: Option<Duration>) -> Result<(), MemcacheError> {
        if  let Stream::TcpStream(ref mut conn) =  self.stream {
            conn.set_read_timeout(timeout)?;
        }
        Ok(())
    }

    pub(crate) fn set_write_timeout(&mut self, timeout: Option<Duration>) -> Result<(), MemcacheError> {
        if  let Stream::TcpStream(ref mut conn) =  self.stream {
            conn.set_write_timeout(timeout)?;
        }
        Ok(())
    }
}

impl Read for Connection {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match self.stream {
            Stream::TcpStream(ref mut stream) => stream.read(buf),
            Stream::UdpSocket(ref mut stream) => stream.read(buf),
            #[cfg(unix)]
            Stream::UnixStream(ref mut stream) => stream.read(buf),
        }
    }
}

impl Write for Connection {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self.stream {
            Stream::TcpStream(ref mut stream) => stream.write(buf),
            Stream::UdpSocket(ref mut stream) => stream.write(buf),
            #[cfg(unix)]
            Stream::UnixStream(ref mut stream) => stream.write(buf),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self.stream {
            Stream::TcpStream(ref mut stream) => stream.flush(),
            Stream::UdpSocket(ref mut stream) => stream.flush(),
            #[cfg(unix)]
            Stream::UnixStream(ref mut stream) => stream.flush(),
        }
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn tcp_nodelay() {
        super::Connection::connect("memcache://localhost:12345?tcp_nodelay=true").unwrap();
    }
}
<|endoftext|>


<commit_before>// https://leetcode.com/problems/intervals-between-identical-elements/
pub fn get_distances(arr: Vec<i32>) -> Vec<i64> {
    todo!()
}

fn main() {
    println!("{}", get_distances(vec![2, 1, 3, 1, 2, 3, 3])); // [4,2,7,2,4,4,5]
    println!("{}", get_distances(vec![10, 5, 10, 10])); // [5,0,3,4]
}
<commit_msg>Update problem 2121<commit_after>use std::collections::HashMap;

// https://leetcode.com/problems/intervals-between-identical-elements/
pub fn get_distances(arr: Vec<i32>) -> Vec<i64> {
    let mut map: HashMap<i32, Vec<usize>> = HashMap::new();
    for (i, num) in arr.iter().enumerate() {
        map.entry(*num).or_insert(vec![]).push(i);
    }
    let mut answer = vec![0; arr.len()];
    for (i, num) in arr.iter().enumerate() {
        let mut sum: i64 = 0;
        for j in map[num].iter() {
            if i == *j {
                continue;
            }
            sum += i64::abs(i as i64 - *j as i64)
        }
        answer[i] = sum;
    }
    answer
}

fn main() {
    println!("{:?}", get_distances(vec![2, 1, 3, 1, 2, 3, 3])); // [4,2,7,2,4,4,5]
    println!("{:?}", get_distances(vec![10, 5, 10, 10])); // [5,0,3,4]
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 Anatoly Ikorsky
//
// 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. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

use conn::futures::query_result::*;
use either::*;
use errors::*;
use lib_futures::Async::Ready;
use lib_futures::Future;
use lib_futures::Poll;

/// Future that drops result and resolves to wrapped `Conn` or `Stmt`.
pub struct DropResult<T> {
    query_result: Option<T>,
}

pub fn new<T: Sized>(query_result: T) -> DropResult<T>
{
    DropResult {
        query_result: Some(query_result),
    }
}

impl<T> Future for DropResult<T>
where T: InnerQueryResult,
      T: UnconsumedQueryResult,
      T::Output: QueryResultOutput<Result=T>,
{
    type Item = <T::Output as QueryResultOutput>::Output;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match try_ready!(self.query_result.as_mut().unwrap().poll()) {
            Left(_) => self.poll(),
            Right(output) => {
                let prev_result = self.query_result.take().unwrap();
                match output.into_next_or_output(prev_result) {
                    (_, Left(next_result)) => {
                        self.query_result = Some(next_result);
                        self.poll()
                    },
                    (_, Right(stmt_or_conn)) => {
                        Ok(Ready(stmt_or_conn))
                    }
                }
            }
        }
    }
}
<commit_msg>Improve DropResult implementation<commit_after>// Copyright (c) 2016 Anatoly Ikorsky
//
// 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. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

use conn::futures::query_result::*;
use either::*;
use errors::*;
use lib_futures::Async::Ready;
use lib_futures::Future;
use lib_futures::Poll;

/// Future that drops result and resolves to wrapped `Conn` or `Stmt`.
///
/// Note that it resolves to `Stmt` for result of `Conn::(prep|first)_exec` because it's result is
/// `BinQueryResult`. You can call `unwrap()` on `Stmt` to get wrapped `Conn`.
pub struct DropResult<T> {
    query_result: Option<T>,
}

pub fn new<T: Sized>(query_result: T) -> DropResult<T>
{
    DropResult {
        query_result: Some(query_result),
    }
}

impl<T> Future for DropResult<T>
where T: InnerQueryResult,
      T: UnconsumedQueryResult,
      T::Output: QueryResultOutput<Result=T>,
{
    type Item = <T::Output as QueryResultOutput>::Output;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match try_ready!(self.query_result.as_mut().unwrap().poll()) {
            Left(_) => self.poll(),
            Right(output) => {
                let prev_result = self.query_result.take().unwrap();
                match output.into_next_or_output(prev_result) {
                    (_, Left(next_result)) => {
                        self.query_result = Some(next_result);
                        self.poll()
                    },
                    (_, Right(stmt_or_conn)) => {
                        Ok(Ready(stmt_or_conn))
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>use std::path::Path;

use serde::{
    Deserialize,
    Serialize,
};

use anyhow::Result;

use sorted_iter::{
    assume::*,
    SortedPairIterator,
};

use crate::{
    accessions::{
        Accession,
        RawAccessionEntry,
    },
    metadata::{
        coordinate::Coordinate,
        merged::Metadata,
        previous::Previous,
        r2dt_hit::R2dtHit,
        rfam_hit::RfamHit,
    },
};

use rnc_core::psql::JsonlIterator;
use rnc_core::grouper::Grouped;

#[derive(Debug, Deserialize, Serialize)]
pub struct Normalized {
    upi: String,
    taxid: usize,
    length: usize,
    last_release: usize,
    coordinates: Vec<Coordinate>,
    accessions: Vec<Accession>,
    deleted: bool,
    previous: Option<Previous>,
    rfam_hits: Vec<RfamHit>,
    r2dt_hits: Vec<R2dtHit>,
}

impl Normalized {
    fn new(
        raw_accessions: Vec<RawAccessionEntry>,
        metadata: Metadata,
    ) -> Result<Self> {
        assert!(raw_accessions.len() != 0, "Must given accessions to normalize");
        let accessions: Vec<Accession> = raw_accessions.into_iter().map(Accession::from).collect();
        let last_release = accessions.iter().map(|a| a.last_release).max().unwrap();
        let deleted = accessions.iter().all(|a| !a.is_active);

        return Ok(Self {
            upi: metadata.upi,
            taxid: metadata.taxid,
            length: metadata.length,
            last_release,
            coordinates: metadata.coordinates,
            accessions,
            deleted,
            previous: metadata.previous,
            rfam_hits: metadata.rfam_hits,
            r2dt_hits: metadata.r2dt_hits.into_iter().collect(),
        });
    }
}

pub fn write(accession_file: &Path, metadata_file: &Path, output: &Path) -> Result<()> {
    let accessions = JsonlIterator::from_path(accession_file)?;
    let accessions = accessions.map(|group: Grouped<RawAccessionEntry>| {
        match group {
            Grouped::Multiple { id, data } => (id, data),
            _ => panic!("Illegal data format for accessions file {:?}", &group),
        }
    });
    let accessions = accessions.into_iter().assume_sorted_by_key();

    let metadata = JsonlIterator::from_path(metadata_file)?;
    let metadata = metadata.map(|metadata: Metadata| (m.id, m));
    let metadata = metadata.into_iter().assume_sorted_by_key();
    let partial = accessions.join(metadata);

    let mut output = rnc_utils::buf_writer(output)?;
    for (_id, data) in partial {
        let (accessions, metadata) = data;
        let norm = Normalized::new(accessions, metadata)?;
        serde_json::to_writer(&mut output, &norm)?;
        writeln!(&mut output)?;
    }

    Ok(())
}
<commit_msg>Fix variable name<commit_after>use std::path::Path;

use serde::{
    Deserialize,
    Serialize,
};

use anyhow::Result;

use sorted_iter::{
    assume::*,
    SortedPairIterator,
};

use crate::{
    accessions::{
        Accession,
        RawAccessionEntry,
    },
    metadata::{
        coordinate::Coordinate,
        merged::Metadata,
        previous::Previous,
        r2dt_hit::R2dtHit,
        rfam_hit::RfamHit,
    },
};

use rnc_core::psql::JsonlIterator;
use rnc_core::grouper::Grouped;

#[derive(Debug, Deserialize, Serialize)]
pub struct Normalized {
    upi: String,
    taxid: usize,
    length: usize,
    last_release: usize,
    coordinates: Vec<Coordinate>,
    accessions: Vec<Accession>,
    deleted: bool,
    previous: Option<Previous>,
    rfam_hits: Vec<RfamHit>,
    r2dt_hits: Vec<R2dtHit>,
}

impl Normalized {
    fn new(
        raw_accessions: Vec<RawAccessionEntry>,
        metadata: Metadata,
    ) -> Result<Self> {
        assert!(raw_accessions.len() != 0, "Must given accessions to normalize");
        let accessions: Vec<Accession> = raw_accessions.into_iter().map(Accession::from).collect();
        let last_release = accessions.iter().map(|a| a.last_release).max().unwrap();
        let deleted = accessions.iter().all(|a| !a.is_active);

        return Ok(Self {
            upi: metadata.upi,
            taxid: metadata.taxid,
            length: metadata.length,
            last_release,
            coordinates: metadata.coordinates,
            accessions,
            deleted,
            previous: metadata.previous,
            rfam_hits: metadata.rfam_hits,
            r2dt_hits: metadata.r2dt_hits.into_iter().collect(),
        });
    }
}

pub fn write(accession_file: &Path, metadata_file: &Path, output: &Path) -> Result<()> {
    let accessions = JsonlIterator::from_path(accession_file)?;
    let accessions = accessions.map(|group: Grouped<RawAccessionEntry>| {
        match group {
            Grouped::Multiple { id, data } => (id, data),
            _ => panic!("Illegal data format for accessions file {:?}", &group),
        }
    });
    let accessions = accessions.into_iter().assume_sorted_by_key();

    let metadata = JsonlIterator::from_path(metadata_file)?;
    let metadata = metadata.map(|m: Metadata| (m.id, m));
    let metadata = metadata.into_iter().assume_sorted_by_key();
    let partial = accessions.join(metadata);

    let mut output = rnc_utils::buf_writer(output)?;
    for (_id, data) in partial {
        let (accessions, metadata) = data;
        let norm = Normalized::new(accessions, metadata)?;
        serde_json::to_writer(&mut output, &norm)?;
        writeln!(&mut output)?;
    }

    Ok(())
}
<|endoftext|>


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

//! Angle units for type-safe, self-documenting code.

use std::fmt;
use std::f64;
use std::ops::*;

use rand::{Rand, Rng};
use rand::distributions::range::SampleRange;

use rust_num::{Float, One, Zero};
use rust_num::traits::cast;

use approx::ApproxEq;
use num::BaseFloat;

/// An angle, in radians
#[derive(Copy, Clone, PartialEq, PartialOrd, RustcEncodable, RustcDecodable)]
pub struct Rad<S> { pub s: S }
/// An angle, in degrees
#[derive(Copy, Clone, PartialEq, PartialOrd, RustcEncodable, RustcDecodable)]
pub struct Deg<S> { pub s: S }

/// Create a new angle, in radians
#[inline] pub fn rad<S: BaseFloat>(s: S) -> Rad<S> { Rad { s: s } }
/// Create a new angle, in degrees
#[inline] pub fn deg<S: BaseFloat>(s: S) -> Deg<S> { Deg { s: s } }

impl<S> From<Rad<S>> for Deg<S> where S: BaseFloat {
    #[inline]
    fn from(r: Rad<S>) -> Deg<S> {
        deg(r.s * cast(180.0 / f64::consts::PI).unwrap())
    }
}

impl<S> From<Deg<S>> for Rad<S> where S: BaseFloat {
    #[inline]
    fn from(d: Deg<S>) -> Rad<S> {
        rad(d.s * cast(f64::consts::PI / 180.0).unwrap())
    }
}

/// Private utility functions for converting to/from scalars
trait ScalarConv<S> {
    fn from(s: S) -> Self;
    fn s<'a>(&'a self) -> &'a S;
    fn mut_s<'a>(&'a mut self) -> &'a mut S;
}

impl<S: BaseFloat> ScalarConv<S> for Rad<S> {
    #[inline] fn from(s: S) -> Rad<S> { rad(s) }
    #[inline] fn s<'a>(&'a self) -> &'a S { &self.s }
    #[inline] fn mut_s<'a>(&'a mut self) -> &'a mut S { &mut self.s }
}

impl<S: BaseFloat> ScalarConv<S> for Deg<S> {
    #[inline] fn from(s: S) -> Deg<S> { deg(s) }
    #[inline] fn s<'a>(&'a self) -> &'a S { &self.s }
    #[inline] fn mut_s<'a>(&'a mut self) -> &'a mut S { &mut self.s }
}

/// Operations on angles.
pub trait Angle where
    Self: Clone + Zero,
    Self: PartialEq + PartialOrd,
    // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092
    Self: ApproxEq<Epsilon = <Self as Angle>::Unitless>,
    Self: Neg<Output = Self>,
    Self: Into<Rad<<Self as Angle>::Unitless>>,
    Self: Into<Deg<<Self as Angle>::Unitless>>,
    Self: ScalarConv<<Self as Angle>::Unitless>,
    Self: fmt::Debug,
{
    type Unitless: BaseFloat;

    /// Create a new angle from any other valid angle.
    fn from<A: Angle<Unitless = Self::Unitless>>(theta: A) -> Self;

    /// Negate this angle, in-place.
    #[inline] fn neg_self(&mut self) { *self = -(*self).clone() }

    /// Add this angle with another, returning the new angle.
    #[inline] fn add_a(&self, other: Self) -> Self { ScalarConv::from(*self.s() + *other.s()) }
    /// Subtract another angle from this one, returning the new angle.
    #[inline] fn sub_a(&self, other: Self) -> Self { ScalarConv::from(*self.s() - *other.s()) }
    /// Divide this angle by another, returning the ratio.
    #[inline] fn div_a(&self, other: Self) -> Self::Unitless { *self.s() / *other.s() }
    /// Take the remainder of this angle with another.
    #[inline] fn rem_a(&self, other: Self) -> Self::Unitless { *self.s() % *other.s() }

    /// Multiply this angle by a scalar, returning the new angle.
    #[inline] fn mul_s(&self, scalar: Self::Unitless) -> Self { ScalarConv::from(*self.s() * scalar) }
    /// Divide this angle by a scalar, returing the new angle.
    #[inline] fn div_s(&self, scalar: Self::Unitless) -> Self { ScalarConv::from(*self.s() / scalar) }
    /// Take the remainder of this angle by a scalar, returning the new angle.
    #[inline] fn rem_s(&self, scalar: Self::Unitless) -> Self { ScalarConv::from(*self.s() % scalar) }

    /// Add this angle with another, in-place.
    #[inline] fn add_self_a(&mut self, other: Self) { *self.mut_s() = *self.s() + *other.s() }
    /// Subtract another angle from this one, in-place.
    #[inline] fn sub_self_a(&mut self, other: Self) { *self.mut_s() = *self.s() - *other.s() }

    /// Multiply this angle by a scalar, in-place.
    #[inline] fn mul_self_s(&mut self, scalar: Self::Unitless) { *self.mut_s() = *self.s() * scalar }
    /// Divide this angle by a scalar, in-place.
    #[inline] fn div_self_s(&mut self, scalar: Self::Unitless) { *self.mut_s() = *self.s() / scalar }
    /// Take the remainder of this angle by a scalar, in-place.
    #[inline] fn rem_self_s(&mut self, scalar: Self::Unitless) { *self.mut_s() = *self.s() % scalar }

    /// Return the angle, normalized to the range `[0, full_turn)`.
    #[inline]
    fn normalize(&self) -> Self {
        let mut a = self.clone();
        a.normalize_self();
        a
    }

    /// Normalize the angle to the range `[0, full_turn)`.
    #[inline]
    fn normalize_self(&mut self) {
        let full_turn = Self::full_turn();
        self.rem_self_s(full_turn.s().clone());
        if *self < Self::zero() { self.add_self_a(full_turn) };
    }

    /// Return the angle rotated by half a turn
    #[inline]
    fn opposite(&self) -> Self {
        self.add_a(Self::turn_div_2()).normalize()
    }

    /// Returns the interior bisector of the two angles
    #[inline]
    fn bisect(&self, other: Self) -> Self {
        self.add_a(self.sub_a(other).mul_s(cast(0.5f64).unwrap())).normalize()
    }

    fn full_turn() -> Self;

    #[inline] fn turn_div_2() -> Self { Self::full_turn().div_s(cast(2i8).unwrap()) }
    #[inline] fn turn_div_3() -> Self { Self::full_turn().div_s(cast(3i8).unwrap()) }
    #[inline] fn turn_div_4() -> Self { Self::full_turn().div_s(cast(4i8).unwrap()) }
    #[inline] fn turn_div_6() -> Self { Self::full_turn().div_s(cast(6i8).unwrap()) }

    #[inline] fn equiv(&self, other: &Self) -> bool { self.normalize() == other.normalize() }
}

#[inline] pub fn bisect<A: Angle>(a: A, b: A) -> A { a.bisect(b) }

impl<R: Into<Rad<S>>, S: BaseFloat> Add<R> for Rad<S> {
    type Output = Rad<S>;

    #[inline]
    fn add(self, other: R) -> Rad<S> { rad(self.s + other.into().s) }
}

impl<R: Into<Rad<S>>, S: BaseFloat> Add<R> for Deg<S> {
    type Output = Deg<S>;

    #[inline]
    fn add(self, other: R) -> Deg<S> { deg(self.s + other.into().s) }
}

impl<R: Into<Rad<S>>, S: BaseFloat> Sub<R> for Rad<S> {
    type Output = Rad<S>;

    #[inline]
    fn sub(self, other: R) -> Rad<S> { rad(self.s - other.into().s) }
}

impl<R: Into<Rad<S>>, S: BaseFloat> Sub<R> for Deg<S> {
    type Output = Deg<S>;

    #[inline]
    fn sub(self, other: R) -> Deg<S> { deg(self.s - other.into().s) }
}

impl<S: BaseFloat> Neg for Rad<S> {
    type Output = Rad<S>;

    #[inline]
    fn neg(self) -> Rad<S> { rad(-self.s) }
}
impl<S: BaseFloat> Neg for Deg<S> {
    type Output = Deg<S>;

    #[inline]
    fn neg(self) -> Deg<S> { deg(-self.s) }
}

impl<S: BaseFloat> Zero for Rad<S> {
    #[inline]
    fn zero() -> Rad<S> { rad(S::zero()) }
    #[inline]
    fn is_zero(&self) -> bool { *self == Self::zero() }
}
impl<S: BaseFloat> Zero for Deg<S> {
    #[inline]
    fn zero() -> Deg<S> { deg(S::zero()) }
    #[inline]
    fn is_zero(&self) -> bool { *self == Self::zero() }
}

impl<R: Into<Rad<S>>, S: BaseFloat> Mul<R> for Rad<S> {
    type Output = Rad<S>;

    #[inline]
    fn mul(self, other: R) -> Rad<S> { rad(self.s * other.into().s) }
}

impl<R: Into<Rad<S>>, S: BaseFloat> Mul<R> for Deg<S> {
    type Output = Deg<S>;

    #[inline]
    fn mul(self, other: R) -> Deg<S> { deg(self.s * other.into().s) }
}

impl<S: BaseFloat> One for Rad<S> {
    #[inline]
    fn one() -> Rad<S> { rad(S::one()) }
}
impl<S: BaseFloat> One for Deg<S> {
    #[inline]
    fn one() -> Deg<S> { deg(S::one()) }
}

const PI_2: f64 = f64::consts::PI * 2f64;

impl<S: BaseFloat> Angle for Rad<S> {
    type Unitless = S;
    #[inline] fn from<A: Angle<Unitless = S>>(theta: A) -> Rad<S> { theta.into() }
    #[inline] fn full_turn() -> Rad<S> { rad(cast(PI_2).unwrap()) }
}

impl<S: BaseFloat> Angle for Deg<S> {
    type Unitless = S;
    #[inline] fn from<A: Angle<Unitless = S>>(theta: A) -> Deg<S> { theta.into() }
    #[inline] fn full_turn() -> Deg<S> { deg(cast(360i32).unwrap()) }
}

#[inline] pub fn sin<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { theta.into().s.sin() }
#[inline] pub fn cos<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { theta.into().s.cos() }
#[inline] pub fn tan<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { theta.into().s.tan() }
#[inline] pub fn sin_cos<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> (S, S) { theta.into().s.sin_cos() }

#[inline] pub fn cot<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { tan(theta.into()).recip() }
#[inline] pub fn sec<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { cos(theta.into()).recip() }
#[inline] pub fn csc<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { sin(theta.into()).recip() }

#[inline] pub fn asin<S: BaseFloat, R: From<Rad<S>>>(s: S) -> R { rad(s.asin()).into() }
#[inline] pub fn acos<S: BaseFloat, R: From<Rad<S>>>(s: S) -> R { rad(s.acos()).into() }
#[inline] pub fn atan<S: BaseFloat, R: From<Rad<S>>>(s: S) -> R { rad(s.atan()).into() }
#[inline] pub fn atan2<S: BaseFloat, R: From<Rad<S>>>(a: S, b: S) -> R { rad(a.atan2(b)).into() }

impl<S: BaseFloat + fmt::Debug> fmt::Debug for Rad<S> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?} rad", self.s)
    }
}

impl<S: BaseFloat + fmt::Debug>
fmt::Debug for Deg<S> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}°", self.s)
    }
}

impl<S: BaseFloat> ApproxEq for Rad<S> {
    type Epsilon = S;

    #[inline]
    fn approx_eq_eps(&self, other: &Rad<S>, epsilon: &S) -> bool {
        self.s.approx_eq_eps(&other.s, epsilon)
    }
}

impl<S: BaseFloat> ApproxEq for Deg<S> {
    type Epsilon = S;

    #[inline]
    fn approx_eq_eps(&self, other: &Deg<S>, epsilon: &S) -> bool {
        self.s.approx_eq_eps(&other.s, epsilon)
    }
}

impl<S: BaseFloat + PartialOrd + SampleRange + Rand> Rand for Rad<S> {
    #[inline]
    fn rand<R: Rng>(rng: &mut R) -> Rad<S> {
        let angle: S = rng.gen_range(cast(-f64::consts::PI).unwrap(), cast(f64::consts::PI).unwrap());
        rad(angle)
    }
}

impl<S: BaseFloat + PartialOrd + SampleRange + Rand> Rand for Deg<S> {
    #[inline]
    fn rand<R: Rng>(rng: &mut R) -> Deg<S> {
        let angle: S = rng.gen_range(cast(-180f64).unwrap(), cast(180f64).unwrap());
        deg(angle)
    }
}
<commit_msg>Fully impl operator permutations, and remove Zero and One impls<commit_after>// Copyright 2013-2014 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Angle units for type-safe, self-documenting code.

use std::fmt;
use std::f64;
use std::ops::*;

use rand::{Rand, Rng};
use rand::distributions::range::SampleRange;

use rust_num::{Float, Zero};
use rust_num::traits::cast;

use approx::ApproxEq;
use num::BaseFloat;

/// An angle, in radians
#[derive(Copy, Clone, PartialEq, PartialOrd, RustcEncodable, RustcDecodable)]
pub struct Rad<S> { pub s: S }
/// An angle, in degrees
#[derive(Copy, Clone, PartialEq, PartialOrd, RustcEncodable, RustcDecodable)]
pub struct Deg<S> { pub s: S }

/// Create a new angle, in radians
#[inline] pub fn rad<S: BaseFloat>(s: S) -> Rad<S> { Rad { s: s } }
/// Create a new angle, in degrees
#[inline] pub fn deg<S: BaseFloat>(s: S) -> Deg<S> { Deg { s: s } }

impl<S> From<Rad<S>> for Deg<S> where S: BaseFloat {
    #[inline]
    fn from(r: Rad<S>) -> Deg<S> {
        deg(r.s * cast(180.0 / f64::consts::PI).unwrap())
    }
}

impl<S> From<Deg<S>> for Rad<S> where S: BaseFloat {
    #[inline]
    fn from(d: Deg<S>) -> Rad<S> {
        rad(d.s * cast(f64::consts::PI / 180.0).unwrap())
    }
}

/// Private utility functions for converting to/from scalars
trait ScalarConv<S> {
    fn from(s: S) -> Self;
    fn s<'a>(&'a self) -> &'a S;
    fn mut_s<'a>(&'a mut self) -> &'a mut S;
}

impl<S: BaseFloat> ScalarConv<S> for Rad<S> {
    #[inline] fn from(s: S) -> Rad<S> { rad(s) }
    #[inline] fn s<'a>(&'a self) -> &'a S { &self.s }
    #[inline] fn mut_s<'a>(&'a mut self) -> &'a mut S { &mut self.s }
}

impl<S: BaseFloat> ScalarConv<S> for Deg<S> {
    #[inline] fn from(s: S) -> Deg<S> { deg(s) }
    #[inline] fn s<'a>(&'a self) -> &'a S { &self.s }
    #[inline] fn mut_s<'a>(&'a mut self) -> &'a mut S { &mut self.s }
}

/// Operations on angles.
pub trait Angle where
    Self: Copy + Clone,
    Self: PartialEq + PartialOrd,
    // FIXME: Ugly type signatures - blocked by rust-lang/rust#24092
    Self: ApproxEq<Epsilon = <Self as Angle>::Unitless>,
    Self: Neg<Output = Self>,
    Self: Into<Rad<<Self as Angle>::Unitless>>,
    Self: Into<Deg<<Self as Angle>::Unitless>>,
    Self: ScalarConv<<Self as Angle>::Unitless>,
    Self: fmt::Debug,
{
    type Unitless: BaseFloat;

    /// Create a new angle from any other valid angle.
    fn from<A: Angle<Unitless = Self::Unitless>>(theta: A) -> Self;

    /// Negate this angle, in-place.
    #[inline] fn neg_self(&mut self) { *self = -*self }

    /// Add this angle with another, returning the new angle.
    #[inline] fn add_a(&self, other: Self) -> Self { ScalarConv::from(*self.s() + *other.s()) }
    /// Subtract another angle from this one, returning the new angle.
    #[inline] fn sub_a(&self, other: Self) -> Self { ScalarConv::from(*self.s() - *other.s()) }
    /// Divide this angle by another, returning the ratio.
    #[inline] fn div_a(&self, other: Self) -> Self::Unitless { *self.s() / *other.s() }
    /// Take the remainder of this angle with another.
    #[inline] fn rem_a(&self, other: Self) -> Self::Unitless { *self.s() % *other.s() }

    /// Multiply this angle by a scalar, returning the new angle.
    #[inline] fn mul_s(&self, scalar: Self::Unitless) -> Self { ScalarConv::from(*self.s() * scalar) }
    /// Divide this angle by a scalar, returing the new angle.
    #[inline] fn div_s(&self, scalar: Self::Unitless) -> Self { ScalarConv::from(*self.s() / scalar) }
    /// Take the remainder of this angle by a scalar, returning the new angle.
    #[inline] fn rem_s(&self, scalar: Self::Unitless) -> Self { ScalarConv::from(*self.s() % scalar) }

    /// Add this angle with another, in-place.
    #[inline] fn add_self_a(&mut self, other: Self) { *self.mut_s() = *self.s() + *other.s() }
    /// Subtract another angle from this one, in-place.
    #[inline] fn sub_self_a(&mut self, other: Self) { *self.mut_s() = *self.s() - *other.s() }

    /// Multiply this angle by a scalar, in-place.
    #[inline] fn mul_self_s(&mut self, scalar: Self::Unitless) { *self.mut_s() = *self.s() * scalar }
    /// Divide this angle by a scalar, in-place.
    #[inline] fn div_self_s(&mut self, scalar: Self::Unitless) { *self.mut_s() = *self.s() / scalar }
    /// Take the remainder of this angle by a scalar, in-place.
    #[inline] fn rem_self_s(&mut self, scalar: Self::Unitless) { *self.mut_s() = *self.s() % scalar }

    /// Return the angle, normalized to the range `[0, full_turn)`.
    #[inline]
    fn normalize(&self) -> Self {
        let mut a = self.clone();
        a.normalize_self();
        a
    }

    /// Normalize the angle to the range `[0, full_turn)`.
    #[inline]
    fn normalize_self(&mut self) {
        let full_turn = Self::full_turn();
        self.rem_self_s(full_turn.s().clone());
        if *self < Self::zero() { self.add_self_a(full_turn) };
    }

    /// Return the angle rotated by half a turn
    #[inline]
    fn opposite(&self) -> Self {
        self.add_a(Self::turn_div_2()).normalize()
    }

    /// Returns the interior bisector of the two angles
    #[inline]
    fn bisect(&self, other: Self) -> Self {
        self.add_a(self.sub_a(other).mul_s(cast(0.5f64).unwrap())).normalize()
    }

    fn zero() -> Self;
    fn full_turn() -> Self;

    #[inline] fn turn_div_2() -> Self { Self::full_turn().div_s(cast(2i8).unwrap()) }
    #[inline] fn turn_div_3() -> Self { Self::full_turn().div_s(cast(3i8).unwrap()) }
    #[inline] fn turn_div_4() -> Self { Self::full_turn().div_s(cast(4i8).unwrap()) }
    #[inline] fn turn_div_6() -> Self { Self::full_turn().div_s(cast(6i8).unwrap()) }

    #[inline] fn equiv(&self, other: &Self) -> bool { self.normalize() == other.normalize() }
}

#[inline] pub fn bisect<A: Angle>(a: A, b: A) -> A { a.bisect(b) }

#[inline] pub fn sin<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { theta.into().s.sin() }
#[inline] pub fn cos<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { theta.into().s.cos() }
#[inline] pub fn tan<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { theta.into().s.tan() }
#[inline] pub fn sin_cos<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> (S, S) { theta.into().s.sin_cos() }

#[inline] pub fn cot<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { tan(theta.into()).recip() }
#[inline] pub fn sec<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { cos(theta.into()).recip() }
#[inline] pub fn csc<S: BaseFloat, R: Into<Rad<S>>>(theta: R) -> S { sin(theta.into()).recip() }

#[inline] pub fn asin<S: BaseFloat, R: From<Rad<S>>>(s: S) -> R { rad(s.asin()).into() }
#[inline] pub fn acos<S: BaseFloat, R: From<Rad<S>>>(s: S) -> R { rad(s.acos()).into() }
#[inline] pub fn atan<S: BaseFloat, R: From<Rad<S>>>(s: S) -> R { rad(s.atan()).into() }
#[inline] pub fn atan2<S: BaseFloat, R: From<Rad<S>>>(a: S, b: S) -> R { rad(a.atan2(b)).into() }

macro_rules! impl_angle {
    ($Angle:ident, $fmt:expr, $full_turn:expr, $hi:expr) => {
        impl<S: BaseFloat> Angle for $Angle<S> {
            type Unitless = S;

            #[inline]
            fn zero() -> $Angle<S> { ScalarConv::from(S::zero()) }

            #[inline]
            fn from<A: Angle<Unitless = S>>(theta: A) -> $Angle<S> { theta.into() }

            #[inline]
            fn full_turn() -> $Angle<S> { ScalarConv::from(cast($full_turn).unwrap()) }
        }

        impl<S: BaseFloat> Neg for $Angle<S> {
            type Output = $Angle<S>;

            #[inline]
            fn neg(self) -> $Angle<S> { ScalarConv::from(-self.s) }
        }

        impl<'a, S: BaseFloat> Neg for &'a $Angle<S> {
            type Output = $Angle<S>;

            #[inline]
            fn neg(self) -> $Angle<S> { ScalarConv::from(-self.s) }
        }

        impl_binary_operator!(<S: BaseFloat> Add<$Angle<S> > for $Angle<S> {
            fn add(lhs, rhs) -> $Angle<S> { ScalarConv::from(lhs.s + rhs.s) }
        });
        impl_binary_operator!(<S: BaseFloat> Sub<$Angle<S> > for $Angle<S> {
            fn sub(lhs, rhs) -> $Angle<S> { ScalarConv::from(lhs.s - rhs.s) }
        });
        impl_binary_operator!(<S: BaseFloat> Div<$Angle<S> > for $Angle<S> {
            fn div(lhs, rhs) -> S { lhs.s / rhs.s }
        });
        impl_binary_operator!(<S: BaseFloat> Rem<$Angle<S> > for $Angle<S> {
            fn rem(lhs, rhs) -> S { lhs.s % rhs.s }
        });

        impl_binary_operator!(<S: BaseFloat> Mul<S> for $Angle<S> {
            fn mul(lhs, scalar) -> $Angle<S> { ScalarConv::from(lhs.s * scalar) }
        });
        impl_binary_operator!(<S: BaseFloat> Div<S> for $Angle<S> {
            fn div(lhs, scalar) -> $Angle<S> { ScalarConv::from(lhs.s / scalar) }
        });
        impl_binary_operator!(<S: BaseFloat> Rem<S> for $Angle<S> {
            fn rem(lhs, scalar) -> $Angle<S> { ScalarConv::from(lhs.s % scalar) }
        });

        impl<S: BaseFloat> ApproxEq for $Angle<S> {
            type Epsilon = S;

            #[inline]
            fn approx_eq_eps(&self, other: &$Angle<S>, epsilon: &S) -> bool {
                self.s.approx_eq_eps(&other.s, epsilon)
            }
        }

        impl<S: BaseFloat + SampleRange> Rand for $Angle<S> {
            #[inline]
            fn rand<R: Rng>(rng: &mut R) -> $Angle<S> {
                let angle: S = rng.gen_range(cast(-$hi).unwrap(), cast($hi).unwrap());
                ScalarConv::from(angle)
            }
        }

        impl<S: BaseFloat> fmt::Debug for $Angle<S> {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, $fmt, self.s)
            }
        }
    }
}

impl_angle!(Rad, "{:?} rad", f64::consts::PI * 2.0, f64::consts::PI);
impl_angle!(Deg, "{:?}°", 360, 180);
<|endoftext|>


<commit_before>use std::io::{self, Read};
use std::sync::mpsc;
use std::thread;
use std::io::BufReader;
use std::io::BufRead;

use sys::tty::get_tty;

/// Construct an asynchronous handle to the TTY standard input, with a delimiter byte.
///
/// This has the same advantages as async_stdin(), but also allows specifying a delimiter byte. The
/// reader will stop reading after consuming the delimiter byte.
pub fn async_stdin_until(delimiter: u8) -> AsyncReader {
    let (send, recv) = mpsc::channel();

    thread::spawn(move || for i in get_tty().unwrap().bytes() {

        match i {
            Ok(byte) => {
                let end_of_stream = &byte == &delimiter;
                let send_error = send.send(Ok(byte)).is_err();

                if end_of_stream || send_error { return; }
            },
            Err(e) => { return; }
        }
    });

    AsyncReader { recv: recv }
}

/// Construct an asynchronous handle to the TTY standard input.
///
/// This allows you to read from standard input _without blocking_ the current thread.
/// Specifically, it works by firing up another thread to handle the event stream, which will then
/// be buffered in a mpsc queue, which will eventually be read by the current thread.
///
/// This will not read the piped standard input, but rather read from the TTY device, since reading
/// asyncronized from piped input would rarely make sense. In other words, if you pipe standard
/// output from another process, it won't be reflected in the stream returned by this function, as
/// this represents the TTY device, and not the piped standard input.
pub fn async_stdin() -> AsyncReader {
    let (send, recv) = mpsc::channel();

    thread::spawn(move || for i in get_tty().unwrap().bytes() {
                      if send.send(i).is_err() {
                          return;
                      }
                  });

    AsyncReader { recv: recv }
}

/// An asynchronous reader.
///
/// This acts as any other stream, with the exception that reading from it won't block. Instead,
/// the buffer will only be partially updated based on how much the internal buffer holds.
pub struct AsyncReader {
    /// The underlying mpsc receiver.
    recv: mpsc::Receiver<io::Result<u8>>,
}

// FIXME: Allow constructing an async reader from an arbitrary stream.

impl Read for AsyncReader {
    /// Read from the byte stream.
    ///
    /// This will never block, but try to drain the event queue until empty. If the total number of
    /// bytes written is lower than the buffer's length, the event queue is empty or that the event
    /// stream halted.
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let mut total = 0;

        loop {
            if total >= buf.len() {
                break;
            }

            match self.recv.try_recv() {
                Ok(Ok(b)) => {
                    buf[total] = b;
                    total += 1;
                }
                Ok(Err(e)) => return Err(e),
                Err(_) => break,
            }
        }

        Ok(total)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::io::Read;

    #[test]
    fn test_async_stdin() {
        let stdin = async_stdin();
        stdin.bytes().next();
    }
}
<commit_msg>Corrected all remaining build warnings<commit_after>use std::io::{self, Read};
use std::sync::mpsc;
use std::thread;

use sys::tty::get_tty;

/// Construct an asynchronous handle to the TTY standard input, with a delimiter byte.
///
/// This has the same advantages as async_stdin(), but also allows specifying a delimiter byte. The
/// reader will stop reading after consuming the delimiter byte.
pub fn async_stdin_until(delimiter: u8) -> AsyncReader {
    let (send, recv) = mpsc::channel();

    thread::spawn(move || for i in get_tty().unwrap().bytes() {

        match i {
            Ok(byte) => {
                let end_of_stream = &byte == &delimiter;
                let send_error = send.send(Ok(byte)).is_err();

                if end_of_stream || send_error { return; }
            },
            Err(_) => { return; }
        }
    });

    AsyncReader { recv: recv }
}

/// Construct an asynchronous handle to the TTY standard input.
///
/// This allows you to read from standard input _without blocking_ the current thread.
/// Specifically, it works by firing up another thread to handle the event stream, which will then
/// be buffered in a mpsc queue, which will eventually be read by the current thread.
///
/// This will not read the piped standard input, but rather read from the TTY device, since reading
/// asyncronized from piped input would rarely make sense. In other words, if you pipe standard
/// output from another process, it won't be reflected in the stream returned by this function, as
/// this represents the TTY device, and not the piped standard input.
pub fn async_stdin() -> AsyncReader {
    let (send, recv) = mpsc::channel();

    thread::spawn(move || for i in get_tty().unwrap().bytes() {
                      if send.send(i).is_err() {
                          return;
                      }
                  });

    AsyncReader { recv: recv }
}

/// An asynchronous reader.
///
/// This acts as any other stream, with the exception that reading from it won't block. Instead,
/// the buffer will only be partially updated based on how much the internal buffer holds.
pub struct AsyncReader {
    /// The underlying mpsc receiver.
    recv: mpsc::Receiver<io::Result<u8>>,
}

// FIXME: Allow constructing an async reader from an arbitrary stream.

impl Read for AsyncReader {
    /// Read from the byte stream.
    ///
    /// This will never block, but try to drain the event queue until empty. If the total number of
    /// bytes written is lower than the buffer's length, the event queue is empty or that the event
    /// stream halted.
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let mut total = 0;

        loop {
            if total >= buf.len() {
                break;
            }

            match self.recv.try_recv() {
                Ok(Ok(b)) => {
                    buf[total] = b;
                    total += 1;
                }
                Ok(Err(e)) => return Err(e),
                Err(_) => break,
            }
        }

        Ok(total)
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::io::Read;

    #[test]
    fn test_async_stdin() {
        let stdin = async_stdin();
        stdin.bytes().next();
    }
}
<|endoftext|>


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

extern crate ion_core;
extern crate sdl2;

use self::ion_core::renderer::traits::WindowBackend;
use self::ion_core::renderer::window::{WindowConfig, WindowState};
use self::ion_core::util::traits::AsAny;
use self::sdl2::event::Event;

use std::any::Any;
use std::os::raw::c_void;

/*===============================================================================================*/
/*------WINDOW BACKEND SDL2 STRUCT---------------------------------------------------------------*/
/*===============================================================================================*/

/// Allows for the creation and handling of a SDL2 window.
pub struct WindowBackendSDL2 {

    // Private
    _window_state:    WindowState,
    _sdl2_context:    Option<sdl2::Sdl>,
    _sdl2_video:      Option<sdl2::VideoSubsystem>,
    _sdl2_window:     Option<sdl2::video::Window>,
    _sdl2_event_pump: Option<sdl2::EventPump>
}

/*===============================================================================================*/
/*------WINDOW BACKEND SDL2 PUBLIC METHODS-------------------------------------------------------*/
/*===============================================================================================*/

impl AsAny for WindowBackendSDL2 {

    fn as_any (&self) -> &Any {
        self
    }
}

/*-----------------------------------------------------------------------------------------------*/

impl WindowBackend for WindowBackendSDL2 {

    fn init (&mut self, config: &WindowConfig) {

        let sdl2_context = sdl2::init ().unwrap ();
        let sdl2_video   = sdl2_context.video ().unwrap ();

        let mut sdl2_window = {

            if config.window_is_resizable {

                sdl2_video.window (&config.window_title,
                config.window_size.x as u32,
                config.window_size.y as u32)
                .resizable ()
                .opengl    ()
                .build     ()
                .unwrap    ()
            }

            else {

                sdl2_video.window (&config.window_title,
                config.window_size.x as u32,
                config.window_size.y as u32)
                .opengl ()
                .build  ()
                .unwrap ()
            }
        };

        if config.window_is_fullscreen {
            sdl2_window.set_fullscreen (sdl2::video::FullscreenType::True).unwrap ();
        }

        let sdl2_event_pump = sdl2_context.event_pump ().unwrap ();

        self._sdl2_context    = Some (sdl2_context);
        self._sdl2_video      = Some (sdl2_video);
        self._sdl2_event_pump = Some (sdl2_event_pump);
        self._sdl2_window     = Some (sdl2_window);
        self._window_state    = WindowState::Active;
    }

/*-----------------------------------------------------------------------------------------------*/

    fn get_window_state (&self) -> WindowState {
        self._window_state
    }

/*-----------------------------------------------------------------------------------------------*/

    fn on_pre_render (&mut self) {

        for event in self._sdl2_event_pump.as_mut ().unwrap ().poll_iter () {

            if let Event::Quit {..} = event {
                self._window_state = WindowState::Closed
            }
        }
    }

/*-----------------------------------------------------------------------------------------------*/

    fn on_render      (&mut self) {}
    fn on_post_render (&mut self) {}

/*-----------------------------------------------------------------------------------------------*/

    unsafe fn get_platform_display (&self) -> Result<*mut c_void, ()> {
        unimplemented! ()
    }

/*-----------------------------------------------------------------------------------------------*/

    unsafe fn get_platform_window (&self) -> Result<*mut c_void, ()> {
        unimplemented! ()
    }
}

/*===============================================================================================*/
/*------WINDOW BACKEND SDL2 PUBLIC STATIC METHODS------------------------------------------------*/
/*===============================================================================================*/

impl WindowBackendSDL2 {

    /// Returns a new `WindowBackendSDL2` instance.
    pub fn new () -> WindowBackendSDL2 {

        WindowBackendSDL2 {

            _window_state:    WindowState::Closed,
            _sdl2_context:    None,
            _sdl2_video:      None,
            _sdl2_event_pump: None,
            _sdl2_window:     None,
        }
    }
}

/*-----------------------------------------------------------------------------------------------*/

impl Default for WindowBackendSDL2 {

    fn default () -> WindowBackendSDL2 {
        WindowBackendSDL2::new ()
    }
}
<commit_msg>Improved window creation<commit_after>/*===============================================================================================*/
// Copyright 2016 Kyle Finlay
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*===============================================================================================*/

extern crate ion_core;
extern crate sdl2;

use self::ion_core::renderer::traits::WindowBackend;
use self::ion_core::renderer::window::{WindowConfig, WindowState};
use self::ion_core::util::traits::AsAny;
use self::sdl2::event::Event;

use std::any::Any;
use std::os::raw::c_void;

/*===============================================================================================*/
/*------WINDOW BACKEND SDL2 STRUCT---------------------------------------------------------------*/
/*===============================================================================================*/

/// Allows for the creation and handling of a SDL2 window.
pub struct WindowBackendSDL2 {

    // Private
    _window_state:    WindowState,
    _sdl2_context:    Option<sdl2::Sdl>,
    _sdl2_video:      Option<sdl2::VideoSubsystem>,
    _sdl2_window:     Option<sdl2::video::Window>,
    _sdl2_event_pump: Option<sdl2::EventPump>
}

/*===============================================================================================*/
/*------WINDOW BACKEND SDL2 PUBLIC METHODS-------------------------------------------------------*/
/*===============================================================================================*/

impl AsAny for WindowBackendSDL2 {

    fn as_any (&self) -> &Any {
        self
    }
}

/*-----------------------------------------------------------------------------------------------*/

impl WindowBackend for WindowBackendSDL2 {

    fn init (&mut self, config: &WindowConfig) {

        // Initialize sdl and video subsystem
        let sdl2_context = sdl2::init ().unwrap ();
        let sdl2_video   = sdl2_context.video ().unwrap ();

        // Create new sdl2 window builder
        let mut sdl2_window_builder = sdl2_video.window (&config.window_title,
            config.window_size.x as u32,
            config.window_size.y as u32);

        // Enable OpenGL and set window position
        sdl2_window_builder.opengl ()
            .position (config.window_pos.x as i32, config.window_pos.y as i32);

        // Set fullscreen and resizable state
        if config.window_is_fullscreen {sdl2_window_builder.fullscreen ();}
        if config.window_is_resizable  {sdl2_window_builder.resizable  ();}

        // Create the sdl2 window and event pump
        let sdl2_window     = sdl2_window_builder.build ().unwrap ();
        let sdl2_event_pump = sdl2_context.event_pump   ().unwrap ();

        // Set window backend variables
        self._sdl2_context    = Some (sdl2_context);
        self._sdl2_video      = Some (sdl2_video);
        self._sdl2_event_pump = Some (sdl2_event_pump);
        self._sdl2_window     = Some (sdl2_window);
        self._window_state    = WindowState::Active;
    }

/*-----------------------------------------------------------------------------------------------*/

    fn get_window_state (&self) -> WindowState {
        self._window_state
    }

/*-----------------------------------------------------------------------------------------------*/

    fn on_pre_render (&mut self) {

        for event in self._sdl2_event_pump.as_mut ().unwrap ().poll_iter () {

            if let Event::Quit {..} = event {
                self._window_state = WindowState::Closed
            }
        }
    }

/*-----------------------------------------------------------------------------------------------*/

    fn on_render      (&mut self) {}
    fn on_post_render (&mut self) {}

/*-----------------------------------------------------------------------------------------------*/

    unsafe fn get_platform_display (&self) -> Result<*mut c_void, ()> {
        unimplemented! ()
    }

/*-----------------------------------------------------------------------------------------------*/

    unsafe fn get_platform_window (&self) -> Result<*mut c_void, ()> {
        unimplemented! ()
    }
}

/*===============================================================================================*/
/*------WINDOW BACKEND SDL2 PUBLIC STATIC METHODS------------------------------------------------*/
/*===============================================================================================*/

impl WindowBackendSDL2 {

    /// Returns a new `WindowBackendSDL2` instance.
    pub fn new () -> WindowBackendSDL2 {

        WindowBackendSDL2 {

            _window_state:    WindowState::Closed,
            _sdl2_context:    None,
            _sdl2_video:      None,
            _sdl2_event_pump: None,
            _sdl2_window:     None,
        }
    }
}

/*-----------------------------------------------------------------------------------------------*/

impl Default for WindowBackendSDL2 {

    fn default () -> WindowBackendSDL2 {
        WindowBackendSDL2::new ()
    }
}
<|endoftext|>