<commit_before>//! # quicksort
//!
//! Quicksort is an efficient in-place sorting algorithm created by Tony Hoare.
//!

use std::cmp::Ordering;

/// In-place sorting of a slice of T.
///
/// ```rust
/// # use ironsort::quicksort;
/// let presorted: Vec<u64> = vec![1, 1, 2, 3, 3, 4, 5, 5, 6, 9];
/// let mut vector: Vec<u64> = vec![3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
/// quicksort(&mut vector);
///
/// assert_eq!(vector, presorted.as_slice());
/// ```
#[inline]
pub fn quicksort<T: Ord>(vec: &mut [T]) {
    quicksort_by(vec, &|x, y| x.cmp(y))
}

pub fn quicksort_by<T: PartialOrd, F>(vec: &mut [T], cmp: &F)
    where F: Fn(&T, &T) -> Ordering {

    let len: usize = vec.len();
    if len <= 1 {
        return;
    }

    vec.swap(0, len / 2);
    let pivot: usize = 0;

    let mut left: usize = 0;
    let mut right: usize = vec.len() - 1;

    while left < right {
        while left < len && cmp(&vec[left], &vec[pivot]) != Ordering::Greater {
            left += 1
        }
        while cmp(&vec[right], &vec[pivot]) == Ordering::Greater {
            right -= 1
        }

        if left < right {
            vec.swap(left, right);
        }
    }

    vec.swap(pivot, right);
    quicksort_by(&mut vec[0..right], cmp);
    quicksort_by(&mut vec[right+1..], cmp);
}

#[cfg(test)]
extern crate rand;

#[cfg(test)]
mod tests {
    use rand::{self, Rng};
    use super::*;

    #[test]
    fn test_vec_of_u64() {
        let presorted: Vec<u64> = vec![1, 1, 2, 3, 3, 4, 5, 5, 6, 9];
        let mut vector: Vec<u64> = vec![3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
        quicksort(&mut vector);

        assert_eq!(vector, presorted.as_slice());
    }

    #[test]
    fn test_vec_of_u8() {
        let presorted = "        Tabcdeeefghhijklmnoooopqrrstuuvwxyz".to_string().into_bytes();
        let mut vector = "The quick brown fox jumps over the lazy dog".to_string().into_bytes();
        quicksort(&mut vector);

        assert_eq!(presorted, vector);
    }

    #[test]
    fn test_array_of_u8() {
        let presorted: [u8; 10] = [1, 2, 3, 4, 5, 5, 5, 7, 9, 10];
        let mut vector: [u8; 10] = [7, 5, 3, 2, 5, 1, 4, 5, 9, 10];
        quicksort(&mut vector);

        assert_eq!(presorted, vector);
    }

    #[test]
    fn test_random() {
        let mut rng = rand::thread_rng();

        for _ in 0u64 .. 10_000u64 {
            let len: usize = rng.gen();
            let mut vector = rng.gen_iter()
                                .take((len % 64) + 1)
                                .collect::<Vec<usize>>();
            quicksort(&mut vector);

            for i in 0 .. vector.len() - 1 {
                assert!(vector[i] <= vector[i + 1])
            }
        }
    }
}
<commit_msg>Add doccomment for quicksort_by<commit_after>//! # quicksort
//!
//! Quicksort is an efficient in-place sorting algorithm created by Tony Hoare.
//!

use std::cmp::Ordering;

/// In-place sorting of a slice of T.
///
/// ```rust
/// # use ironsort::quicksort;
/// let presorted: Vec<u64> = vec![1, 1, 2, 3, 3, 4, 5, 5, 6, 9];
/// let mut vector: Vec<u64> = vec![3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
/// quicksort(&mut vector);
///
/// assert_eq!(vector, presorted.as_slice());
/// ```
#[inline]
pub fn quicksort<T: Ord>(vec: &mut [T]) {
    quicksort_by(vec, &|x, y| x.cmp(y))
}

/// In-place sorting of a slice of T using a custom comparison function.
///
/// ```rust
/// # use ironsort::quicksort_by;
/// # use std::cmp::Ordering;
///
/// let presorted: Vec<u64> = vec![9, 6, 5, 5, 4, 3, 3, 2, 1, 1];
/// let mut vector: Vec<u64> = vec![3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
///
/// quicksort_by(&mut vector, &|x, y| x.cmp(y).reverse());
///
/// assert_eq!(vector, presorted.as_slice());
/// ```
pub fn quicksort_by<T: PartialOrd, F>(vec: &mut [T], cmp: &F)
    where F: Fn(&T, &T) -> Ordering {

    let len: usize = vec.len();
    if len <= 1 {
        return;
    }

    vec.swap(0, len / 2);
    let pivot: usize = 0;

    let mut left: usize = 0;
    let mut right: usize = vec.len() - 1;

    while left < right {
        while left < len && cmp(&vec[left], &vec[pivot]) != Ordering::Greater {
            left += 1
        }
        while cmp(&vec[right], &vec[pivot]) == Ordering::Greater {
            right -= 1
        }

        if left < right {
            vec.swap(left, right);
        }
    }

    vec.swap(pivot, right);
    quicksort_by(&mut vec[0..right], cmp);
    quicksort_by(&mut vec[right+1..], cmp);
}

#[cfg(test)]
extern crate rand;

#[cfg(test)]
mod tests {
    use rand::{self, Rng};
    use super::*;

    #[test]
    fn test_vec_of_u64() {
        let presorted: Vec<u64> = vec![1, 1, 2, 3, 3, 4, 5, 5, 6, 9];
        let mut vector: Vec<u64> = vec![3, 1, 4, 1, 5, 9, 2, 6, 5, 3];
        quicksort(&mut vector);

        assert_eq!(vector, presorted.as_slice());
    }

    #[test]
    fn test_vec_of_u8() {
        let presorted = "        Tabcdeeefghhijklmnoooopqrrstuuvwxyz".to_string().into_bytes();
        let mut vector = "The quick brown fox jumps over the lazy dog".to_string().into_bytes();
        quicksort(&mut vector);

        assert_eq!(presorted, vector);
    }

    #[test]
    fn test_array_of_u8() {
        let presorted: [u8; 10] = [1, 2, 3, 4, 5, 5, 5, 7, 9, 10];
        let mut vector: [u8; 10] = [7, 5, 3, 2, 5, 1, 4, 5, 9, 10];
        quicksort(&mut vector);

        assert_eq!(presorted, vector);
    }

    #[test]
    fn test_random() {
        let mut rng = rand::thread_rng();

        for _ in 0u64 .. 10_000u64 {
            let len: usize = rng.gen();
            let mut vector = rng.gen_iter()
                                .take((len % 64) + 1)
                                .collect::<Vec<usize>>();
            quicksort(&mut vector);

            for i in 0 .. vector.len() - 1 {
                assert!(vector[i] <= vector[i + 1])
            }
        }
    }
}
<|endoftext|>


<commit_before>#![feature(plugin_registrar, quote, rustc_private, core)]
#![deny(missing_docs, warnings)]

//! Stainless is a lightweight, flexible, unopinionated testing framework.
//!
//! ## Example
//!
//! ```ignore
//! describe! stainless {
//!     before_each {
//!         // Start up a test.
//!         let mut stainless = true;
//!     }
//!
//!     it "makes organizing tests easy" {
//!         // Do the test.
//!         assert!(stainless);
//!     }
//!
//!     after_each {
//!         // End the test.
//!         stainless = false;
//!     }
//!
//!     describe! nesting {
//!         it "makes it simple to categorize tests" {
//!             // It even generates submodules!
//!             assert_eq!(2u, 2u);
//!         }
//!     }
//! }
//! ```
//!
//! Expands to (roughly):
//!
//! ```rust
//! mod stainless {
//!     #[test]
//!     fn makes_organizing_tests_easy() {
//!         let mut stainless = true;
//!         assert!(stainless);
//!         stainless = false;
//!     }
//!
//!     mod nesting {
//!         #[test]
//!         fn makes_it_simple_to_categorize_tests() {
//!             assert_eq!(2u, 2u);
//!         }
//!     }
//! }
//! ```
//!
//! Stainless exports the `describe!` syntax extension, which allows
//! you to quickly generate complex testing hierarchies and reduce
//! boilerplate through `before_each` and `after_each`.
//!
//! Stainless currently supports 4 types of subblocks:
//!  - `before_each` and `after_each`,
//!  - `it` and `failing`
//!  - `bench`
//!  - nested `describe!`
//!
//! `before_each` and `after_each` allow you to group common initialization
//! and teardown for a group of tests into a single block, shortening your
//! tests.
//!
//! `it` generates tests which use `before_each` and `after_each`. `failing`
//! does the same, except the generated tests are marked with `#[should_fail]`.
//!
//! `bench` allows you to generate benchmarks in the same fashion, though
//! `before_each` and `after_each` blocks do not affect `bench` blocks.
//!
//! Nested `describe!` blocks allow you to better organize your tests into
//! small units and gives you granular control over where `before_each` and
//! `after_each` apply.
//!
//! Together, these 3 types of subblocks give you more flexibility and control
//! than the built in testing infrastructure.
//!

extern crate syntax;
extern crate rustc;

use self::describe::describe;
use rustc::plugin;
use syntax::parse::token;

mod describe;
mod parse;
mod test;
mod bench;
mod generate;

#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut plugin::Registry) {
    reg.register_syntax_extension(
        token::intern("describe"),
        syntax::ext::base::IdentTT(Box::new(describe), None)
    );
}

<commit_msg>(fix) `rustc 1.0.0-nightly (2fc8b1e7c 2015-03-07) (built 2015-03-07)`.<commit_after>#![feature(plugin_registrar, quote, rustc_private, core)]
#![deny(missing_docs, warnings)]

