<commit_before>extern crate time;

use std::thread;

use std::ops::{Div, Range};

extern crate num;
use num::{One};

#[inline]
pub fn ns_to_s(ns: u64) -> f64 {
    (ns as f64) / 1_000_000_000.
}

/// seconds to nanoseconds
#[inline]
pub fn s_to_ns(s: f64) -> f64 {
    s * 1_000_000_000.
}

#[inline]
pub fn ns_to_ms(ns: u64) -> f64 {
    (ns as f64) / 1_000_000.
}

#[inline]
pub fn ms_to_ns(ns: f64) -> f64 {
    ns * 1_000_000.
}

#[inline]
pub fn fps_to_ns_per_frame(fps: usize) -> u64 {
    (s_to_ns(1.0) / (fps as f64)).round() as u64
}

#[inline]
pub fn current_time_ns() -> u64 {
    time::precise_time_ns()
}

pub fn sleep_for_constant_rate(fps: usize, ns_before: u64) {
    let ns_per_frame = fps_to_ns_per_frame(fps);
    let ns_after: u64 = time::precise_time_ns();
    let ns_elapsed = ns_after - ns_before;
    if ns_elapsed < ns_per_frame {
        let ns_left_to_sleep = ns_per_frame - ns_elapsed;
        thread::sleep_ms(ns_to_ms(ns_left_to_sleep) as u32);
    }
}

/// frequency range that can be modeled when taking the short
/// time fourier transform of a signal with `sample_rate` with
/// a sliding window of `window_sizew`.
/// equivalent to `rayleigh(sample_rate, window_size)..nyquist(sample_rate)`
/// increase the window size to increase the lower frequency
/// increase the sample rate to increase the upper frequency
pub fn hertz_range<T>(sample_rate: T, window_size: T) -> Range<T>
    where T: Div<T, Output=T> + From<u16> + Clone
{
    rayleigh(sample_rate.clone(), window_size)..nyquist(sample_rate)
}

#[test]
fn test_hertz_range() {
    assert_eq!(
        hertz_range(44100., 1024. * 8.),
        (5.38330078125)..22050.);
    assert_eq!(
        hertz_range(44100., 1024. * 4.),
        (10.7666015625)..22050.);
    assert_eq!(
        hertz_range(44100., 1024.),
        (43.06640625)..22050.);
    assert_eq!(
        hertz_range(44100., 512.),
        (86.1328125)..22050.);
}

/// maximum frequency in hertz that can be modeled with a given rate
pub fn nyquist<T>(sample_rate: T) -> T
    where T: Div<T, Output=T> + From<u16>
{
    sample_rate / T::from(2 as u16)
}

#[test]
fn test_nyquist() {
    assert_eq!(nyquist(44100.), 22050.);
}

/// minimum frequency in hertz
pub fn rayleigh<T>(sample_rate: T, window_size: T) -> T
    where T: Div<T, Output=T> + From<u16>
{
    T::from(1 as u16) / seconds_per_window(sample_rate, window_size)
}

#[test]
fn test_rayleigh() {
    assert_eq!(rayleigh(44100., 1024.), 43.06640625);
}

/// window duration in seconds
/// sample_rate in hertz
fn seconds_per_window<T>(samples_per_second: T, samples_per_window: T) -> T
    where T: Div<T, Output=T>
{
    samples_per_window / samples_per_second
}

#[test]
fn test_seconds_per_window() {
    // 11ms time resolution
    assert_eq!(seconds_per_window(44100., 512.), 0.011609977324263039);
    assert_eq!(seconds_per_window(44100., 1024.), 0.023219954648526078);
}
<commit_msg>update docstrings, add crate docstring, improve code<commit_after>/*!

**useful functions for working with frame-rates, sample-rates,
other rates,
time durations,
frequencies, etc and for keeping constant fps.**

`rate`, `sample rate`, `frame rate`, `fps`, `frequency`, etc
express the same concept, are therefore used interchangeably.

you can use hertz to compute the time resolution
and frequency range of a signal that can be meaningfully analyzed by a
[short-time fourier transform](https://en.wikipedia.org/wiki/Short-time_Fourier_transform#Explanation):

```
extern crate hertz;

fn main() {
    let sample_rate = 44100;
    let window_size = 4096;
    let step_size = 512;

    // 11 hertz is the maximum frequency that can be meaningfully analyzed
    assert_eq!(
        11.,
        hertz::rayleigh(sample_rate as f64, window_size as f64).round());

    // 22050 hertz is the maximum frequency that can be meaningfully analyzed
    assert_eq!(
        22050.,
        hertz::nyquist(sample_rate as f64).round());

    // 12 ms is the time resolution we get when analyzing a 44100 hertz
    // signal with a step size of 512
    assert_eq!(
        12.,
        hertz::s_to_ms(hertz::cycles_per_second_to_seconds_per_cycle(
            sample_rate as f64,
            step_size as f64)).round());
}
```

you can use hertz to keep a constant framerate in a game or other
computer graphics application:

```no_run
fn main() {
    let frames_per_second: usize = 60;

    loop {
        let ns_at_frame_start = hertz::current_time_ns();

        // here's where logic and rendering would go.
        // this is never called more than frames_per_second
        // times per second.

        hertz::sleep_for_constant_rate(
            frames_per_second, ns_at_frame_start);
    }
}
```
*/

extern crate time;

use std::ops::{Mul, Div, Range};

/// nanoseconds to seconds
#[inline]
pub fn ns_to_s(ns: u64) -> f64 {
    (ns as f64) / 1_000_000_000.
}

/// seconds to nanoseconds
#[inline]
pub fn s_to_ns(s: f64) -> f64 {
    s * 1_000_000_000.
}

/// nanoseconds to milliseconds
#[inline]
pub fn ns_to_ms(ns: u64) -> f64 {
    (ns as f64) / 1_000_000.
}

/// seconds to milliseconds
#[inline]
pub fn s_to_ms<T>(s: T) -> T
    where T: Mul<T, Output=T> + From<u16>
{
    s * T::from(1000 as u16)
}

#[test]
fn test_s_to_ms() {
    assert_eq!(s_to_ms(1), 1000);
    assert_eq!(s_to_ms(1.), 1000.);
}

/// milliseconds to seconds
#[inline]
pub fn ms_to_s<T>(ms: T) -> T
    where T: Div<T, Output=T> + From<u16>
{
    ms / T::from(1000 as u16)
}

#[test]
fn test_ms_to_s() {
    assert_eq!(ms_to_s(1000), 1);
    assert_eq!(ms_to_s(1000.), 1.);
}

/// milliseconds to nanoseconds
#[inline]
pub fn ms_to_ns(ns: f64) -> f64 {
    ns * 1_000_000.
}

/// when given frames per second (or sample rate)
/// returns the duration of a single frame
#[inline]
pub fn fps_to_ns_per_frame(fps: usize) -> u64 {
    (s_to_ns(1.0) / (fps as f64)).round() as u64
}

/// returns the current timestamp in nanoseconds
#[inline]
pub fn current_time_ns() -> u64 {
    time::precise_time_ns()
}

// /// returns the nanoseconds of sleep which are needed to keep a constant
// /// frame rate
// pub fn ns_sleep_needed_for_constant_rate(fps: usize, ns_at_last_frame_start: u64) -> u64 {

/// useful for keeping a constant framerate
pub fn sleep_for_constant_rate(fps: usize, ns_at_last_frame_start: u64) {
    let ns_per_frame = fps_to_ns_per_frame(fps);
    let ns_after: u64 = time::precise_time_ns();
    let ns_elapsed = ns_after - ns_at_last_frame_start;
    if ns_elapsed < ns_per_frame {
        let ns_left_to_sleep = (ns_per_frame - ns_elapsed) as u32;
        let duration = std::time::Duration::new(0, ns_left_to_sleep);
        std::thread::sleep(duration);
    }
}

/// frequency range that can be modeled when taking the short
/// time fourier transform of a signal with `sample_rate` with
/// a sliding window of `window_sizew`.
/// equivalent to `rayleigh(sample_rate, window_size)..nyquist(sample_rate)`
/// increase the window size to increase the lower frequency
/// increase the sample rate to increase the upper frequency
pub fn hertz_range<T>(sample_rate: T, window_size: T) -> Range<T>
    where T: Div<T, Output=T> + From<u16> + Clone
{
    rayleigh(sample_rate.clone(), window_size)..nyquist(sample_rate)
}

#[test]
fn test_hertz_range() {
    assert_eq!(
        hertz_range(44100., 1024. * 8.),
        (5.38330078125)..22050.);
    assert_eq!(
        hertz_range(44100., 1024. * 4.),
        (10.7666015625)..22050.);
    assert_eq!(
        hertz_range(44100., 1024.),
        (43.06640625)..22050.);
    assert_eq!(
        hertz_range(44100., 512.),
        (86.1328125)..22050.);
}

/// maximum frequency in hertz that can be meaningfully analyzed with a given sample rate
/// [https://en.wikipedia.org/wiki/Short-time_Fourier_transform#Explanation](https://en.wikipedia.org/wiki/Short-time_Fourier_transform#Explanation)
pub fn nyquist<T>(sample_rate: T) -> T
    where T: Div<T, Output=T> + From<u16>
{
    sample_rate / T::from(2 as u16)
}

#[test]
fn test_nyquist() {
    assert_eq!(nyquist(44100.), 22050.);
}

/// minimum frequency in hertz that can be meaningfully analyzed with a given sample rate and
/// window size
/// [https://en.wikipedia.org/wiki/Short-time_Fourier_transform#Rayleigh_frequency](https://en.wikipedia.org/wiki/Short-time_Fourier_transform#Rayleigh_frequency)
pub fn rayleigh<T>(sample_rate: T, window_size: T) -> T
    where T: Div<T, Output=T> + From<u16>
{
    T::from(1 as u16) / cycles_per_second_to_seconds_per_cycle(sample_rate, window_size)
}

#[test]
fn test_rayleigh() {
    assert_eq!(rayleigh(44100., 1024.), 43.06640625);
}

/// window duration in seconds
/// sample_rate in hertz
pub fn cycles_per_second_to_seconds_per_cycle<T>(cycles_per_second: T, cycles: T) -> T
    where T: Div<T, Output=T>
{
    cycles / cycles_per_second
}

#[test]
fn test_seconds_per_window() {
    // 11ms time resolution
    assert_eq!(cycles_per_second_to_seconds_per_cycle(44100., 512.), 0.011609977324263039);
    assert_eq!(cycles_per_second_to_seconds_per_cycle(44100., 1024.), 0.023219954648526078);
}
<|endoftext|>


<commit_before>extern crate num;
extern crate oxcable;

pub mod adsr;
pub mod delay;
pub mod dynamics;
pub mod reverb;
pub mod tremolo;
<commit_msg>Write top level module docs.<commit_after>//! Basic audio filters for making music with Rust.
//!
//! This is an extension to the
//! [`oxcable` framework](https://github.com/oxcable/oxcable). These devices are
//! designed to be used with the basic tools provided in the framework. See the
//! core crate for further details.

extern crate num;
extern crate oxcable;

pub mod adsr;
pub mod delay;
pub mod dynamics;
pub mod reverb;
pub mod tremolo;
<|endoftext|>


<commit_before>#![warn(clippy::all)]
#![cfg_attr(feature = "nightly", feature(never_type))]
#![cfg_attr(all(test, feature = "nightly"), feature(test))]
#[cfg(all(test, feature = "nightly"))]
extern crate test;

// Define a never type useful for some traits (ie. SetupRequest)
#[cfg(feature = "nightly")]
pub type Never = !;
#[cfg(not(feature = "nightly"))]
pub type Never = core::convert::Infallible;

pub mod api_call;
pub mod application;
pub mod credentials;
pub mod encoding;
pub mod errors;
pub mod extensions;
pub mod http;
pub mod service;
pub mod transaction;
pub mod usage;
pub mod user;
pub mod version;

#[cfg(feature = "xml-response")]
pub mod response;
pub mod timestamp;

use std::borrow::Cow;

