<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;

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

mod duration;

/// A measurement of a monotonically increasing clock.
///
/// 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)]
#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
pub struct Instant(time::Instant);

/// A measurement of the system clock appropriate for timestamps such as those
/// on files on the filesystem.
///
/// 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)]
#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
pub struct SystemTime(time::SystemTime);

/// An error returned from the `duration_from_earlier` method on `SystemTime`,
/// used to learn about why how far in the opposite direction a timestamp lies.
#[derive(Clone, Debug)]
#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
pub struct SystemTimeError(Duration);

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Instant {
    /// Returns an instant corresponding to "now".
    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.
    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.
    pub fn elapsed(&self) -> Duration {
        Instant::now().duration_from_earlier(*self)
    }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Add<Duration> for Instant {
    type Output = Instant;

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

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Sub<Duration> for Instant {
    type Output = Instant;

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

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl fmt::Debug for Instant {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl SystemTime {
    /// Returns the system time corresponding to "now".
    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.
    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.
    pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
        SystemTime::now().duration_from_earlier(*self)
    }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Add<Duration> for SystemTime {
    type Output = SystemTime;

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

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Sub<Duration> for SystemTime {
    type Output = SystemTime;

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

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
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_from_earlier` 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.
#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
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_from_earlier`
    /// operation whenever the second system time represents a point later
    /// in time than the `self` of the method call.
    pub fn duration(&self) -> Duration {
        self.0
    }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Error for SystemTimeError {
    fn description(&self) -> &str { "other time was not earlier than self" }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl fmt::Display for SystemTimeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "second time provided was later than self")
    }
}

#[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_from_earlier(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_from_earlier(a);
    }

    #[test]
    fn system_time_math() {
        let a = SystemTime::now();
        let b = SystemTime::now();
        match b.duration_from_earlier(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_from_earlier(a - second).unwrap(), second);
        assert_almost_eq!(a.duration_from_earlier(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_from_earlier(UNIX_EPOCH).unwrap();
        let b = ts.duration_from_earlier(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>Instant/SystemTime doc: add meaning to first line<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.

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

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

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

mod duration;

/// A measurement of a monotonically increasing clock,
/// only meaningful within one process.
///
/// 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)]
#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
pub struct Instant(time::Instant);

/// A measurement of the system clock appropriate for timestamps meaningful
/// outside one process, such as those on files on the filesystem.
///
/// 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)]
#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
pub struct SystemTime(time::SystemTime);

/// An error returned from the `duration_from_earlier` method on `SystemTime`,
/// used to learn about why how far in the opposite direction a timestamp lies.
#[derive(Clone, Debug)]
#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
pub struct SystemTimeError(Duration);

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Instant {
    /// Returns an instant corresponding to "now".
    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.
    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.
    pub fn elapsed(&self) -> Duration {
        Instant::now().duration_from_earlier(*self)
    }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Add<Duration> for Instant {
    type Output = Instant;

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

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Sub<Duration> for Instant {
    type Output = Instant;

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

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl fmt::Debug for Instant {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl SystemTime {
    /// Returns the system time corresponding to "now".
    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.
    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.
    pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
        SystemTime::now().duration_from_earlier(*self)
    }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Add<Duration> for SystemTime {
    type Output = SystemTime;

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

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Sub<Duration> for SystemTime {
    type Output = SystemTime;

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

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
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_from_earlier` 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.
#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
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_from_earlier`
    /// operation whenever the second system time represents a point later
    /// in time than the `self` of the method call.
    pub fn duration(&self) -> Duration {
        self.0
    }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl Error for SystemTimeError {
    fn description(&self) -> &str { "other time was not earlier than self" }
}

#[unstable(feature = "time2", reason = "recently added", issue = "29866")]
impl fmt::Display for SystemTimeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "second time provided was later than self")
    }
}

#[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_from_earlier(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_from_earlier(a);
    }

    #[test]
    fn system_time_math() {
        let a = SystemTime::now();
        let b = SystemTime::now();
        match b.duration_from_earlier(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_from_earlier(a - second).unwrap(), second);
        assert_almost_eq!(a.duration_from_earlier(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_from_earlier(UNIX_EPOCH).unwrap();
        let b = ts.duration_from_earlier(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>Problem 14<commit_after>fn dupli<T: Clone>(list: &[T]) -> ~[T] {
    let mut r = ~[];
    for e in list.iter() {
        r.push(e.clone());
        r.push(e.clone());
    }
    r
}

fn main() {
    let list = ~['a', 'b', 'c', 'c', 'd'];
    println!("{:?}", dupli(list));
}

<|endoftext|>


<commit_before><commit_msg>File dumps and wrapped input<commit_after>use std::fs::File;
use std::path::Path;
use std::error::Error;
use std::io::prelude::*;

pub fn read_in(file_path: &str) -> String
{
    let path = Path::new(file_path);
    let display = path.display();

    let mut file = match File::open(&path)
    {
        Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
        Ok(file) => file,
    };

    let mut file_as_string = String::new();
    match file.read_to_string(&mut file_as_string) {
        Err(why) => panic!("couldn't read {}: {}", display, Error::description(&why)),
        Ok(_) => {},
    }

    file_as_string
}

pub fn dump(file_path: &str, data: String)
{
    let path = Path::new(file_path);
    let display = path.display();

    let mut file = match File::create(&path)
    {
        Err(why) => panic!("couldn't create {}: {}", display, Error::description(&why)),
        Ok(file) => file,
    };

    match file.write_all(data.as_bytes())
    {
        Err(why) => {panic!("couldn't write to {}: {}", display, Error::description(&why))},
        Ok(_) => println!("successfully output to {}", display),
    }
}
<|endoftext|>


<commit_before><commit_msg>Intermediate network commit.<commit_after><|endoftext|>


<commit_before><commit_msg>move semantics, chapter 2<commit_after>// move1.rs
fn main() {
    let s1 = "hello dolly".to_string();
    let s2 = s1;
    println!("s1 {}", s1);
}
<|endoftext|>


<commit_before><commit_msg>Problem 20<commit_after>fn drop<T: Clone>(list: &[T], k: uint) -> ~[T] {
    let mut res = ~[];
    res.push_all(list.slice_to(k-1));
    res.push_all(list.slice_from(k));
    res
}

fn main() {
    let list = ~['a', 'b', 'c', 'd'];
    println!("{:?}", drop(list, 2));
}

<|endoftext|>


<commit_before><commit_msg>Some change to the blackboard<commit_after><|endoftext|>


<commit_before><commit_msg>[Rust] overflow panicked on debug build<commit_after>fn main() {
    let a: u8 = 0xf0;
    let b: u8 = 0xf0;
    println!("{} {} {}", a, b, a + b);
}
<|endoftext|>


<commit_before><commit_msg>test: Ensure we can read proxy params from environment<commit_after>#![cfg(feature = "reqwest-backend")]

use std::env::{remove_var, set_var};

use env_proxy::for_url;
use url::Url;

fn scrub_env() {
    remove_var("http_proxy");
    remove_var("https_proxy");
    remove_var("HTTPS_PROXY");
    remove_var("ftp_proxy");
    remove_var("FTP_PROXY");
    remove_var("all_proxy");
    remove_var("ALL_PROXY");
    remove_var("no_proxy");
    remove_var("NO_PROXY");
}

// Tests for correctly retrieving the proxy (host, port) tuple from $https_proxy
#[test]
fn read_basic_proxy_params() {
    scrub_env();
    set_var("https_proxy", "http://proxy.example.com:8080");
    let u = Url::parse("https://www.example.org").ok().unwrap();
    assert_eq!(
        for_url(&u).host_port(),
        Some(("proxy.example.com".to_string(), 8080))
    );
}
<|endoftext|>


<commit_before><commit_msg>problem: unsafe scrypt params solution: do unsafe only for particular values<commit_after><|endoftext|>


<commit_before><commit_msg>play is ready for hog debugging<commit_after><|endoftext|>


<commit_before><commit_msg>Added rotation and scaling to polygons<commit_after><|endoftext|>


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

// Test that fn item types are zero-sized.

use std::mem::{size_of, size_of_val};

fn main() {
    assert_eq!(size_of_val(&main), 0);

    let (a, b) = (size_of::<u8>, size_of::<u16>);
    assert_eq!(size_of_val(&a), 0);
    assert_eq!(size_of_val(&b), 0);
    assert_eq!((a(), b()), (1, 2));
}
<|endoftext|>


<commit_before><commit_msg>added main<commit_after>
fn main() {
    println!("Thunderdome Graph Server starting up...");

    println!("Thunderdome Graph Server shutting down");
}
<|endoftext|>


<commit_before><commit_msg>Correct line drawing and transformation order.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove a few derives to reduce compile times<commit_after><|endoftext|>


<commit_before><commit_msg>addding new site cmd<commit_after><|endoftext|>


<commit_before><commit_msg>Improve version parsing to handle v12<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor of Print Function (WIP) (#9)<commit_after><|endoftext|>


<commit_before>#[macro_use] extern crate clap;
#[macro_use] extern crate log;
#[macro_use] extern crate serde;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate glob;
#[macro_use] extern crate uuid;
#[macro_use] extern crate regex;
extern crate config;

use cli::CliConfig;
use configuration::Configuration;
use runtime::{ImagLogger, Runtime};
use clap::App;
use module::Module;
use module::ModuleError;
use module::CommandEnv;
use module::bm::BMModule;
use storage::backend::StorageBackend;

mod cli;
mod configuration;
mod runtime;
mod module;
mod storage;
mod ui;

fn main() {
    let yaml = load_yaml!("../etc/cli.yml");
    let app = App::from_yaml(yaml);
    let config = CliConfig::new(app);
    let configuration = Configuration::new(&config);

    let logger = ImagLogger::init(&configuration, &config);
    debug!("Logger created!");

    debug!("CliConfig    : {:?}", &config);
    debug!("Configuration: {:?}", &configuration);

    let rt = Runtime::new(configuration, config);

    debug!("Runtime      : {:?}", &rt);

    if let Some(matches) = rt.config.cli_matches.subcommand_matches("bm") {
        let module            = BMModule::new(&rt);
        let commands          = module.get_commands(&rt);
        if let Some(command)  = matches.subcommand_name() {
            debug!("Subcommand: {}", command);

            let backend = StorageBackend::new(&rt);

            let cmdenv = CommandEnv {
                rt: &rt,
                bk: &backend,
                matches: matches.subcommand_matches(command).unwrap(),
            };

            let result = match commands.get(command) {
                Some(f) => f(&module, cmdenv),
                None    => Err(ModuleError::new("No subcommand found")),
            };

            debug!("Result of command: {:?}", result);
        } else {
            debug!("No subcommand");
        }

        module.shutdown(&rt);
    } else {
        // Err(ModuleError::mk("No commandline call"))
        info!("No commandline call...")
    }

    info!("Hello, world!");
}
<commit_msg>Use prettytable to implement TablePrinter<commit_after>#[macro_use] extern crate clap;
#[macro_use] extern crate log;
#[macro_use] extern crate serde;
#[macro_use] extern crate serde_json;
#[macro_use] extern crate glob;
#[macro_use] extern crate uuid;
#[macro_use] extern crate regex;
#[macro_use] extern crate prettytable;
extern crate config;

use cli::CliConfig;
use configuration::Configuration;
use runtime::{ImagLogger, Runtime};
use clap::App;
use module::Module;
use module::ModuleError;
use module::CommandEnv;
use module::bm::BMModule;
use storage::backend::StorageBackend;

mod cli;
mod configuration;
mod runtime;
mod module;
mod storage;
mod ui;

fn main() {
    let yaml = load_yaml!("../etc/cli.yml");
    let app = App::from_yaml(yaml);
    let config = CliConfig::new(app);
    let configuration = Configuration::new(&config);

    let logger = ImagLogger::init(&configuration, &config);
    debug!("Logger created!");

    debug!("CliConfig    : {:?}", &config);
    debug!("Configuration: {:?}", &configuration);

    let rt = Runtime::new(configuration, config);

    debug!("Runtime      : {:?}", &rt);

    if let Some(matches) = rt.config.cli_matches.subcommand_matches("bm") {
        let module            = BMModule::new(&rt);
        let commands          = module.get_commands(&rt);
        if let Some(command)  = matches.subcommand_name() {
            debug!("Subcommand: {}", command);

            let backend = StorageBackend::new(&rt);

            let cmdenv = CommandEnv {
                rt: &rt,
                bk: &backend,
                matches: matches.subcommand_matches(command).unwrap(),
            };

            let result = match commands.get(command) {
                Some(f) => f(&module, cmdenv),
                None    => Err(ModuleError::new("No subcommand found")),
            };

            debug!("Result of command: {:?}", result);
        } else {
            debug!("No subcommand");
        }

        module.shutdown(&rt);
    } else {
        // Err(ModuleError::mk("No commandline call"))
        info!("No commandline call...")
    }

    info!("Hello, world!");
}
<|endoftext|>


<commit_before><commit_msg>Reverting back to old compile! macro<commit_after><|endoftext|>


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

//! The Rust Prelude
//!
//! Rust comes with a variety of things in its standard library. However, if
//! you had to manually import every single thing that you used, it would be
//! very verbose. But importing a lot of things that a program never uses isn't
//! good either. A balance needs to be struck.
//!
//! The *prelude* is the list of things that Rust automatically imports into
//! every Rust program. It's kept as small as possible, and is focused on
//! things, particuarly traits, which are used in almost every single Rust
//! program.
//!
//! On a technical level, Rust inserts
//!
//! ```ignore
//! extern crate std;
//! ```
//!
//! into the crate root of every crate, and
//!
//! ```ignore
//! use std::prelude::v1::*;
//! ```
//!
//! into every module.
//!
//! # Other preludes
//!
//! Preludes can be seen as a pattern to make using multiple types more
//! convenient. As such, you'll find other preludes in the standard library,
//! such as [`std::io::prelude`]. Various libraries in the Rust ecosystem may
//! also define their own preludes.
//!
//! [`std::io::prelude`]: ../io/prelude/index.html
//!
//! The differece between 'the prelude' and these other preludes is that they
//! are not automatically `use`'d, and must be imported manually. This is still
//! easier than importing all of their consitutent components.
//!
//! # Prelude contents
//!
//! The current version of the prelude (version 1) lives in
//! [`std::prelude::v1`], and reexports the following.
//!
//! * [`std::marker`]::{[`Copy`], [`Send`], [`Sized`], [`Sync`]}. The marker
//!   traits indicate fundamental properties of types.
//! * [`std::ops`]::{[`Drop`], [`Fn`], [`FnMut`], [`FnOnce`]}. Various
//!   operations for both destuctors and overloading `()`.
//! * [`std::mem`]::[`drop`], a convenience function for explicitly dropping a
//!   value.
//! * [`std::boxed`]::[`Box`], a way to allocate values on the heap.
//! * [`std::borrow`]::[`ToOwned`], The conversion trait that defines
//!   [`to_owned()`], the generic method for creating an owned type from a
//!   borrowed type.
//! * [`std::clone`]::[`Clone`], the ubiquitous trait that defines [`clone()`],
//!   the method for producing a copy of a value.
//! * [`std::cmp`]::{[`PartialEq`], [`PartialOrd`], [`Eq`], [`Ord`] }. The
//!   comparison traits, which implement the comparison operators and are often
//!   seen in trait bounds.
//! * [`std::convert`]::{[`AsRef`], [`AsMut`], [`Into`], [`From`]}. Generic
//!   conversions, used by savvy API authors to create overloaded methods.
//! * [`std::default`]::[`Default`], types that have default values.
//! * [`std::iter`]::{[`Iterator`], [`Extend`], [`IntoIterator`],
//!   [`DoubleEndedIterator`], [`ExactSizeIterator`]}. Iterators of various
//!   kinds.
//! * [`std::option`]::[`Option`]::{`self`, `Some`, `None`}. A type which
//!   expresses the presence or absence of a value. This type is so commonly
//!   used, its variants are also exported.
//! * [`std::result`]::[`Result`]::{`self`, `Ok`, `Err`}. A type for functions
//!   that may succeed or fail. Like [`Option`], its variants are exported as
//!   well.
//! * [`std::slice`]::[`SliceConcatExt`], a trait that exists for technical
//!   reasons, but shouldn't have to exist. It provides a few useful methods on
//!   slices.
//! * [`std::string`]::{[`String`], [`ToString`]}, heap allocated strings.
//! * [`std::vec`]::[`Vec`](../vec/struct.Vec.html), a growable, heap-allocated
//!   vector.
//!
//! [`AsMut`]: ../convert/trait.AsMut.html
//! [`AsRef`]: ../convert/trait.AsRef.html
//! [`Box`]: ../boxed/struct.Box.html
//! [`Clone`]: ../clone/trait.Clone.html
//! [`Copy`]: ../marker/trait.Copy.html
//! [`Default`]: ../default/trait.Default.html
//! [`DoubleEndedIterator`]: ../iter/trait.DoubleEndedIterator.html
//! [`Drop`]: ../ops/trait.Drop.html
//! [`Eq`]: ../cmp/trait.Eq.html
//! [`ExactSizeIterator`]: ../iter/trait.ExactSizeIterator.html
//! [`Extend`]: ../iter/trait.Extend.html
//! [`FnMut`]: ../ops/trait.FnMut.html
//! [`FnOnce`]: ../ops/trait.FnOnce.html
//! [`Fn`]: ../ops/trait.Fn.html
//! [`From`]: ../convert/trait.From.html
//! [`IntoIterator`]: ../iter/trait.IntoIterator.html
//! [`Into`]: ../convert/trait.Into.html
//! [`Iterator`]: ../iter/trait.Iterator.html
//! [`Option`]: ../option/enum.Option.html
//! [`Ord`]: ../cmp/trait.Ord.html
//! [`PartialEq`]: ../cmp/trait.PartialEq.html
//! [`PartialOrd`]: ../cmp/trait.PartialOrd.html
//! [`Result`]: ../result/enum.Result.html
//! [`Send`]: ../marker/trait.Send.html
//! [`Sized`]: ../marker/trait.Sized.html
//! [`SliceConcatExt`]: ../slice/trait.SliceConcatExt.html
//! [`String`]: ../string/struct.String.html
//! [`Sync`]: ../marker/trait.Sync.html
//! [`ToOwned`]: ../borrow/trait.ToOwned.html
//! [`ToString`]: ../string/trait.ToString.html
//! [`Vec`]: ../vec/struct.Vec.html
//! [`clone()`]: ../clone/trait.Clone.html#tymethod.clone
//! [`drop`]: ../mem/fn.drop.html
//! [`std::borrow`]: ../borrow/index.html
//! [`std::boxed`]: ../boxed/index.html
//! [`std::clone`]: ../clone/index.html
//! [`std::cmp`]: ../cmp/index.html
//! [`std::convert`]: ../convert/index.html
//! [`std::default`]: ../default/index.html
//! [`std::iter`]: ../iter/index.html
//! [`std::marker`]: ../marker/index.html
//! [`std::mem`]: ../mem/index.html
//! [`std::ops`]: ../ops/index.html
//! [`std::option`]: ../option/index.html
//! [`std::prelude::v1`]: v1/index.html
//! [`std::result`]: ../result/index.html
//! [`std::slice`]: ../slice/index.html
//! [`std::string`]: ../string/index.html
//! [`std::vec`]: ../vec/index.html
//! [`to_owned()`]: ../borrow/trait.ToOwned.html#tymethod.to_owned
//! [book-closures]: ../../book/closures.html
//! [book-dtor]: ../../book/drop.html
//! [book-enums]: ../../book/enums.html
//! [book-iter]: ../../book/iterators.html

#![stable(feature = "rust1", since = "1.0.0")]

pub mod v1;
<commit_msg>doc: fix typo<commit_after>// Copyright 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.

//! The Rust Prelude
//!
//! Rust comes with a variety of things in its standard library. However, if
//! you had to manually import every single thing that you used, it would be
//! very verbose. But importing a lot of things that a program never uses isn't
//! good either. A balance needs to be struck.
//!
//! The *prelude* is the list of things that Rust automatically imports into
//! every Rust program. It's kept as small as possible, and is focused on
//! things, particuarly traits, which are used in almost every single Rust
//! program.
//!
//! On a technical level, Rust inserts
//!
//! ```ignore
//! extern crate std;
//! ```
//!
//! into the crate root of every crate, and
//!
//! ```ignore
//! use std::prelude::v1::*;
//! ```
//!
//! into every module.
//!
//! # Other preludes
//!
//! Preludes can be seen as a pattern to make using multiple types more
//! convenient. As such, you'll find other preludes in the standard library,
//! such as [`std::io::prelude`]. Various libraries in the Rust ecosystem may
//! also define their own preludes.
//!
//! [`std::io::prelude`]: ../io/prelude/index.html
//!
//! The difference between 'the prelude' and these other preludes is that they
//! are not automatically `use`'d, and must be imported manually. This is still
//! easier than importing all of their consitutent components.
//!
//! # Prelude contents
//!
//! The current version of the prelude (version 1) lives in
//! [`std::prelude::v1`], and reexports the following.
//!
//! * [`std::marker`]::{[`Copy`], [`Send`], [`Sized`], [`Sync`]}. The marker
//!   traits indicate fundamental properties of types.
//! * [`std::ops`]::{[`Drop`], [`Fn`], [`FnMut`], [`FnOnce`]}. Various
//!   operations for both destuctors and overloading `()`.
//! * [`std::mem`]::[`drop`], a convenience function for explicitly dropping a
//!   value.
//! * [`std::boxed`]::[`Box`], a way to allocate values on the heap.
//! * [`std::borrow`]::[`ToOwned`], The conversion trait that defines
//!   [`to_owned()`], the generic method for creating an owned type from a
//!   borrowed type.
//! * [`std::clone`]::[`Clone`], the ubiquitous trait that defines [`clone()`],
//!   the method for producing a copy of a value.
//! * [`std::cmp`]::{[`PartialEq`], [`PartialOrd`], [`Eq`], [`Ord`] }. The
//!   comparison traits, which implement the comparison operators and are often
//!   seen in trait bounds.
//! * [`std::convert`]::{[`AsRef`], [`AsMut`], [`Into`], [`From`]}. Generic
//!   conversions, used by savvy API authors to create overloaded methods.
//! * [`std::default`]::[`Default`], types that have default values.
//! * [`std::iter`]::{[`Iterator`], [`Extend`], [`IntoIterator`],
//!   [`DoubleEndedIterator`], [`ExactSizeIterator`]}. Iterators of various
//!   kinds.
//! * [`std::option`]::[`Option`]::{`self`, `Some`, `None`}. A type which
//!   expresses the presence or absence of a value. This type is so commonly
//!   used, its variants are also exported.
//! * [`std::result`]::[`Result`]::{`self`, `Ok`, `Err`}. A type for functions
//!   that may succeed or fail. Like [`Option`], its variants are exported as
//!   well.
//! * [`std::slice`]::[`SliceConcatExt`], a trait that exists for technical
//!   reasons, but shouldn't have to exist. It provides a few useful methods on
//!   slices.
//! * [`std::string`]::{[`String`], [`ToString`]}, heap allocated strings.
//! * [`std::vec`]::[`Vec`](../vec/struct.Vec.html), a growable, heap-allocated
//!   vector.
//!
//! [`AsMut`]: ../convert/trait.AsMut.html
//! [`AsRef`]: ../convert/trait.AsRef.html
//! [`Box`]: ../boxed/struct.Box.html
//! [`Clone`]: ../clone/trait.Clone.html
//! [`Copy`]: ../marker/trait.Copy.html
//! [`Default`]: ../default/trait.Default.html
//! [`DoubleEndedIterator`]: ../iter/trait.DoubleEndedIterator.html
//! [`Drop`]: ../ops/trait.Drop.html
//! [`Eq`]: ../cmp/trait.Eq.html
//! [`ExactSizeIterator`]: ../iter/trait.ExactSizeIterator.html
//! [`Extend`]: ../iter/trait.Extend.html
//! [`FnMut`]: ../ops/trait.FnMut.html
//! [`FnOnce`]: ../ops/trait.FnOnce.html
//! [`Fn`]: ../ops/trait.Fn.html
//! [`From`]: ../convert/trait.From.html
//! [`IntoIterator`]: ../iter/trait.IntoIterator.html
//! [`Into`]: ../convert/trait.Into.html
//! [`Iterator`]: ../iter/trait.Iterator.html
//! [`Option`]: ../option/enum.Option.html
//! [`Ord`]: ../cmp/trait.Ord.html
//! [`PartialEq`]: ../cmp/trait.PartialEq.html
//! [`PartialOrd`]: ../cmp/trait.PartialOrd.html
//! [`Result`]: ../result/enum.Result.html
//! [`Send`]: ../marker/trait.Send.html
//! [`Sized`]: ../marker/trait.Sized.html
//! [`SliceConcatExt`]: ../slice/trait.SliceConcatExt.html
//! [`String`]: ../string/struct.String.html
//! [`Sync`]: ../marker/trait.Sync.html
//! [`ToOwned`]: ../borrow/trait.ToOwned.html
//! [`ToString`]: ../string/trait.ToString.html
//! [`Vec`]: ../vec/struct.Vec.html
//! [`clone()`]: ../clone/trait.Clone.html#tymethod.clone
//! [`drop`]: ../mem/fn.drop.html
//! [`std::borrow`]: ../borrow/index.html
//! [`std::boxed`]: ../boxed/index.html
//! [`std::clone`]: ../clone/index.html
//! [`std::cmp`]: ../cmp/index.html
//! [`std::convert`]: ../convert/index.html
//! [`std::default`]: ../default/index.html
//! [`std::iter`]: ../iter/index.html
//! [`std::marker`]: ../marker/index.html
//! [`std::mem`]: ../mem/index.html
//! [`std::ops`]: ../ops/index.html
//! [`std::option`]: ../option/index.html
//! [`std::prelude::v1`]: v1/index.html
//! [`std::result`]: ../result/index.html
//! [`std::slice`]: ../slice/index.html
//! [`std::string`]: ../string/index.html
//! [`std::vec`]: ../vec/index.html
//! [`to_owned()`]: ../borrow/trait.ToOwned.html#tymethod.to_owned
//! [book-closures]: ../../book/closures.html
//! [book-dtor]: ../../book/drop.html
//! [book-enums]: ../../book/enums.html
//! [book-iter]: ../../book/iterators.html

#![stable(feature = "rust1", since = "1.0.0")]

pub mod v1;
<|endoftext|>


<commit_before>//! Blanket impls for Middleware.
//! This is pre-implemented for any function which takes a
//! `Request` and `Response` parameter and returns anything
//! implementing the `ResponseFinalizer` trait. It is also
//! implemented for a tuple of a function and a type `T`.
//! The function must take a `Request`, a `Response` and a
//! `T`, returning anything that implements `ResponseFinalizer`.
//! The data of type `T` will then be shared and available
//! in any request.
//!
//! Please see the examples for usage.

use request::Request;
use response::Response;
use hyper::status::StatusCode;
use http::headers;
use std::fmt::Display;
use std::num::FromPrimitive;
use middleware::{Middleware, MiddlewareResult, Halt};
use serialize::json;
use mimes::MediaType;

impl<R> Middleware for fn(&Request, &mut Response) -> R
        where R: ResponseFinalizer {
    fn invoke<'a, 'b>(&self, req: &mut Request<'a, 'b>, res: &mut Response) -> MiddlewareResult {
        let r = (*self)(req, res);
        r.respond(res)
    }
}

impl<T, R> Middleware for (fn(&Request, &mut Response, &T) -> R, T)
        where T: Send + Sync + 'static, R: ResponseFinalizer + 'static {
    fn invoke<'a, 'b>(&self, req: &mut Request<'a, 'b>, res: &mut Response) -> MiddlewareResult {
        let (f, ref data) = *self;
        let r = f(req, res, data);
        r.respond(res)
    }
}

impl<R> Middleware for fn(&mut Request, &mut Response) -> R
        where R: ResponseFinalizer {
    fn invoke<'a, 'b>(&self, req: &mut Request<'a, 'b>, res: &mut Response) -> MiddlewareResult {
        let r = (*self)(req, res);
        r.respond(res)
    }
}

impl<T, R> Middleware for (fn(&mut Request, &mut Response, &T) -> R, T)
        where T: Send + Sync + 'static, R: ResponseFinalizer + 'static {
    fn invoke<'a, 'b>(&self, req: &mut Request<'a, 'b>, res: &mut Response) -> MiddlewareResult {
        let (f, ref data) = *self;
        let r = f(req, res, data);
        r.respond(res)
    }
}

/// This trait provides convenience for translating a number
/// of common return types into a `MiddlewareResult` while
/// also modifying the `Response` as required.
///
/// Please see the examples for some uses.
pub trait ResponseFinalizer {
    fn respond(self, &mut Response) -> MiddlewareResult;
}

impl ResponseFinalizer for () {
    fn respond(self, res: &mut Response) -> MiddlewareResult {
        maybe_set_type(res, MediaType::Html);
        Ok(Halt)
    }
}

impl ResponseFinalizer for MiddlewareResult {
    fn respond(self, res: &mut Response) -> MiddlewareResult {
        maybe_set_type(res, MediaType::Html);
        self
    }
}

impl ResponseFinalizer for json::Json {
    fn respond(self, res: &mut Response) -> MiddlewareResult {
        maybe_set_type(res, MediaType::Json);
        // FIXME: remove unwrap
        res.send(json::encode(&self).unwrap());
        Ok(Halt)
    }
}

impl<'a, S: Display> ResponseFinalizer for &'a [S] {
    fn respond(self, res: &mut Response) -> MiddlewareResult {
        maybe_set_type(res, MediaType::Html);
        res.origin.status = StatusCode::Ok;
        for ref s in self.iter() {
            // FIXME : failure unhandled
            let _ = write!(res.origin, "{}", s);
        }
        Ok(Halt)
    }
}

macro_rules! dual_impl {
    ($view:ty, $alloc:ty, |$s:ident, $res:ident| $b:block) => (
        impl<'a> ResponseFinalizer for $view {
            fn respond($s, $res: &mut Response) -> MiddlewareResult $b
        }

        impl ResponseFinalizer for $alloc {
            fn respond($s, $res: &mut Response) -> MiddlewareResult $b
        }
    )
}

dual_impl!(&'a str,
           String,
            |self, res| {
                maybe_set_type(res, MediaType::Html);
                res.origin.status = StatusCode::Ok;
                res.send(self);
                Ok(Halt)
            });

dual_impl!((StatusCode, &'a str),
           (StatusCode, String),
            |self, res| {
                maybe_set_type(res, MediaType::Html);
                let (status, data) = self;
                res.origin.status = status;
                res.send(data);
                Ok(Halt)
            });

dual_impl!((usize, &'a str),
           (usize, String),
           |self, res| {
                maybe_set_type(res, MediaType::Html);
                let (status, data) = self;
                match FromPrimitive::from_uint(status) {
                    Some(status) => {
                        res.origin.status = status;
                        res.send(data);
                        Ok(Halt)
                    }
                    // This is a logic error
                    None => panic!("Bad status code")
                }
            });

dual_impl!((StatusCode, &'a str, Vec<headers::response::Header>),
           (StatusCode, String, Vec<headers::response::Header>),
           |self, res| {
                let (status, data, headers) = self;

                res.origin.status = status;
                for header in headers.into_iter() {
                    res.origin.headers.insert(header);
                }
                maybe_set_type(res, MediaType::Html);
                res.send(data);
                Ok(Halt)
            });

fn maybe_set_type(res: &mut Response, ty: MediaType) {
    if res.origin.headers.content_type.is_none() {
        res.content_type(ty);
    }
}
<commit_msg>refactor(hyper): depreciate one of the blanket impls for now<commit_after>//! Blanket impls for Middleware.
//! This is pre-implemented for any function which takes a
//! `Request` and `Response` parameter and returns anything
//! implementing the `ResponseFinalizer` trait. It is also
//! implemented for a tuple of a function and a type `T`.
//! The function must take a `Request`, a `Response` and a
//! `T`, returning anything that implements `ResponseFinalizer`.
//! The data of type `T` will then be shared and available
//! in any request.
//!
//! Please see the examples for usage.

use request::Request;
use response::Response;
use hyper::status::StatusCode;
use std::fmt::Display;
use std::num::FromPrimitive;
// use hyper::header::{Header, HeaderFormat};
use middleware::{Middleware, MiddlewareResult, Halt};
use serialize::json;
use mimes::MediaType;

impl<R> Middleware for fn(&Request, &mut Response) -> R
        where R: ResponseFinalizer {
    fn invoke<'a, 'b>(&self, req: &mut Request<'a, 'b>, res: &mut Response) -> MiddlewareResult {
        let r = (*self)(req, res);
        r.respond(res)
    }
}

impl<T, R> Middleware for (fn(&Request, &mut Response, &T) -> R, T)
        where T: Send + Sync + 'static, R: ResponseFinalizer + 'static {
    fn invoke<'a, 'b>(&self, req: &mut Request<'a, 'b>, res: &mut Response) -> MiddlewareResult {
        let (f, ref data) = *self;
        let r = f(req, res, data);
        r.respond(res)
    }
}

impl<R> Middleware for fn(&mut Request, &mut Response) -> R
        where R: ResponseFinalizer {
    fn invoke<'a, 'b>(&self, req: &mut Request<'a, 'b>, res: &mut Response) -> MiddlewareResult {
        let r = (*self)(req, res);
        r.respond(res)
    }
}

impl<T, R> Middleware for (fn(&mut Request, &mut Response, &T) -> R, T)
        where T: Send + Sync + 'static, R: ResponseFinalizer + 'static {
    fn invoke<'a, 'b>(&self, req: &mut Request<'a, 'b>, res: &mut Response) -> MiddlewareResult {
        let (f, ref data) = *self;
        let r = f(req, res, data);
        r.respond(res)
    }
}

/// This trait provides convenience for translating a number
/// of common return types into a `MiddlewareResult` while
/// also modifying the `Response` as required.
///
/// Please see the examples for some uses.
pub trait ResponseFinalizer {
    fn respond(self, &mut Response) -> MiddlewareResult;
}

impl ResponseFinalizer for () {
    fn respond(self, res: &mut Response) -> MiddlewareResult {
        maybe_set_type(res, MediaType::Html);
        Ok(Halt)
    }
}

impl ResponseFinalizer for MiddlewareResult {
    fn respond(self, res: &mut Response) -> MiddlewareResult {
        maybe_set_type(res, MediaType::Html);
        self
    }
}

impl ResponseFinalizer for json::Json {
    fn respond(self, res: &mut Response) -> MiddlewareResult {
        maybe_set_type(res, MediaType::Json);
        // FIXME: remove unwrap
        res.send(json::encode(&self).unwrap());
        Ok(Halt)
    }
}

impl<'a, S: Display> ResponseFinalizer for &'a [S] {
    fn respond(self, res: &mut Response) -> MiddlewareResult {
        maybe_set_type(res, MediaType::Html);
        res.origin.status = StatusCode::Ok;
        for ref s in self.iter() {
            // FIXME : failure unhandled
            let _ = write!(res.origin, "{}", s);
        }
        Ok(Halt)
    }
}

macro_rules! dual_impl {
    ($view:ty, $alloc:ty, |$s:ident, $res:ident| $b:block) => (
        impl<'a> ResponseFinalizer for $view {
            fn respond($s, $res: &mut Response) -> MiddlewareResult $b
        }

        impl ResponseFinalizer for $alloc {
            fn respond($s, $res: &mut Response) -> MiddlewareResult $b
        }
    )
}

dual_impl!(&'a str,
           String,
            |self, res| {
                maybe_set_type(res, MediaType::Html);
                res.origin.status = StatusCode::Ok;
                res.send(self);
                Ok(Halt)
            });

dual_impl!((StatusCode, &'a str),
           (StatusCode, String),
            |self, res| {
                maybe_set_type(res, MediaType::Html);
                let (status, data) = self;
                res.origin.status = status;
                res.send(data);
                Ok(Halt)
            });

dual_impl!((usize, &'a str),
           (usize, String),
           |self, res| {
                maybe_set_type(res, MediaType::Html);
                let (status, data) = self;
                match FromPrimitive::from_uint(status) {
                    Some(status) => {
                        res.origin.status = status;
                        res.send(data);
                        Ok(Halt)
                    }
                    // This is a logic error
                    None => panic!("Bad status code")
                }
            });

// FIXME: Hyper uses traits for headers, so this needs to be a Vec of
// trait objects. But, a trait object is unable to have Foo + Bar as a bound.
//
// A better/faster solution would be to impl this for tuples,
// where each tuple element implements the Header trait, which would give a
// static dispatch.
// dual_impl!((StatusCode, &'a str, Vec<Box<ResponseHeader>>),
//            (StatusCode, String, Vec<Box<ResponseHeader>>)
//            |self, res| {
//                 let (status, data, headers) = self;

//                 res.origin.status = status;
//                 for header in headers.into_iter() {
//                     res.origin.headers_mut().set(header);
//                 }
//                 maybe_set_type(res, MediaType::Html);
//                 res.send(data);
//                 Ok(Halt)
//             })

fn maybe_set_type(res: &mut Response, ty: MediaType) {
    if res.origin.headers.content_type.is_none() {
        res.content_type(ty);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add example code to get a project id (from its iid, the value shown in the URL)<commit_after>extern crate gitlab_api as gitlab;

use std::env;
#[macro_use]
extern crate log;
extern crate env_logger;
#[macro_use]
extern crate clap;

use gitlab::GitLab;
use gitlab::issues;
use gitlab::Lister;

use gitlab::errors::*;

fn main() {
    if let Err(ref e) = run() {
        println!("error: {}", e);

        for e in e.iter().skip(1) {
            println!("caused by: {}", e);
        }

        // The backtrace is not always generated. Try to run this example
        // with `RUST_BACKTRACE=1`.
        if let Some(backtrace) = e.backtrace() {
            println!("backtrace: {:?}", backtrace);
        }

        ::std::process::exit(1);
    }
}

fn run() -> Result<()> {
    env_logger::init().unwrap();
    info!("starting up");

    let hostname = match env::var("GITLAB_HOSTNAME") {
        Ok(val) => val,
        Err(_) => {
            let default = String::from("gitlab.com");
            println!("Please set environment variable 'GITLAB_HOSTNAME'. Using default '{}'.",
                     default);
            default
        }
    };

    let token = match env::var("GITLAB_TOKEN") {
        Ok(val) => val,
        Err(_) => {
            panic!("Please set environment variable 'GITLAB_TOKEN'. Take it from \
                    http://{}/profile/account",
                   hostname);
        }
    };

    let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?;
    // let gl = GitLab::new(&hostname, &token).chain_err(|| "failure to create GitLab instance")?.scheme("http").port(80);
    // let gl = gl.scheme("http").port(80);

    let matches = clap::App::new("get_id_project")
        .version("1.0")
        .author("Nicolas Bigaouette <nbigaouette@gmail.com>")
        .about("Get the id of a GitLab project from namespace/project.")
        .arg(clap::Arg::with_name("namespace")
            .help("The project's namespace (or group)")
            .long("namespace")
            .short("n")
            .takes_value(true)
            .required(true))
        .arg(clap::Arg::with_name("project")
            .help("The project's name")
            .long("project")
            .short("p")
            .takes_value(true)
            .required(true))
        .get_matches();

    let project_namespace = matches.value_of("namespace").unwrap();
    let project_name = matches.value_of("project").unwrap();

    let project = gl.get_project(project_namespace, project_name).chain_err(|| "cannot get project")?;
    // println!("project: {:?}", project);

    println!("Id for {}/{}: {}", project_namespace, project_name, project.id);

    Ok(())
}
<|endoftext|>


<commit_before>use std::rc::Rc;
use std::cell::RefCell;
use std::ops::Deref;
use std::process::exit;

use clap::ArgMatches;
use regex::Regex;

use storage::file::File;
use storage::file::hash::FileHash;
use storage::json::parser::JsonHeaderParser;
use storage::parser::FileHeaderParser;
use storage::parser::Parser;

pub trait CliFileFilter {

    fn filter_file(&self, &Rc<RefCell<File>>) -> bool;

    fn not(self) -> CliFileFilterNot
        where Self: Sized + 'static
    {
        CliFileFilterNot {
            a: Box::new(self),
        }
    }

    fn or(self, other: Box<CliFileFilter>) -> CliFileFilterOr
        where Self: Sized + 'static
    {
        CliFileFilterOr {
            a: Box::new(self),
            b: other
        }
    }

    fn and(self, other: Box<CliFileFilter>) -> CliFileFilterAnd
        where Self: Sized + 'static
    {
        CliFileFilterAnd {
            a: Box::new(self),
            b: other
        }
    }

}

pub struct CliFileFilterNot {
    a: Box<CliFileFilter>,
}

impl CliFileFilter for CliFileFilterNot {

    fn filter_file(&self, f: &Rc<RefCell<File>>) -> bool {
        !self.a.filter_file(f)
    }

}

pub struct CliFileFilterOr {
    a: Box<CliFileFilter>,
    b: Box<CliFileFilter>
}

impl CliFileFilter for CliFileFilterOr {

    fn filter_file(&self, f: &Rc<RefCell<File>>) -> bool {
        self.a.filter_file(f) || self.b.filter_file(f)
    }

}

pub struct CliFileFilterAnd {
    a: Box<CliFileFilter>,
    b: Box<CliFileFilter>
}

impl CliFileFilter for CliFileFilterAnd {

    fn filter_file(&self, f: &Rc<RefCell<File>>) -> bool {
        self.a.filter_file(f) && self.b.filter_file(f)
    }

}

pub struct CliFileFilterByHash {
    default: bool,
    hash: Option<FileHash>,
}

impl CliFileFilter for CliFileFilterByHash {

    fn filter_file(&self, file: &Rc<RefCell<File>>) -> bool {
        self.hash.clone().map(|h| {
            debug!("Filtering file with hash = {}", h);
            let f = file.deref().borrow();
            f.id().get_id() == h
        })
        .unwrap_or(self.default)
    }

}

pub struct CliFileFilterByDataRegex {
    default: bool,
    regex: Option<Regex>,
}

impl CliFileFilter for CliFileFilterByDataRegex {

    fn filter_file(&self, file: &Rc<RefCell<File>>) -> bool {
        self.regex.clone().map(|r| {
            debug!("Filtering file with regex = {:?}", r);
            let f = file.deref().borrow();
            r.is_match(&f.data()[..])
        })
        .unwrap_or(self.default)
    }

}

pub struct CliFileFilterByHeaderRegex {
    default: bool,
    header_field_name: &'static str,
    regex: Option<Regex>,
}

impl CliFileFilter for CliFileFilterByHeaderRegex {

    fn filter_file(&self, file: &Rc<RefCell<File>>) -> bool {
        use module::helpers::header::data::get_named_text_from_header;

        self.regex.clone().map(|r| {
            debug!("Filtering file (header field = {}) with regex = {:?}", self.header_field_name, r);

            let f = file.deref().borrow();
            get_named_text_from_header(self.header_field_name, f.header())
                .map(|headerfield| r.is_match(&headerfield[..]))
                .unwrap_or(self.default)
        })
        .unwrap_or(self.default)
    }

}

pub struct CliFileFilterByTags {
    default: bool,
    tags: Option<Vec<String>>,
}

impl CliFileFilter for CliFileFilterByTags {

    fn filter_file(&self, file: &Rc<RefCell<File>>) -> bool {
        use module::helpers::header::tags::data::get_tags_from_header;

        self.tags.clone().map(|ts| {
            debug!("Filtering file with tags = {:?}", ts);

            let f = file.deref().borrow();
            get_tags_from_header(f.header())
                .iter()
                .any(|tag| ts.iter().any(|remtag| remtag == tag))
        })
        .unwrap_or(self.default)
    }

}

/*
 *
 *
 * Functions to generate filters
 *
 *
 */

pub fn create_hash_filter(matches: &ArgMatches, id_key: &'static str, default: bool) -> CliFileFilterByHash {
    CliFileFilterByHash {
        hash: matches.value_of(id_key).map(FileHash::from),
        default: default
    }
}

pub fn create_content_grep_filter(matches: &ArgMatches, match_key: &'static str, default: bool) -> CliFileFilterByDataRegex {
    use std::process::exit;

     CliFileFilterByDataRegex {
        regex: matches.value_of(match_key).map(|m| {
            Regex::new(&m[..]).unwrap_or_else(|e| {
                error!("Regex compiler error: {}", e);
                exit(1);
            })
        }),
        default: default,
     }
}

pub fn create_text_header_field_grep_filter(matches: &ArgMatches,
                                            match_key: &'static str,
                                            header_field_name: &'static str,
                                            default: bool)
    -> CliFileFilterByHeaderRegex
{
    CliFileFilterByHeaderRegex {
        default: default,
        header_field_name: header_field_name,
        regex: matches.value_of(match_key)
                      .map(|m| {
                        Regex::new(&m[..]).unwrap_or_else(|e| {
                            error!("Regex compiler error: {}", e);
                            exit(1);
                        })
                      }),
    }
}

pub fn create_tag_filter(matches: &ArgMatches, tag_key: &'static str, default: bool) -> CliFileFilterByTags {

    CliFileFilterByTags {
        default: default,
        tags: matches.value_of(tag_key)
                     .map(|m| m.split(",")
                               .map(String::from)
                               .collect::<Vec<String>>()
                     ),
    }
}

<commit_msg>Remove unused imports<commit_after>use std::rc::Rc;
use std::cell::RefCell;
use std::ops::Deref;
use std::process::exit;

use clap::ArgMatches;
use regex::Regex;

use storage::file::File;
use storage::file::hash::FileHash;

pub trait CliFileFilter {

    fn filter_file(&self, &Rc<RefCell<File>>) -> bool;

    fn not(self) -> CliFileFilterNot
        where Self: Sized + 'static
    {
        CliFileFilterNot {
            a: Box::new(self),
        }
    }

    fn or(self, other: Box<CliFileFilter>) -> CliFileFilterOr
        where Self: Sized + 'static
    {
        CliFileFilterOr {
            a: Box::new(self),
            b: other
        }
    }

    fn and(self, other: Box<CliFileFilter>) -> CliFileFilterAnd
        where Self: Sized + 'static
    {
        CliFileFilterAnd {
            a: Box::new(self),
            b: other
        }
    }

}

pub struct CliFileFilterNot {
    a: Box<CliFileFilter>,
}

impl CliFileFilter for CliFileFilterNot {

    fn filter_file(&self, f: &Rc<RefCell<File>>) -> bool {
        !self.a.filter_file(f)
    }

}

pub struct CliFileFilterOr {
    a: Box<CliFileFilter>,
    b: Box<CliFileFilter>
}

impl CliFileFilter for CliFileFilterOr {

    fn filter_file(&self, f: &Rc<RefCell<File>>) -> bool {
        self.a.filter_file(f) || self.b.filter_file(f)
    }

}

pub struct CliFileFilterAnd {
    a: Box<CliFileFilter>,
    b: Box<CliFileFilter>
}

impl CliFileFilter for CliFileFilterAnd {

    fn filter_file(&self, f: &Rc<RefCell<File>>) -> bool {
        self.a.filter_file(f) && self.b.filter_file(f)
    }

}

pub struct CliFileFilterByHash {
    default: bool,
    hash: Option<FileHash>,
}

impl CliFileFilter for CliFileFilterByHash {

    fn filter_file(&self, file: &Rc<RefCell<File>>) -> bool {
        self.hash.clone().map(|h| {
            debug!("Filtering file with hash = {}", h);
            let f = file.deref().borrow();
            f.id().get_id() == h
        })
        .unwrap_or(self.default)
    }

}

pub struct CliFileFilterByDataRegex {
    default: bool,
    regex: Option<Regex>,
}

impl CliFileFilter for CliFileFilterByDataRegex {

    fn filter_file(&self, file: &Rc<RefCell<File>>) -> bool {
        self.regex.clone().map(|r| {
            debug!("Filtering file with regex = {:?}", r);
            let f = file.deref().borrow();
            r.is_match(&f.data()[..])
        })
        .unwrap_or(self.default)
    }

}

pub struct CliFileFilterByHeaderRegex {
    default: bool,
    header_field_name: &'static str,
    regex: Option<Regex>,
}

impl CliFileFilter for CliFileFilterByHeaderRegex {

    fn filter_file(&self, file: &Rc<RefCell<File>>) -> bool {
        use module::helpers::header::data::get_named_text_from_header;

        self.regex.clone().map(|r| {
            debug!("Filtering file (header field = {}) with regex = {:?}", self.header_field_name, r);

            let f = file.deref().borrow();
            get_named_text_from_header(self.header_field_name, f.header())
                .map(|headerfield| r.is_match(&headerfield[..]))
                .unwrap_or(self.default)
        })
        .unwrap_or(self.default)
    }

}

pub struct CliFileFilterByTags {
    default: bool,
    tags: Option<Vec<String>>,
}

impl CliFileFilter for CliFileFilterByTags {

    fn filter_file(&self, file: &Rc<RefCell<File>>) -> bool {
        use module::helpers::header::tags::data::get_tags_from_header;

        self.tags.clone().map(|ts| {
            debug!("Filtering file with tags = {:?}", ts);

            let f = file.deref().borrow();
            get_tags_from_header(f.header())
                .iter()
                .any(|tag| ts.iter().any(|remtag| remtag == tag))
        })
        .unwrap_or(self.default)
    }

}

/*
 *
 *
 * Functions to generate filters
 *
 *
 */

pub fn create_hash_filter(matches: &ArgMatches, id_key: &'static str, default: bool) -> CliFileFilterByHash {
    CliFileFilterByHash {
        hash: matches.value_of(id_key).map(FileHash::from),
        default: default
    }
}

pub fn create_content_grep_filter(matches: &ArgMatches, match_key: &'static str, default: bool) -> CliFileFilterByDataRegex {
    use std::process::exit;

     CliFileFilterByDataRegex {
        regex: matches.value_of(match_key).map(|m| {
            Regex::new(&m[..]).unwrap_or_else(|e| {
                error!("Regex compiler error: {}", e);
                exit(1);
            })
        }),
        default: default,
     }
}

pub fn create_text_header_field_grep_filter(matches: &ArgMatches,
                                            match_key: &'static str,
                                            header_field_name: &'static str,
                                            default: bool)
    -> CliFileFilterByHeaderRegex
{
    CliFileFilterByHeaderRegex {
        default: default,
        header_field_name: header_field_name,
        regex: matches.value_of(match_key)
                      .map(|m| {
                        Regex::new(&m[..]).unwrap_or_else(|e| {
                            error!("Regex compiler error: {}", e);
                            exit(1);
                        })
                      }),
    }
}

pub fn create_tag_filter(matches: &ArgMatches, tag_key: &'static str, default: bool) -> CliFileFilterByTags {

    CliFileFilterByTags {
        default: default,
        tags: matches.value_of(tag_key)
                     .map(|m| m.split(",")
                               .map(String::from)
                               .collect::<Vec<String>>()
                     ),
    }
}

<|endoftext|>


<commit_before><commit_msg>Added guard example<commit_after>fn main() {
    let pair = (2, -2);
    // TODO ^ Try different values for `pair`

    println!("Tell me about {:?}", pair);
    match pair {
        (x, y) if x == y => println!("These are twins"),
        // The ^ `if condition` part is a guard
        (x, y) if x + y == 0 => println!("Antimatter, kaboom!"),
        (x, _) if x % 2 == 1 => println!("The first one is odd"),
        _ => println!("No correlation..."),
    }
}
<|endoftext|>


<commit_before><commit_msg>docs(examples): add simple_example<commit_after>extern crate rocks;

use rocks::prelude::*;

const DB_PATH: &str = "/tmp/rocksdb_simple_example";

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Optimize RocksDB. This is the easiest way to get RocksDB to perform well
    // NOTE: Is rust, Options is splited into 2 parts.
    let options = Options::default()
        .map_db_options(|db| db.create_if_missing(true).increase_parallelism(16))
        .map_cf_options(|cf| cf.optimize_level_style_compaction(512 * 1024 * 1024));

    // open DB
    let db = DB::open(&options, DB_PATH)?;

    // Put key-value
    db.put(WriteOptions::default_instance(), b"key1", b"value")?;

    // get value
    let value = db.get(ReadOptions::default_instance(), b"key1")?;
    assert_eq!(value, b"value");

    // atomically apply a set of updates
    {
        let mut batch = WriteBatch::default();
        batch.delete(b"key1");
        batch.put(b"key2", &value);

        db.write(WriteOptions::default_instance(), &batch)?;
    }

    let ret = db.get(ReadOptions::default_instance(), b"key1");
    assert!(ret.is_err() && ret.unwrap_err().is_not_found());

    let value = db.get(ReadOptions::default_instance(), b"key2")?;
    assert_eq!(value, b"value");

    Ok(())
}
<|endoftext|>


<commit_before>#![feature(plugin)]
#![plugin(afl_coverage_plugin)]

extern crate afl_coverage;
extern crate tar;
extern crate nom;

use tar::*;
use nom::IResult;
use std::fs::File;
use std::io::{self, Read};

fn main() {
    let mut contents: Vec<u8> = Vec::new();
    let result = io::stdin().read_to_end(&mut contents).unwrap();
    let tar = &contents[..];

    match parse_tar(tar) {
        IResult::Done(_, entries) => {
            for e in entries.iter() {
                //println!("{:?}", e);
            }
        }
        e  => {
            //println!("error or incomplete: {:?}", e);
            //panic!("cannot parse tar archive");
        }
    }
}
<commit_msg>fuzzed: silence warnings<commit_after>#![feature(plugin)]
#![plugin(afl_coverage_plugin)]

extern crate afl_coverage;
extern crate tar;
extern crate nom;

use tar::*;
use nom::IResult;
use std::io::{self, Read};

fn main() {
    let mut contents: Vec<u8> = Vec::new();
    io::stdin().read_to_end(&mut contents).unwrap();
    let tar = &contents[..];

    match parse_tar(tar) {
        IResult::Done(_, entries) => {
            for e in entries.iter() {
                println!("{:?}", e);
            }
        }
        e  => {
            println!("error or incomplete: {:?}", e);
            panic!("cannot parse tar archive");
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


<commit_before><commit_msg>Add redact endpoint.<commit_after><|endoftext|>


<commit_before><commit_msg>Call `sdl2::init` to enable OpenGL 4.1<commit_after><|endoftext|>


<commit_before><commit_msg>Add an unit test for Builder corresponding to IRBuilder in C++ API.<commit_after>#![feature(libc)]

extern crate libc;
extern crate llvm;

use llvm::*;
use llvm::Attribute::*;

#[test]
pub fn test() {
  let ctx = Context::new();
  let module = Module::new("simple", &ctx);
  let func = module.add_function("fib", Type::get::<fn(u64) -> u64>(&ctx));
  func.add_attributes(&[NoUnwind, ReadNone]);
  let value = &func[0];

  let entry    = func.append("entry");
  let then_bb  = func.append("then_block");
  let else_bb  = func.append("else_block");
  let merge_bb = func.append("merge_bb");

  let builder = Builder::new(&ctx);
  builder.position_at_end(entry);

  let local1 = builder.create_alloca(Type::get::<u64>(&ctx));
  builder.create_store(8u64.compile(&ctx), local1);
  let local2 = builder.create_alloca(Type::get::<u64>(&ctx));
  builder.create_store(16u64.compile(&ctx), local2);

  let cond = builder.create_cmp(value, 5u64.compile(&ctx), Predicate::GreaterThan);
  builder.create_cond_br(cond, then_bb, Some(else_bb));

  builder.position_at_end(then_bb);
  let eight = builder.create_load(local1);
  builder.create_br(merge_bb);

  builder.position_at_end(else_bb);
  let sixteen = builder.create_load(local2);
  builder.create_br(merge_bb);

  builder.position_at_end(merge_bb);
  let phi = builder.create_phi(Type::get::<u64>(&ctx), "cond");
  phi.add_incoming(eight, then_bb);
  phi.add_incoming(sixteen, else_bb);
  builder.create_ret(phi);

  module.verify().unwrap();

  let ee = JitEngine::new(&module, JitOptions {opt_level: 0}).unwrap();
  ee.with_function(func, |fib: extern fn(u64) -> u64| {
      for i in 0..10 {
          println!("fib {} = {}", i, fib(i))
      }
  });
}<|endoftext|>


<commit_before><commit_msg>Add test for the options<commit_after>// Copyright (c) 2018 Guillaume Pinot <texitoi(a)texitoi.eu>
//
// This work is free. You can redistribute it and/or modify it under
// the terms of the Do What The Fuck You Want To Public License,
// Version 2, as published by Sam Hocevar. See the COPYING file for
// more details.

#[macro_use]
extern crate structopt;

use structopt::StructOpt;

#[test]
fn required_option() {
    #[derive(StructOpt, PartialEq, Debug)]
    struct Opt {
        #[structopt(short = "a", long = "arg")]
        arg: i32,
    }
    assert_eq!(Opt { arg: 42 },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42"])));
    assert_eq!(Opt { arg: 42 },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a", "42"])));
    assert_eq!(Opt { arg: 42 },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test", "--arg", "42"])));
    assert!(Opt::clap().get_matches_from_safe(&["test"]).is_err());
    assert!(Opt::clap().get_matches_from_safe(&["test", "-a42", "-a24"]).is_err());
}

#[test]
fn optional_option() {
    #[derive(StructOpt, PartialEq, Debug)]
    struct Opt {
        #[structopt(short = "a")]
        arg: Option<i32>,
    }
    assert_eq!(Opt { arg: Some(42) },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a42"])));
    assert_eq!(Opt { arg: None },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test"])));
    assert!(Opt::clap().get_matches_from_safe(&["test", "-a42", "-a24"]).is_err());
}

#[test]
fn option_with_default() {
    #[derive(StructOpt, PartialEq, Debug)]
    struct Opt {
        #[structopt(short = "a", default_value = "42")]
        arg: i32,
    }
    assert_eq!(Opt { arg: 24 },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a24"])));
    assert_eq!(Opt { arg: 42 },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test"])));
    assert!(Opt::clap().get_matches_from_safe(&["test", "-a42", "-a24"]).is_err());
}

#[test]
fn option_with_raw_default() {
    #[derive(StructOpt, PartialEq, Debug)]
    struct Opt {
        #[structopt(short = "a", raw(default_value = "\"42\""))]
        arg: i32,
    }
    assert_eq!(Opt { arg: 24 },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a24"])));
    assert_eq!(Opt { arg: 42 },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test"])));
    assert!(Opt::clap().get_matches_from_safe(&["test", "-a42", "-a24"]).is_err());
}

#[test]
fn options() {
    #[derive(StructOpt, PartialEq, Debug)]
    struct Opt {
        #[structopt(short = "a", long = "arg")]
        arg: Vec<i32>,
    }
    assert_eq!(Opt { arg: vec![24] },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a24"])));
    assert_eq!(Opt { arg: vec![] },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test"])));
    assert_eq!(Opt { arg: vec![24, 42] },
               Opt::from_clap(&Opt::clap().get_matches_from(&["test", "-a24", "--arg", "42"])));
}
<|endoftext|>