//! Stainless is a lightweight, flexible, unopinionated testing framework.
//!
//! ## Example
//!
//! ```ignore
//! describe! stainless {
//!     before_each {
//!         // Start up a test.
//!         let mut stainless = true;
//!     }
//!
//!     it "makes organizing tests easy" {
//!         // Do the test.
//!         assert!(stainless);
//!     }
//!
//!     after_each {
//!         // End the test.
//!         stainless = false;
//!     }
//!
//!     describe! nesting {
//!         it "makes it simple to categorize tests" {
//!             // It even generates submodules!
//!             assert_eq!(2u, 2u);
//!         }
//!     }
//! }
//! ```
//!
//! Expands to (roughly):
//!
//! ```rust
//! mod stainless {
//!     #[test]
//!     fn makes_organizing_tests_easy() {
//!         let mut stainless = true;
//!         assert!(stainless);
//!         stainless = false;
//!     }
//!
//!     mod nesting {
//!         #[test]
//!         fn makes_it_simple_to_categorize_tests() {
//!             assert_eq!(2u, 2u);
//!         }
//!     }
//! }
//! ```
//!
//! Stainless exports the `describe!` syntax extension, which allows
//! you to quickly generate complex testing hierarchies and reduce
//! boilerplate through `before_each` and `after_each`.
//!
//! Stainless currently supports 4 types of subblocks:
//!  - `before_each` and `after_each`,
//!  - `it` and `failing`
//!  - `bench`
//!  - nested `describe!`
//!
//! `before_each` and `after_each` allow you to group common initialization
//! and teardown for a group of tests into a single block, shortening your
//! tests.
//!
//! `it` generates tests which use `before_each` and `after_each`. `failing`
//! does the same, except the generated tests are marked with `#[should_fail]`.
//!
//! `bench` allows you to generate benchmarks in the same fashion, though
//! `before_each` and `after_each` blocks do not affect `bench` blocks.
//!
//! Nested `describe!` blocks allow you to better organize your tests into
//! small units and gives you granular control over where `before_each` and
//! `after_each` apply.
//!
//! Together, these 3 types of subblocks give you more flexibility and control
//! than the built in testing infrastructure.
//!

extern crate syntax;
extern crate rustc;

use self::describe::describe;
use rustc::plugin;
use syntax::parse::token;

mod describe;
mod parse;
mod test;
mod bench;
mod generate;

#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut plugin::Registry) {
    reg.register_syntax_extension(
        token::intern("describe"),
        syntax::ext::base::IdentTT(Box::new(describe), None, false)
    );
}

<|endoftext|>


<commit_before>// Copyright (c) 2016 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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.

#![deny(missing_docs)]
#![deny(non_camel_case_types)]
#![deny(warnings)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]

//! A library providing Rust bindings for the XKCD web API.
//!
//! The library provides a `XkcdRequestSender` trait which can be implemented by
//! various request senders. These implementations may then be used to execute
//! requests to the API.
//!
//! If the `hyper` feature is enabled during compilation, then this library
//! provides an implementation of the `XkcdRequestSender` trait for the
//! `hyper::Client` of the [`hyper`](https://github.com/hyperium/hyper) library.
//!
//! Response bodies are deserialized from JSON into structs via the
//! [`serde_json`](https://github.com/serde-rs/json) library.

#[cfg(feature = "hyper")]
extern crate hyper;

#[macro_use]
extern crate log;
extern crate rand;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate url;
extern crate url_serde;

mod error;

pub use self::error::{Error, HttpRequestError, HttpRequestResult, Result};
pub use self::model::XkcdResponse;

pub mod comics;
pub mod model;
pub mod random;

use std::fmt::Debug;

use serde::Deserialize;

fn parse_xkcd_response<T>(response: &str) -> Result<T>
    where T: Debug + Deserialize,
{
    let parsed_response = serde_json::from_str(response)?;
    trace!("Parsed response: {:?}", parsed_response);
    Ok(parsed_response)
}

/// Functionality for sending requests to the XKCD API via HTTPS.
///
/// Should be implemented for clients to send requests to the XKCD API.
pub trait XkcdRequestSender {
    /// Performs an API call to the XKCD web API.
    fn send(&self, method: &str) -> HttpRequestResult<String>;
}

#[cfg(feature = "hyper")]
mod hyper_support {
    use std::io::Read;

    use hyper;
    use hyper::status::StatusCode;
    use url::Url;

    use error::{HttpRequestError, HttpRequestResult};

    use super::XkcdRequestSender;

    impl XkcdRequestSender for hyper::Client {
        fn send(&self, method: &str) -> HttpRequestResult<String> {
            let url_string = format!("https://xkcd.com/{}", method);
            let url = url_string.parse::<Url>().expect("Unable to parse URL");

            trace!("Sending query to url: {}", url);
            let mut response = self.get(url.clone()).send()?;

            trace!("Status code: {}", response.status);
            // Ensure we got a valid status code.
            match response.status {
                StatusCode::NotFound => return Err(HttpRequestError::not_found(url)),
                _ => {}
            }

            let mut result = String::new();
            response.read_to_string(&mut result)?;
            trace!("Query result: {}", result);

            Ok(result)
        }
    }

    impl From<hyper::Error> for HttpRequestError {
        fn from(error: hyper::Error) -> HttpRequestError {
            match error {
                hyper::Error::Io(e) => HttpRequestError::Io(e),
                e => HttpRequestError::Other(Box::new(e)),
            }
        }
    }
}

#[cfg(feature = "hyper")]
pub use hyper_support::*;

#[cfg(test)]
mod test_helpers {
    use super::{XkcdRequestSender, HttpRequestError};

    pub struct MockXkcdRequestSender {
        response: String,
    }

    impl MockXkcdRequestSender {
        pub fn respond_with<S: Into<String>>(response: S) -> Self {
            MockXkcdRequestSender { response: response.into() }
        }
    }

    impl XkcdRequestSender for MockXkcdRequestSender {
        fn send(&self, _: &str) -> Result<String, HttpRequestError> {
            Ok(self.response.clone())
        }
    }
}

#[cfg(test)]
mod tests {
    use url::Url;

    use model::XkcdResponse;

    use super::parse_xkcd_response;

    #[test]
    fn test_parse_xkcd_response() {
        let result = r#"
            {
                "month": "6",
                "num": 1698,
                "link": "",
                "year": "2016",
                "news": "",
                "safe_title": "Theft Quadrants",
                "transcript": "",
                "alt": "TinyURL was the most popular link shortener for long enough that it made it into a lot of printed publications. I wonder what year the domain will finally lapse and get picked up by a porn site.",
                "img": "http:\/\/imgs.xkcd.com\/comics\/theft_quadrants.png",
                "title": "Theft Quadrants",
                "day": "24"
            }
        "#;
        let response = parse_xkcd_response::<XkcdResponse>(&result).unwrap();
        assert_eq!(response,
                   XkcdResponse {
                       month: 6,
                       num: 1698,
                       link: "".to_owned(),
                       year: 2016,
                       news: "".to_owned(),
                       safe_title: "Theft Quadrants".to_owned(),
                       transcript: "".to_owned(),
                       alt: "TinyURL was the most popular link shortener for long enough that it \
                             made it into a lot of printed publications. I wonder what year the \
                             domain will finally lapse and get picked up by a porn site."
                           .to_owned(),
                       img: "http://imgs.xkcd.com/comics/theft_quadrants.png"
                           .to_owned()
                           .parse::<Url>()
                           .unwrap(),
                       title: "Theft Quadrants".to_owned(),
                       day: 24,
                   });
    }
}
<commit_msg>chore: replace match with if let<commit_after>// Copyright (c) 2016 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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.

#![deny(missing_docs)]
#![deny(non_camel_case_types)]
#![deny(warnings)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]

//! A library providing Rust bindings for the XKCD web API.
//!
//! The library provides a `XkcdRequestSender` trait which can be implemented by
//! various request senders. These implementations may then be used to execute
//! requests to the API.
//!
//! If the `hyper` feature is enabled during compilation, then this library
//! provides an implementation of the `XkcdRequestSender` trait for the
//! `hyper::Client` of the [`hyper`](https://github.com/hyperium/hyper) library.
//!
//! Response bodies are deserialized from JSON into structs via the
//! [`serde_json`](https://github.com/serde-rs/json) library.

#[cfg(feature = "hyper")]
extern crate hyper;

#[macro_use]
extern crate log;
extern crate rand;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate url;
extern crate url_serde;

mod error;

pub use self::error::{Error, HttpRequestError, HttpRequestResult, Result};
pub use self::model::XkcdResponse;

pub mod comics;
pub mod model;
pub mod random;

use std::fmt::Debug;

use serde::Deserialize;

fn parse_xkcd_response<T>(response: &str) -> Result<T>
    where T: Debug + Deserialize,
{
    let parsed_response = serde_json::from_str(response)?;
    trace!("Parsed response: {:?}", parsed_response);
    Ok(parsed_response)
}

/// Functionality for sending requests to the XKCD API via HTTPS.
///
/// Should be implemented for clients to send requests to the XKCD API.
pub trait XkcdRequestSender {
    /// Performs an API call to the XKCD web API.
    fn send(&self, method: &str) -> HttpRequestResult<String>;
}

#[cfg(feature = "hyper")]
mod hyper_support {
    use std::io::Read;

    use hyper;
    use hyper::status::StatusCode;
    use url::Url;

    use error::{HttpRequestError, HttpRequestResult};

    use super::XkcdRequestSender;

    impl XkcdRequestSender for hyper::Client {
        fn send(&self, method: &str) -> HttpRequestResult<String> {
            let url_string = format!("https://xkcd.com/{}", method);
            let url = url_string.parse::<Url>().expect("Unable to parse URL");

            trace!("Sending query to url: {}", url);
            let mut response = self.get(url.clone()).send()?;

            trace!("Status code: {}", response.status);
            // Ensure we got a valid status code.
            if let StatusCode::NotFound = response.status {
                return Err(HttpRequestError::not_found(url));
            }

            let mut result = String::new();
            response.read_to_string(&mut result)?;
            trace!("Query result: {}", result);

            Ok(result)
        }
    }