// This is the trait to be implemented by structures that can set parameters to API calls.
//
// Note that the 'this lifetime requires a lifetime long enough to keep keys and values.
// The keys can potentially be modified to adapt them to the specific call circumstances,
// so in order to take advantage of single allocations when modifications are not needed,
// a copy-on-write type is used. Values are always kept as is, so just references are ok.
pub trait ToParams<'k, 'v, 'this, E>
    where 'this: 'k + 'v,
          E: Extend<(Cow<'k, str>, &'v str)>
{
    fn to_params(&'this self, extendable: &mut E) {
        self.to_params_with_prefix(extendable, None);
    }

    fn to_params_with_prefix(&'this self, extendable: &mut E, prefix: Option<&'k str>) {
        self.to_params_with_mangling(extendable, &mut |c| match prefix {
                Some(p) => c + p,
                _ => c,
            });
    }

    fn to_params_with_mangling<F: FnMut(Cow<'k, str>) -> Cow<'k, str>>(&'this self,
                                                                       extendable: &mut E,
                                                                       key_mangling: &mut F);
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {}
}
<commit_msg>lib: make the ToParams trait crate-only and use doc comments<commit_after>#![warn(clippy::all)]
#![cfg_attr(feature = "nightly", feature(never_type))]
#![cfg_attr(all(test, feature = "nightly"), feature(test))]
#[cfg(all(test, feature = "nightly"))]
extern crate test;

// Define a never type useful for some traits (ie. SetupRequest)
#[cfg(feature = "nightly")]
pub type Never = !;
#[cfg(not(feature = "nightly"))]
pub type Never = core::convert::Infallible;

pub mod api_call;
pub mod application;
pub mod credentials;
pub mod encoding;
pub mod errors;
pub mod extensions;
pub mod http;
pub mod service;
pub mod transaction;
pub mod usage;
pub mod user;
pub mod version;

#[cfg(feature = "xml-response")]
pub mod response;
pub mod timestamp;

use std::borrow::Cow;

/// This is the trait to be implemented by structures that can set parameters to API calls.
///
/// Note that the 'this lifetime requires a lifetime long enough to keep keys and values.
/// The keys can potentially be modified to adapt them to the specific call circumstances,
/// so in order to take advantage of single allocations when modifications are not needed,
/// a copy-on-write type is used. Values are always kept as is, so just references are ok.
pub(crate) trait ToParams<'k, 'v, 'this, E>
    where 'this: 'k + 'v,
          E: Extend<(Cow<'k, str>, &'v str)>
{
    fn to_params(&'this self, extendable: &mut E) {
        self.to_params_with_prefix(extendable, None);
    }

    fn to_params_with_prefix(&'this self, extendable: &mut E, prefix: Option<&'k str>) {
        self.to_params_with_mangling(extendable, &mut |c| match prefix {
                Some(p) => c + p,
                _ => c,
            });
    }

    fn to_params_with_mangling<F: FnMut(Cow<'k, str>) -> Cow<'k, str>>(&'this self,
                                                                       extendable: &mut E,
                                                                       key_mangling: &mut F);
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {}
}
<|endoftext|>


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

//! Terminal formatting library.
//!
//! This crate provides the `Terminal` trait, which abstracts over an [ANSI
//! Terminal][ansi] to provide color printing, among other things. There are two
//! implementations, the `TerminfoTerminal`, which uses control characters from
//! a [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console
//! API][win].
//!
//! # Usage
//!
//! This crate is [on crates.io](https://crates.io/crates/term) and can be
//! used by adding `term` to the dependencies in your project's `Cargo.toml`.
//!
//! ```toml
//! [dependencies]
//!
//! term = "0.2"
//! ```
//!
//! and this to your crate root:
//!
//! ```rust
//! extern crate term;
//! ```
//!
//! # Examples
//!
//! ```no_run
//! extern crate term;
//! use std::io::prelude::*;
//!
//! fn main() {
//!     let mut t = term::stdout().unwrap();
//!
//!     t.fg(term::color::GREEN).unwrap();
//!     (write!(t, "hello, ")).unwrap();
//!
//!     t.fg(term::color::RED).unwrap();
//!     (writeln!(t, "world!")).unwrap();
//!
//!     assert!(t.reset().unwrap());
//! }
//! ```
//!
//! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
//! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx
//! [ti]: https://en.wikipedia.org/wiki/Terminfo

#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
       html_root_url = "http://doc.rust-lang.org/nightly/",
       html_playground_url = "http://play.rust-lang.org/")]
#![deny(missing_docs)]
#![cfg_attr(test, deny(warnings))]
#![cfg_attr(rust_build, feature(staged_api))]
#![cfg_attr(rust_build, staged_api)]
#![cfg_attr(rust_build,
            unstable(feature = "rustc_private",
                     reason = "use the crates.io `term` library instead"))]

use std::io::prelude::*;

pub use terminfo::TerminfoTerminal;
#[cfg(windows)]
pub use win::WinConsole;

use std::io::{self, Stdout, Stderr};

pub mod terminfo;

#[cfg(windows)]
mod win;

/// Alias for stdout terminals.
pub type StdoutTerminal = Terminal<Output=Stdout> + Send;
/// Alias for stderr terminals.
pub type StderrTerminal = Terminal<Output=Stderr> + Send;

#[cfg(not(windows))]
/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
/// opened.
pub fn stdout() -> Option<Box<StdoutTerminal>> {
    TerminfoTerminal::new(io::stdout()).map(|t| {
        Box::new(t) as Box<StdoutTerminal>
    })
}

#[cfg(windows)]
/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
/// opened.
pub fn stdout() -> Option<Box<StdoutTerminal>> {
    TerminfoTerminal::new(io::stdout()).map(|t| {
        Box::new(t) as Box<StdoutTerminal>
    }).or_else(|| WinConsole::new(io::stdout()).ok().map(|t| {
        Box::new(t) as Box<StdoutTerminal>
    }))
}

#[cfg(not(windows))]
/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
/// opened.
pub fn stderr() -> Option<Box<StderrTerminal>> {
    TerminfoTerminal::new(io::stderr()).map(|t| {
        Box::new(t) as Box<StderrTerminal>
    })
}

#[cfg(windows)]
/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
/// opened.
pub fn stderr() -> Option<Box<StderrTerminal>> {
    TerminfoTerminal::new(io::stderr()).map(|t| {
        Box::new(t) as Box<StderrTerminal>
    }).or_else(|| WinConsole::new(io::stderr()).ok().map(|t| {
        Box::new(t) as Box<StderrTerminal>
    }))
}

/// Terminal color definitions
#[allow(missing_docs)]
pub mod color {
    /// Number for a terminal color
    pub type Color = u16;

    pub const BLACK:   Color = 0;
    pub const RED:     Color = 1;
    pub const GREEN:   Color = 2;
    pub const YELLOW:  Color = 3;
    pub const BLUE:    Color = 4;
    pub const MAGENTA: Color = 5;
    pub const CYAN:    Color = 6;
    pub const WHITE:   Color = 7;

    pub const BRIGHT_BLACK:   Color = 8;
    pub const BRIGHT_RED:     Color = 9;
    pub const BRIGHT_GREEN:   Color = 10;
    pub const BRIGHT_YELLOW:  Color = 11;
    pub const BRIGHT_BLUE:    Color = 12;
    pub const BRIGHT_MAGENTA: Color = 13;
    pub const BRIGHT_CYAN:    Color = 14;
    pub const BRIGHT_WHITE:   Color = 15;
}

/// Terminal attributes for use with term.attr().
///
/// Most attributes can only be turned on and must be turned off with term.reset().
/// The ones that can be turned off explicitly take a boolean value.
/// Color is also represented as an attribute for convenience.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Attr {
    /// Bold (or possibly bright) mode
    Bold,
    /// Dim mode, also called faint or half-bright. Often not supported
    Dim,
    /// Italics mode. Often not supported
    Italic(bool),
    /// Underline mode
    Underline(bool),
    /// Blink mode
    Blink,
    /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
    Standout(bool),
    /// Reverse mode, inverts the foreground and background colors
    Reverse,
    /// Secure mode, also called invis mode. Hides the printed text
    Secure,
    /// Convenience attribute to set the foreground color
    ForegroundColor(color::Color),
    /// Convenience attribute to set the background color
    BackgroundColor(color::Color)
}

/// A terminal with similar capabilities to an ANSI Terminal
/// (foreground/background colors etc).
pub trait Terminal: Write {
    /// The terminal's output writer type.
    type Output: Write;

    /// Sets the foreground color to the given color.
    ///
    /// If the color is a bright color, but the terminal only supports 8 colors,
    /// the corresponding normal color will be used instead.
    ///
    /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn fg(&mut self, color: color::Color) -> io::Result<bool>;

    /// Sets the background color to the given color.
    ///
    /// If the color is a bright color, but the terminal only supports 8 colors,
    /// the corresponding normal color will be used instead.
    ///
    /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn bg(&mut self, color: color::Color) -> io::Result<bool>;

    /// Sets the given terminal attribute, if supported.  Returns `Ok(true)`
    /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
    /// there was an I/O error.
    fn attr(&mut self, attr: Attr) -> io::Result<bool>;

    /// Returns whether the given terminal attribute is supported.
    fn supports_attr(&self, attr: Attr) -> bool;

    /// Resets all terminal attributes and color to the default.
    ///
    /// Returns `Ok(true)` if the terminal was reset, `Ok(false)` otherwise, and `Err(e)` if there
    /// was an I/O error.
    fn reset(&mut self) -> io::Result<bool>;

    /// Moves the cursor up one line.
    ///
    /// Returns `Ok(true)` if the cursor was moved, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn cursor_up(&mut self) -> io::Result<bool>;

    /// Deletes the text from the cursor location to the end of the line.
    ///
    /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn delete_line(&mut self) -> io::Result<bool>;

    /// Moves the cursor to the left edge of the current line.
    ///
    /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn carriage_return(&mut self) -> io::Result<bool>;

    /// Gets an immutable reference to the stream inside
    fn get_ref<'a>(&'a self) -> &'a Self::Output;

    /// Gets a mutable reference to the stream inside
    fn get_mut<'a>(&'a mut self) -> &'a mut Self::Output;

    /// Returns the contained stream, destroying the `Terminal`
    fn into_inner(self) -> Self::Output where Self: Sized;
}
<commit_msg>Remove some unneeded disambiguation in the doc examples<commit_after>// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Terminal formatting library.
//!
//! This crate provides the `Terminal` trait, which abstracts over an [ANSI
//! Terminal][ansi] to provide color printing, among other things. There are two
//! implementations, the `TerminfoTerminal`, which uses control characters from
//! a [terminfo][ti] database, and `WinConsole`, which uses the [Win32 Console
//! API][win].
//!
//! # Usage
//!
//! This crate is [on crates.io](https://crates.io/crates/term) and can be
//! used by adding `term` to the dependencies in your project's `Cargo.toml`.
//!
//! ```toml
//! [dependencies]
//!
//! term = "0.2"
//! ```
//!
//! and this to your crate root:
//!
//! ```rust
//! extern crate term;
//! ```
//!
//! # Examples
//!
//! ```no_run
//! extern crate term;
//! use std::io::prelude::*;
//!
//! fn main() {
//!     let mut t = term::stdout().unwrap();
//!
//!     t.fg(term::color::GREEN).unwrap();
//!     write!(t, "hello, ").unwrap();
//!
//!     t.fg(term::color::RED).unwrap();
//!     writeln!(t, "world!").unwrap();
//!
//!     assert!(t.reset().unwrap());
//! }
//! ```
//!
//! [ansi]: https://en.wikipedia.org/wiki/ANSI_escape_code
//! [win]: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682010%28v=vs.85%29.aspx
//! [ti]: https://en.wikipedia.org/wiki/Terminfo

#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
       html_root_url = "http://doc.rust-lang.org/nightly/",
       html_playground_url = "http://play.rust-lang.org/")]
#![deny(missing_docs)]
#![cfg_attr(test, deny(warnings))]
#![cfg_attr(rust_build, feature(staged_api))]
#![cfg_attr(rust_build, staged_api)]
#![cfg_attr(rust_build,
            unstable(feature = "rustc_private",
                     reason = "use the crates.io `term` library instead"))]

use std::io::prelude::*;

pub use terminfo::TerminfoTerminal;
#[cfg(windows)]
pub use win::WinConsole;

use std::io::{self, Stdout, Stderr};

pub mod terminfo;

#[cfg(windows)]
mod win;

/// Alias for stdout terminals.
pub type StdoutTerminal = Terminal<Output=Stdout> + Send;
/// Alias for stderr terminals.
pub type StderrTerminal = Terminal<Output=Stderr> + Send;

