<commit_before>// Copyright 2012-2014 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.

//! Temporal quantification.

#![stable(feature = "time", since = "1.3.0")]

use error::Error;
use fmt;
use ops::{Add, Sub};
use sys::time;
use sys_common::FromInner;

#[stable(feature = "time", since = "1.3.0")]
pub use self::duration::Duration;

mod duration;

/// A measurement of a monotonically increasing clock.
///  Opaque and useful only with `Duration`.
///
/// Instants are always guaranteed to be greater than any previously measured
/// instant when created, and are often useful for tasks such as measuring
/// benchmarks or timing how long an operation takes.
///
/// Note, however, that instants are not guaranteed to be **steady**.  In other
/// words, each tick of the underlying clock may not be the same length (e.g.
/// some seconds may be longer than others). An instant may jump forwards or
/// experience time dilation (slow down or speed up), but it will never go
/// backwards.
///
/// Instants are opaque types that can only be compared to one another. There is
/// no method to get "the number of seconds" from an instant. Instead, it only
/// allows measuring the duration between two instants (or comparing two
/// instants).
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[stable(feature = "time2", since = "1.8.0")]
pub struct Instant(time::Instant);

/// A measurement of the system clock, useful for talking to
/// external entities like the file system or other processes.
///
/// Distinct from the `Instant` type, this time measurement **is not
/// monotonic**. This means that you can save a file to the file system, then
/// save another file to the file system, **and the second file has a
/// `SystemTime` measurement earlier than the second**. In other words, an
/// operation that happens after another operation in real time may have an
/// earlier `SystemTime`!
///
/// Consequently, comparing two `SystemTime` instances to learn about the
/// duration between them returns a `Result` instead of an infallible `Duration`
/// to indicate that this sort of time drift may happen and needs to be handled.
///
/// Although a `SystemTime` cannot be directly inspected, the `UNIX_EPOCH`
/// constant is provided in this module as an anchor in time to learn
/// information about a `SystemTime`. By calculating the duration from this
/// fixed point in time, a `SystemTime` can be converted to a human-readable time,
/// or perhaps some other string representation.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[stable(feature = "time2", since = "1.8.0")]
pub struct SystemTime(time::SystemTime);

/// An error returned from the `duration_since` method on `SystemTime`,
/// used to learn about why how far in the opposite direction a timestamp lies.
#[derive(Clone, Debug)]
#[stable(feature = "time2", since = "1.8.0")]
pub struct SystemTimeError(Duration);

impl Instant {
    /// Returns an instant corresponding to "now".
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn now() -> Instant {
        Instant(time::Instant::now())
    }