    impl From<hyper::Error> for HttpRequestError {
        fn from(error: hyper::Error) -> HttpRequestError {
            match error {
                hyper::Error::Io(e) => HttpRequestError::Io(e),
                e => HttpRequestError::Other(Box::new(e)),
            }
        }
    }
}

#[cfg(feature = "hyper")]
pub use hyper_support::*;

#[cfg(test)]
mod test_helpers {
    use super::{XkcdRequestSender, HttpRequestError};

    pub struct MockXkcdRequestSender {
        response: String,
    }

    impl MockXkcdRequestSender {
        pub fn respond_with<S: Into<String>>(response: S) -> Self {
            MockXkcdRequestSender { response: response.into() }
        }
    }

    impl XkcdRequestSender for MockXkcdRequestSender {
        fn send(&self, _: &str) -> Result<String, HttpRequestError> {
            Ok(self.response.clone())
        }
    }
}

#[cfg(test)]
mod tests {
    use url::Url;

    use model::XkcdResponse;

    use super::parse_xkcd_response;

    #[test]
    fn test_parse_xkcd_response() {
        let result = r#"
            {
                "month": "6",
                "num": 1698,
                "link": "",
                "year": "2016",
                "news": "",
                "safe_title": "Theft Quadrants",
                "transcript": "",
                "alt": "TinyURL was the most popular link shortener for long enough that it made it into a lot of printed publications. I wonder what year the domain will finally lapse and get picked up by a porn site.",
                "img": "http:\/\/imgs.xkcd.com\/comics\/theft_quadrants.png",
                "title": "Theft Quadrants",
                "day": "24"
            }
        "#;
        let response = parse_xkcd_response::<XkcdResponse>(&result).unwrap();
        assert_eq!(response,
                   XkcdResponse {
                       month: 6,
                       num: 1698,
                       link: "".to_owned(),
                       year: 2016,
                       news: "".to_owned(),
                       safe_title: "Theft Quadrants".to_owned(),
                       transcript: "".to_owned(),
                       alt: "TinyURL was the most popular link shortener for long enough that it \
                             made it into a lot of printed publications. I wonder what year the \
                             domain will finally lapse and get picked up by a porn site."
                           .to_owned(),
                       img: "http://imgs.xkcd.com/comics/theft_quadrants.png"
                           .to_owned()
                           .parse::<Url>()
                           .unwrap(),
                       title: "Theft Quadrants".to_owned(),
                       day: 24,
                   });
    }
}
<|endoftext|>


<commit_before>//! A signal processing framework for making music with rust.
//!
//! `oxcable` is designed with simple but powerful abstractions, with minimal
//! performance loss, while functioning in real-time.
//!
//! `oxcable` seeks to provide the basic building blocks necessary to build
//! digital instruments and effects, and provide the tools to chain these
//! devices together quickly and easily.
//!
//! # Getting started
//!
//! Let's start with a simple example. This script will generate a sine wave at
//! 440Hz, and play it on your computer's speakers or headphones in an infinite
//! loop:
//!
//! ```
//! extern crate oxcable;
//! use oxcable::chain::{DeviceChain, Tick};
//! use oxcable::io::audio::AudioEngine;
//! use oxcable::oscillator::{Oscillator, Sine};
//!
//! fn main() {
//!     let engine = AudioEngine::with_buffer_size(256).unwrap();
//!     let mut chain = DeviceChain::from(
//!         Oscillator::new(Sine).freq(440.0)
//!     ).into(
//!         engine.default_output(1).unwrap()
//!     );
//! # }
//! # // wrap tick_forever() in a function that gets compiled by not run by
//! # //doctest
//! # fn dummy(chain: &mut DeviceChain) {
//!     chain.tick_forever();
//! }
//! ```
//!
//! # Devices
//!
//! Defining an audio device can be done by implenting the
//! [`AudioDevice` trait](types/trait.AudioDevice.html).
//!
//! Let's define a very simple audio device: one that simply passes its input
//! straight to the output. This can be done in just a few lines:
//!
//! ```
//! use oxcable::types::{AudioDevice, Sample, Time};
//!
//! struct IdentityFilter;
//! impl AudioDevice for IdentityFilter {
//!     fn num_inputs(&self) -> usize { 1 }
//!     fn num_outputs(&self) -> usize { 1 }
//!     fn tick(&mut self, _: Time, inputs: &[Sample], outputs: &mut[Sample]) {
//!         outputs[0] = inputs[0];
//!     }
//! }
//! ```
//!
//! Once we've defined a device, it is simple to use the device in isolation.
//! Say I want to test my filter. I can manually call tick a few times to
//! generate outputs:
//!
//! ```
//! # use oxcable::types::{AudioDevice, Sample, Time};
//! # struct IdentityFilter;
//! # impl AudioDevice for IdentityFilter {
//! #     fn num_inputs(&self) -> usize { 1 }
//! #     fn num_outputs(&self) -> usize { 1 }
//! #     fn tick(&mut self, _: Time, inputs: &[Sample], outputs: &mut[Sample]) {
//! #         outputs[0] = inputs[0];
//! #     }
//! # }
//! #
//! let mut input = [0.0];
//! let mut output = [0.0];
//! let mut filter = IdentityFilter;
//!
//! for i in 0..8 {
//!     input[0] = i as f32;
//!     filter.tick(i, &input, &mut output);
//!     assert_eq!(i as f32, output[0]);
//! }
//! ```
//!
//! By adhering to the `AudioDevice` trait, however, this new device will drop
//! straight into generic containers like [`DeviceChain`](chain/index.html) or
//! [`DeviceGraph`](graph/index.html), and into wrappers such as the `Buffered`
//! wrapper:
//!
//! ```
//! # use oxcable::types::{AudioDevice, Sample, Time};
//! # struct IdentityFilter;
//! # impl AudioDevice for IdentityFilter {
//! #     fn num_inputs(&self) -> usize { 1 }
//! #     fn num_outputs(&self) -> usize { 1 }
//! #     fn tick(&mut self, _: Time, inputs: &[Sample], outputs: &mut[Sample]) {
//! #         outputs[0] = inputs[0];
//! #     }
//! # }
//! #
//! use oxcable::wrappers::Buffered;
//! let mut filter = Buffered::from(IdentityFilter);
//!
//! for i in 0..8 {
//!     filter.inputs[0] = i as f32;
//!     filter.tick(i);
//!     assert_eq!(i as f32, filter.outputs[0]);
//! }
//! ```
//!
//! `oxcable` defines many simple devices itself. A list of these devices may be
//! found under [the `AudioDevice`
//! documentation](types/trait.AudioDevice.html#implementors).
//!
//! # Thread Safety
//!
//! Unfortunately, `oxcable` is not able to provide `AudioDevice` containers
//! that are `Send`. This is due to a limitation in the `rust-portaudio` crate,
//! in which audio streams are not `Send`. This prohibits binding `AudioDevice`
//! trait objects with `Send`.
//!
//! Therefore, when using generic containers, the signal chain must be
//! initialized in the thread it will eventually process audio.

extern crate byteorder;
extern crate num;
extern crate portaudio;
extern crate portmidi;
extern crate rand;

pub mod adsr;
pub mod chain;
pub mod delay;
pub mod dynamics;
pub mod filters;
pub mod graph;
pub mod io;
pub mod mixers;
pub mod oscillator;
pub mod reverb;
pub mod tick;
pub mod tremolo;
pub mod types;
pub mod utils;
pub mod voice_array;
pub mod wrappers;
<commit_msg>Add message passing to root documentation<commit_after>//! A signal processing framework for making music with rust.
//!
//! `oxcable` is designed with simple but powerful abstractions, with minimal
//! performance loss, while functioning in real-time.
//!
//! `oxcable` seeks to provide the basic building blocks necessary to build
//! digital instruments and effects, and provide the tools to chain these
//! devices together quickly and easily.
//!
//! # Getting started
//!
//! Let's start with a simple example. This script will generate a sine wave at
//! 440Hz, and play it on your computer's speakers or headphones in an infinite
//! loop:
//!
//! ```
//! extern crate oxcable;
//! use oxcable::chain::{DeviceChain, Tick};
//! use oxcable::io::audio::AudioEngine;
//! use oxcable::oscillator::{Oscillator, Sine};
//!
//! fn main() {
//!     let engine = AudioEngine::with_buffer_size(256).unwrap();
//!     let mut chain = DeviceChain::from(
//!         Oscillator::new(Sine).freq(440.0)
//!     ).into(
//!         engine.default_output(1).unwrap()
//!     );
//! # }
//! # // wrap tick_forever() in a function that gets compiled by not run by
//! # //doctest
//! # fn dummy(chain: &mut DeviceChain) {
//!     chain.tick_forever();
//! }
//! ```
//!
//! # Devices
//!
//! Defining an audio device can be done by implenting the
//! [`AudioDevice` trait](types/trait.AudioDevice.html).
//!
//! Let's define a very simple audio device: one that simply passes its input
//! straight to the output. This can be done in just a few lines:
//!
//! ```
//! use oxcable::types::{AudioDevice, Sample, Time};
//!
//! struct IdentityFilter;
//! impl AudioDevice for IdentityFilter {
//!     fn num_inputs(&self) -> usize { 1 }
//!     fn num_outputs(&self) -> usize { 1 }
//!     fn tick(&mut self, _: Time, inputs: &[Sample], outputs: &mut[Sample]) {
//!         outputs[0] = inputs[0];
//!     }
//! }
//! ```
//!
//! Once we've defined a device, it is simple to use the device in isolation.
//! Say I want to test my filter. I can manually call tick a few times to
//! generate outputs:
//!
//! ```
//! # use oxcable::types::{AudioDevice, Sample, Time};
//! # struct IdentityFilter;
//! # impl AudioDevice for IdentityFilter {
//! #     fn num_inputs(&self) -> usize { 1 }
//! #     fn num_outputs(&self) -> usize { 1 }
//! #     fn tick(&mut self, _: Time, inputs: &[Sample], outputs: &mut[Sample]) {
//! #         outputs[0] = inputs[0];
//! #     }
//! # }
//! #
//! let mut input = [0.0];
//! let mut output = [0.0];
//! let mut filter = IdentityFilter;
//!
//! for i in 0..8 {
//!     input[0] = i as f32;
//!     filter.tick(i, &input, &mut output);
//!     assert_eq!(i as f32, output[0]);
//! }
//! ```
//!
//! By adhering to the `AudioDevice` trait, however, this new device will drop
//! straight into generic containers like [`DeviceChain`](chain/index.html) or
//! [`DeviceGraph`](graph/index.html), and into wrappers such as the `Buffered`
//! wrapper:
//!
//! ```
//! # use oxcable::types::{AudioDevice, Sample, Time};
//! # struct IdentityFilter;
//! # impl AudioDevice for IdentityFilter {
//! #     fn num_inputs(&self) -> usize { 1 }
//! #     fn num_outputs(&self) -> usize { 1 }
//! #     fn tick(&mut self, _: Time, inputs: &[Sample], outputs: &mut[Sample]) {
//! #         outputs[0] = inputs[0];
//! #     }
//! # }
//! #
//! use oxcable::wrappers::Buffered;
//! let mut filter = Buffered::from(IdentityFilter);
//!
//! for i in 0..8 {
//!     filter.inputs[0] = i as f32;
//!     filter.tick(i);
//!     assert_eq!(i as f32, filter.outputs[0]);
//! }
//! ```
//!
//! `oxcable` defines many simple devices itself. A list of these devices may be
//! found under the [`AudioDevice`
//! documentation](types/trait.AudioDevice.html#implementors).
//!
//! # Message Passing
//!
//! To allow modifying audio device parameters while they are inside containers
//! or processesing in seperate threads, all setter behavior is instead
//! encapsulated inside a message passing system. Each device has its own
//! message `enum` type that describes the different actions it can handle.  The
//! device then handles those messages by implementing the
//! [`MessageReceiver` trait](types/trait.MessageReceiver.html).
//!
//! Using this trait, setters can be used by calling the `handle_message`
//! function and passing the specific message directly to the device.
//!
//! However, when devices are hidden behind trait objects or used to process in
//! a seperate thread, there is no way to get to the device to hand it the
//! message directly. In this case the [`Messaged`
//! wrapper](wrappers/struct.Messaged.html) provides an abstraction using
//! [Rust channels](https://doc.rust-lang.org/std/sync/mpsc/fn.channel.html).
//!
//! # Thread Safety
//!
//! Unfortunately, `oxcable` is not able to provide `AudioDevice` containers
//! that are `Send`. This is due to a limitation in the `rust-portaudio` crate,
//! in which audio streams are not `Send`. This prohibits binding `AudioDevice`
//! trait objects with `Send`.
//!
//! Therefore, when using generic containers, the signal chain must be
//! initialized in the thread it will eventually process audio.