#[cfg(not(windows))]
/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
/// opened.
pub fn stdout() -> Option<Box<StdoutTerminal>> {
    TerminfoTerminal::new(io::stdout()).map(|t| {
        Box::new(t) as Box<StdoutTerminal>
    })
}

#[cfg(windows)]
/// Return a Terminal wrapping stdout, or None if a terminal couldn't be
/// opened.
pub fn stdout() -> Option<Box<StdoutTerminal>> {
    TerminfoTerminal::new(io::stdout()).map(|t| {
        Box::new(t) as Box<StdoutTerminal>
    }).or_else(|| WinConsole::new(io::stdout()).ok().map(|t| {
        Box::new(t) as Box<StdoutTerminal>
    }))
}

#[cfg(not(windows))]
/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
/// opened.
pub fn stderr() -> Option<Box<StderrTerminal>> {
    TerminfoTerminal::new(io::stderr()).map(|t| {
        Box::new(t) as Box<StderrTerminal>
    })
}

#[cfg(windows)]
/// Return a Terminal wrapping stderr, or None if a terminal couldn't be
/// opened.
pub fn stderr() -> Option<Box<StderrTerminal>> {
    TerminfoTerminal::new(io::stderr()).map(|t| {
        Box::new(t) as Box<StderrTerminal>
    }).or_else(|| WinConsole::new(io::stderr()).ok().map(|t| {
        Box::new(t) as Box<StderrTerminal>
    }))
}

/// Terminal color definitions
#[allow(missing_docs)]
pub mod color {
    /// Number for a terminal color
    pub type Color = u16;

    pub const BLACK:   Color = 0;
    pub const RED:     Color = 1;
    pub const GREEN:   Color = 2;
    pub const YELLOW:  Color = 3;
    pub const BLUE:    Color = 4;
    pub const MAGENTA: Color = 5;
    pub const CYAN:    Color = 6;
    pub const WHITE:   Color = 7;

    pub const BRIGHT_BLACK:   Color = 8;
    pub const BRIGHT_RED:     Color = 9;
    pub const BRIGHT_GREEN:   Color = 10;
    pub const BRIGHT_YELLOW:  Color = 11;
    pub const BRIGHT_BLUE:    Color = 12;
    pub const BRIGHT_MAGENTA: Color = 13;
    pub const BRIGHT_CYAN:    Color = 14;
    pub const BRIGHT_WHITE:   Color = 15;
}

/// Terminal attributes for use with term.attr().
///
/// Most attributes can only be turned on and must be turned off with term.reset().
/// The ones that can be turned off explicitly take a boolean value.
/// Color is also represented as an attribute for convenience.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Attr {
    /// Bold (or possibly bright) mode
    Bold,
    /// Dim mode, also called faint or half-bright. Often not supported
    Dim,
    /// Italics mode. Often not supported
    Italic(bool),
    /// Underline mode
    Underline(bool),
    /// Blink mode
    Blink,
    /// Standout mode. Often implemented as Reverse, sometimes coupled with Bold
    Standout(bool),
    /// Reverse mode, inverts the foreground and background colors
    Reverse,
    /// Secure mode, also called invis mode. Hides the printed text
    Secure,
    /// Convenience attribute to set the foreground color
    ForegroundColor(color::Color),
    /// Convenience attribute to set the background color
    BackgroundColor(color::Color)
}

/// A terminal with similar capabilities to an ANSI Terminal
/// (foreground/background colors etc).
pub trait Terminal: Write {
    /// The terminal's output writer type.
    type Output: Write;

    /// Sets the foreground color to the given color.
    ///
    /// If the color is a bright color, but the terminal only supports 8 colors,
    /// the corresponding normal color will be used instead.
    ///
    /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn fg(&mut self, color: color::Color) -> io::Result<bool>;

    /// Sets the background color to the given color.
    ///
    /// If the color is a bright color, but the terminal only supports 8 colors,
    /// the corresponding normal color will be used instead.
    ///
    /// Returns `Ok(true)` if the color was set, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn bg(&mut self, color: color::Color) -> io::Result<bool>;

    /// Sets the given terminal attribute, if supported.  Returns `Ok(true)`
    /// if the attribute was supported, `Ok(false)` otherwise, and `Err(e)` if
    /// there was an I/O error.
    fn attr(&mut self, attr: Attr) -> io::Result<bool>;

    /// Returns whether the given terminal attribute is supported.
    fn supports_attr(&self, attr: Attr) -> bool;

    /// Resets all terminal attributes and color to the default.
    ///
    /// Returns `Ok(true)` if the terminal was reset, `Ok(false)` otherwise, and `Err(e)` if there
    /// was an I/O error.
    fn reset(&mut self) -> io::Result<bool>;

    /// Moves the cursor up one line.
    ///
    /// Returns `Ok(true)` if the cursor was moved, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn cursor_up(&mut self) -> io::Result<bool>;

    /// Deletes the text from the cursor location to the end of the line.
    ///
    /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn delete_line(&mut self) -> io::Result<bool>;

    /// Moves the cursor to the left edge of the current line.
    ///
    /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)`
    /// if there was an I/O error.
    fn carriage_return(&mut self) -> io::Result<bool>;

    /// Gets an immutable reference to the stream inside
    fn get_ref<'a>(&'a self) -> &'a Self::Output;

    /// Gets a mutable reference to the stream inside
    fn get_mut<'a>(&'a mut self) -> &'a mut Self::Output;

    /// Returns the contained stream, destroying the `Terminal`
    fn into_inner(self) -> Self::Output where Self: Sized;
}
<|endoftext|>


<commit_before>#![feature(macro_rules)]
use std::collections::{HashMap, TreeMap, VecMap, TrieMap};
use std::hash::Hash;

/// Conversion from an `Iterator` of pairs.
pub trait Groupable<K, V> {
    /// Loops through the entire iterator, grouping all keys into a container
    /// implementing `FromKeyedIterator` with a container of values per key.
    /// The values will be aggregated per key into a container implementing
    /// `Extendable` for the value type.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::collections::HashMap;
    /// use groupable::Groupable;
    ///
    /// let evens = range(0u, 10).map(|i| (i % 2 == 0, i))
    ///                         .group::<HashMap<bool, Vec<uint>>>();
    ///
    /// assert_eq!(evens[true].as_slice(), [0, 2, 4, 6, 8].as_slice());
    /// assert_eq!(evens[false].as_slice(), [1, 3, 5, 7, 9].as_slice());
    /// ```
    fn group<B: FromKeyedIterator<K, V>>(&mut self) -> B;
}

impl<K, V, I: Iterator<(K, V)>> Groupable<K, V> for I {
    fn group<B: FromKeyedIterator<K, V>>(&mut self) -> B {
        FromKeyedIterator::from_keyed_iter(self.by_ref())
    }
}

/// Conversion from an `Iterator` of key-value pairs.
pub trait FromKeyedIterator<K, V> {
    /// Build a container with groups of elements from an external iterator.
    fn from_keyed_iter<I: Iterator<(K, V)>>(I) -> Self;
}

#[inline(always)]
fn group_into<K,
              V,
              U: Extendable<V>,
              I: Iterator<(K, V)>,
              M: MutableMap<K, U>>(mut iter: I, map: &mut M) {
    for (key, val) in iter {
        let val_iter = Some(val).into_iter();
        match map.find_mut(&key) {
            Some(collection) => {
                collection.extend(val_iter);
                continue
            },
            None => {} // insert below
        }

        map.insert(key, FromIterator::from_iter(val_iter));
    }
}

macro_rules! impl_keyed_iter (
    ($name:ident: $($bounds:ident),+) => (
        impl <K: $($bounds+)+, V, U: Extendable<V>> FromKeyedIterator<K, V> for $name<K, U> {
            fn from_keyed_iter<T: Iterator<(K, V)>>(iter: T) -> $name<K, U> {
                let mut map = $name::<K, U>::new();
                group_into(iter, &mut map);
                map
            }
        }
    )
)

macro_rules! impl_uint_keyed_iter (
    ($name:ident) => (
        impl <V, U: Extendable<V>> FromKeyedIterator<uint, V> for $name<U> {
            fn from_keyed_iter<T: Iterator<(uint, V)>>(iter: T) -> $name<U> {
                let mut map = $name::<U>::new();
                group_into(iter, &mut map);
                map
            }
        }
    )
)

impl_keyed_iter!(HashMap: Ord, Hash)
impl_keyed_iter!(TreeMap: Ord)
impl_uint_keyed_iter!(VecMap)
impl_uint_keyed_iter!(TrieMap)
<commit_msg>Use a macro as MutableMap no longer exists<commit_after>#![feature(macro_rules)]
use std::collections::{HashMap, TreeMap, VecMap, TrieMap};
use std::hash::Hash;

/// Conversion from an `Iterator` of pairs.
pub trait Groupable<K, V> {
    /// Loops through the entire iterator, grouping all keys into a container
    /// implementing `FromKeyedIterator` with a container of values per key.
    /// The values will be aggregated per key into a container implementing
    /// `Extendable` for the value type.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::collections::HashMap;
    /// use groupable::Groupable;
    ///
    /// let evens = range(0u, 10).map(|i| (i % 2 == 0, i))
    ///                         .group::<HashMap<bool, Vec<uint>>>();
    ///
    /// assert_eq!(evens[true].as_slice(), [0, 2, 4, 6, 8].as_slice());
    /// assert_eq!(evens[false].as_slice(), [1, 3, 5, 7, 9].as_slice());
    /// ```
    fn group<B: FromKeyedIterator<K, V>>(&mut self) -> B;
}

impl<K, V, I: Iterator<(K, V)>> Groupable<K, V> for I {
    fn group<B: FromKeyedIterator<K, V>>(&mut self) -> B {
        FromKeyedIterator::from_keyed_iter(self.by_ref())
    }
}

/// Conversion from an `Iterator` of key-value pairs.
pub trait FromKeyedIterator<K, V> {
    /// Build a container with groups of elements from an external iterator.
    fn from_keyed_iter<I: Iterator<(K, V)>>(I) -> Self;
}

macro_rules! group_into(
    ($iter:ident, $map:ident) => (
        for (key, val) in $iter {
            let val_iter = Some(val).into_iter();
            match $map.find_mut(&key) {
                Some(collection) => {
                    collection.extend(val_iter);
                    continue
                },
                None => {} // insert below
            }

            $map.insert(key, FromIterator::from_iter(val_iter));
        }
    )
)

macro_rules! impl_keyed_iter (
    ($name:ident: $($bounds:ident),+) => (
        impl <K: $($bounds+)+, V, U: Extendable<V>> FromKeyedIterator<K, V> for $name<K, U> {
            fn from_keyed_iter<T: Iterator<(K, V)>>(mut iter: T) -> $name<K, U> {
                let mut map = $name::<K, U>::new();
                group_into!(iter, map);
                map
            }
        }
    )
)

macro_rules! impl_uint_keyed_iter (
    ($name:ident) => (
        impl <V, U: Extendable<V>> FromKeyedIterator<uint, V> for $name<U> {
            fn from_keyed_iter<T: Iterator<(uint, V)>>(mut iter: T) -> $name<U> {
                let mut map = $name::<U>::new();
                group_into!(iter, map)
                map
            }
        }
    )
)

impl_keyed_iter!(HashMap: Ord, Hash)
impl_keyed_iter!(TreeMap: Ord)
impl_uint_keyed_iter!(VecMap)
impl_uint_keyed_iter!(TrieMap)
<|endoftext|>