    /// Returns the amount of time elapsed from another instant to this one.
    ///
    /// # Panics
    ///
    /// This function will panic if `earlier` is later than `self`, which should
    /// only be possible if `earlier` was created after `self`. Because
    /// `Instant` is monotonic, the only time that this should happen should be
    /// a bug.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn duration_since(&self, earlier: Instant) -> Duration {
        self.0.sub_instant(&earlier.0)
    }

    /// Deprecated, renamed to `duration_since`
    #[unstable(feature = "time2_old", issue = "29866")]
    #[rustc_deprecated(since = "1.8.0", reason = "renamed to duration_since")]
    pub fn duration_from_earlier(&self, earlier: Instant) -> Duration {
        self.0.sub_instant(&earlier.0)
    }

    /// Returns the amount of time elapsed since this instant was created.
    ///
    /// # Panics
    ///
    /// This function may panic if the current time is earlier than this
    /// instant, which is something that can happen if an `Instant` is
    /// produced synthetically.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn elapsed(&self) -> Duration {
        Instant::now() - *self
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Add<Duration> for Instant {
    type Output = Instant;

    fn add(self, other: Duration) -> Instant {
        Instant(self.0.add_duration(&other))
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Sub<Duration> for Instant {
    type Output = Instant;

    fn sub(self, other: Duration) -> Instant {
        Instant(self.0.sub_duration(&other))
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Sub<Instant> for Instant {
    type Output = Duration;

    fn sub(self, other: Instant) -> Duration {
        self.duration_since(other)
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl fmt::Debug for Instant {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl SystemTime {
    /// Returns the system time corresponding to "now".
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn now() -> SystemTime {
        SystemTime(time::SystemTime::now())
    }

    /// Returns the amount of time elapsed from an earlier point in time.
    ///
    /// This function may fail because measurements taken earlier are not
    /// guaranteed to always be before later measurements (due to anomalies such
    /// as the system clock being adjusted either forwards or backwards).
    ///
    /// If successful, `Ok(Duration)` is returned where the duration represents
    /// the amount of time elapsed from the specified measurement to this one.
    ///
    /// Returns an `Err` if `earlier` is later than `self`, and the error
    /// contains how far from `self` the time is.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn duration_since(&self, earlier: SystemTime)
                          -> Result<Duration, SystemTimeError> {
        self.0.sub_time(&earlier.0).map_err(SystemTimeError)
    }

    /// Deprecated, renamed to `duration_since`
    #[unstable(feature = "time2_old", issue = "29866")]
    #[rustc_deprecated(since = "1.8.0", reason = "renamed to duration_since")]
    pub fn duration_from_earlier(&self, earlier: SystemTime)
                                 -> Result<Duration, SystemTimeError> {
        self.0.sub_time(&earlier.0).map_err(SystemTimeError)
    }

    /// Returns the amount of time elapsed since this system time was created.
    ///
    /// This function may fail as the underlying system clock is susceptible to
    /// drift and updates (e.g. the system clock could go backwards), so this
    /// function may not always succeed. If successful, `Ok(duration)` is
    /// returned where the duration represents the amount of time elapsed from
    /// this time measurement to the current time.
    ///
    /// Returns an `Err` if `self` is later than the current system time, and
    /// the error contains how far from the current system time `self` is.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
        SystemTime::now().duration_since(*self)
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Add<Duration> for SystemTime {
    type Output = SystemTime;

    fn add(self, dur: Duration) -> SystemTime {
        SystemTime(self.0.add_duration(&dur))
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Sub<Duration> for SystemTime {
    type Output = SystemTime;

    fn sub(self, dur: Duration) -> SystemTime {
        SystemTime(self.0.sub_duration(&dur))
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl fmt::Debug for SystemTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// An anchor in time which can be used to create new `SystemTime` instances or
/// learn about where in time a `SystemTime` lies.
///
/// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
/// respect to the system clock. Using `duration_since` on an existing
/// `SystemTime` instance can tell how far away from this point in time a
/// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
/// `SystemTime` instance to represent another fixed point in time.
#[stable(feature = "time2", since = "1.8.0")]
pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);

impl SystemTimeError {
    /// Returns the positive duration which represents how far forward the
    /// second system time was from the first.
    ///
    /// A `SystemTimeError` is returned from the `duration_since`
    /// operation whenever the second system time represents a point later
    /// in time than the `self` of the method call.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn duration(&self) -> Duration {
        self.0
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Error for SystemTimeError {
    fn description(&self) -> &str { "other time was not earlier than self" }
}

#[stable(feature = "time2", since = "1.8.0")]
impl fmt::Display for SystemTimeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "second time provided was later than self")
    }
}

impl FromInner<time::SystemTime> for SystemTime {
    fn from_inner(time: time::SystemTime) -> SystemTime {
        SystemTime(time)
    }
}

#[cfg(test)]
mod tests {
    use super::{Instant, SystemTime, Duration, UNIX_EPOCH};

    macro_rules! assert_almost_eq {
        ($a:expr, $b:expr) => ({
            let (a, b) = ($a, $b);
            if a != b {
                let (a, b) = if a > b {(a, b)} else {(b, a)};
                assert!(a - Duration::new(0, 100) <= b);
            }
        })
    }

    #[test]
    fn instant_monotonic() {
        let a = Instant::now();
        let b = Instant::now();
        assert!(b >= a);
    }

    #[test]
    fn instant_elapsed() {
        let a = Instant::now();
        a.elapsed();
    }

    #[test]
    fn instant_math() {
        let a = Instant::now();
        let b = Instant::now();
        let dur = b.duration_since(a);
        assert_almost_eq!(b - dur, a);
        assert_almost_eq!(a + dur, b);

        let second = Duration::new(1, 0);
        assert_almost_eq!(a - second + second, a);
    }

    #[test]
    #[should_panic]
    fn instant_duration_panic() {
        let a = Instant::now();
        (a - Duration::new(1, 0)).duration_since(a);
    }

    #[test]
    fn system_time_math() {
        let a = SystemTime::now();
        let b = SystemTime::now();
        match b.duration_since(a) {
            Ok(dur) if dur == Duration::new(0, 0) => {
                assert_almost_eq!(a, b);
            }
            Ok(dur) => {
                assert!(b > a);
                assert_almost_eq!(b - dur, a);
                assert_almost_eq!(a + dur, b);
            }
            Err(dur) => {
                let dur = dur.duration();
                assert!(a > b);
                assert_almost_eq!(b + dur, a);
                assert_almost_eq!(b - dur, a);
            }
        }

        let second = Duration::new(1, 0);
        assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
        assert_almost_eq!(a.duration_since(a + second).unwrap_err()
                           .duration(), second);

        assert_almost_eq!(a - second + second, a);

        let eighty_years = second * 60 * 60 * 24 * 365 * 80;
        assert_almost_eq!(a - eighty_years + eighty_years, a);
        assert_almost_eq!(a - (eighty_years * 10) + (eighty_years * 10), a);

        let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
        let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
            + Duration::new(0, 500_000_000);
        assert_eq!(one_second_from_epoch, one_second_from_epoch2);
    }

    #[test]
    fn system_time_elapsed() {
        let a = SystemTime::now();
        drop(a.elapsed());
    }

    #[test]
    fn since_epoch() {
        let ts = SystemTime::now();
        let a = ts.duration_since(UNIX_EPOCH).unwrap();
        let b = ts.duration_since(UNIX_EPOCH - Duration::new(1, 0)).unwrap();
        assert!(b > a);
        assert_eq!(b - a, Duration::new(1, 0));

        // let's assume that we're all running computers later than 2000
        let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
        assert!(a > thirty_years);

        // let's assume that we're all running computers earlier than 2090.
        // Should give us ~70 years to fix this!
        let hundred_twenty_years = thirty_years * 4;
        assert!(a < hundred_twenty_years);
    }
}
<commit_msg>Add code examples for libstd/time<commit_after>// Copyright 2012-2014 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.

//! Temporal quantification.
//!
//! Example:
//!
//! ```
//! use std::time::Duration;
//!
//! let five_seconds = Duration::new(5, 0);
//! // both declarations are equivalent
//! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
//! ```

#![stable(feature = "time", since = "1.3.0")]

use error::Error;
use fmt;
use ops::{Add, Sub};
use sys::time;
use sys_common::FromInner;

#[stable(feature = "time", since = "1.3.0")]
pub use self::duration::Duration;

mod duration;

/// A measurement of a monotonically increasing clock.
///  Opaque and useful only with `Duration`.
///
/// Instants are always guaranteed to be greater than any previously measured
/// instant when created, and are often useful for tasks such as measuring
/// benchmarks or timing how long an operation takes.
///
/// Note, however, that instants are not guaranteed to be **steady**.  In other
/// words, each tick of the underlying clock may not be the same length (e.g.
/// some seconds may be longer than others). An instant may jump forwards or
/// experience time dilation (slow down or speed up), but it will never go
/// backwards.
///
/// Instants are opaque types that can only be compared to one another. There is
/// no method to get "the number of seconds" from an instant. Instead, it only
/// allows measuring the duration between two instants (or comparing two
/// instants).
///
/// Example:
///
/// ```no_run
/// use std::time::{Duration, Instant};
/// use std::thread::sleep;
///
/// fn main() {
///    let now = Instant::now();
///
///    // we sleep for 2 seconds
///    sleep(Duration::new(2, 0));
///    // it prints '2'
///    println!("{}", now.elapsed().as_secs());
/// }
/// ```
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[stable(feature = "time2", since = "1.8.0")]
pub struct Instant(time::Instant);

/// A measurement of the system clock, useful for talking to
/// external entities like the file system or other processes.
///
/// Distinct from the `Instant` type, this time measurement **is not
/// monotonic**. This means that you can save a file to the file system, then
/// save another file to the file system, **and the second file has a
/// `SystemTime` measurement earlier than the second**. In other words, an
/// operation that happens after another operation in real time may have an
/// earlier `SystemTime`!
///
/// Consequently, comparing two `SystemTime` instances to learn about the
/// duration between them returns a `Result` instead of an infallible `Duration`
/// to indicate that this sort of time drift may happen and needs to be handled.
///
/// Although a `SystemTime` cannot be directly inspected, the `UNIX_EPOCH`
/// constant is provided in this module as an anchor in time to learn
/// information about a `SystemTime`. By calculating the duration from this
/// fixed point in time, a `SystemTime` can be converted to a human-readable time,
/// or perhaps some other string representation.
///
/// Example:
///
/// ```no_run
/// use std::time::{Duration, SystemTime};
/// use std::thread::sleep;
///
/// fn main() {
///    let now = SystemTime::now();
///
///    // we sleep for 2 seconds
///    sleep(Duration::new(2, 0));
///    match now.elapsed() {
///        Ok(elapsed) => {
///            // it prints '2'
///            println!("{}", elapsed.as_secs());
///        }
///        Err(e) => {
///            // an error occured!
///            println!("Error: {:?}", e);
///        }
///    }
/// }
/// ```
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[stable(feature = "time2", since = "1.8.0")]
pub struct SystemTime(time::SystemTime);

/// An error returned from the `duration_since` method on `SystemTime`,
/// used to learn about why how far in the opposite direction a timestamp lies.
#[derive(Clone, Debug)]
#[stable(feature = "time2", since = "1.8.0")]
pub struct SystemTimeError(Duration);

impl Instant {
    /// Returns an instant corresponding to "now".
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn now() -> Instant {
        Instant(time::Instant::now())
    }

    /// Returns the amount of time elapsed from another instant to this one.
    ///
    /// # Panics
    ///
    /// This function will panic if `earlier` is later than `self`, which should
    /// only be possible if `earlier` was created after `self`. Because
    /// `Instant` is monotonic, the only time that this should happen should be
    /// a bug.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn duration_since(&self, earlier: Instant) -> Duration {
        self.0.sub_instant(&earlier.0)
    }

    /// Deprecated, renamed to `duration_since`
    #[unstable(feature = "time2_old", issue = "29866")]
    #[rustc_deprecated(since = "1.8.0", reason = "renamed to duration_since")]
    pub fn duration_from_earlier(&self, earlier: Instant) -> Duration {
        self.0.sub_instant(&earlier.0)
    }

    /// Returns the amount of time elapsed since this instant was created.
    ///
    /// # Panics
    ///
    /// This function may panic if the current time is earlier than this
    /// instant, which is something that can happen if an `Instant` is
    /// produced synthetically.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn elapsed(&self) -> Duration {
        Instant::now() - *self
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Add<Duration> for Instant {
    type Output = Instant;

    fn add(self, other: Duration) -> Instant {
        Instant(self.0.add_duration(&other))
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Sub<Duration> for Instant {
    type Output = Instant;

    fn sub(self, other: Duration) -> Instant {
        Instant(self.0.sub_duration(&other))
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Sub<Instant> for Instant {
    type Output = Duration;

    fn sub(self, other: Instant) -> Duration {
        self.duration_since(other)
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl fmt::Debug for Instant {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl SystemTime {
    /// Returns the system time corresponding to "now".
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn now() -> SystemTime {
        SystemTime(time::SystemTime::now())
    }

    /// Returns the amount of time elapsed from an earlier point in time.
    ///
    /// This function may fail because measurements taken earlier are not
    /// guaranteed to always be before later measurements (due to anomalies such
    /// as the system clock being adjusted either forwards or backwards).
    ///
    /// If successful, `Ok(Duration)` is returned where the duration represents
    /// the amount of time elapsed from the specified measurement to this one.
    ///
    /// Returns an `Err` if `earlier` is later than `self`, and the error
    /// contains how far from `self` the time is.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn duration_since(&self, earlier: SystemTime)
                          -> Result<Duration, SystemTimeError> {
        self.0.sub_time(&earlier.0).map_err(SystemTimeError)
    }

    /// Deprecated, renamed to `duration_since`
    #[unstable(feature = "time2_old", issue = "29866")]
    #[rustc_deprecated(since = "1.8.0", reason = "renamed to duration_since")]
    pub fn duration_from_earlier(&self, earlier: SystemTime)
                                 -> Result<Duration, SystemTimeError> {
        self.0.sub_time(&earlier.0).map_err(SystemTimeError)
    }

    /// Returns the amount of time elapsed since this system time was created.
    ///
    /// This function may fail as the underlying system clock is susceptible to
    /// drift and updates (e.g. the system clock could go backwards), so this
    /// function may not always succeed. If successful, `Ok(duration)` is
    /// returned where the duration represents the amount of time elapsed from
    /// this time measurement to the current time.
    ///
    /// Returns an `Err` if `self` is later than the current system time, and
    /// the error contains how far from the current system time `self` is.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
        SystemTime::now().duration_since(*self)
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Add<Duration> for SystemTime {
    type Output = SystemTime;

    fn add(self, dur: Duration) -> SystemTime {
        SystemTime(self.0.add_duration(&dur))
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Sub<Duration> for SystemTime {
    type Output = SystemTime;

    fn sub(self, dur: Duration) -> SystemTime {
        SystemTime(self.0.sub_duration(&dur))
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl fmt::Debug for SystemTime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// An anchor in time which can be used to create new `SystemTime` instances or
/// learn about where in time a `SystemTime` lies.
///
/// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
/// respect to the system clock. Using `duration_since` on an existing
/// `SystemTime` instance can tell how far away from this point in time a
/// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
/// `SystemTime` instance to represent another fixed point in time.
#[stable(feature = "time2", since = "1.8.0")]
pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);

impl SystemTimeError {
    /// Returns the positive duration which represents how far forward the
    /// second system time was from the first.
    ///
    /// A `SystemTimeError` is returned from the `duration_since`
    /// operation whenever the second system time represents a point later
    /// in time than the `self` of the method call.
    #[stable(feature = "time2", since = "1.8.0")]
    pub fn duration(&self) -> Duration {
        self.0
    }
}

#[stable(feature = "time2", since = "1.8.0")]
impl Error for SystemTimeError {
    fn description(&self) -> &str { "other time was not earlier than self" }
}

#[stable(feature = "time2", since = "1.8.0")]
impl fmt::Display for SystemTimeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "second time provided was later than self")
    }
}

impl FromInner<time::SystemTime> for SystemTime {
    fn from_inner(time: time::SystemTime) -> SystemTime {
        SystemTime(time)
    }
}

#[cfg(test)]
mod tests {
    use super::{Instant, SystemTime, Duration, UNIX_EPOCH};

    macro_rules! assert_almost_eq {
        ($a:expr, $b:expr) => ({
            let (a, b) = ($a, $b);
            if a != b {
                let (a, b) = if a > b {(a, b)} else {(b, a)};
                assert!(a - Duration::new(0, 100) <= b);
            }
        })
    }

    #[test]
    fn instant_monotonic() {
        let a = Instant::now();
        let b = Instant::now();
        assert!(b >= a);
    }

    #[test]
    fn instant_elapsed() {
        let a = Instant::now();
        a.elapsed();
    }

    #[test]
    fn instant_math() {
        let a = Instant::now();
        let b = Instant::now();
        let dur = b.duration_since(a);
        assert_almost_eq!(b - dur, a);
        assert_almost_eq!(a + dur, b);

        let second = Duration::new(1, 0);
        assert_almost_eq!(a - second + second, a);
    }

    #[test]
    #[should_panic]
    fn instant_duration_panic() {
        let a = Instant::now();
        (a - Duration::new(1, 0)).duration_since(a);
    }

    #[test]
    fn system_time_math() {
        let a = SystemTime::now();
        let b = SystemTime::now();
        match b.duration_since(a) {
            Ok(dur) if dur == Duration::new(0, 0) => {
                assert_almost_eq!(a, b);
            }
            Ok(dur) => {
                assert!(b > a);
                assert_almost_eq!(b - dur, a);
                assert_almost_eq!(a + dur, b);
            }
            Err(dur) => {
                let dur = dur.duration();
                assert!(a > b);
                assert_almost_eq!(b + dur, a);
                assert_almost_eq!(b - dur, a);
            }
        }

        let second = Duration::new(1, 0);
        assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
        assert_almost_eq!(a.duration_since(a + second).unwrap_err()
                           .duration(), second);

        assert_almost_eq!(a - second + second, a);

        let eighty_years = second * 60 * 60 * 24 * 365 * 80;
        assert_almost_eq!(a - eighty_years + eighty_years, a);
        assert_almost_eq!(a - (eighty_years * 10) + (eighty_years * 10), a);

        let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
        let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
            + Duration::new(0, 500_000_000);
        assert_eq!(one_second_from_epoch, one_second_from_epoch2);
    }

    #[test]
    fn system_time_elapsed() {
        let a = SystemTime::now();
        drop(a.elapsed());
    }

    #[test]
    fn since_epoch() {
        let ts = SystemTime::now();
        let a = ts.duration_since(UNIX_EPOCH).unwrap();
        let b = ts.duration_since(UNIX_EPOCH - Duration::new(1, 0)).unwrap();
        assert!(b > a);
        assert_eq!(b - a, Duration::new(1, 0));

        // let's assume that we're all running computers later than 2000
        let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
        assert!(a > thirty_years);

        // let's assume that we're all running computers earlier than 2090.
        // Should give us ~70 years to fix this!
        let hundred_twenty_years = thirty_years * 4;
        assert!(a < hundred_twenty_years);
    }
}
<|endoftext|>


<commit_before><commit_msg>fix(Options): fixes a bug where option arguments in succession get their values skipped<commit_after><|endoftext|>


<commit_before><commit_msg>Add "circle-texture" example<commit_after>extern crate sdl2;
#[macro_use] extern crate glitter;

use sdl2::video::GLProfile;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use glitter::prelude::*;

fn circle_image(width: usize, height: usize, radius: f32) -> glitter::Pixels {
    let (center_x, center_y) = (width as f32/2.0, height as f32/2.0);

    let mut pixels = glitter::Pixels::new(width, height);
    for x in 0..width {
        for y in 0..height {
            let dx = center_x - x as f32;
            let dy = center_y - y as f32;
            let distance = (dx*dx + dy*dy).sqrt();

            let color = if distance < radius {
                // The point is within the circle, so it should be red
                glitter::Pixel::rgb(0xFF0000)
            }
            else {
                // The point is outside the circle, so it should be black
                glitter::Pixel::rgb(0x000000)
            };
            pixels[y][x] = color;
        }
    }

    pixels
}

fn setup_gl(video: &sdl2::VideoSubsystem) {
    let gl_attr = video.gl_attr();

    // Use OpenGL 4.1 core. Note that glitter is (currently) only designed
    // for OpenGL ES 2.0, but OpenGL 4.1 added the GL_ARB_ES2_compatibility
    // extension, which adds OpenGL ES 2 compatibility
    gl_attr.set_context_profile(GLProfile::Core);
    gl_attr.set_context_version(4, 1);
    gl_attr.set_context_flags().debug().set();

    // Load the system's OpenGL library
    video.gl_load_library_default().expect("Failed to load OpenGL library");

    // Load OpenGL function pointers
    unsafe {
        glitter::Context::load_with(|s| {
            video.gl_get_proc_address(s) as *const _
        });
    }
}

unsafe fn gl_vao_hack() {
    use glitter::gl;
    use glitter::gl::types::GLuint;

    // So... OpenGL 4.1 and OpenGL ES 2.0 aren't EXACTLY compatible.
    // For example, look at glEnableVertexAttribArray. In OpenGL 4.1, it
    // requires a vertex array object to be currently bound. However,
    // OpenGL ES 2.0 doesn't have vertex array objects (without an extension).
    // To work around this, we just create and bind a vertex array
    // object globally, so we can use these functions as we would in
    // OpenGL ES 2.0. This specific issue will be solved in a future release
    // of glitter.
    let mut vertex_array_object: GLuint = 0;
    gl::GenVertexArrays(1, &mut vertex_array_object);
    gl::BindVertexArray(vertex_array_object);
}

fn main() {
    // Initialize SDL and the video submodule
    let sdl = sdl2::init().expect("Failed to initailize SDL");
    let video = sdl.video().expect("Failed to intialize SDL video system");

    // Do all the necessary SDL OpenGL setup
    setup_gl(&video);

    // Create our window (and make it usable with OpenGL)
    let window = video.window("Hello Circle!", 800, 600)
                      .opengl()
                      .build()
                      .expect("Failed to create SDL window");

    // Create a new OpenGL context
    let _context = window.gl_create_context().expect("Failed to create OpenGL context");

    // Bind the window's OpenGL context
    window.gl_set_context_to_current().expect("Failed to set current context");

    // Workaround for OpenGL 4.1/OpenGL ES 2 vertex array object disparity
    unsafe { gl_vao_hack(); }

    // Get the current OpenGL context
    let mut gl = unsafe { glitter::Context::current_context() };

    // Clear the screen to black
    gl.clear_color(glitter::Color { r: 0.0, g: 0.0, b: 0.0, a: 0.0 });
    gl.clear(glitter::COLOR_BUFFER_BIT);

    // The data that makes up a single vertex of our triangle
    // (a 2D position coordinate, and a texture coordinate)
    #[derive(Clone, Copy)]
    struct Vertex {
        position: [f32; 2],
        tex_coord: [f32; 2]
    }

    // Mark our `Vertex` as a type that we can treat as a vertex for our shader
    impl_vertex_data!(Vertex, position, tex_coord);

    // The vertices the make up our screen's quad
    let vertices = [
        Vertex { position: [-1.0, -1.0], tex_coord: [0.0, 0.0] },
        Vertex { position: [-1.0,  1.0], tex_coord: [0.0, 1.0] },
        Vertex { position: [ 1.0,  1.0], tex_coord: [1.0, 1.0] },
        Vertex { position: [ 1.0, -1.0], tex_coord: [1.0, 0.0] }
    ];

    // The indices that make up our screen's quad
    let indices = [
        0, 1, 2,
        0, 2, 3
    ];

    // Create our circle texture.
    let mut circle = gl.build_texture_2d()
                       .image_2d(&circle_image(800, 600, 250.0))
                       .min_filter(glitter::NEAREST)
                       .mag_filter(glitter::NEAREST)
                       .wrap_s(glitter::CLAMP_TO_EDGE)
                       .wrap_t(glitter::CLAMP_TO_EDGE)
                       .unwrap();

    // The vertex shader, which translates our vertices to screen coordinates
    let vertex_source = r##"#version 100
        // Our inputs (the fields from our `Vertex` struct)
        attribute vec2 position;
        attribute vec2 texCoord;

        // Our output (the texture coordinate for our fragment shader)
        varying vec2 _texCoord;

        void main() {
            gl_Position = vec4(position, -1.0, 1.0);
            _texCoord = texCoord;
        }
    "##;

    // The fragment shader, which knows how to color pixels for the final image
    let fragment_source = r##"#version 100
        // Our uniform (the texture we read from)
        uniform sampler2D sampler;

        // Our input (the texture coordinate copied from our vertex shader)
        varying highp vec2 _texCoord;

        void main() {
            gl_FragColor = texture2D(sampler, _texCoord);
        }
    "##;

    // Compile our vertex and fragment shader, panicking if there was a
    // compilation error
    let vertex_shader = gl.build_vertex_shader(vertex_source).unwrap();
    let fragment_shader = gl.build_fragment_shader(fragment_source).unwrap();

    // Combine our shaders into a program, panicking if there was a
    // linking error
    let mut program = gl.build_program(&[vertex_shader, fragment_shader]).unwrap();

    // Create a buffer to send our quad's vertices to
    let mut vertex_buffer: glitter::VertexBuffer<Vertex> = gl.new_vertex_buffer();

    // Create a buffer to send our quad's indices to
    let mut index_buffer: glitter::IndexBuffer<u16> = gl.new_index_buffer();

    // The "attrib pointers" that connects the input attributes from our
    // vertex shader to the fields of our `Vertex` struct
    let attribs = attrib_pointers! {
        position => gl.get_attrib_location(&program, "position").unwrap(),
        tex_coord => gl.get_attrib_location(&program, "texCoord").unwrap()
    };

    // Add our attributes to our vertex buffer
    vertex_buffer.bind_attrib_pointers(attribs);

    // Bind the vertex buffer to the OpenGL context, so that we can actually
    // send our vertex data to it
    let (mut gl_vertex_buffer, gl) = gl.bind_vertex_buffer(&mut vertex_buffer);

    // Send our vertex data to our binding. We use `glitter::STATIC_DRAW`
    // because the geometry of our triangle is static
    gl.buffer_vertices(&mut gl_vertex_buffer, &vertices, glitter::STATIC_DRAW);

    // Bind the index buffer to the OpenGL context, so that we can actually
    // send our index data to it
    let (mut gl_index_buffer, gl) = gl.bind_index_buffer(&mut index_buffer);

    // Send our index data to our binding.
    gl.buffer_indices(&mut gl_index_buffer, &indices, glitter::STATIC_DRAW);

    // Set texture unit 0 as the active texture unit
    let (gl_tex_unit, gl) = gl.active_texture_0();

    // Bind our circle texture to the texture unit
    let (_, gl_tex_unit) = gl_tex_unit.bind_texture_2d(&mut circle);

    // Get the sampler of the texture unit
    let circle_sampler = gl_tex_unit.sampler();

    // Get the program uniform that we set the sampler to, panicking
    // if the sampler was not found
    let sampler_uniform = gl.get_uniform_location(&program, "sampler").unwrap();

    // Bind our program to the OpenGL context
    let (gl_program, gl) = gl.use_program(&mut program);

    // Set the sampler uniform to reference our circle texture
    gl.set_uniform(&gl_program, sampler_uniform, circle_sampler);

    // Finally, draw the screen quad!
    gl.draw_elements_buffered_vbo(&gl_vertex_buffer,
                                  &gl_index_buffer,
                                  glitter::TRIANGLES);

    // Display what we've rendered so far
    window.gl_swap_window();

    // Handle any extra input events
    let mut event_pump = sdl.event_pump().expect("Failed to get SDL events");
    'running: loop {
        // Handle any input events we need to
        for event in event_pump.poll_iter() {
            match event {
                Event::Quit {..} |
                Event::KeyDown { keycode: Some(Keycode::Escape), .. } => {
                    break 'running
                },
                _ => { }
            }
        }

        // Our main loop goes here (in most applications, this is
        // where we would actually do our rendering)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add single counter_button example<commit_after>extern crate domafic;
use domafic::{KeyIter, IntoNode};
use domafic::tags::{button, div, h1};
use domafic::events::EventType::Click;
use domafic::listener::on;

// If rendering client-side with ASM-JS:
// use domafic::web_render::run;

// If rendering server-side:
// use domafic::DOMNodes;
// use domafic::html_writer::HtmlWriter;

type State = isize;

enum Msg {
    Increment,
    Decrement,
}

fn main() {
    let update = |state: &mut State, msg: Msg, _keys: KeyIter| {
        *state = match msg {
            Msg::Increment => *state + 1,
            Msg::Decrement => *state - 1,
        }
    };

    let render = |state: &State| {
        div ((
            h1("Hello from rust!".into_node()),
            button ((
                on(Click, |_| Msg::Decrement),
                "-".into_node(),
            )),
            state.to_string().into_node(),
            button ((
                on(Click, |_| Msg::Increment),
                "+".into_node(),
            )),
        ))
    };

    // If rendering client-side with ASM-JS:
    // run("body", update, render, 0);

    // If rendering server-side:
    // let mut string_buffer = Vec::new();
    // render(0).process_all::<HtmlWriter<Vec<u8>>>(&mut string_buffer).unwrap();
    // let string = String::from_utf8(string_buffer).unwrap();
    // render(0).process_all<HtmlWriter>();
}
<|endoftext|>


<commit_before><commit_msg>Let pop method return tuple of dbpage and idx<commit_after><|endoftext|>


<commit_before><commit_msg>Some Rust style cleanup in lib.rs.<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #2153 - RalfJung:ptr-invalid, r=RalfJung<commit_after>// compile-flags: -Zmiri-permissive-provenance
#![feature(strict_provenance)]

// Ensure that a `ptr::invalid` ptr is truly invalid.
fn main() {
    let x = 42;
    let xptr = &x as *const i32;
    let xptr_invalid = std::ptr::invalid::<i32>(xptr.expose_addr());
    let _val = unsafe { *xptr_invalid }; //~ ERROR is not a valid pointer
}
<|endoftext|>


<commit_before><commit_msg>Some preliminary boilerplate<commit_after><|endoftext|>


<commit_before><commit_msg>Implement root and internal node splitting<commit_after><|endoftext|>


<commit_before><commit_msg>Wrote a test for worlds that tests object collision and tilemaps<commit_after><|endoftext|>


<commit_before><commit_msg>Update for latest Rust<commit_after><|endoftext|>


<commit_before>#![crate_name = "liquid"]

#![feature(globs)]
#![feature(slicing_syntax)]
#![feature(phase)]
#[phase(plugin)]
extern crate regex_macros;
extern crate regex;

use std::collections::HashMap;
use template::Template;
use lexer::Token;
use lexer::Element;
use tags::IfBlock;
use tags::RawBlock;
use std::string::ToString;

mod template;
mod variable;
mod text;
mod lexer;
mod parser;
mod tags;

pub enum Value{
    Num(f32),
    Str(String),
    Object(HashMap<String, Value>)
}

impl ToString for Value{
    fn to_string(&self) -> String{
        match self{
            &Value::Num(ref x) => x.to_string(),
            &Value::Str(ref x) => x.to_string(),
            _ => "[Object object]".to_string() // TODO
        }
    }
}

pub trait Block {
    fn initialize<'a>(&'a self, tag_name: &str, arguments: &[Token], tokens: Vec<Element>, options : &'a LiquidOptions<'a>) -> Box<Renderable>;
}

pub trait Tag {
    fn initialize(&self, tag_name: &str, arguments: &[Token], options : &LiquidOptions) -> Box<Renderable>;
}

pub struct LiquidOptions<'a> {
    blocks : HashMap<String, Box<Block + 'a>>,
    tags : HashMap<String, Box<Tag + 'a>>
}

pub trait Renderable{
    fn render(&self, context: &HashMap<String, Value>) -> Option<String>;
}

pub fn parse<'a> (text: &str, options: &'a mut LiquidOptions<'a>) -> Template<'a>{
    let tokens = lexer::tokenize(text.as_slice());
    options.blocks.insert("raw".to_string(), box RawBlock as Box<Block>);
    options.blocks.insert("if".to_string(), box IfBlock as Box<Block>);
    let renderables = parser::parse(tokens, options);
    Template::new(renderables)
}

#[test]
fn test_liquid() {
    let mut blocks = HashMap::new();
    let mut tags = HashMap::new();

    let mut options = LiquidOptions {
        blocks: blocks,
        tags: tags,
    };

    let template = parse("{%if num < numTwo%}wat{%else%}wot{%endif%} {%if num > numTwo%}wat{%else%}wot{%endif%}", &mut options);

    let mut data = HashMap::new();
    data.insert("num".to_string(), Value::Num(5f32));
    data.insert("numTwo".to_string(), Value::Num(6f32));

    let output = template.render(&data);
    assert_eq!(output.unwrap(), "wat wot".to_string());
}

#[test]
fn test_custom_output() {
    struct Multiply{
        numbers: Vec<f32>
    }
    impl Renderable for Multiply{
        fn render(&self, context: &HashMap<String, Value>) -> Option<String>{
            let x = self.numbers.iter().fold(1f32, |a, &b| a * b);
            Some(x.to_string())
        }
    }

    struct MultiplyTag;
    impl Tag for MultiplyTag{
        fn initialize(&self, tag_name: &str, arguments: &[Token], options: &LiquidOptions) -> Box<Renderable>{
            let numbers = arguments.iter().filter_map( |x| {
                match x {
                    &Token::NumberLiteral(ref num) => Some(*num),
                    _ => None
                }
            }).collect();
            box Multiply{numbers: numbers} as Box<Renderable>
        }
    }

    let mut blocks = HashMap::new();
    let mut tags = HashMap::new();
    tags.insert("multiply".to_string(), box MultiplyTag as Box<Tag>);

    let mut options = LiquidOptions {
        blocks: blocks,
        tags: tags,
    };
    let template = parse("wat\n{{hello}}\n{{multiply 5 3}}{%raw%}{{multiply 5 3}}{%endraw%} test", &mut options);

    let mut data = HashMap::new();
    data.insert("hello".to_string(), Value::Str("world".to_string()));

    let output = template.render(&data);
    assert_eq!(output.unwrap(), "wat\nworld\n15{{multiply 5 3}} test".to_string());
}

<commit_msg>Turn lib tests into benchmarks<commit_after>#![crate_name = "liquid"]

#![feature(globs)]
#![feature(slicing_syntax)]
#![feature(phase)]
#[phase(plugin)]
extern crate regex_macros;
extern crate regex;
extern crate test;

use test::Bencher;
use std::collections::HashMap;
use template::Template;
use lexer::Token;
use lexer::Element;
use tags::IfBlock;
use tags::RawBlock;
use std::string::ToString;

mod template;
mod variable;
mod text;
mod lexer;
mod parser;
mod tags;

pub enum Value{
    Num(f32),
    Str(String),
    Object(HashMap<String, Value>)
}

impl ToString for Value{
    fn to_string(&self) -> String{
        match self{
            &Value::Num(ref x) => x.to_string(),
            &Value::Str(ref x) => x.to_string(),
            _ => "[Object object]".to_string() // TODO
        }
    }
}

pub trait Block {
    fn initialize<'a>(&'a self, tag_name: &str, arguments: &[Token], tokens: Vec<Element>, options : &'a LiquidOptions<'a>) -> Box<Renderable>;
}

pub trait Tag {
    fn initialize(&self, tag_name: &str, arguments: &[Token], options : &LiquidOptions) -> Box<Renderable>;
}

pub struct LiquidOptions<'a> {
    blocks : HashMap<String, Box<Block + 'a>>,
    tags : HashMap<String, Box<Tag + 'a>>
}

pub trait Renderable{
    fn render(&self, context: &HashMap<String, Value>) -> Option<String>;
}

pub fn parse<'a> (text: &str, options: &'a mut LiquidOptions<'a>) -> Template<'a>{
    let tokens = lexer::tokenize(text.as_slice());
    options.blocks.insert("raw".to_string(), box RawBlock as Box<Block>);
    options.blocks.insert("if".to_string(), box IfBlock as Box<Block>);
    let renderables = parser::parse(tokens, options);
    Template::new(renderables)
}

#[bench]
fn simple_parse(b: &mut Bencher) {
    let mut blocks = HashMap::new();
    let mut tags = HashMap::new();

    let mut options = LiquidOptions {
        blocks: blocks,
        tags: tags,
    };

    let template = parse("{%if num < numTwo%}wat{%else%}wot{%endif%} {%if num > numTwo%}wat{%else%}wot{%endif%}", &mut options);

    let mut data = HashMap::new();
    data.insert("num".to_string(), Value::Num(5f32));
    data.insert("numTwo".to_string(), Value::Num(6f32));

    let output = template.render(&data);
    assert_eq!(output.unwrap(), "wat wot".to_string());

    b.iter(|| template.render(&data));
}

#[bench]
fn custom_output(b: &mut Bencher) {
    struct Multiply{
        numbers: Vec<f32>
    }
    impl Renderable for Multiply{
        fn render(&self, context: &HashMap<String, Value>) -> Option<String>{
            let x = self.numbers.iter().fold(1f32, |a, &b| a * b);
            Some(x.to_string())
        }
    }

    struct MultiplyTag;
    impl Tag for MultiplyTag{
        fn initialize(&self, tag_name: &str, arguments: &[Token], options: &LiquidOptions) -> Box<Renderable>{
            let numbers = arguments.iter().filter_map( |x| {
                match x {
                    &Token::NumberLiteral(ref num) => Some(*num),
                    _ => None
                }
            }).collect();
            box Multiply{numbers: numbers} as Box<Renderable>
        }
    }

    let mut blocks = HashMap::new();
    let mut tags = HashMap::new();
    tags.insert("multiply".to_string(), box MultiplyTag as Box<Tag>);

    let mut options = LiquidOptions {
        blocks: blocks,
        tags: tags,
    };
    let template = parse("wat\n{{hello}}\n{{multiply 5 3}}{%raw%}{{multiply 5 3}}{%endraw%} test", &mut options);

    let mut data = HashMap::new();
    data.insert("hello".to_string(), Value::Str("world".to_string()));

    let output = template.render(&data);
    assert_eq!(output.unwrap(), "wat\nworld\n15{{multiply 5 3}} test".to_string());

    b.iter(|| template.render(&data));
}

<|endoftext|>


<commit_before><commit_msg>fix(Argon2PasswordHasher): re-export Argon2Err<commit_after><|endoftext|>


<commit_before><commit_msg>fix: check-in sse2/i8x16 mod<commit_after>extern crate llvmint;

use super::super::super::super::*;
use super::super::super::super::core::*;
use super::super::SSE2;

impl CmpEq<M16<i8>> for SSE2 {
#[inline(always)]
  fn cmpeq(&self, a: M16<i8>, b: M16<i8>) -> M16<i8> {
    Multi::wrap(a.unwrap() == b.unwrap())
  }
}

impl CmpGt<M16<i8>> for SSE2 {
#[inline(always)]
  fn cmpgt(&self, a: M16<i8>, b: M16<i8>) -> M16<i8> {
    Multi::wrap(a.unwrap() > b.unwrap())
  }
}

impl CmpLt<M16<i8>> for SSE2 {
#[inline(always)]
  fn cmplt(&self, a: M16<i8>, b: M16<i8>) -> M16<i8> {
    Multi::wrap(a.unwrap() < b.unwrap())
  }
}

impl Set1<M16<i8>> for SSE2 {
#[inline(always)]
  fn set1(&self, a: i8) -> M16<i8> {
    Twice{
      lo: Twice{
        lo: Twice{
          lo: Twice{lo: a, hi: a},
          hi: Twice{lo: a, hi: a}
        },
        hi: Twice{
          lo: Twice{lo: a, hi: a},
          hi: Twice{lo: a, hi: a}
        },
      },
      hi: Twice{
        lo: Twice{
          lo: Twice{lo: a, hi: a},
          hi: Twice{lo: a, hi: a}
        },
        hi: Twice{
          lo: Twice{lo: a, hi: a},
          hi: Twice{lo: a, hi: a}
        }
      }
    }
  }
}

impl Add<M16<i8>> for SSE2 {
#[inline(always)]
  fn add(&self, a: M16<i8>, b: M16<i8>) -> M16<i8> {
    Multi::wrap(a.unwrap() + b.unwrap())
  }
}

impl AddS<M16<i8>> for SSE2 {
#[inline(always)]
  fn adds(&self, a: M16<i8>, b: M16<i8>) -> M16<i8> {
    unsafe {
      Multi::wrap(llvmint::x86::sse2_padds_b(a.unwrap(), b.unwrap()))
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>[x86_64] first pass on MSR<commit_after>//
//  SOS: the Stupid Operating System
//  by Hawk Weisman (hi@hawkweisman.me)
//
//  Copyright (c) 2015 Hawk Weisman
//  Released under the terms of the MIT license. See `LICENSE` in the root
//  directory of this repository for more information.
//
//! Code for interacting with the Model-Specific Registers (MSRs).
use core::mem;

/// Extended Feature Enable Register (EFER) on IA-32
pub const IA32_EFER: u32 = 0xc0000080;

/// Write `value` to the specified `msr`
///
/// # Arguments
/// + `msr`: which MSR to write to
/// + `value`: the  bits to write
pub unsafe fn write(msr: u32, value: u64) {
    let (high, low): (u32, u32) = mem::transmute(value);
    asm!(   "wrmsr"
         :: "{ecx}" (msr), "{eax}" (low), "{edx}" (high)
         :  "memory"
         : "volatile" );
}

/// Read 64 bits from the specified `msr`
pub unsafe fn read(msr: u32) -> u64 {
    let low: u32;
    let high: u32;
    asm!( "rdmsr"
        : "={eax}" (low), "={edx}" (high)
        : "{ecx}" (msr)
        : "memory"
        : "volatile" );
    mem::transmute((high,low))
}

/// Enable the NXE (No Execute) in the IA-32 EFER register.
///
/// This allows us to set the NXE bit on pages.
pub unsafe fn enable_nxe() {
    let nxe_bit = 1 << 11;
    let efer = read(IA32_EFER);
    write(IA32_EFER, efer | nxe_bit);
}
<|endoftext|>


<commit_before><commit_msg>Add test for when no tests run<commit_after><|endoftext|>


<commit_before><commit_msg>Convenience function to add entity<commit_after><|endoftext|>


<commit_before><commit_msg>Correct the error documentation for Archive::from_bytes<commit_after><|endoftext|>


<commit_before><commit_msg>refresh session in every request<commit_after><|endoftext|>


<commit_before><commit_msg>Use new profile enum instead of raw SDL value<commit_after><|endoftext|>


<commit_before>/*
Copyright 2014 Benjamin Elder from https://github.com/BenTheElder/slack-rs

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
extern crate hyper;
extern crate websocket;
extern crate "rustc-serialize" as rustc_serialize;
extern crate url;

use rustc_serialize::json::{Json};
use std::sync::mpsc::{Sender,channel};
use std::thread::Thread;
use std::sync::atomic::{AtomicIsize, Ordering};
use websocket::message::WebSocketMessage;
use websocket::handshake::WebSocketRequest;
use url::Url;

///Implement this trait in your code to handle message events
pub trait MessageHandler {
	///When a message is received this will be called with self, the slack client,
	///and the json encoded string payload.
	fn on_receive(&mut self, cli: &mut RtmClient, json_str: &str);

	///Called when a ping is received; you do NOT need to handle the reply pong,
	///but you may use this event to track the connection as a keep-alive.
	fn on_ping(&mut self, cli: &mut RtmClient);

	///Called when the connection is closed for any reason.
	fn on_close(&mut self, cli: &mut RtmClient);
}

///Contains information about the team the bot is logged into.
pub struct Team {
	name : String,
	id : String
}

impl Team {
	///private, create empty team.
	fn new() -> Team {
		Team{name: String::new(), id: String::new()}
	}

	///Returns the team's name as a String
	pub fn get_name(&self) -> String {
		self.name.clone()
	}

	///Returns the team's id as a String
	pub fn get_id(&self) -> String {
		self.id.clone()
	}
}

///The actual messaging client.
pub struct RtmClient {
	name : String,
	id : String,
	team : Team,
	msg_num: AtomicIsize,
	outs : Option<Sender<String>>
}

///Error string. (FIXME: better error return values/ custom error type)
static RTM_INVALID : &'static str = "Invalid data returned from slack (rtm.start)";

impl RtmClient {

	///Creates a new empty client.
	pub fn new() -> RtmClient {
		RtmClient{
			name : String::new(),
			id : String::new(),
			team : Team::new(),
			msg_num: AtomicIsize::new(0),
			outs : None
		}
	}

	///Returns the name of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_name(&self) -> String {
		return self.name.clone();
	}

	///Returns the id of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_id(&self) -> String {
		return self.id.clone();
	}

	///Returns the Team struct of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_team<'a>(&'a self) -> &'a Team {
		&self.team
	}

	///Returns a unique identifier to be used in the 'id' field of a message
	///sent to slack.
	pub fn get_msg_uid(&self) -> isize {
		self.msg_num.fetch_add(1, Ordering::SeqCst)
	}

	///Allows sending a json string message over the websocket connection.
	///Note that this only passes the message over a channel to the
	///Messaging task, and therfore a succesful return value does not
	///mean the message has been actually put on the wire yet.
	///Note that you will need to form a valid json reply yourself if you
	///use this method, and you will also need to retrieve a unique id for
	///the message via RtmClient.get_msg_uid()
	///Only valid after login.
	pub fn send(&mut self, s : &str) -> Result<(),String> {
		let tx = match self.outs {
			Some(ref tx) => tx,
			None => return Err("Failed to get tx!".to_string())
		};
		match tx.send(s.to_string()) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		Ok(())
	}

	///Allows sending a textual string message over the websocket connection,
	///to the requested channel id. Ideal usage would be EG:
	///extract the channel in on_receive and then send back a message to the channel.
	///Note that this only passes the message over a channel to the
	///Messaging task, and therfore a succesful return value does not
	///mean the message has been actually put on the wire yet.
	///This method also handles getting a unique id and formatting the actual json
	///sent.
	///Only valid after login.
	pub fn send_message(&self, chan: &str, msg: &str) -> Result<(),String>{
		let n = self.get_msg_uid();
		let mstr = "{".to_string()+format!(r#""id": {},"type": "message","channel": "{}","text": "{}""#,n,chan,msg).as_slice()+"}";
		let tx = match self.outs {
			Some(ref tx) => tx,
			None => return Err("Failed to get tx!".to_string())
		};
		match tx.send(mstr) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		Ok(())
	}

	///Runs the main loop for the client after logging in to slack,
	///returns an error if the process fails at an point, or an Ok(()) on succesful
	///close.
	///Takes a MessageHandler (implemented by the user) to call events handlers on.
	///once the first on_receive() or on_ping is called on the MessageHandler, you
	///can soon the 'Only valid after login' methods are safe to use.
	///Sending is run in a thread in parallel while the receive loop runs on the main thread.
	///Both loops should end on return.
	///Sending should be thread safe as the messages are passed in via a channel in
	///RtmClient.send and RtmClient.send_message
	pub fn login_and_run<T: MessageHandler>(&mut self, handler: &mut T, token : &str) -> Result<(),String> {
		//Slack real time api url
		let url = "https://slack.com/api/rtm.start?token=".to_string()+token;

		//Create http client and send request to slack
		let mut client = hyper::Client::new();
		let mut res = match client.get(url.as_slice()).send() {
			Ok(res) => res,
			Err(err) => return Err(format!("Hyper Error: {:?}", err))
		};

		//Read result string
		let res_str = match res.read_to_string() {
			Ok(res_str) => res_str,
			Err(err) => return Err(format!("{:?}", err))
		};

		//Start parsing json. We do not map to a structure,
		//because slack makes no guarantee that there won't be extra fields.
		let js = match Json::from_str(res_str.as_slice()) {
			Ok(js) => js,
			Err(err) => return Err(format!("{:?}", err))
		};

		if !js.is_object() {
			return Err(format!("{} : json is not an object.", RTM_INVALID))
		}
		let jo = js.as_object().unwrap();

		match jo.get("ok") {
			Some(v) => {
				if !(v.is_boolean() && v.as_boolean().unwrap() == true) {
					return Err(format!("{} : js.get(\"ok\") != true : {:?}", RTM_INVALID, jo))
				}
			},
			None => return Err(format!("{} : jo.get(\"ok\") returned None. : {:?}", RTM_INVALID, jo))
		}

		let wss_url_string = match jo.get("url") {
			Some(wss_url) => {
				if wss_url.is_string() {
					wss_url.as_string().unwrap()
				}else{
					return Err(format!("{} : jo.get(\"url\") failed! : {:?}", RTM_INVALID, jo))
				}
			},
			None => return Err(format!("{} : jo.get(\"url\") returned None. : {:?}", RTM_INVALID, jo))
		};

		let wss_url = match Url::parse(wss_url_string) {
			Ok(url) => url,
			Err(err) => return Err(format!("{:?}", err))
		};

		let jself = match jo.get("self") {
			Some(jself) => {
				if jself.is_object() {
					jself.as_object().unwrap()
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		};
		match jself.get("name") {
			Some(jname) => {
				if jname.is_string() {
					self.name = jname.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		}
		match jself.get("id") {
			Some(jid) => {
				if jid.is_string() {
					self.id = jid.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		}

		let jteam = match jo.get("team") {
			Some(jteam) => {
				if jteam.is_object() {
					jteam.as_object().unwrap()
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		};
		match jteam.get("name") {
			Some(jtname) => {
				if jtname.is_string() {
					self.team.name = jtname.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			}
			None => return Err(RTM_INVALID.to_string())
		}
		match jteam.get("id") {
			Some(jtid) => {
				if jtid.is_string() {
					self.team.id = jtid.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			}
			None => return Err(RTM_INVALID.to_string())
		}

		//Make websocket request
		let req = match WebSocketRequest::connect(wss_url) {
			Ok(req) => req,
			Err(err) => return Err(format!("{:?}", err))
		};

		//Get the key so we can verify it later.
		let key = match req.key() {
			Some(key) => key.clone(),
			None => return Err("Request host key match failed.".to_string())
		};

		//Connect via tls, do websocket handshake.
		let res = match req.send() {
			Ok(res) => res,
			Err(err) => return Err(format!("{:?}", err))
		};

		match res.validate(&key) {
			Ok(()) => { }
			Err(err) => return Err(format!("{:?}", err))
		}

		let mut client = res.begin();

		//for sending messages
		let (tx,rx) = channel::<String>();
		self.outs = Some(tx);

		let mut captured_client = client.clone();

		//websocket send loop
		let guard = Thread::spawn(move || -> () {
			loop {
				let m = match rx.recv() {
					Ok(m) => m,
					Err(err) => panic!(format!("{:?}", err))
				};
			 	let msg = WebSocketMessage::Text(m);
			 	match captured_client.send_message(msg) {
			 		Ok(_) => {},
			 		Err(err) => panic!(format!("{:?}", err))
			 	}
			 }
		});

		let mut sending_client = client.clone();

		//receive loop
		for message in client.incoming_messages() {
			let message = match message {
				Ok(message) => message,
				Err(err) => return Err(format!("{:?}", err))
			};

			match message {
				WebSocketMessage::Text(data) => {
					handler.on_receive(self, data.as_slice());
				},
				WebSocketMessage::Ping(data) => {
					handler.on_ping(self);
					let message = WebSocketMessage::Pong(data);
					match sending_client.send_message(message) {
						Ok(_) => {},
						Err(err) => { return Err(format!("{:?}", err)); }
					}
				},
				WebSocketMessage::Close(data) => {
					handler.on_close(self);
					let message = WebSocketMessage::Close(data);
					match sending_client.send_message(message) {
						Ok(_) => {},
						Err(err) => { return Err(format!("{:?}", err)); }
					}
					return Ok(());
				},
				_ => {}
			}
		}

		Ok(())
	}
}
<commit_msg>more debug stuff<commit_after>/*
Copyright 2014 Benjamin Elder from https://github.com/BenTheElder/slack-rs

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
extern crate hyper;
extern crate websocket;
extern crate "rustc-serialize" as rustc_serialize;
extern crate url;

use rustc_serialize::json::{Json};
use std::sync::mpsc::{Sender,channel};
use std::thread::Thread;
use std::sync::atomic::{AtomicIsize, Ordering};
use websocket::message::WebSocketMessage;
use websocket::handshake::WebSocketRequest;
use url::Url;

///Implement this trait in your code to handle message events
pub trait MessageHandler {
	///When a message is received this will be called with self, the slack client,
	///and the json encoded string payload.
	fn on_receive(&mut self, cli: &mut RtmClient, json_str: &str);

	///Called when a ping is received; you do NOT need to handle the reply pong,
	///but you may use this event to track the connection as a keep-alive.
	fn on_ping(&mut self, cli: &mut RtmClient);

	///Called when the connection is closed for any reason.
	fn on_close(&mut self, cli: &mut RtmClient);
}

///Contains information about the team the bot is logged into.
pub struct Team {
	name : String,
	id : String
}

impl Team {
	///private, create empty team.
	fn new() -> Team {
		Team{name: String::new(), id: String::new()}
	}

	///Returns the team's name as a String
	pub fn get_name(&self) -> String {
		self.name.clone()
	}

	///Returns the team's id as a String
	pub fn get_id(&self) -> String {
		self.id.clone()
	}
}

///The actual messaging client.
pub struct RtmClient {
	name : String,
	id : String,
	team : Team,
	msg_num: AtomicIsize,
	outs : Option<Sender<String>>
}

///Error string. (FIXME: better error return values/ custom error type)
static RTM_INVALID : &'static str = "Invalid data returned from slack (rtm.start)";

impl RtmClient {

	///Creates a new empty client.
	pub fn new() -> RtmClient {
		RtmClient{
			name : String::new(),
			id : String::new(),
			team : Team::new(),
			msg_num: AtomicIsize::new(0),
			outs : None
		}
	}

	///Returns the name of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_name(&self) -> String {
		return self.name.clone();
	}

	///Returns the id of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_id(&self) -> String {
		return self.id.clone();
	}

	///Returns the Team struct of the bot/user connected to the client.
	///Only valid after login.
	pub fn get_team<'a>(&'a self) -> &'a Team {
		&self.team
	}

	///Returns a unique identifier to be used in the 'id' field of a message
	///sent to slack.
	pub fn get_msg_uid(&self) -> isize {
		self.msg_num.fetch_add(1, Ordering::SeqCst)
	}

	///Allows sending a json string message over the websocket connection.
	///Note that this only passes the message over a channel to the
	///Messaging task, and therfore a succesful return value does not
	///mean the message has been actually put on the wire yet.
	///Note that you will need to form a valid json reply yourself if you
	///use this method, and you will also need to retrieve a unique id for
	///the message via RtmClient.get_msg_uid()
	///Only valid after login.
	pub fn send(&mut self, s : &str) -> Result<(),String> {
		let tx = match self.outs {
			Some(ref tx) => tx,
			None => return Err("Failed to get tx!".to_string())
		};
		match tx.send(s.to_string()) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		Ok(())
	}

	///Allows sending a textual string message over the websocket connection,
	///to the requested channel id. Ideal usage would be EG:
	///extract the channel in on_receive and then send back a message to the channel.
	///Note that this only passes the message over a channel to the
	///Messaging task, and therfore a succesful return value does not
	///mean the message has been actually put on the wire yet.
	///This method also handles getting a unique id and formatting the actual json
	///sent.
	///Only valid after login.
	pub fn send_message(&self, chan: &str, msg: &str) -> Result<(),String>{
		let n = self.get_msg_uid();
		let mstr = "{".to_string()+format!(r#""id": {},"type": "message","channel": "{}","text": "{}""#,n,chan,msg).as_slice()+"}";
		let tx = match self.outs {
			Some(ref tx) => tx,
			None => return Err("Failed to get tx!".to_string())
		};
		match tx.send(mstr) {
			Ok(_) => {},
			Err(err) => return Err(format!("{:?}", err))
		}
		Ok(())
	}

	///Runs the main loop for the client after logging in to slack,
	///returns an error if the process fails at an point, or an Ok(()) on succesful
	///close.
	///Takes a MessageHandler (implemented by the user) to call events handlers on.
	///once the first on_receive() or on_ping is called on the MessageHandler, you
	///can soon the 'Only valid after login' methods are safe to use.
	///Sending is run in a thread in parallel while the receive loop runs on the main thread.
	///Both loops should end on return.
	///Sending should be thread safe as the messages are passed in via a channel in
	///RtmClient.send and RtmClient.send_message
	pub fn login_and_run<T: MessageHandler>(&mut self, handler: &mut T, token : &str) -> Result<(),String> {
		//Slack real time api url
		let url = "https://slack.com/api/rtm.start?token=".to_string()+token;

		//Create http client and send request to slack
		let mut client = hyper::Client::new();
		let mut res = match client.get(url.as_slice()).send() {
			Ok(res) => res,
			Err(err) => return Err(format!("Hyper Error: {:?}", err))
		};

		//Read result string
		let res_str = match res.read_to_string() {
			Ok(res_str) => res_str,
			Err(err) => return Err(format!("{:?}", err))
		};

		//Start parsing json. We do not map to a structure,
		//because slack makes no guarantee that there won't be extra fields.
		let js = match Json::from_str(res_str.as_slice()) {
			Ok(js) => js,
			Err(err) => return Err(format!("{:?}", err))
		};

		if !js.is_object() {
			return Err(format!("{} : json is not an object.", RTM_INVALID))
		}
		let jo = js.as_object().unwrap();

		match jo.get("ok") {
			Some(v) => {
				if !(v.is_boolean() && v.as_boolean().unwrap() == true) {
					return Err(format!("{} : js.get(\"ok\") != true : {:?}", RTM_INVALID, jo))
				}
			},
			None => return Err(format!("{} : jo.get(\"ok\") returned None. : {:?}", RTM_INVALID, jo))
		}

		let wss_url_string = match jo.get("url") {
			Some(wss_url) => {
				if wss_url.is_string() {
					wss_url.as_string().unwrap()
				}else{
					return Err(format!("{} : jo.get(\"url\") failed! : {:?}", RTM_INVALID, jo))
				}
			},
			None => return Err(format!("{} : jo.get(\"url\") returned None. : {:?}", RTM_INVALID, jo))
		};

		let wss_url = match Url::parse(wss_url_string) {
			Ok(url) => url,
			Err(err) => return Err(format!("{:?}", err))
		};

		let jself = match jo.get("self") {
			Some(jself) => {
				if jself.is_object() {
					jself.as_object().unwrap()
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		};
		match jself.get("name") {
			Some(jname) => {
				if jname.is_string() {
					self.name = jname.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		}
		match jself.get("id") {
			Some(jid) => {
				if jid.is_string() {
					self.id = jid.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		}

		let jteam = match jo.get("team") {
			Some(jteam) => {
				if jteam.is_object() {
					jteam.as_object().unwrap()
				}else{
					return Err(RTM_INVALID.to_string())
				}
			},
			None => return Err(RTM_INVALID.to_string())
		};
		match jteam.get("name") {
			Some(jtname) => {
				if jtname.is_string() {
					self.team.name = jtname.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			}
			None => return Err(RTM_INVALID.to_string())
		}
		match jteam.get("id") {
			Some(jtid) => {
				if jtid.is_string() {
					self.team.id = jtid.as_string().unwrap().to_string();
				}else{
					return Err(RTM_INVALID.to_string())
				}
			}
			None => return Err(RTM_INVALID.to_string())
		}

		//Make websocket request
		let req = match WebSocketRequest::connect(wss_url) {
			Ok(req) => req,
			Err(err) => return Err(format!("{:?} : WebSocketRequest::connect(wss_url): wss_url{:?}", err, wss))
		};

		//Get the key so we can verify it later.
		let key = match req.key() {
			Some(key) => key.clone(),
			None => return Err("Request host key match failed.".to_string())
		};

		//Connect via tls, do websocket handshake.
		let res = match req.send() {
			Ok(res) => res,
			Err(err) => return Err(format!("{:?}, Websocket request to `{:?}` failed", err, wss_url))
		};

		match res.validate(&key) {
			Ok(()) => { }
			Err(err) => return Err(format!("Websocket request key validation error: {:?}", err))
		}

		let mut client = res.begin();

		//for sending messages
		let (tx,rx) = channel::<String>();
		self.outs = Some(tx);

		let mut captured_client = client.clone();

		//websocket send loop
		let guard = Thread::spawn(move || -> () {
			loop {
				let m = match rx.recv() {
					Ok(m) => m,
					Err(err) => panic!(format!("{:?}", err))
				};
			 	let msg = WebSocketMessage::Text(m);
			 	match captured_client.send_message(msg) {
			 		Ok(_) => {},
			 		Err(err) => panic!(format!("{:?}", err))
			 	}
			 }
		});

		let mut sending_client = client.clone();

		//receive loop
		for message in client.incoming_messages() {
			let message = match message {
				Ok(message) => message,
				Err(err) => return Err(format!("{:?}", err))
			};

			match message {
				WebSocketMessage::Text(data) => {
					handler.on_receive(self, data.as_slice());
				},
				WebSocketMessage::Ping(data) => {
					handler.on_ping(self);
					let message = WebSocketMessage::Pong(data);
					match sending_client.send_message(message) {
						Ok(_) => {},
						Err(err) => { return Err(format!("{:?}", err)); }
					}
				},
				WebSocketMessage::Close(data) => {
					handler.on_close(self);
					let message = WebSocketMessage::Close(data);
					match sending_client.send_message(message) {
						Ok(_) => {},
						Err(err) => { return Err(format!("{:?}", err)); }
					}
					return Ok(());
				},
				_ => {}
			}
		}

		Ok(())
	}
}
<|endoftext|>


<commit_before><commit_msg>visibility: fixed<commit_after><|endoftext|>


<commit_before><commit_msg>Make ClientCookies cloneable.<commit_after><|endoftext|>


<commit_before><commit_msg>add example 'place'<commit_after>extern crate egg_mode;

mod common;

use egg_mode::place::PlaceType;

fn main() {
    let config = common::Config::load();

    let result = egg_mode::place::search_query("columbia")
                                 .granularity(PlaceType::Admin)
                                 .max_results(10)
                                 .call(&config.con_token, &config.access_token).unwrap();

    println!("{} results for \"columbia\", administrative regions or larger:", result.response.results.len());

    for place in &result.response.results {
        println!("{}", place.full_name);
    }
}
<|endoftext|>


<commit_before><commit_msg>PmDeviceId -> PortMidiDeviceId<commit_after><|endoftext|>


<commit_before><commit_msg>Problem 41<commit_after>fn primes(start: uint, end: uint) -> ~[uint] {
    let mut primes = ~[2];
    let mut i = 3;
    while i < end {
        while primes.iter().any(|&x| i%x == 0) {
            i += 2;
        }
        primes.push(i);
    }
    primes.move_iter().filter(|&p| p >= start && p < end).to_owned_vec()
}

fn goldbach(n: uint) -> Option<(uint, uint)> {
    let primes = primes(2, n);
    for &p in primes.iter() {
        match primes.bsearch_elem(&(n-p)) {
            Some(_) => return Some((p, n-p)),
            None => {}
        }
    }
    None
}

fn goldbach_list(start: uint, end: uint) -> ~[(uint, Option<(uint, uint)>)] {
    range(start, end+1).filter_map(
        |x|
        if x%2 == 0 {
            Some((x, goldbach(x)))
        } else {
            None
        }
        ).to_owned_vec()
}

fn goldbach_limit(start: uint, end: uint, limit: uint) -> ~[(uint, Option<(uint, uint)>)] {
    goldbach_list(start, end).move_iter().filter(
        |&x|
        match x {
            (_, Some((a, b))) if a > limit && b > limit => true,
            (_, Some(_)) => false,
            (n, None)    => fail!(format!("Goldbach conjecture is false for {}", n))
        }
        ).to_owned_vec()
}

fn main() {
    println!("{:?}", goldbach_list(9, 20));
    println!("{:?}", goldbach_limit(3, 2000, 50));
}

<|endoftext|>


<commit_before><commit_msg>Documentation<commit_after><|endoftext|>


<commit_before><commit_msg>convert to lib<commit_after><|endoftext|>


<commit_before><commit_msg>Update to use PhantomFn and PhantomData<commit_after><|endoftext|>


<commit_before><commit_msg>adding tests<commit_after><|endoftext|>


<commit_before><commit_msg>Cleaner randndomization<commit_after><|endoftext|>


<commit_before><commit_msg>ffmpeg connected again<commit_after><|endoftext|>


<commit_before><commit_msg>Update docs on StoredCookie::from_set_cookie.<commit_after><|endoftext|>


<commit_before><commit_msg>Rename "S" field in struct to "state".<commit_after><|endoftext|>


<commit_before><commit_msg>add mod tests<commit_after><|endoftext|>


<commit_before><commit_msg>Factor out parts using transmute()<commit_after><|endoftext|>


<commit_before><commit_msg>Use slice indexing rather than Iterator::skip.<commit_after><|endoftext|>


<commit_before><commit_msg>Add initial interface design.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for iterator property.<commit_after><|endoftext|>


<commit_before><commit_msg>modularize<commit_after>#![recursion_limit = "1024"]
use std::str;
use std::vec::Vec;

extern crate regex;

extern crate theban_interval_tree;
extern crate memrange;

extern crate rust_htslib;
use rust_htslib::bam::record::Cigar;

#[macro_use]
extern crate error_chain;

pub mod errors {
    error_chain!{
        foreign_links {
            Io(::std::io::Error) #[cfg(unix)];
            Utf8(::std::str::Utf8Error);
            Regex(::regex::Error);
            ReaderPath(::rust_htslib::bam::ReaderPathError);
        }
        errors {
            NoneError
        }
    }
    pub trait ToResult<T> {
        fn r(self) -> Result<T>;
    }
    impl<T> ToResult<T> for Option<T> {
        fn r(self) -> Result<T> {
            match self {
                Some(v) => Ok(v),
                None => Err(ErrorKind::NoneError.into()),
            }
        }
    }
}

use errors::*;

pub fn cigar2exons(exons: &mut Vec<(u64, u64)>, cigar: &[Cigar], pos: u64) -> Result<()> {
    let mut pos = pos;
    for op in cigar {
        match op {
            &Cigar::Match(length) => {
                pos += length as u64;
                exons.push((pos - length as u64, pos));
                Ok(())
            }
            &Cigar::RefSkip(length) |
            &Cigar::Del(length) => {
                pos += length as u64;
                Ok(())
            }
            &Cigar::Ins(_) |
            &Cigar::SoftClip(_) |
            &Cigar::HardClip(_) |
            &Cigar::Pad(_) => Ok(()),
            c => Err(format!("Bad CIGAR string: {:?}", c)),
        }?;
    }
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Update formatting of lib.rs<commit_after><|endoftext|>


<commit_before><commit_msg>format code using the rustfmt tool<commit_after><|endoftext|>


<commit_before><commit_msg>Make reparg! syntax mimic array initialization<commit_after><|endoftext|>


<commit_before><commit_msg>Fix release not building<commit_after><|endoftext|>


<commit_before><commit_msg>Added a test for vector arithmetic and vector equality<commit_after><|endoftext|>


<commit_before>//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readiness-based API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating an [EventLoop](struct.EventLoop.html), which
//! handles receiving events from the OS and dispatching them to a supplied
//! [Handler](handler/trait.Handler.html).
//!
//! # Example
//!
//! ```
//! use mio::{event, EventLoop, IoAcceptor, Handler, Token};
//! use mio::net::{SockAddr};
//! use mio::net::tcp::{TcpSocket, TcpAcceptor};
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = SockAddr::parse("127.0.0.1:13265")
//!     .expect("could not parse InetAddr");
//!
//! // Setup the server socket
//! let server = TcpSocket::v4().unwrap()
//!     .bind(&addr).unwrap()
//!     .listen(256u).unwrap();
//!
//! // Create an event loop
//! let mut event_loop = EventLoop::<(), ()>::new().unwrap();
//!
//! // Start listening for incoming connections
//! event_loop.register(&server, SERVER).unwrap();
//!
//! // Setup the client socket
//! let sock = TcpSocket::v4().unwrap();
//!
//! // Connect to the server
//! sock.connect(&addr).unwrap();
//!
//! // Register the socket
//! event_loop.register(&sock, CLIENT).unwrap();
//!
//! // Define a handler to process the events
//! struct MyHandler(TcpAcceptor);
//!
//! impl Handler<(), ()> for MyHandler {
//!     fn readable(&mut self, event_loop: &mut EventLoop<(), ()>, token: Token, _: event::ReadHint) {
//!         match token {
//!             SERVER => {
//!                 let MyHandler(ref mut server) = *self;
//!                 // Accept and drop the socket immediately, this will close
//!                 // the socket and notify the client of the EOF.
//!                 let _ = server.accept();
//!             }
//!             CLIENT => {
//!                 // The server just shuts down the socket, let's just
//!                 // shutdown the event loop
//!                 event_loop.shutdown();
//!             }
//!             _ => panic!("unexpected token"),
//!         }
//!     }
//! }
//!
//! // Start handling events
//! let _ = event_loop.run(MyHandler(server));
//!
//! ```

#![crate_name = "mio"]

// mio is still in rapid development
#![unstable]

// Enable extra features
#![feature(globs)]
#![feature(phase)]
#![feature(unsafe_destructor)]

// Disable dead code warnings
#![allow(dead_code)]

extern crate alloc;
extern crate nix;
extern crate time;

#[phase(plugin, link)]
extern crate log;

pub use buf::{
    Buf,
    MutBuf,
};
pub use error::{
    MioResult,
    MioError,
    MioErrorKind
};
pub use handler::{
    Handler,
};
pub use io::{
    pipe,
    NonBlock,
    IoReader,
    IoWriter,
    IoAcceptor,
    PipeReader,
    PipeWriter,
};
pub use poll::{
    Poll
};
pub use event_loop::{
    EventLoop,
    EventLoopConfig,
    EventLoopResult,
    EventLoopSender,
};
pub use timer::{
    Timeout,
};
pub use os::token::{
    Token,
};

pub use os::event;

pub mod buf;
pub mod net;
pub mod util;

mod error;
mod event_loop;
mod handler;
mod io;
mod notify;
mod os;
mod poll;
mod timer;
<commit_msg>Actually export EventLoopError.<commit_after>//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readiness-based API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating an [EventLoop](struct.EventLoop.html), which
//! handles receiving events from the OS and dispatching them to a supplied
//! [Handler](handler/trait.Handler.html).
//!
//! # Example
//!
//! ```
//! use mio::{event, EventLoop, IoAcceptor, Handler, Token};
//! use mio::net::{SockAddr};
//! use mio::net::tcp::{TcpSocket, TcpAcceptor};
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = SockAddr::parse("127.0.0.1:13265")
//!     .expect("could not parse InetAddr");
//!
//! // Setup the server socket
//! let server = TcpSocket::v4().unwrap()
//!     .bind(&addr).unwrap()
//!     .listen(256u).unwrap();
//!
//! // Create an event loop
//! let mut event_loop = EventLoop::<(), ()>::new().unwrap();
//!
//! // Start listening for incoming connections
//! event_loop.register(&server, SERVER).unwrap();
//!
//! // Setup the client socket
//! let sock = TcpSocket::v4().unwrap();
//!
//! // Connect to the server
//! sock.connect(&addr).unwrap();
//!
//! // Register the socket
//! event_loop.register(&sock, CLIENT).unwrap();
//!
//! // Define a handler to process the events
//! struct MyHandler(TcpAcceptor);
//!
//! impl Handler<(), ()> for MyHandler {
//!     fn readable(&mut self, event_loop: &mut EventLoop<(), ()>, token: Token, _: event::ReadHint) {
//!         match token {
//!             SERVER => {
//!                 let MyHandler(ref mut server) = *self;
//!                 // Accept and drop the socket immediately, this will close
//!                 // the socket and notify the client of the EOF.
//!                 let _ = server.accept();
//!             }
//!             CLIENT => {
//!                 // The server just shuts down the socket, let's just
//!                 // shutdown the event loop
//!                 event_loop.shutdown();
//!             }
//!             _ => panic!("unexpected token"),
//!         }
//!     }
//! }
//!
//! // Start handling events
//! let _ = event_loop.run(MyHandler(server));
//!
//! ```

#![crate_name = "mio"]

// mio is still in rapid development
#![unstable]

// Enable extra features
#![feature(globs)]
#![feature(phase)]
#![feature(unsafe_destructor)]

// Disable dead code warnings
#![allow(dead_code)]

extern crate alloc;
extern crate nix;
extern crate time;

#[phase(plugin, link)]
extern crate log;

pub use buf::{
    Buf,
    MutBuf,
};
pub use error::{
    MioResult,
    MioError,
    MioErrorKind
};
pub use handler::{
    Handler,
};
pub use io::{
    pipe,
    NonBlock,
    IoReader,
    IoWriter,
    IoAcceptor,
    PipeReader,
    PipeWriter,
};
pub use poll::{
    Poll
};
pub use event_loop::{
    EventLoop,
    EventLoopConfig,
    EventLoopResult,
    EventLoopSender,
    EventLoopError
};
pub use timer::{
    Timeout,
};
pub use os::token::{
    Token,
};

pub use os::event;

pub mod buf;
pub mod net;
pub mod util;

mod error;
mod event_loop;
mod handler;
mod io;
mod notify;
mod os;
mod poll;
mod timer;
<|endoftext|>


<commit_before>//! A macro that parses brainfuck code at compile time.

#![crate_name="brainfuck_macros"]
#![crate_type="dylib"]

#![feature(quote, plugin_registrar, macro_rules)]

extern crate syntax;
extern crate rustc;

use syntax::ast;
use syntax::ptr::P;
use syntax::codemap;
use syntax::ext::base::{ExtCtxt, MacResult, MacExpr};
use syntax::ext::build::AstBuilder;
use syntax::parse::token;

use rustc::plugin::Registry;

#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(registrar: &mut Registry) {
    registrar.register_macro("brainfuck", brainfuck)
}

// This essentially translates token-wise, using the symbol mappings
// given in the table at:
// http://en.wikipedia.org/wiki/Brainfuck#Commands
fn brainfuck(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
    let bf = BF {
        array: quote_expr!(&mut *cx, _array),
        idx: quote_expr!(&mut *cx, _i),
        rdr: quote_expr!(&mut *cx, _r),
        wtr: quote_expr!(&mut *cx, _w),
        cx: cx,
    };
    let core_code = bf.tts_to_expr(sp, tts);

    MacExpr::new(quote_expr!(bf.cx, {
        fn run(_r: &mut Reader, _w: &mut Writer) -> ::std::io::IoResult<Vec<u8>> {
            let mut _array = Vec::from_elem(30_000, 0u8);
            let mut _i = 0;
            $core_code;
            Ok(_array)
        }
        run
    }))
}

struct BF<'a> {
    cx: &'a ExtCtxt<'a>,
    array: P<ast::Expr>,
    idx: P<ast::Expr>,
    rdr: P<ast::Expr>,
    wtr: P<ast::Expr>
}

impl<'a> BF<'a> {
    fn tts_to_expr(&self, sp: codemap::Span, tts: &[ast::TokenTree]) -> P<ast::Expr> {
        let v = tts.iter()
            .filter_map(|tt| self.tt_to_expr(sp,tt).map(|e| self.cx.stmt_expr(e)))
            .collect();

        let block = self.cx.block(sp, v, None);
        self.cx.expr_block(block)
    }

    fn tt_to_expr(&self, sp: codemap::Span, tt: &ast::TokenTree) -> Option<P<ast::Expr>> {
        match *tt {
            ast::TTTok(sp, ref tok) => self.token_to_expr(sp, tok),

            // [...] or (...) or {...}
            ast::TTDelim(ref toks) => {
                match (**toks)[0] {
                    // [...]
                    ast::TTTok(_, token::LBRACKET) => {
                        // drop the first and last (i.e. the [ & ]).
                        let centre = self.tts_to_expr(sp, toks.slice(1, toks.len() - 1));

                        let array = &self.array;
                        let idx = &self.idx;

                        Some(quote_expr!(self.cx, {
                            while *$array.get($idx) != 0 {
                                $centre
                            }
                        }))

                    }
                    _ => {
                        // not [...], so just translate directly (any
                        // invalid tokens (like the delimiters) will
                        // be automatically ignored)
                        Some(self.tts_to_expr(sp,toks.as_slice()))
                    }
                }
            }
            ast::TTSeq(sp, _, _, _) => {
                self.cx.span_err(sp, "sequences unsupported in `brainfuck!`");
                None
            }
            ast::TTNonterminal(sp, _) => {
                self.cx.span_err(sp, "nonterminals unsupported in `brainfuck!`");
                None
            }
        }
    }

    fn token_to_expr(&self, sp: codemap::Span,
                     tok: &token::Token) -> Option<P<ast::Expr>> {
        // some tokens consist of multiple characters that brainfuck
        // needs to know about, so we do the obvious thing of just
        // taking each one and combining into a single expression.
        macro_rules! recompose {
            ($($token: expr),*) => {
                {
                    let stmts = vec!(
                        $(
                            {
                                let e = self.token_to_expr(sp,&$token)
                                    .expect("brainfuck: invalid token decomposition?");
                                self.cx.stmt_expr(e)
                            } ),* );
                    Some(self.cx.expr_block(self.cx.block(sp, stmts, None)))
                }
            }
        }
        let idx = &self.idx;
        let array = &self.array;
        match *tok {
            token::LT | token::GT => {
                let left = *tok == token::LT;
                Some(quote_expr!(self.cx, {
                    if $left {
                        if $idx > 0 {
                            $idx -= 1;
                        }
                    } else {
                        if $idx < $array.len() - 1 {
                            $idx += 1;
                        }
                    }
                }))
            }
            // <<
            token::BINOP(token::SHL) => recompose!(token::LT, token::LT),
            // >>
            token::BINOP(token::SHR) => recompose!(token::GT, token::GT),

            token::DOT => {
                let wtr = &self.wtr;
                Some(quote_expr!(self.cx, try!($wtr.write([*$array.get($idx)]))))
            }
            // ..
            token::DOTDOT => recompose!(token::DOT, token::DOT),
            // ...
            token::DOTDOTDOT => recompose!(token::DOT, token::DOT, token::DOT),

            token::COMMA => {
                let rdr = &self.rdr;
                Some(quote_expr!(self.cx, {
                    use std::io;
                    *$array.get_mut($idx) = match $rdr.read_byte() {
                        Ok(b) => b,
                        Err(io::IoError { kind: io::EndOfFile, .. }) => -1,
                        Err(e) => return Err(e)
                    }
                }))
            }

            token::BINOP(a @ token::PLUS) | token::BINOP(a @ token::MINUS) => {
                let dir: u8 = if a == token::PLUS { 1 } else { -1 };

                Some(quote_expr!(self.cx, {
                    *$array.get_mut($idx) += $dir
                }))
            }
            // ->
            token::RARROW => recompose!(token::BINOP(token::MINUS), token::GT),
            // <-
            token::LARROW => recompose!(token::LT, token::BINOP(token::MINUS)),
            _ => {
                None
            }
        }
    }
}
<commit_msg>Update to 96991e933 2014-10-22 23:57:11 +0000.<commit_after>//! A macro that parses brainfuck code at compile time.

#![crate_name="brainfuck_macros"]
#![crate_type="dylib"]

#![feature(quote, plugin_registrar, macro_rules)]

extern crate syntax;
extern crate rustc;

use syntax::ast;
use syntax::ptr::P;
use syntax::codemap;
use syntax::ext::base::{ExtCtxt, MacResult, MacExpr};
use syntax::ext::build::AstBuilder;
use syntax::parse::token;

use rustc::plugin::Registry;

#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(registrar: &mut Registry) {
    registrar.register_macro("brainfuck", brainfuck)
}

// This essentially translates token-wise, using the symbol mappings
// given in the table at:
// http://en.wikipedia.org/wiki/Brainfuck#Commands
fn brainfuck(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult+'static> {
    let bf = BF {
        array: quote_expr!(&mut *cx, _array),
        idx: quote_expr!(&mut *cx, _i),
        rdr: quote_expr!(&mut *cx, _r),
        wtr: quote_expr!(&mut *cx, _w),
        cx: cx,
    };
    let core_code = bf.tts_to_expr(sp, tts);

    MacExpr::new(quote_expr!(bf.cx, {
        fn run(_r: &mut Reader, _w: &mut Writer) -> ::std::io::IoResult<Vec<u8>> {
            let mut _array = Vec::from_elem(30_000, 0u8);
            let mut _i = 0;
            $core_code;
            Ok(_array)
        }
        run
    }))
}

struct BF<'a> {
    cx: &'a ExtCtxt<'a>,
    array: P<ast::Expr>,
    idx: P<ast::Expr>,
    rdr: P<ast::Expr>,
    wtr: P<ast::Expr>
}

impl<'a> BF<'a> {
    fn tts_to_expr(&self, sp: codemap::Span, tts: &[ast::TokenTree]) -> P<ast::Expr> {
        let v = tts.iter()
            .filter_map(|tt| self.tt_to_expr(sp,tt).map(|e| self.cx.stmt_expr(e)))
            .collect();

        let block = self.cx.block(sp, v, None);
        self.cx.expr_block(block)
    }

    fn tt_to_expr(&self, sp: codemap::Span, tt: &ast::TokenTree) -> Option<P<ast::Expr>> {
        match *tt {
            ast::TTTok(sp, ref tok) => self.token_to_expr(sp, tok),

            // [...] or (...) or {...}
            ast::TTDelim(ref toks) => {
                match (**toks)[0] {
                    // [...]
                    ast::TTTok(_, token::LBRACKET) => {
                        // drop the first and last (i.e. the [ & ]).
                        let centre = self.tts_to_expr(sp, toks.slice(1, toks.len() - 1));

                        let array = &self.array;
                        let idx = &self.idx;

                        Some(quote_expr!(self.cx, {
                            while $array[$idx] != 0 {
                                $centre
                            }
                        }))

                    }
                    _ => {
                        // not [...], so just translate directly (any
                        // invalid tokens (like the delimiters) will
                        // be automatically ignored)
                        Some(self.tts_to_expr(sp,toks.as_slice()))
                    }
                }
            }
            ast::TTSeq(sp, _, _, _) => {
                self.cx.span_err(sp, "sequences unsupported in `brainfuck!`");
                None
            }
            ast::TTNonterminal(sp, _) => {
                self.cx.span_err(sp, "nonterminals unsupported in `brainfuck!`");
                None
            }
        }
    }

    fn token_to_expr(&self, sp: codemap::Span,
                     tok: &token::Token) -> Option<P<ast::Expr>> {
        // some tokens consist of multiple characters that brainfuck
        // needs to know about, so we do the obvious thing of just
        // taking each one and combining into a single expression.
        macro_rules! recompose {
            ($($token: expr),*) => {
                {
                    let stmts = vec!(
                        $(
                            {
                                let e = self.token_to_expr(sp,&$token)
                                    .expect("brainfuck: invalid token decomposition?");
                                self.cx.stmt_expr(e)
                            } ),* );
                    Some(self.cx.expr_block(self.cx.block(sp, stmts, None)))
                }
            }
        }
        let idx = &self.idx;
        let array = &self.array;
        match *tok {
            token::LT | token::GT => {
                let left = *tok == token::LT;
                Some(quote_expr!(self.cx, {
                    if $left {
                        if $idx > 0 {
                            $idx -= 1;
                        }
                    } else {
                        if $idx < $array.len() - 1 {
                            $idx += 1;
                        }
                    }
                }))
            }
            // <<
            token::BINOP(token::SHL) => recompose!(token::LT, token::LT),
            // >>
            token::BINOP(token::SHR) => recompose!(token::GT, token::GT),

            token::DOT => {
                let wtr = &self.wtr;
                Some(quote_expr!(self.cx, try!($wtr.write([$array[$idx]]))))
            }
            // ..
            token::DOTDOT => recompose!(token::DOT, token::DOT),
            // ...
            token::DOTDOTDOT => recompose!(token::DOT, token::DOT, token::DOT),

            token::COMMA => {
                let rdr = &self.rdr;
                Some(quote_expr!(self.cx, {
                    use std::io;
                    $array[$idx] = match $rdr.read_byte() {
                        Ok(b) => b,
                        Err(io::IoError { kind: io::EndOfFile, .. }) => -1,
                        Err(e) => return Err(e)
                    }
                }))
            }

            token::BINOP(a @ token::PLUS) | token::BINOP(a @ token::MINUS) => {
                let dir: u8 = if a == token::PLUS { 1 } else { -1 };

                Some(quote_expr!(self.cx, {
                    $array[$idx] += $dir
                }))
            }
            // ->
            token::RARROW => recompose!(token::BINOP(token::MINUS), token::GT),
            // <-
            token::LARROW => recompose!(token::LT, token::BINOP(token::MINUS)),
            _ => {
                None
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Repharse example in Url::join docs.<commit_after><|endoftext|>


<commit_before><commit_msg>updated to current buildable api<commit_after><|endoftext|>


<commit_before><commit_msg>Disallow missing docs<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unnecessary Clone bound<commit_after><|endoftext|>


<commit_before><commit_msg>`IXAudio2Voice::GetEffectState()`<commit_after><|endoftext|>


<commit_before><commit_msg>Added a solution for the Fibonnaci word problem<commit_after>use entropy::shannon_entropy;
mod entropy;

fn main() {
    println!("{:>2s}:{:>10s} {:s}", "N", "length", "entropy");

    let mut previous = ~"1";
    println!("{:>2i}:{:>10u} {:f}", 1, previous.len(), shannon_entropy(previous));

    let mut next = ~"0";
    println!("{:>2i}:{:>10u} {:f}", 2, next.len(), shannon_entropy(next));

    for i in range(3, 38) {
        let temp = next.clone();
        next.push_str(previous);
        previous = temp;
        println!("{:>2i}:{:>10u} {:.15f}", i, next.len(), shannon_entropy(next));
    }
}<|endoftext|>


<commit_before><commit_msg>od: add byteorder_io<commit_after>// from: https://github.com/netvl/immeta/blob/4460ee/src/utils.rs#L76

use std::io::{self, Read, BufRead, ErrorKind};

use byteorder::{self, ReadBytesExt, LittleEndian, BigEndian};
use byteorder::ByteOrder as ByteOrderTrait;

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ByteOrder {
    Little,
    Big,
}

macro_rules! gen_byte_order_ops {
    ($($read_name:ident, $write_name:ident -> $tpe:ty),+) => {
        impl ByteOrder {
            $(
            #[inline]
            pub fn $read_name(self, source: &[u8]) -> $tpe {
                match self {
                    ByteOrder::Little => LittleEndian::$read_name(source),
                    ByteOrder::Big => BigEndian::$read_name(source),
                }
            }

            pub fn $write_name(self, target: &mut [u8], n: $tpe) {
                match self {
                    ByteOrder::Little => LittleEndian::$write_name(target, n),
                    ByteOrder::Big => BigEndian::$write_name(target, n),
                }
            }
            )+
        }
    }
}

gen_byte_order_ops! {
    read_u16, write_u16 -> u16,
    read_u32, write_u32 -> u32,
    read_u64, write_u64 -> u64,
    read_i16, write_i16 -> i16,
    read_i32, write_i32 -> i32,
    read_i64, write_i64 -> i64,
    read_f32, write_f32 -> f32,
    read_f64, write_f64 -> f64
}
<|endoftext|>