extern crate byteorder;
extern crate num;
extern crate portaudio;
extern crate portmidi;
extern crate rand;

pub mod adsr;
pub mod chain;
pub mod delay;
pub mod dynamics;
pub mod filters;
pub mod graph;
pub mod io;
pub mod mixers;
pub mod oscillator;
pub mod reverb;
pub mod tick;
pub mod tremolo;
pub mod types;
pub mod utils;
pub mod voice_array;
pub mod wrappers;
<|endoftext|>


<commit_before>extern crate libc;

use std::os::raw;
use std::ffi::CString;
use std::mem::transmute;

#[link(name = "rust")]
extern {
  fn klee_make_symbolic(data: *const raw::c_void, length: libc::size_t, name: *const raw::c_char);
}

pub fn any(data: *const raw::c_void, length: usize, name: &str) {
  let name_cstr = CString::new(name).unwrap();
  unsafe {
    klee_make_symbolic(data, length as libc::size_t, name_cstr.as_ptr());
  }
}

pub fn i32(data: *const i32, name: &str) {
  unsafe { any(transmute(data), 4, name); }
}

pub fn u32(data: *const u32, name: &str) {
  unsafe { any(transmute(data), 4, name); }
}

pub fn bytes(data: *const [u8], name: &str) {
  unsafe { any(transmute(data), &data.len(), name); }
}
<commit_msg>Update lib.rs<commit_after>extern crate libc;

use std::os::raw;
use std::ffi::CString;
use std::mem::transmute;

#[link(name = "rust")]
extern {
  fn klee_make_symbolic(data: *const raw::c_void, length: libc::size_t, name: *const raw::c_char);
}

pub fn any(data: *const raw::c_void, length: usize, name: &str) {
  let name_cstr = CString::new(name).unwrap();
  unsafe {
    klee_make_symbolic(data, length as libc::size_t, name_cstr.as_ptr());
  }
}

pub fn i32(data: *const i32, name: &str) {
  unsafe { any(transmute(data), 4, name); }
}

pub fn u32(data: *const u32, name: &str) {
  unsafe { any(transmute(data), 4, name); }
}

pub fn bytes(data: &[u8], name: &str) {
  unsafe { any(transmute(data.as_ptr()), data.len(), name); }
}
<|endoftext|>


<commit_before>#![license = "MIT"]
#![deny(missing_docs)]
#![feature(unsafe_destructor)]

//! A library for setting current values for stack scope,
//! such as application structure.

pub use current::{ Current, CurrentGuard };

use std::cell::RefCell;

mod current;

/// Specifies whether to use a shared reference,
/// or the current object of that type.
pub enum Usage<'a, T: 'a> {
    /// Use a shared reference.
    Use(&'a RefCell<T>),
    /// Use the current object.
    UseCurrent,
}

impl<'a, T: 'a> Usage<'a, T> {
    /// Calls closure with a shared reference to used object.
    pub fn with<U>(&self, f: |&RefCell<T>| -> U) -> Option<U> {
        match *self {
            Use(val) => Some(f(val)),
            UseCurrent => Current::with_current(f),
        }
    }

    /// Calls closure with a shared reference to used object.
    /// Gives a nicer error message if current object is not set.
    pub fn with_unwrap<U>(&self, f: |&RefCell<T>| -> U) -> U {
        match *self {
            Use(val) => f(val),
            UseCurrent => Current::with_current_unwrap(f),
        }
    }

    /// Unwraps to the scope of usage.
    /// Should only be called when the usage object or returned reference
    /// does not outlives the guard of the current object.
    #[inline(always)]
    pub unsafe fn unsafe_unwrap(&self) -> &RefCell<T> {
        match *self {
            Use(val) => val,
            UseCurrent => {
                Current::with_current_unwrap(|current: &RefCell<T>| {
                    use std::mem::transmute;
                    transmute(current)
                })
            }
        }
    }
}

impl<'a, T: Get<U>, U> Get<U> for Usage<'a, T> {
    #[inline(always)]
    fn get(&self) -> U {
        self.with_unwrap(|val: &RefCell<T>| {
            val.borrow().deref().get()
        })
    }
}

impl<'a, F, T: Modifier<F>> Modifier<Usage<'a, F>> for T {
    #[inline(always)]
    fn modify(self, obj: &mut Usage<'a, F>) {
        unsafe {
            let val: &RefCell<F> = obj.unsafe_unwrap();
            self.modify(val.borrow_mut().deref_mut())
        }
    }
}

/// Allows use of the implemented type as an argument to Set::set.
///
/// This allows types to be used for ad-hoc overloading of Set::set
/// to perform complex updates to the parameter of Modifier.
pub trait Modifier<F> {
    /// Modify `F` with self.
    fn modify(self, &mut F);
}

/// A blanket trait providing the set and set_mut methods for all types.
pub trait Set<M: Modifier<Self>> {
    /// Modify self using the provided modifier.
    #[inline(always)]
    fn set(mut self, modifier: M) -> Self {
        modifier.modify(&mut self);
        self
    }

    /// Modify self through a mutable reference with the provided modifier.
    #[inline(always)]
    fn set_mut(&mut self, modifier: M) -> &mut Self {
        modifier.modify(self);
        self
    }
}

impl<T, U: Modifier<T>> Set<U> for T {}

/// Implemented by types that can be constructed from another value.
pub trait Get<T> {
    /// Returns new value.
    fn get(&self) -> T;
}

/// Transmutes the current value to a lifetime scope.
/// The scope must not outlive the guard.
/// This is used to work around issues with closure that require move by value.
pub unsafe fn unsafe_current_unwrap<T>(_scope: &()) -> &T {
    Current::with_current_unwrap(|current: &T| {
        use std::mem::transmute;
        transmute(current)
    })
}

/// Sets value on current type, assuming using a `RefCell` to make it safe.
/// Panics if there is no current object of type `T`.
pub fn set<T, U: Modifier<T>>(val: U) {
    let scope = &();
    let current: &RefCell<T> = unsafe { unsafe_current_unwrap(scope) };
    val.modify(&mut*current.borrow_mut());
}

/// Gets value from current object of type `T`.
/// The returned type must implement the `GetFrom` trait.
pub fn get<T: Get<U>, U>() -> U {
    Current::with_current_unwrap(|current: &RefCell<T>| {
        match current.try_borrow() {
            Some(val) => val.get(),
            None => {
                use std::intrinsics::get_tydesc;
                let name = unsafe { (*get_tydesc::<T>()).name };
                panic!("The current `{}` is already in use", name);
            }
        }
    })
}
<commit_msg>Added `Get` and `Modifier` for `RefCell`<commit_after>#![license = "MIT"]
#![deny(missing_docs)]
#![feature(unsafe_destructor)]

//! A library for setting current values for stack scope,
//! such as application structure.

pub use current::{ Current, CurrentGuard };

use std::cell::RefCell;

mod current;

/// Specifies whether to use a shared reference,
/// or the current object of that type.
pub enum Usage<'a, T: 'a> {
    /// Use a shared reference.
    Use(&'a RefCell<T>),
    /// Use the current object.
    UseCurrent,
}

impl<'a, T: 'a> Usage<'a, T> {
    /// Calls closure with a shared reference to used object.
    pub fn with<U>(&self, f: |&RefCell<T>| -> U) -> Option<U> {
        match *self {
            Use(val) => Some(f(val)),
            UseCurrent => Current::with_current(f),
        }
    }