<commit_before>//! A skiplist is a way of storing sorted elements in such a way that they can
//! be accessed, inserted and removed, all in `O(log(n))` on average.
//!
//! Conceptually, a skiplist is arranged as follows:
//!
//! ```text
//! <head> ----------> [2] --------------------------------------------------> [9] ---------->
//! <head> ----------> [2] ------------------------------------[7] ----------> [9] ---------->
//! <head> ----------> [2] ----------> [4] ------------------> [7] ----------> [9] --> [10] ->
//! <head> --> [1] --> [2] --> [3] --> [4] --> [5] --> [6] --> [7] --> [8] --> [9] --> [10] ->
//! ```
//!
//! Each node contains at the very least a link to the next element in the list
//! (corresponding to the lowest level in the above diagram), but it can
//! randomly contain more links which skip further down the list (the *towers*
//! in the above diagram).  This allows for the algorithm to move down the list
//! faster than having to visit every element.
//!
//! Conceptually, the skiplist can be thought of as a stack of linked lists.  At
//! the very bottom is the full linked list with every element, and each layer
//! above corresponds to a linked list containing a random subset of the
//! elements from the layer immediately below it.  The probability distribution
//! that determines this random subset can be customized, but typically a layer
//! will contain half the nodes from the layer below.
//!
//! # Safety
//!
//! The ordered skiplist relies on a well-behaved comparison function.
//! Specifically, given some ordering function `f(a, b)`, it **must** satisfy
//! the following properties:
//!
//! - Be well defined: `f(a, b)` should always return the same value
//! - Be anti-symmetric: `f(a, b) == Greater` if and only if `f(b, a) == Less`,
//!   and `f(a, b) == Equal == f(b, a)`.
//! - By transitive: If `f(a, b) == Greater` and `f(b, c) == Greater` then `f(a,
//!   c) == Greater`.
//!
//! **Failure to satisfy these properties can result in unexpected behavior at
//! best, and at worst will cause a segfault, null deref, or some other bad
//! behavior.**

// In this library, the notion of 'height' of a node refers to how many links a
// node has (as a result, the minimum height is 1).  The 'levels' refer to the
// layers in the above diagram, with level 0 being the bottom-most layer, level
// 1 being the one above level 0, etc.

extern crate rand;
pub mod level_generator;
pub mod ordered_skiplist;
pub mod skiplist;
pub mod skipmap;
mod skipnode;

pub use crate::ordered_skiplist::OrderedSkipList;
pub use crate::skiplist::SkipList;
pub use crate::skipmap::SkipMap;
<commit_msg>Disable mods<commit_after>//! A skiplist is a way of storing sorted elements in such a way that they can
//! be accessed, inserted and removed, all in `O(log(n))` on average.
//!
//! Conceptually, a skiplist is arranged as follows:
//!
//! ```text
//! <head> ----------> [2] --------------------------------------------------> [9] ---------->
//! <head> ----------> [2] ------------------------------------[7] ----------> [9] ---------->
//! <head> ----------> [2] ----------> [4] ------------------> [7] ----------> [9] --> [10] ->
//! <head> --> [1] --> [2] --> [3] --> [4] --> [5] --> [6] --> [7] --> [8] --> [9] --> [10] ->
//! ```
//!
//! Each node contains at the very least a link to the next element in the list
//! (corresponding to the lowest level in the above diagram), but it can
//! randomly contain more links which skip further down the list (the *towers*
//! in the above diagram).  This allows for the algorithm to move down the list
//! faster than having to visit every element.
//!
//! Conceptually, the skiplist can be thought of as a stack of linked lists.  At
//! the very bottom is the full linked list with every element, and each layer
//! above corresponds to a linked list containing a random subset of the
//! elements from the layer immediately below it.  The probability distribution
//! that determines this random subset can be customized, but typically a layer
//! will contain half the nodes from the layer below.
//!
//! # Safety
//!
//! The ordered skiplist relies on a well-behaved comparison function.
//! Specifically, given some ordering function `f(a, b)`, it **must** satisfy
//! the following properties:
//!
//! - Be well defined: `f(a, b)` should always return the same value
//! - Be anti-symmetric: `f(a, b) == Greater` if and only if `f(b, a) == Less`,
//!   and `f(a, b) == Equal == f(b, a)`.
//! - By transitive: If `f(a, b) == Greater` and `f(b, c) == Greater` then `f(a,
//!   c) == Greater`.
//!
//! **Failure to satisfy these properties can result in unexpected behavior at
//! best, and at worst will cause a segfault, null deref, or some other bad
//! behavior.**

// In this library, the notion of 'height' of a node refers to how many links a
// node has (as a result, the minimum height is 1).  The 'levels' refer to the
// layers in the above diagram, with level 0 being the bottom-most layer, level
// 1 being the one above level 0, etc.

extern crate rand;
pub mod level_generator;
#[cfg(not(unix))]
pub mod ordered_skiplist;
pub mod skiplist;
#[cfg(not(unix))]
pub mod skipmap;
mod skipnode;

#[cfg(not(unix))]
pub use crate::ordered_skiplist::OrderedSkipList;
pub use crate::skiplist::SkipList;
#[cfg(not(unix))]
pub use crate::skipmap::SkipMap;
<|endoftext|>


<commit_before>#![cfg_attr(test, feature(plugin))]
#![cfg_attr(test, plugin(quickcheck_macros))]

extern crate num;

#[cfg(test)] extern crate quickcheck;

use num::{Float, Num, NumCast, Zero, cast};
use std::f64::consts::PI;
use std::fmt::{Display, Formatter, Error};
use std::ops::{Add, Div, Mul, Neg, Sub};

/// An angle.
///
/// Might be a value in degrees or in radians.
#[derive(Copy, Clone, Debug)]
pub enum Angle<T=f64> {
    Radians(T),
    Degrees(T)
}

impl<T: NumCast> Angle<T> {
    /// Yield the value encoded in radians.
    pub fn in_radians(self) -> T {
        match self {
            Radians(v) => v,
            Degrees(v) => cast(cast::<T, f64>(v).unwrap() / 180.0 * PI).unwrap()
        }
    }

    /// Yield the value encoded in degrees.
    pub fn in_degrees(self) -> T {
        match self {
            Radians(v) => cast(cast::<T, f64>(v).unwrap() / PI * 180.0).unwrap(),
            Degrees(v) => v
        }
    }
}

impl<T: Copy + Num + NumCast + PartialOrd> Angle<T> {
    /// Create a new angle by normalizing the value into the range of
    /// [0, 2π) rad.
    pub fn normalized(self) -> Angle<T> {
        let (v, upper) = match self {
            Radians(v) => (v, cast(2.0 * PI).unwrap()),
            Degrees(v) => (v, cast(360.0).unwrap())
        };

        let normalized = if v < upper && v >= Zero::zero() {
            v
        } else {
            let v = v % upper;

            if v >= Zero::zero() {
                v
            } else {
                v + upper
            }
        };

        match self {
            Radians(_) => Radians(normalized),
            Degrees(_) => Degrees(normalized)
        }
    }
}

impl<T: Float + NumCast> Angle<T> {
    /// Compute the sine of the angle.
    pub fn sin(self) -> T {
        self.in_radians().sin()
    }

    /// Compute the cosine of the angle.
    pub fn cos(self) -> T {
        self.in_radians().cos()
    }

    /// Compute the tangent of the angle.
    pub fn tan(self) -> T {
        self.in_radians().tan()
    }

    /// Simultaneously compute the sine and cosine of the number, `x`.
    /// Return `(sin(x), cos(x))`.
    pub fn sin_cos(self) -> (T, T) {
        self.in_radians().sin_cos()
    }

    /*
    /// Computes the approximate mean of a set of angles by averaging the
    /// Cartesian coordinates of the angles on the unit circle.
    pub fn mean(angles: &[Angle<T>]) -> Angle<T> {
        let mut x: T = Zero::zero();
        let mut y: T = Zero::zero();

        for angle in angles.iter() {
            let radian = angle.as_radian();
            x = x + radian.cos();
            y = y + radian.sin();
        }

        let n = cast(angles.len()).unwrap();
        let a = (y/n).atan2(x/n);

        Radian(a).normalize()
    }

    /// Computes the minimal unsigned distance between two normalized angles.
    pub fn distance(&self, other: Angle<T>) -> Angle<T> {
        // FIXME: Once associated types are implemented fix this nightmares of casts #17841
        let pi: T = cast(f64::consts::PI).unwrap();
        let pi2: T = pi * cast(2.0).unwrap();
        let d = (self.as_radian() - other.as_radian()).abs();
        Radian(pi - ((d % (pi2)) - pi).abs())
    }*/
}

impl<T: Float> Angle<T> {
    /// Compute the arcsine of a number. Return value is in the range of
    /// [-π/2, π/2] rad or `None` if the number is outside the range [-1, 1].
    pub fn asin(value: T) -> Option<Angle<T>> {
        let value = value.asin();
        if value.is_nan() {
            None
        } else {
            Some(Radians(value))
        }
    }

    /// Compute the arccosine of a number. Return value is in the range of
    /// [0, π] rad or `None` if the number is outside the range [-1, 1].
    pub fn acos(value: T) -> Option<Angle<T>> {
        let value = value.acos();
        if value.is_nan() {
            None
        } else {
            Some(Radians(value))
        }
    }

    /// Compute the arctangent of a number. Return value is in the range of
    /// [-π/2, π/2] rad.
    pub fn atan(value: T) -> Angle<T> {
        Radians(value.atan())
    }

    // Computes the four quadrant arctangent of `y` and `x`.
    pub fn atan2(y: T, x: T) -> Angle<T> {
        Radians(y.atan2(x))
    }
}

impl<T: Zero + Copy + NumCast> Zero for Angle<T> {
    fn zero() -> Self {
        Radians(T::zero())
    }

    fn is_zero(&self) -> bool {
        match self {
            &Radians(ref v) => v.is_zero(),
            &Degrees(ref v) => v.is_zero()
        }
    }
}

impl<T: PartialEq + Copy + NumCast> PartialEq for Angle<T> {
    fn eq(&self, other: &Angle<T>) -> bool {
        if let (Degrees(a), Degrees(b)) = (*self, *other) {
            a == b
        } else {
            self.in_radians() == other.in_radians()
        }
    }
}

macro_rules! math_additive(
    ($bound:ident, $func:ident) => (
        impl<T: $bound + Copy + NumCast> $bound for Angle<T> {
            type Output = Angle<T::Output>;
            fn $func(self, rhs: Angle<T>) -> Self::Output {
                if let (Degrees(a), Degrees(b)) = (self, rhs) {
                    Degrees(a.$func(b))
                } else {
                    Radians(self.in_radians().$func(rhs.in_radians()))
                }
            }
        }
    );
);

math_additive!(Add, add);
math_additive!(Sub, sub);

macro_rules! math_multiplicative(
    ($bound:ident, $func:ident, $($t:ident),*) => (
        impl<T: $bound> $bound<T> for Angle<T> {
            type Output = Angle<T::Output>;
            fn $func(self, rhs: T) -> Self::Output {
                match self {
                    Radians(v) => Radians(v.$func(rhs)),
                    Degrees(v) => Degrees(v.$func(rhs))
                }
            }
        }

        $(
            impl $bound<Angle<$t>> for $t {
                type Output = Angle<$t>;
                fn $func(self, rhs: Angle<$t>) -> Self::Output {
                    match rhs {
                        Radians(v) => Radians(self.$func(v)),
                        Degrees(v) => Degrees(self.$func(v))
                    }
                }
            }
        )*
    );
);

math_multiplicative!(Mul, mul, u8, u16, u32, u64, i8, i16, i32, i64, usize, isize, f32, f64);
math_multiplicative!(Div, div, u8, u16, u32, u64, i8, i16, i32, i64, usize, isize, f32, f64);

impl<T: Neg> Neg for Angle<T> {
    type Output = Angle<T::Output>;
    fn neg(self) -> Self::Output {
        match self {
            Radians(v) => Radians(-v),
            Degrees(v) => Degrees(-v)
        }
    }
}

impl<T: Display> Display for Angle<T> {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match *self {
            Radians(ref v) => write!(f, "{}rad", v),
            Degrees(ref v) => write!(f, "{}°", v)
        }
    }
}

unsafe impl<T: Send> Send for Angle<T> {  }

/*
impl<T: Encodable + Float + NumCast> Encodable for Angle<T> {
    fn encode<S: Encoder>(&self,  s: &mut S) -> Result<(), S::Error> {
        self.as_radian().encode(s)
    }
}

impl<T: Decodable + Float + NumCast> Decodable for Angle<T> {
    fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
        let t = try!(T::decode(d));
        Ok(Angle::Radian(t))
    }
}
*/

// re-exports
pub use Angle::{Radians, Degrees};

#[cfg(test)]
mod tests {
    use num::{Float, cast};
    use quickcheck::{Arbitrary, Gen};
    use std::f64::consts::PI;
    use super::{Angle, Radians, Degrees};

    #[quickcheck]
    fn test_angle_conversions(angle: Angle<f64>) -> bool {
        are_close(angle.in_radians(), Degrees(angle.in_degrees()).in_radians())
    }