    /// Calls closure with a shared reference to used object.
    /// Gives a nicer error message if current object is not set.
    pub fn with_unwrap<U>(&self, f: |&RefCell<T>| -> U) -> U {
        match *self {
            Use(val) => f(val),
            UseCurrent => Current::with_current_unwrap(f),
        }
    }

    /// Unwraps to the scope of usage.
    /// Should only be called when the usage object or returned reference
    /// does not outlives the guard of the current object.
    #[inline(always)]
    pub unsafe fn unsafe_unwrap(&self) -> &RefCell<T> {
        match *self {
            Use(val) => val,
            UseCurrent => {
                Current::with_current_unwrap(|current: &RefCell<T>| {
                    use std::mem::transmute;
                    transmute(current)
                })
            }
        }
    }
}

impl<'a, T: Get<U>, U> Get<U> for Usage<'a, T> {
    #[inline(always)]
    fn get(&self) -> U {
        self.with_unwrap(|val: &RefCell<T>| {
            val.borrow().deref().get()
        })
    }
}

impl<'a, F, T: Modifier<F>> Modifier<Usage<'a, F>> for T {
    #[inline(always)]
    fn modify(self, obj: &mut Usage<'a, F>) {
        unsafe {
            let val: &RefCell<F> = obj.unsafe_unwrap();
            self.modify(val.borrow_mut().deref_mut())
        }
    }
}

impl<T: Get<U>, U> Get<U> for RefCell<T> {
    #[inline(always)]
    fn get(&self) -> U {
        self.borrow().deref().get()
    }
}

impl<F, T: Modifier<F>> Modifier<RefCell<F>> for T {
    #[inline(always)]
    fn modify(self, obj: &mut RefCell<F>) {
        self.modify(obj.borrow_mut().deref_mut())
    }
}

/// Allows use of the implemented type as an argument to Set::set.
///
/// This allows types to be used for ad-hoc overloading of Set::set
/// to perform complex updates to the parameter of Modifier.
pub trait Modifier<F> {
    /// Modify `F` with self.
    fn modify(self, &mut F);
}

/// A blanket trait providing the set and set_mut methods for all types.
pub trait Set<M: Modifier<Self>> {
    /// Modify self using the provided modifier.
    #[inline(always)]
    fn set(mut self, modifier: M) -> Self {
        modifier.modify(&mut self);
        self
    }

    /// Modify self through a mutable reference with the provided modifier.
    #[inline(always)]
    fn set_mut(&mut self, modifier: M) -> &mut Self {
        modifier.modify(self);
        self
    }
}

impl<T, U: Modifier<T>> Set<U> for T {}

/// Implemented by types that can be constructed from another value.
pub trait Get<T> {
    /// Returns new value.
    fn get(&self) -> T;
}

/// Transmutes the current value to a lifetime scope.
/// The scope must not outlive the guard.
/// This is used to work around issues with closure that require move by value.
pub unsafe fn unsafe_current_unwrap<T>(_scope: &()) -> &T {
    Current::with_current_unwrap(|current: &T| {
        use std::mem::transmute;
        transmute(current)
    })
}

/// Sets value on current type, assuming using a `RefCell` to make it safe.
/// Panics if there is no current object of type `T`.
pub fn set<T, U: Modifier<T>>(val: U) {
    let scope = &();
    let current: &RefCell<T> = unsafe { unsafe_current_unwrap(scope) };
    val.modify(&mut*current.borrow_mut());
}

/// Gets value from current object of type `T`.
/// The returned type must implement the `GetFrom` trait.
pub fn get<T: Get<U>, U>() -> U {
    Current::with_current_unwrap(|current: &RefCell<T>| {
        match current.try_borrow() {
            Some(val) => val.get(),
            None => {
                use std::intrinsics::get_tydesc;
                let name = unsafe { (*get_tydesc::<T>()).name };
                panic!("The current `{}` is already in use", name);
            }
        }
    })
}
<|endoftext|>


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

// TODO: should be able to remove these once the API stabilizes
#![feature(collections)]   // to_lowercase()
#![feature(core)]          // std::error::Error, num::from_str_radix

pub mod atom;
pub mod lexer;
pub mod sequence;
<commit_msg>Update to Rust nightly 2015-03-31<commit_after>/*
 * Copyright 2015 Nathan Fiedler
 *
 * 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.
 */

// TODO: should be able to remove these once the API stabilizes
#![allow(deprecated)]      // num::from_str_radix
#![feature(collections)]   // to_lowercase()
#![feature(core)]          // std::error::Error, num::from_str_radix

pub mod atom;
pub mod lexer;
pub mod sequence;
<|endoftext|>


<commit_before>
extern crate hyper;
extern crate ws;

mod message;
mod user;
mod client;
mod kraken;
mod irc;
mod channel;

macro_rules! get_arg {
	($e:expr) => (env::args().nth($e).unwrap_or(String::from("")));
}

#[cfg(test)]
mod tests {

	use std::env;
	use client::TwitchClient;
	use client::Event;

	#[test]
	fn it_works() {

		let client: TwitchClient;
		let mut user = String::from("");
		let mut pass = String::from("");
		let mut channel = String::from("");
		let mut logging = false;

		for (index, arg) in env::args().enumerate() {
			if index == 0 { continue; }

			match arg.as_ref() {
				"-u" => user = get_arg!(index + 1),
				"-p" => pass = get_arg!(index + 1),
				"-c" => channel = get_arg!(index + 1),
				"-l" => logging = true,
				_ => panic!("Unexpected argument passed: {}", arg),
			}
		}

		client = TwitchClient::from(user, pass, channel, logging);

		client.connect();

		loop {
			match client.recv_event() {
				Ok(Event::MessageReceived(m)) => {

				}
				Err(err) => println!("Error {:?}", err),
			}
		}
	}
}
<commit_msg>Changed crates to proper depends and added rfc module<commit_after>
extern crate ws;

mod message;
mod user;
mod twitch;
mod kraken;
mod irc;
mod channel;
mod rfc;

macro_rules! get_arg {
	($e:expr) => (env::args().nth($e).unwrap_or(String::from("")));
}

#[cfg(test)]
mod tests {

	use std::env;
	use client::TwitchClient;
	use client::Event;

	#[test]
	fn it_works() {

		let client: TwitchClient;
		let mut user = String::from("");
		let mut pass = String::from("");
		let mut channel = String::from("");
		let mut logging = false;

		for (index, arg) in env::args().enumerate() {
			if index == 0 { continue; }

			match arg.as_ref() {
				"-u" => user = get_arg!(index + 1),
				"-p" => pass = get_arg!(index + 1),
				"-c" => channel = get_arg!(index + 1),
				"-l" => logging = true,
				_ => panic!("Unexpected argument passed: {}", arg),
			}
		}

		client = TwitchClient::from(user, pass, channel, logging);

		client.connect();

		loop {
			match client.recv_event() {
				Ok(Event::MessageReceived(m)) => {

				}
				Err(err) => println!("Error {:?}", err),
			}
		}
	}
}
<|endoftext|>


<commit_before>//! `rust-uritemplate` is a Rust implementation of
//! [RFC6570  - URI Template](http://tools.ietf.org/html/rfc6570) that can
//! process URI Templates up to and including ones designated as Level 4 by the
//! specification. It passes all of the tests in the
//! [uritemplate-test](https://github.com/uri-templates/uritemplate-test) test
//! suite.
//!
//! Basic Usage
//! -----------
//! Variable setting can be chained for nice, clean code.
//!
//! ```ignore
//! extern crate uritemplate;
//! use uritemplate::UriTemplate;
//!
//! let uri = UriTemplate::new("/view/{object:1}/{/object,names}{?query*}")
//!     .set("object", "lakes")
//!     .set("names", &["Erie", "Superior", "Ontario"])
//!     .set("query", &[("size", "15"), ("lang", "en")])
//!     .build();
//!
//! assert_eq!(uri, "/view/l/lakes/Erie,Superior,Ontario?size=15&lang=en");
//! ```
//!
//! It is not possible to set a variable to the value "undefined". Instead,
//! simply delete the variable if you have already set it.
//!
//! ```ignore
//! let mut t = UriTemplate::new("{hello}");
//! t.set("hello", "Hello World!");
//! assert_eq!(t.build(), "Hello%20World%21");
//!
//! t.delete("hello");
//! assert_eq!(t.build(), "");
//! ```
//!
//! The `delete` function returns `true` if the variable existed and `false`
//! otherwise.
//!
//! Supported Types
//! ---------------
//! Any type that implements `IntoTemplateVar` can be set as the value of a
//! `UriTemplate` variable. The following implementations are provided by
//! default for each type of variable:
//!
//! - Scalar Values: `String`, `&str`
//! - Lists: `Vec<String>`, `&[String]`, `&[str]`
//! - Associative Arrays: `Vec<(String, String)>`, `&[(String, String)]`,
//!   `&[(&str, &str)]`, `&HashMap<String, String>`
//!
//! In addition, you can implement `IntoTemplateVar` for your own types. View the
//! documentation for `IntoTemplateVar` for information on how that works.

extern crate regex;

mod percent_encoding;
mod templatevar;

use percent_encoding::{encode_reserved, encode_unreserved};
use std::collections::HashMap;
use std::str::FromStr;

pub use templatevar::{IntoTemplateVar, TemplateVar};

enum VarSpecType {
    Raw,
    Prefixed(u16),
    Exploded
}

struct VarSpec {
    name: String,
    var_type: VarSpecType
}

#[derive(PartialEq)]
enum Operator {
    Null,
    Plus,
    Dot,
    Slash,
    Semi,
    Question,
    Ampersand,
    Hash
}

enum TemplateComponent {
    Literal(String),
    VarList(Operator, Vec<VarSpec>)
}

/// The main struct that processes and builds URI Templates.
pub struct UriTemplate {
    components: Vec<TemplateComponent>,
    vars: HashMap<String, TemplateVar>
}