    #[quickcheck]
    fn test_angle_math_multiplicative(a: Angle<f64>, x: f64) -> bool {
        match a {
            Radians(v) => (a * x).in_radians() == v * x &&
                          (a / x).in_radians() == v / x,
            Degrees(v) => (a * x).in_degrees() == v * x &&
                          (a / x).in_degrees() == v / x
        }
    }

    #[quickcheck]
    fn test_angle_math_additive(a: Angle, b: Angle) -> bool {
        if let (Radians(x), Radians(y)) = (a, b) {
            (a + b).in_radians() == x + y &&
            (a - b).in_radians() == x - y
        } else if let (Degrees(x), Degrees(y)) = (a, b) {
            (a + b).in_degrees() == x + y &&
            (a - b).in_degrees() == x - y
        } else {
            (a + b).in_radians() == a.in_radians() + b.in_radians()
        }
    }

    #[quickcheck]
    fn test_angle_normalization(angle: Angle) -> bool {
        let v = angle.normalized();
        let rad = v.in_radians();
        let deg = v.in_degrees();

        0.0 <= rad && rad < 2.0 * PI &&
        0.0 <= deg && deg < 360.0 &&
        are_close(rad.cos(), angle.cos())
    }

    fn are_close<T: Float>(a: T, b: T) -> bool {
        (a - b).abs() < cast(1.0e-10).unwrap()
    }

    impl<T: Arbitrary> Arbitrary for Angle<T> {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            let v = Arbitrary::arbitrary(g);
            if bool::arbitrary(g) {
                Radians(v)
            } else {
                Degrees(v)
            }
        }
    }
}
<commit_msg>Implement Angle::abs()<commit_after>#![cfg_attr(test, feature(plugin))]
#![cfg_attr(test, plugin(quickcheck_macros))]

extern crate num;

#[cfg(test)] extern crate quickcheck;

use num::{Float, Num, NumCast, Signed, Zero, cast};
use std::f64::consts::PI;
use std::fmt::{Display, Formatter, Error};
use std::ops::{Add, Div, Mul, Neg, Sub};

/// An angle.
///
/// Might be a value in degrees or in radians.
#[derive(Copy, Clone, Debug)]
pub enum Angle<T=f64> {
    Radians(T),
    Degrees(T)
}

impl<T: NumCast> Angle<T> {
    /// Yield the value encoded in radians.
    pub fn in_radians(self) -> T {
        match self {
            Radians(v) => v,
            Degrees(v) => cast(cast::<T, f64>(v).unwrap() / 180.0 * PI).unwrap()
        }
    }

    /// Yield the value encoded in degrees.
    pub fn in_degrees(self) -> T {
        match self {
            Radians(v) => cast(cast::<T, f64>(v).unwrap() / PI * 180.0).unwrap(),
            Degrees(v) => v
        }
    }
}

impl<T: Copy + Num + NumCast + PartialOrd> Angle<T> {
    /// Create a new angle by normalizing the value into the range of
    /// [0, 2π) rad.
    pub fn normalized(self) -> Angle<T> {
        let (v, upper) = match self {
            Radians(v) => (v, cast(2.0 * PI).unwrap()),
            Degrees(v) => (v, cast(360.0).unwrap())
        };

        let normalized = if v < upper && v >= Zero::zero() {
            v
        } else {
            let v = v % upper;

            if v >= Zero::zero() {
                v
            } else {
                v + upper
            }
        };

        match self {
            Radians(_) => Radians(normalized),
            Degrees(_) => Degrees(normalized)
        }
    }
}

impl<T: Signed> Angle<T> {
    /// Compute the absolute angle.
    pub fn abs(self) -> Angle<T> {
        match self {
            Radians(v) => Radians(v.abs()),
            Degrees(v) => Degrees(v.abs())
        }
    }
}

impl<T: Float + NumCast> Angle<T> {
    /// Compute the sine of the angle.
    pub fn sin(self) -> T {
        self.in_radians().sin()
    }

    /// Compute the cosine of the angle.
    pub fn cos(self) -> T {
        self.in_radians().cos()
    }

    /// Compute the tangent of the angle.
    pub fn tan(self) -> T {
        self.in_radians().tan()
    }

    /// Simultaneously compute the sine and cosine of the number, `x`.
    /// Return `(sin(x), cos(x))`.
    pub fn sin_cos(self) -> (T, T) {
        self.in_radians().sin_cos()
    }

    /*
    /// Computes the approximate mean of a set of angles by averaging the
    /// Cartesian coordinates of the angles on the unit circle.
    pub fn mean(angles: &[Angle<T>]) -> Angle<T> {
        let mut x: T = Zero::zero();
        let mut y: T = Zero::zero();

        for angle in angles.iter() {
            let radian = angle.as_radian();
            x = x + radian.cos();
            y = y + radian.sin();
        }

        let n = cast(angles.len()).unwrap();
        let a = (y/n).atan2(x/n);

        Radian(a).normalize()
    }

    /// Computes the minimal unsigned distance between two normalized angles.
    pub fn distance(&self, other: Angle<T>) -> Angle<T> {
        // FIXME: Once associated types are implemented fix this nightmares of casts #17841
        let pi: T = cast(f64::consts::PI).unwrap();
        let pi2: T = pi * cast(2.0).unwrap();
        let d = (self.as_radian() - other.as_radian()).abs();
        Radian(pi - ((d % (pi2)) - pi).abs())
    }*/
}

impl<T: Float> Angle<T> {
    /// Compute the arcsine of a number. Return value is in the range of
    /// [-π/2, π/2] rad or `None` if the number is outside the range [-1, 1].
    pub fn asin(value: T) -> Option<Angle<T>> {
        let value = value.asin();
        if value.is_nan() {
            None
        } else {
            Some(Radians(value))
        }
    }

    /// Compute the arccosine of a number. Return value is in the range of
    /// [0, π] rad or `None` if the number is outside the range [-1, 1].
    pub fn acos(value: T) -> Option<Angle<T>> {
        let value = value.acos();
        if value.is_nan() {
            None
        } else {
            Some(Radians(value))
        }
    }

    /// Compute the arctangent of a number. Return value is in the range of
    /// [-π/2, π/2] rad.
    pub fn atan(value: T) -> Angle<T> {
        Radians(value.atan())
    }

    // Computes the four quadrant arctangent of `y` and `x`.
    pub fn atan2(y: T, x: T) -> Angle<T> {
        Radians(y.atan2(x))
    }
}

impl<T: Zero + Copy + NumCast> Zero for Angle<T> {
    fn zero() -> Self {
        Radians(T::zero())
    }

    fn is_zero(&self) -> bool {
        match self {
            &Radians(ref v) => v.is_zero(),
            &Degrees(ref v) => v.is_zero()
        }
    }
}

impl<T: PartialEq + Copy + NumCast> PartialEq for Angle<T> {
    fn eq(&self, other: &Angle<T>) -> bool {
        if let (Degrees(a), Degrees(b)) = (*self, *other) {
            a == b
        } else {
            self.in_radians() == other.in_radians()
        }
    }
}

macro_rules! math_additive(
    ($bound:ident, $func:ident) => (
        impl<T: $bound + Copy + NumCast> $bound for Angle<T> {
            type Output = Angle<T::Output>;
            fn $func(self, rhs: Angle<T>) -> Self::Output {
                if let (Degrees(a), Degrees(b)) = (self, rhs) {
                    Degrees(a.$func(b))
                } else {
                    Radians(self.in_radians().$func(rhs.in_radians()))
                }
            }
        }
    );
);

math_additive!(Add, add);
math_additive!(Sub, sub);

macro_rules! math_multiplicative(
    ($bound:ident, $func:ident, $($t:ident),*) => (
        impl<T: $bound> $bound<T> for Angle<T> {
            type Output = Angle<T::Output>;
            fn $func(self, rhs: T) -> Self::Output {
                match self {
                    Radians(v) => Radians(v.$func(rhs)),
                    Degrees(v) => Degrees(v.$func(rhs))
                }
            }
        }

        $(
            impl $bound<Angle<$t>> for $t {
                type Output = Angle<$t>;
                fn $func(self, rhs: Angle<$t>) -> Self::Output {
                    match rhs {
                        Radians(v) => Radians(self.$func(v)),
                        Degrees(v) => Degrees(self.$func(v))
                    }
                }
            }
        )*
    );
);

math_multiplicative!(Mul, mul, u8, u16, u32, u64, i8, i16, i32, i64, usize, isize, f32, f64);
math_multiplicative!(Div, div, u8, u16, u32, u64, i8, i16, i32, i64, usize, isize, f32, f64);

impl<T: Neg> Neg for Angle<T> {
    type Output = Angle<T::Output>;
    fn neg(self) -> Self::Output {
        match self {
            Radians(v) => Radians(-v),
            Degrees(v) => Degrees(-v)
        }
    }
}

impl<T: Display> Display for Angle<T> {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        match *self {
            Radians(ref v) => write!(f, "{}rad", v),
            Degrees(ref v) => write!(f, "{}°", v)
        }
    }
}

unsafe impl<T: Send> Send for Angle<T> {  }

/*
impl<T: Encodable + Float + NumCast> Encodable for Angle<T> {
    fn encode<S: Encoder>(&self,  s: &mut S) -> Result<(), S::Error> {
        self.as_radian().encode(s)
    }
}

impl<T: Decodable + Float + NumCast> Decodable for Angle<T> {
    fn decode<D: Decoder>(d: &mut D) -> Result<Self, D::Error> {
        let t = try!(T::decode(d));
        Ok(Angle::Radian(t))
    }
}
*/

// re-exports
pub use Angle::{Radians, Degrees};

#[cfg(test)]
mod tests {
    use num::{Float, cast};
    use quickcheck::{Arbitrary, Gen};
    use std::f64::consts::PI;
    use super::{Angle, Radians, Degrees};

    #[quickcheck]
    fn test_angle_conversions(angle: Angle<f64>) -> bool {
        are_close(angle.in_radians(), Degrees(angle.in_degrees()).in_radians())
    }

    #[quickcheck]
    fn test_angle_math_multiplicative(a: Angle<f64>, x: f64) -> bool {
        match a {
            Radians(v) => (a * x).in_radians() == v * x &&
                          (a / x).in_radians() == v / x,
            Degrees(v) => (a * x).in_degrees() == v * x &&
                          (a / x).in_degrees() == v / x
        }
    }

    #[quickcheck]
    fn test_angle_math_additive(a: Angle, b: Angle) -> bool {
        if let (Radians(x), Radians(y)) = (a, b) {
            (a + b).in_radians() == x + y &&
            (a - b).in_radians() == x - y
        } else if let (Degrees(x), Degrees(y)) = (a, b) {
            (a + b).in_degrees() == x + y &&
            (a - b).in_degrees() == x - y
        } else {
            (a + b).in_radians() == a.in_radians() + b.in_radians()
        }
    }

    #[quickcheck]
    fn test_angle_normalization(angle: Angle) -> bool {
        let v = angle.normalized();
        let rad = v.in_radians();
        let deg = v.in_degrees();

        0.0 <= rad && rad < 2.0 * PI &&
        0.0 <= deg && deg < 360.0 &&
        are_close(rad.cos(), angle.cos())
    }

    fn are_close<T: Float>(a: T, b: T) -> bool {
        (a - b).abs() < cast(1.0e-10).unwrap()
    }

    impl<T: Arbitrary> Arbitrary for Angle<T> {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            let v = Arbitrary::arbitrary(g);
            if bool::arbitrary(g) {
                Radians(v)
            } else {
                Degrees(v)
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2017 Amos Onn.
//
// 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.
//! Wrapper around fuse-mt providing extra functionality for ease of implementation: `open` and
//! `opendir` methods now return a `FileLike` and `DirLike` object (respectively), which is then
//! passed to `read`, etc. calls (instead of a `fh: u64`).
#![deny(missing_docs,
        missing_debug_implementations, missing_copy_implementations,
        unstable_features,
        unused_import_braces, unused_qualifications)]

extern crate fuse_mt;
extern crate libc;
extern crate time;

mod fusefl;
mod handler_table;
pub mod filelike;

pub use fusefl::{
    CreatedEntryObj,
    ResultOpenObj,
    ResultCreateObj,
    FilesystemFL,
    FuseFL,
};
pub use fuse_mt::{
    RequestInfo,
    DirectoryEntry,
    Statfs,
    Xattr,
    ResultEmpty,
    ResultGetattr,
    ResultEntry,
    ResultReaddir,
    ResultData,
    ResultWrite,
    ResultStatfs,
    ResultXattr,
    FuseMT,
};

use std::result;
/// All results for fuse calls have `libc::c_int` as the Err variant.
pub type Result<T> = result::Result<T, libc::c_int>;

#[test]
fn it_works() {}
<commit_msg>Added missing pubs in lib from fuse through fuse_mt.<commit_after>// Copyright 2017 Amos Onn.
//
// 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.
//! Wrapper around fuse-mt providing extra functionality for ease of implementation: `open` and
//! `opendir` methods now return a `FileLike` and `DirLike` object (respectively), which is then
//! passed to `read`, etc. calls (instead of a `fh: u64`).
#![deny(missing_docs,
        missing_debug_implementations, missing_copy_implementations,
        unstable_features,
        unused_import_braces, unused_qualifications)]