fn prefixed(s: &str, prefix: u16) -> String {
    let prefix = prefix as usize;
    if prefix >= s.len() {
        s.to_string()
    } else {
        s[0..prefix].to_string()
    }
}

fn parse_varlist(varlist: &str) -> TemplateComponent {
    let mut varlist = varlist.to_string();
    let operator = match varlist.chars().nth(0) {
        Some(ch) => ch,
        None => {
            return TemplateComponent::VarList(Operator::Null, Vec::new());
        }
    };
    let operator = match operator {
        '+' => Operator::Plus,
        '.' => Operator::Dot,
        '/' => Operator::Slash,
        ';' => Operator::Semi,
        '?' => Operator::Question,
        '&' => Operator::Ampersand,
        '#' => Operator::Hash,
        _ => Operator::Null
    };
    if operator != Operator::Null {
        varlist.remove(0);
    }
    let varspecs = varlist.split(",");
    let mut varspec_list = Vec::new();
    for varspec in varspecs {
        let mut varspec = varspec.to_string();
        let len = varspec.len();
        if len >= 1 && varspec.chars().nth(len - 1).unwrap() == '*' {
            varspec.pop();
            varspec_list.push(VarSpec {
                name: varspec,
                var_type: VarSpecType::Exploded
            });
            continue;
        }
        if varspec.contains(":") {
            let parts: Vec<_> = varspec.splitn(2, ":").collect();
            let prefix = u16::from_str(parts[1]).ok();
            let prefix = match prefix {
                Some(p) => p,
                None => 9999u16
            };
            varspec_list.push(VarSpec {
                name: parts[0].to_string(),
                var_type: VarSpecType::Prefixed(prefix)
            });
            continue;
        }
        varspec_list.push(VarSpec {
            name: varspec,
            var_type: VarSpecType::Raw
        });
    }

    TemplateComponent::VarList(operator, varspec_list)
}

fn encode_vec<E>(v: &Vec<String>, encoder: E) -> Vec<String>
    where E: Fn(&str) -> String
{
    v.iter().map(|s| encoder(&s)).collect()
}

impl UriTemplate {

    /// Creates a new URI Template from the given template string.
    ///
    /// Example
    /// -------
    /// ```ignore
    /// let t = UriTemplate::new("http://example.com/{name}");
    /// ```
    pub fn new(template: &str) -> UriTemplate {
        let mut components = Vec::new();
        let mut buf = String::new();
        let mut in_varlist = false;

        for ch in template.chars() {
            if in_varlist && ch == '}' {
                components.push(parse_varlist(&buf));
                buf = String::new();
                in_varlist = false;
                continue;
            }
            if !in_varlist && ch == '{' {
                if buf.len() > 0 {
                    components.push(TemplateComponent::Literal(buf));
                    buf = String::new();
                }
                in_varlist = true;
                continue;
            }
            buf.push(ch);
        }

        if buf.len() > 0 {
            components.push(TemplateComponent::Literal(buf));
        }

        UriTemplate {
            components: components,
            vars: HashMap::new()
        }
    }

    /// Sets the value of a variable in the URI Template.
    ///
    /// Example
    /// -------
    /// ```ignore
    /// let mut t = UriTemplate::new("{name}");
    /// t.set("name", "John Smith");
    /// ```
    ///
    /// This function returns the `URITemplate` so that the `set()` calls can
    /// be chained before building.
    ///
    /// ```ignore
    /// let uri = UriTemplate::new("{firstname}/{lastname}")
    ///     .set("firstname", "John")
    ///     .set("lastname", "Smith")
    ///     .build();
    /// assert_eq!(uri, "John/Smith");
    /// ```
    pub fn set<I: IntoTemplateVar>(&mut self, varname: &str, var: I)
        -> &mut UriTemplate
    {
        self.vars.insert(varname.to_string(), var.into_template_var());
        self
    }

    /// Deletes the value of a variable in the URI Template. Returns `true` if
    /// the variable existed and `false` otherwise.
    ///
    /// Example
    ///
    /// ```ignore
    /// let mut t = UriTemplate::new("{animal}");
    /// t.set("animal", "dog");
    /// assert_eq!(t.delete("house"), false);
    /// assert_eq!(t.delete("animal"), true);
    /// ```
    pub fn delete(&mut self, varname: &str) -> bool {
        match self.vars.remove(varname) {
            Some(_) => true,
            None => false
        }
    }

    /// Deletes the values of all variables currently set in the `URITemplate`.
    pub fn delete_all(&mut self) {
        self.vars.clear();
    }

    fn build_varspec<E>(&self, v: &VarSpec, sep: &str, named: bool, ifemp: &str,
        encoder: E) -> Option<String> where E: Fn(&str) -> String
    {
        let mut res = String::new();

        let var = match self.vars.get(&v.name) {
            Some(v) => v,
            None => { return None }
        };

        match *var {
            TemplateVar::Scalar(ref s) => {
                if named {
                    res.push_str(&encode_reserved(&v.name));
                    if s == "" {
                        res.push_str(ifemp);
                        return Some(res);
                    }
                    res.push('=');
                }
                match v.var_type {
                    VarSpecType::Raw | VarSpecType::Exploded => {
                        res.push_str(&encoder(s));
                    }
                    VarSpecType::Prefixed(p) => {
                        res.push_str(&encoder(&prefixed(s, p)));
                    }
                };
            },
            TemplateVar::List(ref l) => {
                if l.len() == 0 {
                    return None;
                }
                match v.var_type {
                    VarSpecType::Raw | VarSpecType::Prefixed(_) => {
                        if named {
                            res.push_str(&encode_reserved(&v.name));
                            if l.connect("").len() == 0 {
                                res.push_str(ifemp);
                                return Some(res);
                            }
                            res.push('=');
                        }
                        res.push_str(&encode_vec(l, encoder).connect(","));
                    },
                    VarSpecType::Exploded => {
                        if named {
                            let pairs: Vec<String> = l
                                .iter()
                                .map(|x| {
                                    let val: String = if x == "" {
                                        format!(
                                            "{}{}",
                                            &encode_reserved(&v.name),
                                            ifemp
                                        )
                                    } else {
                                        format!(
                                            "{}={}",
                                            &encode_reserved(&v.name),
                                            &encoder(x)
                                        )
                                    };
                                    val
                                })
                                .collect();
                            res.push_str(&pairs.connect(sep));
                        } else {
                            res.push_str(
                                &encode_vec(&l, encoder).connect(sep)
                            );
                        }
                    }
                }
            },
            TemplateVar::AssociativeArray(ref a) => {
                if a.len() == 0 {
                    return None;
                }
                match v.var_type {
                    VarSpecType::Raw | VarSpecType::Prefixed(_) => {
                        if named {
                            res.push_str(&encode_reserved(&v.name));
                            res.push('=');
                        }
                        let pairs: Vec<String> = a
                            .iter()
                            .map(|&(ref k, ref v)| {
                                format!("{},{}",
                                    &encode_reserved(k),
                                    &encoder(v)
                                )
                            })
                            .collect();
                        res.push_str(&pairs.connect(","));
                    },
                    VarSpecType::Exploded => {
                        if named {
                            let pairs: Vec<String> = a
                                .iter()
                                .map(|&(ref k, ref v)| {
                                    let val: String = if v == "" {
                                        format!(
                                            "{}{}",
                                            &encode_reserved(k),
                                            ifemp
                                        )
                                    } else {
                                        format!(
                                            "{}={}",
                                            &encode_reserved(k),
                                            &encoder(v)
                                        )
                                    };
                                    val
                                })
                                .collect();
                            res.push_str(&pairs.connect(sep));
                        } else {
                            let pairs: Vec<String> = a
                                .iter()
                                .map(|&(ref k, ref v)| {
                                    format!(
                                        "{}={}",
                                        &encode_reserved(k),
                                        &encoder(v)
                                    )
                                })
                                .collect();
                            res.push_str(&pairs.connect(sep));
                        }
                    }
                }
            }
        }

        Some(res)
    }

    fn build_varlist(&self, operator: &Operator, varlist: &Vec<VarSpec>)
        -> String
    {
        let mut values: Vec<String> = Vec::new();
        let (first, sep, named, ifemp, allow_reserved) = match *operator {
            Operator::Null => ("", ",", false, "", false),
            Operator::Plus => ("", ",", false, "", true),
            Operator::Dot => (".", ".", false, "", false),
            Operator::Slash => ("/", "/", false, "", false),
            Operator::Semi => (";", ";", true, "", false),
            Operator::Question => ("?", "&", true, "=", false),
            Operator::Ampersand => ("&", "&", true, "=", false),
            Operator::Hash => ("#", ",", false, "", true)
        };

        for varspec in varlist {
            let built = if allow_reserved {
                self.build_varspec(varspec, sep, named, ifemp, encode_reserved)
            } else {
                self.build_varspec(
                    varspec,
                    sep,
                    named,
                    ifemp,
                    encode_unreserved
                )
            };
            match built {
                Some(s) => { values.push(s) },
                None => {}
            }
        }

        let mut res = String::new();
        if values.len() != 0 {
            res.push_str(first);
            res.push_str(&values.connect(sep));
        }

        res
    }

    /// Expands the template using the set variable values and returns the
    /// final String.
    ///
    /// Example
    /// -------
    ///
    /// ```ignore
    /// let mut t = UriTemplate::new("{hello}");
    /// t.set("hello", "Hello World!");
    /// assert_eq!(t.build(), "Hello%20World%21");
    /// ```
    pub fn build(&self) -> String {
        let mut res = String::new();
        for component in &self.components {
            let next = match *component {
                TemplateComponent::Literal(ref s) => encode_reserved(s),
                TemplateComponent::VarList(ref op, ref varlist) => {
                    self.build_varlist(op, varlist)
                }
            };
            res.push_str(&next);
        }
        res
    }

}
<commit_msg>Use non-deprecated join method<commit_after>//! `rust-uritemplate` is a Rust implementation of
//! [RFC6570  - URI Template](http://tools.ietf.org/html/rfc6570) that can
//! process URI Templates up to and including ones designated as Level 4 by the
//! specification. It passes all of the tests in the
//! [uritemplate-test](https://github.com/uri-templates/uritemplate-test) test
//! suite.
//!
//! Basic Usage
//! -----------
//! Variable setting can be chained for nice, clean code.
//!
//! ```ignore
//! extern crate uritemplate;
//! use uritemplate::UriTemplate;
//!
//! let uri = UriTemplate::new("/view/{object:1}/{/object,names}{?query*}")
//!     .set("object", "lakes")
//!     .set("names", &["Erie", "Superior", "Ontario"])
//!     .set("query", &[("size", "15"), ("lang", "en")])
//!     .build();
//!
//! assert_eq!(uri, "/view/l/lakes/Erie,Superior,Ontario?size=15&lang=en");
//! ```
//!
//! It is not possible to set a variable to the value "undefined". Instead,
//! simply delete the variable if you have already set it.
//!
//! ```ignore
//! let mut t = UriTemplate::new("{hello}");
//! t.set("hello", "Hello World!");
//! assert_eq!(t.build(), "Hello%20World%21");
//!
//! t.delete("hello");
//! assert_eq!(t.build(), "");
//! ```
//!
//! The `delete` function returns `true` if the variable existed and `false`
//! otherwise.
//!
//! Supported Types
//! ---------------
//! Any type that implements `IntoTemplateVar` can be set as the value of a
//! `UriTemplate` variable. The following implementations are provided by
//! default for each type of variable:
//!
//! - Scalar Values: `String`, `&str`
//! - Lists: `Vec<String>`, `&[String]`, `&[str]`
//! - Associative Arrays: `Vec<(String, String)>`, `&[(String, String)]`,
//!   `&[(&str, &str)]`, `&HashMap<String, String>`
//!
//! In addition, you can implement `IntoTemplateVar` for your own types. View the
//! documentation for `IntoTemplateVar` for information on how that works.

extern crate regex;

mod percent_encoding;
mod templatevar;

use percent_encoding::{encode_reserved, encode_unreserved};
use std::collections::HashMap;
use std::str::FromStr;

pub use templatevar::{IntoTemplateVar, TemplateVar};

enum VarSpecType {
    Raw,
    Prefixed(u16),
    Exploded
}

struct VarSpec {
    name: String,
    var_type: VarSpecType
}

#[derive(PartialEq)]
enum Operator {
    Null,
    Plus,
    Dot,
    Slash,
    Semi,
    Question,
    Ampersand,
    Hash
}

enum TemplateComponent {
    Literal(String),
    VarList(Operator, Vec<VarSpec>)
}

/// The main struct that processes and builds URI Templates.
pub struct UriTemplate {
    components: Vec<TemplateComponent>,
    vars: HashMap<String, TemplateVar>
}

fn prefixed(s: &str, prefix: u16) -> String {
    let prefix = prefix as usize;
    if prefix >= s.len() {
        s.to_string()
    } else {
        s[0..prefix].to_string()
    }
}

fn parse_varlist(varlist: &str) -> TemplateComponent {
    let mut varlist = varlist.to_string();
    let operator = match varlist.chars().nth(0) {
        Some(ch) => ch,
        None => {
            return TemplateComponent::VarList(Operator::Null, Vec::new());
        }
    };
    let operator = match operator {
        '+' => Operator::Plus,
        '.' => Operator::Dot,
        '/' => Operator::Slash,
        ';' => Operator::Semi,
        '?' => Operator::Question,
        '&' => Operator::Ampersand,
        '#' => Operator::Hash,
        _ => Operator::Null
    };
    if operator != Operator::Null {
        varlist.remove(0);
    }
    let varspecs = varlist.split(",");
    let mut varspec_list = Vec::new();
    for varspec in varspecs {
        let mut varspec = varspec.to_string();
        let len = varspec.len();
        if len >= 1 && varspec.chars().nth(len - 1).unwrap() == '*' {
            varspec.pop();
            varspec_list.push(VarSpec {
                name: varspec,
                var_type: VarSpecType::Exploded
            });
            continue;
        }
        if varspec.contains(":") {
            let parts: Vec<_> = varspec.splitn(2, ":").collect();
            let prefix = u16::from_str(parts[1]).ok();
            let prefix = match prefix {
                Some(p) => p,
                None => 9999u16
            };
            varspec_list.push(VarSpec {
                name: parts[0].to_string(),
                var_type: VarSpecType::Prefixed(prefix)
            });
            continue;
        }
        varspec_list.push(VarSpec {
            name: varspec,
            var_type: VarSpecType::Raw
        });
    }

    TemplateComponent::VarList(operator, varspec_list)
}

fn encode_vec<E>(v: &Vec<String>, encoder: E) -> Vec<String>
    where E: Fn(&str) -> String
{
    v.iter().map(|s| encoder(&s)).collect()
}

impl UriTemplate {

    /// Creates a new URI Template from the given template string.
    ///
    /// Example
    /// -------
    /// ```ignore
    /// let t = UriTemplate::new("http://example.com/{name}");
    /// ```
    pub fn new(template: &str) -> UriTemplate {
        let mut components = Vec::new();
        let mut buf = String::new();
        let mut in_varlist = false;

        for ch in template.chars() {
            if in_varlist && ch == '}' {
                components.push(parse_varlist(&buf));
                buf = String::new();
                in_varlist = false;
                continue;
            }
            if !in_varlist && ch == '{' {
                if buf.len() > 0 {
                    components.push(TemplateComponent::Literal(buf));
                    buf = String::new();
                }
                in_varlist = true;
                continue;
            }
            buf.push(ch);
        }

        if buf.len() > 0 {
            components.push(TemplateComponent::Literal(buf));
        }

        UriTemplate {
            components: components,
            vars: HashMap::new()
        }
    }

    /// Sets the value of a variable in the URI Template.
    ///
    /// Example
    /// -------
    /// ```ignore
    /// let mut t = UriTemplate::new("{name}");
    /// t.set("name", "John Smith");
    /// ```
    ///
    /// This function returns the `URITemplate` so that the `set()` calls can
    /// be chained before building.
    ///
    /// ```ignore
    /// let uri = UriTemplate::new("{firstname}/{lastname}")
    ///     .set("firstname", "John")
    ///     .set("lastname", "Smith")
    ///     .build();
    /// assert_eq!(uri, "John/Smith");
    /// ```
    pub fn set<I: IntoTemplateVar>(&mut self, varname: &str, var: I)
        -> &mut UriTemplate
    {
        self.vars.insert(varname.to_string(), var.into_template_var());
        self
    }

    /// Deletes the value of a variable in the URI Template. Returns `true` if
    /// the variable existed and `false` otherwise.
    ///
    /// Example
    ///
    /// ```ignore
    /// let mut t = UriTemplate::new("{animal}");
    /// t.set("animal", "dog");
    /// assert_eq!(t.delete("house"), false);
    /// assert_eq!(t.delete("animal"), true);
    /// ```
    pub fn delete(&mut self, varname: &str) -> bool {
        match self.vars.remove(varname) {
            Some(_) => true,
            None => false
        }
    }

    /// Deletes the values of all variables currently set in the `URITemplate`.
    pub fn delete_all(&mut self) {
        self.vars.clear();
    }

    fn build_varspec<E>(&self, v: &VarSpec, sep: &str, named: bool, ifemp: &str,
        encoder: E) -> Option<String> where E: Fn(&str) -> String
    {
        let mut res = String::new();

        let var = match self.vars.get(&v.name) {
            Some(v) => v,
            None => { return None }
        };

        match *var {
            TemplateVar::Scalar(ref s) => {
                if named {
                    res.push_str(&encode_reserved(&v.name));
                    if s == "" {
                        res.push_str(ifemp);
                        return Some(res);
                    }
                    res.push('=');
                }
                match v.var_type {
                    VarSpecType::Raw | VarSpecType::Exploded => {
                        res.push_str(&encoder(s));
                    }
                    VarSpecType::Prefixed(p) => {
                        res.push_str(&encoder(&prefixed(s, p)));
                    }
                };
            },
            TemplateVar::List(ref l) => {
                if l.len() == 0 {
                    return None;
                }
                match v.var_type {
                    VarSpecType::Raw | VarSpecType::Prefixed(_) => {
                        if named {
                            res.push_str(&encode_reserved(&v.name));
                            if l.join("").len() == 0 {
                                res.push_str(ifemp);
                                return Some(res);
                            }
                            res.push('=');
                        }
                        res.push_str(&encode_vec(l, encoder).join(","));
                    },
                    VarSpecType::Exploded => {
                        if named {
                            let pairs: Vec<String> = l
                                .iter()
                                .map(|x| {
                                    let val: String = if x == "" {
                                        format!(
                                            "{}{}",
                                            &encode_reserved(&v.name),
                                            ifemp
                                        )
                                    } else {
                                        format!(
                                            "{}={}",
                                            &encode_reserved(&v.name),
                                            &encoder(x)
                                        )
                                    };
                                    val
                                })
                                .collect();
                            res.push_str(&pairs.join(sep));
                        } else {
                            res.push_str(
                                &encode_vec(&l, encoder).join(sep)
                            );
                        }
                    }
                }
            },
            TemplateVar::AssociativeArray(ref a) => {
                if a.len() == 0 {
                    return None;
                }
                match v.var_type {
                    VarSpecType::Raw | VarSpecType::Prefixed(_) => {
                        if named {
                            res.push_str(&encode_reserved(&v.name));
                            res.push('=');
                        }
                        let pairs: Vec<String> = a
                            .iter()
                            .map(|&(ref k, ref v)| {
                                format!("{},{}",
                                    &encode_reserved(k),
                                    &encoder(v)
                                )
                            })
                            .collect();
                        res.push_str(&pairs.join(","));
                    },
                    VarSpecType::Exploded => {
                        if named {
                            let pairs: Vec<String> = a
                                .iter()
                                .map(|&(ref k, ref v)| {
                                    let val: String = if v == "" {
                                        format!(
                                            "{}{}",
                                            &encode_reserved(k),
                                            ifemp
                                        )
                                    } else {
                                        format!(
                                            "{}={}",
                                            &encode_reserved(k),
                                            &encoder(v)
                                        )
                                    };
                                    val
                                })
                                .collect();
                            res.push_str(&pairs.join(sep));
                        } else {
                            let pairs: Vec<String> = a
                                .iter()
                                .map(|&(ref k, ref v)| {
                                    format!(
                                        "{}={}",
                                        &encode_reserved(k),
                                        &encoder(v)
                                    )
                                })
                                .collect();
                            res.push_str(&pairs.join(sep));
                        }
                    }
                }
            }
        }

        Some(res)
    }