extern crate fuse_mt;
extern crate libc;
extern crate time;

mod fusefl;
mod handler_table;
pub mod filelike;

pub use fusefl::{
    CreatedEntryObj,
    ResultOpenObj,
    ResultCreateObj,
    FilesystemFL,
    FuseFL,
};
pub use fuse_mt::{
    RequestInfo,
    DirectoryEntry,
    Statfs,
    Xattr,
    ResultEmpty,
    ResultGetattr,
    ResultEntry,
    ResultReaddir,
    ResultData,
    ResultWrite,
    ResultStatfs,
    ResultXattr,
    FuseMT,
    // These come from fuse.
    FileAttr,
    FileType,
    mount,
    spawn_mount,
};

use std::result;
/// All results for fuse calls have `libc::c_int` as the Err variant.
pub type Result<T> = result::Result<T, libc::c_int>;

#[test]
fn it_works() {}
<|endoftext|>


<commit_before>#![feature(box_raw)]

extern crate winapi;
extern crate ws2_32;
extern crate kernel32;
extern crate iocp;
extern crate libc;

use winapi::winsock2::*;
use winapi::ws2def::*;
use winapi::minwinbase::*;

use std::io::prelude::*;
use std::net::TcpStream;

use ws2_32::*;

use std::boxed;

use std::os::raw::{c_ulong,c_void};
use std::ptr::null;

use std::thread;
use std::boxed::Box;
use std::slice;

use std::collections::HashMap;

use std::os::windows::io::AsRawSocket;
use std::sync::{Mutex,Arc};

use std::cell::RefCell;
use std::borrow::Borrow;
use std::ops::Deref;
use std::str;

type CallbackStore<T> = Arc<Mutex<HashMap<usize, ( Box<Fn(T) + Send> , usize)  >>>;

struct AsyncIO {
    iocp:iocp::IoCompletionPort,
    handlers:CallbackStore<&'static [u8]>,
}

impl AsyncIO {

    pub fn new()->Option<Arc<Box<AsyncIO>>> {
        match iocp::IoCompletionPort::new(4)  {
            Ok(iocp) => {
                let mut aio_bare =AsyncIO {
                    iocp:iocp,
                    handlers:Arc::new(Mutex::new(HashMap::new())),
                };
                let mut aio_boxed = Box::new(aio_bare );
                let mut aio = Arc::new(aio_boxed);
                AsyncIO::init(aio.clone());
                return Some(aio);
            },
            Err(err) => {
                print!("Failed to start iocp");
                return None;
            }
        }
    }

    pub fn register(&self,tcp_stream:&TcpStream){
        unsafe { self.iocp.associate(tcp_stream.as_raw_socket() as *mut c_void,0) };
    }

    fn init(aio:Arc<Box<AsyncIO>>){

        thread::spawn(move||{
            println!("aio thread started");
            loop {

                match aio.iocp.get_queued(600000) {

                    Ok(status) => {
                        println!("Result {}",status.overlapped as usize);
                        let overlapped_ptr = status.overlapped as usize;
                        let handlers = aio.handlers.try_lock().unwrap();
                        let handler = handlers.get(&overlapped_ptr).unwrap();

                        let wsa_buf_boxed = unsafe { Box::<WSABUF>::from_raw(handler.1 as *mut winapi::ws2def::WSABUF) };
                        let mut wsa_buf = *wsa_buf_boxed;

                        // just to free it
                        let overlapped = unsafe { Box::<OVERLAPPED>::from_raw(status.overlapped) };

                        let mut buf= unsafe { slice::from_raw_parts(wsa_buf.buf as *mut u8,wsa_buf.len as usize) };
                        handler.0( buf);

                    },
                    Err(err) => {

                        println!("get_queued error {}",err);

                    }

                }

            }

        });

    }

}

trait AsyncRead  {
    fn async_read<F: Fn(&[u8]) + Send +'static >(&self,aio:&AsyncIO,handler:F);
}

impl AsyncRead  for TcpStream {

    fn async_read<F: Fn(&[u8]) + Send +'static >(&self,aio:&AsyncIO,handler:F){

        const BUFFER_SIZE:usize = 4096;

        let mut buf = [0;BUFFER_SIZE];
        let wsa_buf:Box<WSABUF> = Box::new( WSABUF{len:BUFFER_SIZE as u32,buf:buf.as_mut_ptr() as *mut i8 } );
        let lp_wsa_buf: *mut WSABUF = unsafe { Box::into_raw(wsa_buf) };

        let dw_buf_count = 1;
        let bytes_len: *mut u32 = unsafe { Box::into_raw(Box::new(0)) };

        let mut flags = 0;
        let lp_flags:*mut u32 = &mut flags;

        let overlapped = Box::new(OVERLAPPED {
            Internal: 0,
            InternalHigh: 0,
            Offset: 0,
            OffsetHigh: 0,
            hEvent: 0 as *mut c_void,
        });
        let lp_overlapped: *mut OVERLAPPED = unsafe { Box::into_raw(overlapped) };

        let buf_ptr = lp_wsa_buf as usize;

        let null : *mut libc::c_void;
        let err;
        unsafe {
            err = ws2_32::WSARecv(self.as_raw_socket(),lp_wsa_buf, dw_buf_count, bytes_len ,lp_flags, lp_overlapped, None);
        }
        aio.handlers.try_lock().unwrap().insert(lp_overlapped as usize,(Box::new(handler),buf_ptr));
    }

}

#[test]
fn simple_example() {

	let mut stream = TcpStream::connect("127.0.0.1:8124").unwrap();

	let mut aio = AsyncIO::new().unwrap();
	aio.register(&stream);
	stream.async_read(aio.deref(),|buf:&[u8]|{

		let s = match str::from_utf8(buf) {
			Ok(v) => {
				println!("result: {}", v);
				v
			},
			Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
		};

	});

	// this loop is just to prevent closing, too lazey to get a bette solution ;D
    loop {

    }

}<commit_msg>remove AsyncIO box<commit_after>#![feature(box_raw)]

extern crate winapi;
extern crate ws2_32;
extern crate kernel32;
extern crate iocp;
extern crate libc;

use winapi::winsock2::*;
use winapi::ws2def::*;
use winapi::minwinbase::*;

use std::io::prelude::*;
use std::net::TcpStream;

use ws2_32::*;

use std::boxed;

use std::os::raw::{c_ulong,c_void};
use std::ptr::null;

use std::thread;
use std::boxed::Box;
use std::slice;

use std::collections::HashMap;

use std::os::windows::io::AsRawSocket;
use std::sync::{Mutex,Arc};

use std::cell::RefCell;
use std::borrow::Borrow;
use std::ops::Deref;
use std::str;

type CallbackStore<T> = Arc<Mutex<HashMap<usize, ( Box<Fn(T) + Send> , usize)  >>>;

struct AsyncIO {
    iocp:iocp::IoCompletionPort,
    handlers:CallbackStore<&'static [u8]>,
}

impl AsyncIO {

    pub fn new()->Option<Arc<AsyncIO>> {
        match iocp::IoCompletionPort::new(4)  {
            Ok(iocp) => {
                let mut aio_bare =AsyncIO {
                    iocp:iocp,
                    handlers:Arc::new(Mutex::new(HashMap::new())),
                };
                let mut aio = Arc::new(aio_bare);
                AsyncIO::init(aio.clone());
                return Some(aio);
            },
            Err(err) => {
                print!("Failed to start iocp");
                return None;
            }
        }
    }

    pub fn register(&self,tcp_stream:&TcpStream){
        unsafe { self.iocp.associate(tcp_stream.as_raw_socket() as *mut c_void,0) };
    }

    fn init(aio:Arc<AsyncIO>){

        thread::spawn(move||{
            println!("aio thread started");
            loop {

                match aio.iocp.get_queued(600000) {

                    Ok(status) => {
                        println!("Result {}",status.overlapped as usize);
                        let overlapped_ptr = status.overlapped as usize;
                        let handlers = aio.handlers.try_lock().unwrap();
                        let handler = handlers.get(&overlapped_ptr).unwrap();

                        let wsa_buf_boxed = unsafe { Box::<WSABUF>::from_raw(handler.1 as *mut winapi::ws2def::WSABUF) };
                        let mut wsa_buf = *wsa_buf_boxed;

                        // just to free it
                        let overlapped = unsafe { Box::<OVERLAPPED>::from_raw(status.overlapped) };

                        let mut buf= unsafe { slice::from_raw_parts(wsa_buf.buf as *mut u8,wsa_buf.len as usize) };
                        handler.0( buf);

                    },
                    Err(err) => {

                        println!("get_queued error {}",err);

                    }

                }

            }

        });

    }

}

trait AsyncRead  {
    fn async_read<F: Fn(&[u8]) + Send +'static >(&self,aio:&AsyncIO,handler:F);
}

impl AsyncRead  for TcpStream {

    fn async_read<F: Fn(&[u8]) + Send +'static >(&self,aio:&AsyncIO,handler:F){

        const BUFFER_SIZE:usize = 4096;

        let mut buf = [0;BUFFER_SIZE];
        let wsa_buf:Box<WSABUF> = Box::new( WSABUF{len:BUFFER_SIZE as u32,buf:buf.as_mut_ptr() as *mut i8 } );
        let lp_wsa_buf: *mut WSABUF = unsafe { Box::into_raw(wsa_buf) };

        let dw_buf_count = 1;
        let bytes_len: *mut u32 = unsafe { Box::into_raw(Box::new(0)) };

        let mut flags = 0;
        let lp_flags:*mut u32 = &mut flags;

        let overlapped = Box::new(OVERLAPPED {
            Internal: 0,
            InternalHigh: 0,
            Offset: 0,
            OffsetHigh: 0,
            hEvent: 0 as *mut c_void,
        });
        let lp_overlapped: *mut OVERLAPPED = unsafe { Box::into_raw(overlapped) };

        let buf_ptr = lp_wsa_buf as usize;

        let null : *mut libc::c_void;
        let err;
        unsafe {
            err = ws2_32::WSARecv(self.as_raw_socket(),lp_wsa_buf, dw_buf_count, bytes_len ,lp_flags, lp_overlapped, None);
        }
        aio.handlers.try_lock().unwrap().insert(lp_overlapped as usize,(Box::new(handler),buf_ptr));
    }

}

#[test]
fn simple_example() {

	let mut stream = TcpStream::connect("127.0.0.1:8124").unwrap();

	let mut aio = AsyncIO::new().unwrap();
	aio.register(&stream);
	stream.async_read(&aio,|buf:&[u8]|{

		let s = match str::from_utf8(buf) {
			Ok(v) => {
				println!("result: {}", v);
				v
			},
			Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
		};

	});

	// this loop is just to prevent closing, too lazey to get a bette solution ;D
    loop {

    }

}<|endoftext|>


<commit_before>// Copyright (c) 2015 Anders Kaseorg <andersk@mit.edu>

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// “Software”), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//! This crate exports a macro `enum_from_primitive!` that wraps an
//! `enum` declaration and automatically adds an implementation of
//! `num::FromPrimitive` (reexported here), to allow conversion from
//! primitive integers to the enum.  It therefore provides an
//! alternative to the built-in `#[derive(FromPrimitive)]`, which
//! requires the unstable `std::num::FromPrimitive` and is disabled in
//! Rust 1.0.
//!
//! The current implementation requires all variants of the enum to
//! have an explicit discriminator value.  This restriction may be
//! relaxed in future versions.
//!
//! # Example
//!
//! ```
//! #[macro_use] extern crate enum_primitive;
//! extern crate num;
//! use num::FromPrimitive;
//!
//! enum_from_primitive! {
//! #[derive(Debug, PartialEq)]
//! enum FooBar {
//!     Foo = 17,
//!     Bar = 42,
//! }
//! }
//!
//! fn main() {
//!     assert_eq!(FooBar::from_i32(17), Some(FooBar::Foo));
//!     assert_eq!(FooBar::from_i32(42), Some(FooBar::Bar));
//!     assert_eq!(FooBar::from_i32(91), None);
//! }
//! ```