    fn build_varlist(&self, operator: &Operator, varlist: &Vec<VarSpec>)
        -> String
    {
        let mut values: Vec<String> = Vec::new();
        let (first, sep, named, ifemp, allow_reserved) = match *operator {
            Operator::Null => ("", ",", false, "", false),
            Operator::Plus => ("", ",", false, "", true),
            Operator::Dot => (".", ".", false, "", false),
            Operator::Slash => ("/", "/", false, "", false),
            Operator::Semi => (";", ";", true, "", false),
            Operator::Question => ("?", "&", true, "=", false),
            Operator::Ampersand => ("&", "&", true, "=", false),
            Operator::Hash => ("#", ",", false, "", true)
        };

        for varspec in varlist {
            let built = if allow_reserved {
                self.build_varspec(varspec, sep, named, ifemp, encode_reserved)
            } else {
                self.build_varspec(
                    varspec,
                    sep,
                    named,
                    ifemp,
                    encode_unreserved
                )
            };
            match built {
                Some(s) => { values.push(s) },
                None => {}
            }
        }

        let mut res = String::new();
        if values.len() != 0 {
            res.push_str(first);
            res.push_str(&values.join(sep));
        }

        res
    }

    /// Expands the template using the set variable values and returns the
    /// final String.
    ///
    /// Example
    /// -------
    ///
    /// ```ignore
    /// let mut t = UriTemplate::new("{hello}");
    /// t.set("hello", "Hello World!");
    /// assert_eq!(t.build(), "Hello%20World%21");
    /// ```
    pub fn build(&self) -> String {
        let mut res = String::new();
        for component in &self.components {
            let next = match *component {
                TemplateComponent::Literal(ref s) => encode_reserved(s),
                TemplateComponent::VarList(ref op, ref varlist) => {
                    self.build_varlist(op, varlist)
                }
            };
            res.push_str(&next);
        }
        res
    }

}
<|endoftext|>


<commit_before>#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
#![warn(missing_docs)]

//! Library for building cellular automata.
//!
//! Cellular automaton is made by supplying some cell to
//! grid and "engine". Grid stores all cells, chooses
//! how to iterate them, how to split itself etc.
//! Engine runs grid evolution in some way and passes
//! updates to so-called consumers.
//!
//! Consumers are interface parts to outer world.
//! They can be GUI, Web or simple file writers.

extern crate serde;
#[cfg(test)]
extern crate bincode;

pub mod grid;
pub mod engine;
pub mod traits;
mod utils;

mod examples;
<commit_msg>engbad<commit_after>#![feature(custom_derive, plugin)]
#![plugin(serde_macros)]
#![warn(missing_docs)]

//! Library for building cellular automata.
//!
//! Cellular automaton is made by supplying some cell to
//! grid and "engine". Grid stores all cells, chooses
//! how to iterate them, how to split itself etc.
//! Engine runs grid evolution in some way and passes
//! updates to so-called consumers.
//!
//! Consumers are interface to outer world.
//! They can be GUI, Web or simple file writers.

extern crate serde;
#[cfg(test)]
extern crate bincode;

pub mod grid;
pub mod engine;
pub mod traits;
mod utils;

mod examples;
<|endoftext|>


<commit_before>#![cfg_attr(feature = "dev", feature(plugin))]
#![cfg_attr(feature = "dev", plugin(clippy))]

//! `ruroonga_command` provides extensible Groonga command query builder and
//! generator. It reduces runtime errors about Groonga queries.

extern crate url;

mod util;
/// `queryable` provides a shortcut to create URI style Groonga query.
///
/// Note that if you want to change URL prefix from `/d/`,
/// you have to use `CommandQuery` directly and
/// specify it with `set_prefix` in `CommandQuery`.
pub mod queryable;
mod commandlinable;
/// `commandable` provides a shortcut to create command line Groonga query.
pub mod commandable;
/// `extendable` provides appending user-defined key-value pair query functionality trait.
///
/// Note that this provided trait method is marked as `unsafe`.
/// You should use this trait **at your own risk**.
#[macro_use]
pub mod extendable;
/// `request_cancellable` provides appending `request_id` functionality trait.
#[macro_use]
pub mod request_cancellable;
/// `request_timeoutable` provides appending `timeout` functionality trait.
#[macro_use]
pub mod request_timeoutable;
/// Provides types for Query builders.
pub mod types;
/// Type variant definitions for Groonga commands.
pub mod command;
/// An entity type for `queryable` trait.
pub mod command_query;
/// An entity type for `commandable` trait.
pub mod command_line;
pub mod dump;
/// `SelectCommand` type creates `select` query.
///
/// This type is **one of the most important type** in this crate.
/// Because this type is to be able to combine with `drilldown` related types.
///
/// It recommends to refer to the documents under `selectable` module.
pub mod select;
/// Provides manupilation way to construct and concatinate drilldown with select query.
pub mod selectable;
pub mod load;
pub mod status;
pub mod cache_limit;
pub mod delete;
pub mod io_flush;
pub mod log_level;
pub mod log_put;
pub mod log_reopen;
pub mod table_create;
pub mod table_list;
pub mod table_rename;
pub mod table_remove;
pub mod column_copy;
pub mod column_create;
pub mod column_list;
pub mod column_rename;
pub mod column_remove;
pub mod database_unmap;
/// Using request cancel mechanism.
/// If you use this cancel feature,
/// you should use `request_cancellable` trait to add `request_id` into each request.
pub mod request_cancel;
pub mod object_exist;
pub mod object_inspect;
pub mod object_remove;
pub mod normalize;
pub mod normalizer_list;
pub mod plugin_register;
pub mod plugin_unregister;
pub mod thread_limit;
pub mod tokenize;
pub mod tokenizer_list;
pub mod truncate;
/// This module provides fully user-defined query creation mechanism.
/// This module is only provided for funture extensibility.
/// You should use this module **at your own risk**.
pub mod extension;
pub mod schema;
pub mod shutdown;
/// `dsl` provides its `XXXCommand` returning dsl syntax like this:
///
/// ## DSL Example
///
/// ```
/// use ruroonga_command::dsl::*;
/// let select = select("Entries".to_string())
///                  .filter("content @ \"fast\"".to_string());
/// ```
pub mod dsl;
<commit_msg>Add comment for notification why a module should be internal<commit_after>#![cfg_attr(feature = "dev", feature(plugin))]
#![cfg_attr(feature = "dev", plugin(clippy))]

//! `ruroonga_command` provides extensible Groonga command query builder and
//! generator. It reduces runtime errors about Groonga queries.

extern crate url;

mod util;
/// `queryable` provides a shortcut to create URI style Groonga query.
///
/// Note that if you want to change URL prefix from `/d/`,
/// you have to use `CommandQuery` directly and
/// specify it with `set_prefix` in `CommandQuery`.
pub mod queryable;
// This module is used internally.
// To escape operation against raw query string to be valid query.
mod commandlinable;
/// `commandable` provides a shortcut to create command line Groonga query.
pub mod commandable;
/// `extendable` provides appending user-defined key-value pair query functionality trait.
///
/// Note that this provided trait method is marked as `unsafe`.
/// You should use this trait **at your own risk**.
#[macro_use]
pub mod extendable;
/// `request_cancellable` provides appending `request_id` functionality trait.
#[macro_use]
pub mod request_cancellable;
/// `request_timeoutable` provides appending `timeout` functionality trait.
#[macro_use]
pub mod request_timeoutable;
/// Provides types for Query builders.
pub mod types;
/// Type variant definitions for Groonga commands.
pub mod command;
/// An entity type for `queryable` trait.
pub mod command_query;
/// An entity type for `commandable` trait.
pub mod command_line;
pub mod dump;
/// `SelectCommand` type creates `select` query.
///
/// This type is **one of the most important type** in this crate.
/// Because this type is to be able to combine with `drilldown` related types.
///
/// It recommends to refer to the documents under `selectable` module.
pub mod select;
/// Provides manupilation way to construct and concatinate drilldown with select query.
pub mod selectable;
pub mod load;
pub mod status;
pub mod cache_limit;
pub mod delete;
pub mod io_flush;
pub mod log_level;
pub mod log_put;
pub mod log_reopen;
pub mod table_create;
pub mod table_list;
pub mod table_rename;
pub mod table_remove;
pub mod column_copy;
pub mod column_create;
pub mod column_list;
pub mod column_rename;
pub mod column_remove;
pub mod database_unmap;
/// Using request cancel mechanism.
/// If you use this cancel feature,
/// you should use `request_cancellable` trait to add `request_id` into each request.
pub mod request_cancel;
pub mod object_exist;
pub mod object_inspect;
pub mod object_remove;
pub mod normalize;
pub mod normalizer_list;
pub mod plugin_register;
pub mod plugin_unregister;
pub mod thread_limit;
pub mod tokenize;
pub mod tokenizer_list;
pub mod truncate;
/// This module provides fully user-defined query creation mechanism.
/// This module is only provided for funture extensibility.
/// You should use this module **at your own risk**.
pub mod extension;
pub mod schema;
pub mod shutdown;
/// `dsl` provides its `XXXCommand` returning dsl syntax like this:
///
/// ## DSL Example
///
/// ```
/// use ruroonga_command::dsl::*;
/// let select = select("Entries".to_string())
///                  .filter("content @ \"fast\"".to_string());
/// ```
pub mod dsl;
<|endoftext|>