extern crate num;

pub use num::FromPrimitive;

/// Helper macro for internal use by `enum_from_primitive!`.
#[macro_export]
macro_rules! enum_from_primitive_impl_ty {
    ($meth:ident, $ty:ty, $name:ident, $( $variant:ident ),*) => {
        #[allow(non_upper_case_globals)]
        fn $meth(n: $ty) -> ::std::option::Option<Self> {
            $( const $variant: $ty = $name::$variant as $ty; )*
            match n {
                $( $variant => ::std::option::Option::Some($name::$variant), )*
                _ => ::std::option::Option::None,
            }
        }
    }
}

/// Helper macro for internal use by `enum_from_primitive!`.
#[macro_export]
#[macro_use(enum_from_primitive_impl_ty)]
macro_rules! enum_from_primitive_impl {
    ($name:ident, $( $variant:ident ),*) => {
        impl ::num::FromPrimitive for $name {
            enum_from_primitive_impl_ty! { from_i64, i64, $name, $( $variant ),* }
            enum_from_primitive_impl_ty! { from_u64, u64, $name, $( $variant ),* }
        }
    }
}

/// Wrap this macro around an `enum` declaration to get an
/// automatically generated implementation of `num::FromPrimitive`.
#[macro_export]
#[macro_use(enum_from_primitive_impl)]
macro_rules! enum_from_primitive {
    (
        $( #[$enum_attr:meta] )*
        enum $name:ident {
            $( $( #[$variant_attr:meta] )* $variant:ident = $discriminator:expr ),*
        }
    ) => {
        $( #[$enum_attr] )*
        enum $name {
            $( $( #[$variant_attr] )* $variant = $discriminator ),*
        }
        enum_from_primitive_impl! { $name, $($variant),* }
    };

    (
        $( #[$enum_attr:meta] )*
        enum $name:ident {
            $( $( #[$variant_attr:meta] )* $variant:ident = $discriminator:expr ),*,
        }
    ) => {
        enum_from_primitive! {
            $( #[$enum_attr] )*
            enum $name {
                $( $( #[$variant_attr] )* $variant = $discriminator ),*
            }
        }
    };

    (
        $( #[$enum_attr:meta] )*
        pub enum $name:ident {
            $( $( #[$variant_attr:meta] )* $variant:ident = $discriminator:expr ),*
        }
    ) => {
        $( #[$enum_attr] )*
        pub enum $name {
            $( $( #[$variant_attr] )* $variant = $discriminator ),*
        }
        enum_from_primitive_impl! { $name, $( $variant ),* }
    };

    (
        $( #[$enum_attr:meta] )*
        pub enum $name:ident {
            $( $( #[$variant_attr:meta] )* $variant:ident = $discriminator:expr ),*,
        }
    ) => {
        enum_from_primitive! {
            $( #[$enum_attr] )*
            pub enum $name {
                $( $( #[$variant_attr] )* $variant = $discriminator ),*
            }
        }
    };
}
<commit_msg>Use $crate for hygienic references to FromPrimitive and Option<commit_after>// Copyright (c) 2015 Anders Kaseorg <andersk@mit.edu>

// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// “Software”), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//! This crate exports a macro `enum_from_primitive!` that wraps an
//! `enum` declaration and automatically adds an implementation of
//! `num::FromPrimitive` (reexported here), to allow conversion from
//! primitive integers to the enum.  It therefore provides an
//! alternative to the built-in `#[derive(FromPrimitive)]`, which
//! requires the unstable `std::num::FromPrimitive` and is disabled in
//! Rust 1.0.
//!
//! The current implementation requires all variants of the enum to
//! have an explicit discriminator value.  This restriction may be
//! relaxed in future versions.
//!
//! # Example
//!
//! ```
//! #[macro_use] extern crate enum_primitive;
//! extern crate num;
//! use num::FromPrimitive;
//!
//! enum_from_primitive! {
//! #[derive(Debug, PartialEq)]
//! enum FooBar {
//!     Foo = 17,
//!     Bar = 42,
//! }
//! }
//!
//! fn main() {
//!     assert_eq!(FooBar::from_i32(17), Some(FooBar::Foo));
//!     assert_eq!(FooBar::from_i32(42), Some(FooBar::Bar));
//!     assert_eq!(FooBar::from_i32(91), None);
//! }
//! ```

extern crate num;

pub use std::option::Option;
pub use num::FromPrimitive;

/// Helper macro for internal use by `enum_from_primitive!`.
#[macro_export]
macro_rules! enum_from_primitive_impl_ty {
    ($meth:ident, $ty:ty, $name:ident, $( $variant:ident ),*) => {
        #[allow(non_upper_case_globals)]
        fn $meth(n: $ty) -> $crate::Option<Self> {
            $( const $variant: $ty = $name::$variant as $ty; )*
            match n {
                $( $variant => $crate::Option::Some($name::$variant), )*
                _ => $crate::Option::None,
            }
        }
    }
}

/// Helper macro for internal use by `enum_from_primitive!`.
#[macro_export]
#[macro_use(enum_from_primitive_impl_ty)]
macro_rules! enum_from_primitive_impl {
    ($name:ident, $( $variant:ident ),*) => {
        impl $crate::FromPrimitive for $name {
            enum_from_primitive_impl_ty! { from_i64, i64, $name, $( $variant ),* }
            enum_from_primitive_impl_ty! { from_u64, u64, $name, $( $variant ),* }
        }
    }
}

/// Wrap this macro around an `enum` declaration to get an
/// automatically generated implementation of `num::FromPrimitive`.
#[macro_export]
#[macro_use(enum_from_primitive_impl)]
macro_rules! enum_from_primitive {
    (
        $( #[$enum_attr:meta] )*
        enum $name:ident {
            $( $( #[$variant_attr:meta] )* $variant:ident = $discriminator:expr ),*
        }
    ) => {
        $( #[$enum_attr] )*
        enum $name {
            $( $( #[$variant_attr] )* $variant = $discriminator ),*
        }
        enum_from_primitive_impl! { $name, $($variant),* }
    };

    (
        $( #[$enum_attr:meta] )*
        enum $name:ident {
            $( $( #[$variant_attr:meta] )* $variant:ident = $discriminator:expr ),*,
        }
    ) => {
        enum_from_primitive! {
            $( #[$enum_attr] )*
            enum $name {
                $( $( #[$variant_attr] )* $variant = $discriminator ),*
            }
        }
    };

    (
        $( #[$enum_attr:meta] )*
        pub enum $name:ident {
            $( $( #[$variant_attr:meta] )* $variant:ident = $discriminator:expr ),*
        }
    ) => {
        $( #[$enum_attr] )*
        pub enum $name {
            $( $( #[$variant_attr] )* $variant = $discriminator ),*
        }
        enum_from_primitive_impl! { $name, $( $variant ),* }
    };

    (
        $( #[$enum_attr:meta] )*
        pub enum $name:ident {
            $( $( #[$variant_attr:meta] )* $variant:ident = $discriminator:expr ),*,
        }
    ) => {
        enum_from_primitive! {
            $( #[$enum_attr] )*
            pub enum $name {
                $( $( #[$variant_attr] )* $variant = $discriminator ),*
            }
        }
    };
}
<|endoftext|>


<commit_before>#![feature(macro_rules)]
#![allow(unused_imports)]
extern crate serialize;
extern crate rest_client;

/// Reexported types
pub use self::ferrite::{
    JsonError,
    RestClient,
    RestError,
    decode,
    APIError,
    RestErr,
    StatusErr,
    JsonErr
};

mod ferrite {
    pub use serialize::json::DecoderError as JsonError;
    pub use rest_client::{RestClient, RestError};
    pub use serialize::json::decode;

    #[deriving(Show)]
    pub enum APIError {
        RestErr(RestError),
        StatusErr(String),
        JsonErr(JsonError),
    }
}

macro_rules! rest(
    ($verb_ext: ident $url:expr: fn $fn_name:ident ($(?$param:ident: $ty: ty),+ $($arg:ident: $ty:ty),+) -> $ret:ty) => (
        fn $fn_name($($arg: $ty),+) -> Result<$ret, APIError> {
            use ferrite::{
                JsonError,
                RestClient,
                RestError,
                decode,
                APIError,
                RestErr,
                StatusErr,
                JsonErr
            };

            pair!()

            let url = format!($url, $($param),+);

            let owned = [$((stringify!($arg), $arg.to_string())),+];
            let params: Vec<(&str, &str)> = owned.iter().map(pair).collect();

            let response = try!(RestClient::$verb_ext(url.as_slice(), params.as_slice()).map_err(|e| RestErr(e)));

            if response.body.is_empty() {
                Err(StatusErr(response.status.to_string()))
            } else {
                decode::<$ret>(response.body.as_slice()).map_err(|e| JsonErr(e))
            }
        }
    );
    ($verb:ident $url:expr: fn $fn_name:ident ($(?$param:ident: $ty:ty),+) -> $ret:ty) => (
        fn $fn_name($($param: $ty),+) -> Result<$ret, APIError> {
            use ferrite::{
                JsonError,
                RestClient,
                RestError,
                decode,
                APIError,
                RestErr,
                StatusErr,
                JsonErr
            };

            let url = format!($url, $($param),+);

            let response = try!(RestClient::$verb(url.as_slice()).map_err(|e| RestErr(e)));

            if response.body.is_empty() {
                Err(StatusErr(response.status.to_string()))
            } else {
                decode::<$ret>(response.body.as_slice()).map_err(|e| JsonErr(e))
            }
        }
    );
    ($verb:ident $url:expr: fn $fn_name:ident () -> $ret:ty) => (
        fn $fn_name() -> Result<$ret, APIError> {
            use ferrite::{
                JsonError,
                RestClient,
                RestError,
                decode,
                APIError,
                RestErr,
                StatusErr,
                JsonErr
            };

            const URL: &'static str = $url;

            let response = try!(RestClient::$verb(URL).map_err(|e| RestErr(e)));

            if response.body.is_empty() {
                Err(StatusErr(response.status.to_string()))
            } else {
                decode::<$ret>(response.body.as_slice()).map_err(|e| JsonErr(e))
            }
        }
    );
    ($verb_ext:ident $url:expr: fn $fn_name:ident ($($arg:ident: $ty:ty),+) -> $ret:ty) => (
        fn $fn_name($($arg: $ty),+) -> Result<$ret, APIError> {
            use ferrite::{
                JsonError,
                RestClient,
                RestError,
                decode,
                APIError,
                RestErr,
                StatusErr,
                JsonErr
            };

            pair!()

            const URL: &'static str = $url;

            let owned = [$((stringify!($arg), $arg.to_string())),+];
            let params: Vec<(&str, &str)> =  owned.iter().map(pair).collect();

            let response = try!(RestClient::$verb_ext(URL, params.as_slice()).map_err(|e| RestErr(e)));

            if response.body.is_empty() {
                Err(StatusErr(response.status.to_string()))
            } else {
                decode::<$ret>(response.body.as_slice()).map_err(|e| JsonErr(e))
            }
        }
    );

)

macro_rules! pair(
    () => (
        fn pair<'a>(tup: &'a (&'a str, String)) -> (&'a str, &'a str) {
            let (ref a, ref b) = *tup;
            (*a, b.as_slice())
        }
    )
)

#[macro_export]
macro_rules! get(
    ($url:expr: fn $fn_name:ident () -> $ret:ty) => (
        rest!(get $url: fn $fn_name() -> $ret)
    );
    ($url:expr: fn $fn_name:ident ($(?$param:ident: $ty: ty),+) -> $ret:ty) => (
        rest!(get $url: fn $fn_name($(?$param: $ty),+) -> $ret)
    );
    ($url:expr: fn $fn_name:ident ($(?$param:ident: $ty: ty),+ $($arg:ident: $ty:ty),+) -> $ret:ty) => (
        rest!(get_with_params $url: fn $fn_name($(?$param: $ty),+ $($arg: $ty),+) -> $ret)
    );
    ($url:expr: fn $fn_name:ident ($($arg:ident: $ty:ty),*) -> $ret:ty) => (
        rest!(get_with_params $url: fn $fn_name($($arg: $ty),+) -> $ret)
    );
)

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

    #[deriving(Decodable)]
    struct Test {
        hello: String,
    }

    // TODO: Host these on GitHub-Pages or a local test server
    get!("https://raw.githubusercontent.com/cybergeek94/ferrite/master/json/hello_world.json": fn hello_world() -> Test)

    get!("https://raw.githubusercontent.com/cybergeek94/ferrite/master/json/hello_vec.json": fn hello_vec() -> Vec<Test>)

    get!("https://raw.githubusercontent.com/cybergeek94/ferrite/master/json/hello_{}.json": fn hello(?val: &str) -> Test)

    #[test]
    fn test_hello_world() {
        let test = hello_world().unwrap();

        assert!(test.hello.as_slice() == "world");
    }

    #[test]
    fn test_hello() {
        let test = hello("world").unwrap();

        assert!(test.hello.as_slice() == "world");
    }

    #[test]
    fn test_hello_vec() {
        let test_vec = hello_vec().unwrap();
        let mut test_iter = test_vec.iter();

        assert!(test_iter.next().unwrap().hello.as_slice() == "world");
        assert!(test_iter.next().unwrap().hello.as_slice() == "nation");
        assert!(test_iter.next().unwrap().hello.as_slice() == "city");
        assert!(test_iter.next().unwrap().hello.as_slice() == "person");
        assert!(test_iter.next().is_none());
    }

}
<commit_msg>Remove superfluous macro variants, disambiguate URL params<commit_after>#![feature(macro_rules)]
#![allow(unused_imports)]
extern crate serialize;
extern crate rest_client;

/// Reexported types
pub use self::ferrite::{
    JsonError,
    RestClient,
    RestError,
    decode,
    APIError,
    RestErr,
    StatusErr,
    JsonErr
};

mod ferrite {
    pub use serialize::json::DecoderError as JsonError;
    pub use rest_client::{RestClient, RestError};
    pub use serialize::json::decode;

    #[deriving(Show)]
    pub enum APIError {
        RestErr(RestError),
        StatusErr(String),
        JsonErr(JsonError),
    }
}

macro_rules! rest(
    ($method:ident $url:expr: fn $fn_name:ident {$($param:ident: $p_ty: ty),*}($($arg:ident: $a_ty:ty),*) -> $ret:ty) => (
        fn $fn_name($($param: $p_ty),* $($arg: $a_ty),*) -> Result<$ret, APIError> {
            use ferrite::{
                JsonError,
                RestClient,
                RestError,
                decode,
                APIError,
                RestErr,
                StatusErr,
                JsonErr
            };

            pair!()

            let url = format!($url, $($param),*);

            let owned: Vec<(&str, String)> = vec![$((stringify!($arg), $arg.to_string())),*];
            let params: Vec<(&str, &str)> = owned.iter().map(pair).collect();

            let response = try!(RestClient::$method(url.as_slice(), params.as_slice()).map_err(|e| RestErr(e)));

            if response.body.is_empty() {
                Err(StatusErr(response.status.to_string()))
            } else {
                decode::<$ret>(response.body.as_slice()).map_err(|e| JsonErr(e))
            }
        }
    );
    ($method:ident $url:expr: fn $fn_name:ident ($($arg:ident: $a_ty:ty),*) -> $ret:ty) => (
        rest!($method $url fn $fn_name{}($($arg: $a_ty),*) -> $ret)
    )
)

macro_rules! pair(
    () => (
        fn pair<'a>(tup: &'a (&'a str, String)) -> (&'a str, &'a str) {
            let (ref a, ref b) = *tup;
            (*a, b.as_slice())
        }
    )
)

#[macro_export]
macro_rules! get(
    ($url:expr: fn $fn_name:ident {$($param:ident: $p_ty: ty),*}($($arg:ident: $a_ty:ty),*) -> $ret:ty) => (
        rest!(get_with_params $url:
            fn $fn_name{$($param: $p_ty),*}($($arg: $a_ty),*) -> $ret
        )
    );
    ($url:expr: fn $fn_name:ident ($($arg:ident: $a_ty:ty),*) -> $ret:ty) => (
        rest!(get_with_params $url:
            fn $fn_name{}($($arg: $a_ty),*) -> $ret
        )
    )
)

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

    #[deriving(Decodable)]
    struct Test {
        hello: String,
    }

    // TODO: Host these on GitHub-Pages or a local test server
    get!("https://raw.githubusercontent.com/cybergeek94/ferrite/master/json/hello_world.json": fn hello_world() -> Test)

    get!("https://raw.githubusercontent.com/cybergeek94/ferrite/master/json/hello_vec.json": fn hello_vec() -> Vec<Test>)

    get!("https://raw.githubusercontent.com/cybergeek94/ferrite/master/json/hello_{}.json": fn hello{val: &str}() -> Test)

    #[test]
    fn test_hello_world() {
        let test = hello_world().unwrap();

        assert!(test.hello.as_slice() == "world");
    }

    #[test]
    fn test_hello() {
        let test = hello("world").unwrap();

        assert!(test.hello.as_slice() == "world");
    }

    #[test]
    fn test_hello_vec() {
        let test_vec = hello_vec().unwrap();
        let mut test_iter = test_vec.iter();

        assert!(test_iter.next().unwrap().hello.as_slice() == "world");
        assert!(test_iter.next().unwrap().hello.as_slice() == "nation");
        assert!(test_iter.next().unwrap().hello.as_slice() == "city");
        assert!(test_iter.next().unwrap().hello.as_slice() == "person");
        assert!(test_iter.next().is_none());
    }

}
<|endoftext|>


<commit_before>//! Use the API Documentation below to learn about the various things you can do with this crate.
//!
//! **If this is your first time using Rust or using this crate, read the Guide on
//! [turtle.rs](http://turtle.rs) to learn how to start.**
//!
//! * The [`Turtle` struct](struct.Turtle.html) - lists of all the various drawing commands that the
//!   turtle supports
//! * The [`Drawing` struct](struct.Drawing.html) - allows you to manipulate the title, size,
//!   background and more of the drawing that you are creating
//! * The [`color` module](color/index.html) - describes the different ways to create colors and
//!   includes a list of the hundreds of predefined color names that you can use to easily set the
//!   pen, fill, and background color of your drawings
//!
//! Note: Call [`turtle::start()`](fn.start.html) if you do not create a turtle with
//! [`Turtle::new()`](struct.Turtle.html#method.new) right at the beginning of your program. Most
//! programs will never need to call this function as it is called for you in
//! [`Turtle::new()`](struct.Turtle.html#method.new).
//!
//! # Random Values
//!
//! See the [`rand` module](rand/index.html) for information about generating random colors, speeds,
//! angles, and more which can be used in your programs to produce some interesting results!
//!
//! # Event Handling
//!
//! The [`Event` enum](event/enum.Event.html) documentation provides information about how you can
//! create an event loop. This allows you to draw things in response to certain events like the
//! mouse moving, keys being pressed, and more.
//!
//! The `Turtle` struct contains a few convenience methods so you can do some common event-related
//! things without creating the entire event loop. For example, use
//! [`wait_for_click()`](struct.Turtle.html#method.wait_for_click) to wait for the user to click
//! anywhere on the screen before proceeding.

#![cfg_attr(target_arch = "wasm32", crate_type = "cdylib")]

#[cfg(all(test, not(feature = "test")))]
compile_error!("Make sure you run tests with `cargo test --features test`");

mod turtle_window;

mod animation;
#[cfg(not(target_arch = "wasm32"))]
mod app;
mod drawing;
mod extensions;
#[cfg(not(target_arch = "wasm32"))]
mod messenger;
mod point;
mod query;
mod radians;
#[cfg(not(target_arch = "wasm32"))]
mod renderer;
mod renderer_process;
#[cfg(not(target_arch = "wasm32"))]
mod server;
mod speed;
mod state;
mod timer;
mod turtle;

pub mod color;
#[cfg(not(target_arch = "wasm32"))]
pub mod event;
#[cfg(target_arch = "wasm32")]
mod event {
    use serde::{Serialize, Deserialize};
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub enum Event {}
}
pub mod rand;

pub use crate::color::Color;
pub use crate::drawing::{Drawing, Size};
pub use crate::event::Event;
pub use crate::point::Point;
#[cfg(target_arch = "wasm32")]
pub use renderer_process::{alloc, dealloc, dealloc_str};
pub use crate::speed::Speed;
pub use crate::turtle::{Angle, Distance, Turtle};

#[cfg(not(target_arch = "wasm32"))]
pub use crate::server::start;
#[cfg(target_arch = "wasm32")]
pub fn start() {}
<commit_msg>Add documentation for unstable feature<commit_after>//! Use the API Documentation below to learn about the various things you can do with this crate.
//!
//! **If this is your first time using Rust or using this crate, read the Guide on
//! [turtle.rs](http://turtle.rs) to learn how to start.**
//!
//! * The [`Turtle` struct](struct.Turtle.html) - lists of all the various drawing commands that the
//!   turtle supports
//! * The [`Drawing` struct](struct.Drawing.html) - allows you to manipulate the title, size,
//!   background and more of the drawing that you are creating
//! * The [`color` module](color/index.html) - describes the different ways to create colors and
//!   includes a list of the hundreds of predefined color names that you can use to easily set the
//!   pen, fill, and background color of your drawings
//!
//! Note: Call [`turtle::start()`](fn.start.html) if you do not create a turtle with
//! [`Turtle::new()`](struct.Turtle.html#method.new) right at the beginning of your program. Most
//! programs will never need to call this function as it is called for you in
//! [`Turtle::new()`](struct.Turtle.html#method.new).
//!
//! # Random Values
//!
//! See the [`rand` module](rand/index.html) for information about generating random colors, speeds,
//! angles, and more which can be used in your programs to produce some interesting results!
//!
//! # Event Handling
//!
//! The [`Event` enum](event/enum.Event.html) documentation provides information about how you can
//! create an event loop. This allows you to draw things in response to certain events like the
//! mouse moving, keys being pressed, and more.
//!
//! The `Turtle` struct contains a few convenience methods so you can do some common event-related
//! things without creating the entire event loop. For example, use
//! [`wait_for_click()`](struct.Turtle.html#method.wait_for_click) to wait for the user to click
//! anywhere on the screen before proceeding.
//! # Unstable features
//! Some parts of this library are unstable, such as maximizing and unmaximizing the window.
//! You can explicitly opt-in to using those features with the `unstable` feature like so:
//!
//! ```bash
//! $ cargo build --features "unstable"
//! ```
//!
//! If you want to use this from inside your own crate, you will need to add this to your Cargo.toml
//! ```toml
//! [dependencies]
//! turtle = { version = "...", features = ["unstable"] }
//! ```

#![cfg_attr(target_arch = "wasm32", crate_type = "cdylib")]

#[cfg(all(test, not(feature = "test")))]
compile_error!("Make sure you run tests with `cargo test --features test`");

mod turtle_window;

mod animation;
#[cfg(not(target_arch = "wasm32"))]
mod app;
mod drawing;
mod extensions;
#[cfg(not(target_arch = "wasm32"))]
mod messenger;
mod point;
mod query;
mod radians;
#[cfg(not(target_arch = "wasm32"))]
mod renderer;
mod renderer_process;
#[cfg(not(target_arch = "wasm32"))]
mod server;
mod speed;
mod state;
mod timer;
mod turtle;

pub mod color;
#[cfg(not(target_arch = "wasm32"))]
pub mod event;
#[cfg(target_arch = "wasm32")]
mod event {
    use serde::{Serialize, Deserialize};
    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub enum Event {}
}
pub mod rand;

pub use crate::color::Color;
pub use crate::drawing::{Drawing, Size};
pub use crate::event::Event;
pub use crate::point::Point;
#[cfg(target_arch = "wasm32")]
pub use renderer_process::{alloc, dealloc, dealloc_str};
pub use crate::speed::Speed;
pub use crate::turtle::{Angle, Distance, Turtle};

#[cfg(not(target_arch = "wasm32"))]
pub use crate::server::start;
#[cfg(target_arch = "wasm32")]
pub fn start() {}
<|endoftext|>