<commit_before>//! Types dealing with ranges of values

extern mod extra;

use std::cmp;
use extra::time::Timespec;

/// A trait that normalizes a range bound for a type
pub trait Normalizable {
    /// Given a range bound, returns the normalized version of that bound. For
    /// discrete types such as i32, the normalized lower bound is always
    /// inclusive and the normalized upper bound is always exclusive. Other
    /// types, such as Timespec, have no normalization process so their
    /// implementation is a no-op.
    ///
    /// The logic here should match the logic performed by the equivalent
    /// Postgres type.
    fn normalize<S: BoundSided>(bound: RangeBound<S, Self>)
            -> RangeBound<S, Self>;
}

macro_rules! bounded_normalizable(
    ($t:ty) => (
        impl Normalizable for $t {
            fn normalize<S: BoundSided>(bound: RangeBound<S, $t>)
                    -> RangeBound<S, $t> {
                match BoundSided::side(None::<S>) {
                    Upper if bound.type_ == Inclusive => {
                        assert!(bound.value != Bounded::max_value());
                        RangeBound::new(bound.value + 1, Exclusive)
                    }
                    Lower if bound.type_ == Exclusive => {
                        assert!(bound.value != Bounded::max_value());
                        RangeBound::new(bound.value + 1, Inclusive)
                    }
                    _ => bound
                }
            }
        }
    )
)

bounded_normalizable!(i32)
bounded_normalizable!(i64)

impl Normalizable for Timespec {
    fn normalize<S: BoundSided>(bound: RangeBound<S, Timespec>)
            -> RangeBound<S, Timespec> {
        bound
    }
}

enum BoundSide {
    Upper,
    Lower
}

trait BoundSided {
    // param is a hack to get around lack of hints for self type
    fn side(_: Option<Self>) -> BoundSide;
}

/// A tag type representing an upper bound
#[deriving(Eq,Clone)]
pub struct UpperBound;

/// A tag type representing a lower bound
#[deriving(Eq,Clone)]
pub struct LowerBound;

impl BoundSided for UpperBound {
    fn side(_: Option<UpperBound>) -> BoundSide {
        Upper
    }
}

impl BoundSided for LowerBound {
    fn side(_: Option<LowerBound>) -> BoundSide {
        Lower
    }
}

/// The type of a range bound
#[deriving(Eq,Clone)]
pub enum BoundType {
    /// The bound includes its value
    Inclusive,
    /// The bound excludes its value
    Exclusive
}

/// Represents a one-sided bound.
///
/// The side is determined by the `S` phantom parameter.
#[deriving(Eq,Clone)]
pub struct RangeBound<S, T> {
    /// The value of the bound
    value: T,
    /// The type of the bound
    type_: BoundType
}

impl<S: BoundSided, T: Ord> Ord for RangeBound<S, T> {
    fn lt(&self, other: &RangeBound<S, T>) -> bool {
        match (BoundSided::side(None::<S>), self.type_, other.type_) {
            (Upper, Exclusive, Inclusive)
            | (Lower, Inclusive, Exclusive) => self.value <= other.value,
            _ => self.value < other.value
        }
    }
}

impl<S: BoundSided, T: Ord> RangeBound<S, T> {
    /// Constructs a new range bound
    pub fn new(value: T, type_: BoundType) -> RangeBound<S, T> {
        RangeBound { value: value, type_: type_ }
    }

    /// Determines if a value lies within the range specified by this bound.
    pub fn in_bounds(&self, value: &T) -> bool {
        match (self.type_, BoundSided::side(None::<S>)) {
            (Inclusive, Upper) if value <= &self.value => true,
            (Exclusive, Upper) if value < &self.value => true,
            (Inclusive, Lower) if value >= &self.value => true,
            (Exclusive, Lower) if value > &self.value => true,
            _ => false
        }
    }
}

/// Represents a range of values.
#[deriving(Eq,Clone)]
pub enum Range<T> {
    priv Empty,
    priv Normal(Option<RangeBound<LowerBound, T>>,
                Option<RangeBound<UpperBound, T>>)
}

impl<T: Ord+Normalizable> Range<T> {
    /// Creates a new range.
    ///
    /// If a bound is `None`, the range is unbounded in that direction.
    pub fn new(lower: Option<RangeBound<LowerBound, T>>,
               upper: Option<RangeBound<UpperBound, T>>) -> Range<T> {
        let lower = lower.map(|bound| { Normalizable::normalize(bound) });
        let upper = upper.map(|bound| { Normalizable::normalize(bound) });

        match (&lower, &upper) {
            (&Some(ref lower), &Some(ref upper)) => {
                let empty = match (lower.type_, upper.type_) {
                    (Inclusive, Inclusive) => lower.value > upper.value,
                    _ => lower.value >= upper.value
                };
                if empty {
                    return Empty;
                }
            }
            _ => {}
        }

        Normal(lower, upper)
    }

    /// Creates a new empty range.
    pub fn empty() -> Range<T> {
        Empty
    }

    /// Determines if this range is the empty range.
    pub fn is_empty(&self) -> bool {
        match *self {
            Empty => true,
            Normal(*) => false
        }
    }

    /// Returns the lower bound if it exists.
    pub fn lower<'a>(&'a self) -> &'a Option<RangeBound<LowerBound, T>> {
        match *self {
            Empty => &None,
            Normal(ref lower, _) => lower
        }
    }

    /// Returns the upper bound if it exists.
    pub fn upper<'a>(&'a self) -> &'a Option<RangeBound<UpperBound, T>> {
        match *self {
            Empty => &None,
            Normal(_, ref upper) => upper
        }
    }

    /// Determines if a value lies within this range.
    pub fn contains(&self, value: &T) -> bool {
        match *self {
            Empty => false,
            Normal(ref lower, ref upper) => {
                lower.as_ref().map_default(true, |b| { b.in_bounds(value) }) &&
                    upper.as_ref().map_default(true, |b| { b.in_bounds(value) })
            }
        }
    }
}

impl<T: Ord+Normalizable+Clone> Range<T> {
    /// Returns the intersection of this range with another
    pub fn intersect(&self, other: &Range<T>) -> Range<T> {
        if self.is_empty() || other.is_empty() {
            return Range::empty();
        }

        let lower = match (self.lower(), other.lower()) {
            (&Some(ref a), &Some(ref b)) => Some(cmp::max(a, b).clone()),
            (&Some(ref a), &None) => Some(a.clone()),
            (&None, &Some(ref b)) => Some(b.clone()),
            (&None, &None) => None
        };

        let upper = match (self.upper(), other.upper()) {
            (&Some(ref a), &Some(ref b)) => Some(cmp::min(a, b).clone()),
            (&Some(ref a), &None) => Some(a.clone()),
            (&None, &Some(ref b)) => Some(b.clone()),
            (&None, &None) => None
        };

        Range::new(lower, upper)
    }
}

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

    #[test]
    fn test_range_bound_lower_lt() {
        fn check(val1: int, inc1: BoundType, val2: int, inc2: BoundType, expected: bool) {
            let a: RangeBound<LowerBound, int> = RangeBound::new(val1, inc1);
            let b: RangeBound<LowerBound, int> = RangeBound::new(val2, inc2);
            assert_eq!(expected, a < b);
        }

        check(1, Inclusive, 2, Exclusive, true);
        check(1, Exclusive, 2, Inclusive, true);
        check(1, Inclusive, 1, Exclusive, true);
        check(2, Inclusive, 1, Inclusive, false);
        check(2, Exclusive, 1, Exclusive, false);
        check(1, Exclusive, 1, Inclusive, false);
        check(1, Exclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Inclusive, false);
    }

    #[test]
    fn test_range_bound_upper_lt() {
        fn check(val1: int, inc1: BoundType, val2: int, inc2: BoundType, expected: bool) {
            let a: RangeBound<UpperBound, int> = RangeBound::new(val1, inc1);
            let b: RangeBound<UpperBound, int> = RangeBound::new(val2, inc2);
            assert_eq!(expected, a < b);
        }

        check(1, Inclusive, 2, Exclusive, true);
        check(1, Exclusive, 2, Exclusive, true);
        check(1, Exclusive, 1, Inclusive, true);
        check(2, Inclusive, 1, Inclusive, false);
        check(2, Exclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Inclusive, false);
        check(1, Exclusive, 1, Exclusive, false);
    }

    #[test]
    fn test_range_bound_lower_in_bounds() {
        fn check(bound: int, inc: BoundType, val: int, expected: bool) {
            let b: RangeBound<LowerBound, int> = RangeBound::new(bound, inc);
            assert_eq!(expected, b.in_bounds(&val));
        }

        check(1, Inclusive, 1, true);
        check(1, Exclusive, 1, false);
        check(1, Inclusive, 2, true);
        check(1, Inclusive, 0, false);
    }

    #[test]
    fn test_range_bound_upper_in_bounds() {
        fn check(bound: int, inc: BoundType, val: int, expected: bool) {
            let b: RangeBound<UpperBound, int> = RangeBound::new(bound, inc);
            assert_eq!(expected, b.in_bounds(&val));
        }

        check(1, Inclusive, 1, true);
        check(1, Exclusive, 1, false);
        check(1, Inclusive, 2, false);
        check(1, Inclusive, 0, true);
    }

    #[test]
    fn test_range_contains() {
        let r =  Range::new(Some(RangeBound::new(1i32, Inclusive)),
                            Some(RangeBound::new(3i32, Inclusive)));
        assert!(!r.contains(&4));
        assert!(r.contains(&3));
        assert!(r.contains(&2));
        assert!(r.contains(&1));
        assert!(!r.contains(&0));

        let r =  Range::new(Some(RangeBound::new(1i32, Exclusive)),
                            Some(RangeBound::new(3i32, Exclusive)));
        assert!(!r.contains(&4));
        assert!(!r.contains(&3));
        assert!(r.contains(&2));
        assert!(!r.contains(&1));
        assert!(!r.contains(&0));

        let r = Range::new(None, Some(RangeBound::new(3i32, Inclusive)));
        assert!(!r.contains(&4));
        assert!(r.contains(&2));
        assert!(r.contains(&Bounded::min_value()));

        let r = Range::new(Some(RangeBound::new(1i32, Inclusive)), None);
        assert!(r.contains(&Bounded::max_value()));
        assert!(r.contains(&4));
        assert!(!r.contains(&0));

        let r = Range::new(None, None);
        assert!(r.contains(&Bounded::max_value()));
        assert!(r.contains(&0i32));
        assert!(r.contains(&Bounded::min_value()));
    }

    #[test]
    fn test_normalize_lower() {
        let r: RangeBound<LowerBound, i32> = RangeBound::new(10i32, Inclusive);
        assert_eq!(RangeBound::new(10i32, Inclusive), Normalizable::normalize(r));

        let r: RangeBound<LowerBound, i32> = RangeBound::new(10i32, Exclusive);
        assert_eq!(RangeBound::new(11i32, Inclusive), Normalizable::normalize(r));
    }

    #[test]
    fn test_normalize_upper() {
        let r: RangeBound<UpperBound, i32> = RangeBound::new(10i32, Inclusive);
        assert_eq!(RangeBound::new(11i32, Exclusive), Normalizable::normalize(r));

        let r: RangeBound<UpperBound, i32> = RangeBound::new(10i32, Exclusive);
        assert_eq!(RangeBound::new(10i32, Exclusive), Normalizable::normalize(r));
    }

    #[test]
    fn test_range_normalizes() {
        let r1 = Range::new(Some(RangeBound::new(10i32, Exclusive)),
                            Some(RangeBound::new(15i32, Inclusive)));
        let r2 = Range::new(Some(RangeBound::new(11i32, Inclusive)),
                            Some(RangeBound::new(16i32, Exclusive)));
        assert_eq!(r1, r2);
    }

    #[test]
    fn test_range_empty() {
        assert!(Range::new(Some(RangeBound::new(9i32, Exclusive)),
                           Some(RangeBound::new(10i32, Exclusive))).is_empty());
        assert!(Range::new(Some(RangeBound::new(10i32, Inclusive)),
                           Some(RangeBound::new(10i32, Exclusive))).is_empty());
        assert!(Range::new(Some(RangeBound::new(10i32, Exclusive)),
                           Some(RangeBound::new(10i32, Inclusive))).is_empty());
        assert!(Range::new(Some(RangeBound::new(10i32, Inclusive)),
                           Some(RangeBound::new(9i32, Inclusive))).is_empty());
    }

    #[test]
    fn test_intersection() {
        let r1 = Range::new(Some(RangeBound::new(10i32, Inclusive)),
                            Some(RangeBound::new(15i32, Exclusive)));
        let r2 = Range::new(Some(RangeBound::new(20i32, Exclusive)),
                            Some(RangeBound::new(25i32, Inclusive)));
        assert!(r1.intersect(&r2).is_empty());
        assert!(r2.intersect(&r1).is_empty());
        assert_eq!(r1, r1.intersect(&Range::new(None, None)));
        assert_eq!(r1, Range::new(None, None).intersect(&r1));

        let r2 = Range::new(Some(RangeBound::new(10i32, Exclusive)), None);
        let exp = Range::new(r2.lower().clone(), r1.upper().clone());
        assert_eq!(exp, r1.intersect(&r2));
        assert_eq!(exp, r2.intersect(&r1));

        let r2 = Range::new(None, Some(RangeBound::new(15i32, Inclusive)));
        assert_eq!(r1, r1.intersect(&r2));
        assert_eq!(r1, r2.intersect(&r1));

        let r2 = Range::new(Some(RangeBound::new(11i32, Inclusive)),
                            Some(RangeBound::new(14i32, Exclusive)));
        assert_eq!(r2, r1.intersect(&r2));
        assert_eq!(r2, r2.intersect(&r1));
    }
}
<commit_msg>Add Range::contains_range<commit_after>//! Types dealing with ranges of values

extern mod extra;

use std::cmp;
use extra::time::Timespec;

/// A trait that normalizes a range bound for a type
pub trait Normalizable {
    /// Given a range bound, returns the normalized version of that bound. For
    /// discrete types such as i32, the normalized lower bound is always
    /// inclusive and the normalized upper bound is always exclusive. Other
    /// types, such as Timespec, have no normalization process so their
    /// implementation is a no-op.
    ///
    /// The logic here should match the logic performed by the equivalent
    /// Postgres type.
    fn normalize<S: BoundSided>(bound: RangeBound<S, Self>)
            -> RangeBound<S, Self>;
}

macro_rules! bounded_normalizable(
    ($t:ty) => (
        impl Normalizable for $t {
            fn normalize<S: BoundSided>(bound: RangeBound<S, $t>)
                    -> RangeBound<S, $t> {
                match BoundSided::side(None::<S>) {
                    Upper if bound.type_ == Inclusive => {
                        assert!(bound.value != Bounded::max_value());
                        RangeBound::new(bound.value + 1, Exclusive)
                    }
                    Lower if bound.type_ == Exclusive => {
                        assert!(bound.value != Bounded::max_value());
                        RangeBound::new(bound.value + 1, Inclusive)
                    }
                    _ => bound
                }
            }
        }
    )
)

bounded_normalizable!(i32)
bounded_normalizable!(i64)

impl Normalizable for Timespec {
    fn normalize<S: BoundSided>(bound: RangeBound<S, Timespec>)
            -> RangeBound<S, Timespec> {
        bound
    }
}

#[deriving(Eq)]
enum BoundSide {
    Upper,
    Lower
}

trait BoundSided {
    // param is a hack to get around lack of hints for self type
    fn side(_: Option<Self>) -> BoundSide;
}

/// A tag type representing an upper bound
#[deriving(Eq,Clone)]
pub struct UpperBound;

/// A tag type representing a lower bound
#[deriving(Eq,Clone)]
pub struct LowerBound;

impl BoundSided for UpperBound {
    fn side(_: Option<UpperBound>) -> BoundSide {
        Upper
    }
}

impl BoundSided for LowerBound {
    fn side(_: Option<LowerBound>) -> BoundSide {
        Lower
    }
}

/// The type of a range bound
#[deriving(Eq,Clone)]
pub enum BoundType {
    /// The bound includes its value
    Inclusive,
    /// The bound excludes its value
    Exclusive
}

/// Represents a one-sided bound.
///
/// The side is determined by the `S` phantom parameter.
#[deriving(Eq,Clone)]
pub struct RangeBound<S, T> {
    /// The value of the bound
    value: T,
    /// The type of the bound
    type_: BoundType
}

impl<S: BoundSided, T: Ord> Ord for RangeBound<S, T> {
    fn lt(&self, other: &RangeBound<S, T>) -> bool {
        match (BoundSided::side(None::<S>), self.type_, other.type_) {
            (Upper, Exclusive, Inclusive)
            | (Lower, Inclusive, Exclusive) => self.value <= other.value,
            _ => self.value < other.value
        }
    }
}

impl<S: BoundSided, T: Ord> RangeBound<S, T> {
    /// Constructs a new range bound
    pub fn new(value: T, type_: BoundType) -> RangeBound<S, T> {
        RangeBound { value: value, type_: type_ }
    }

    /// Determines if a value lies within the range specified by this bound.
    pub fn in_bounds(&self, value: &T) -> bool {
        match (self.type_, BoundSided::side(None::<S>)) {
            (Inclusive, Upper) if value <= &self.value => true,
            (Exclusive, Upper) if value < &self.value => true,
            (Inclusive, Lower) if value >= &self.value => true,
            (Exclusive, Lower) if value > &self.value => true,
            _ => false
        }
    }
}

struct OptBound<'self, S, T>(&'self Option<RangeBound<S, T>>);

impl<'self, S: BoundSided, T: Ord> Ord for OptBound<'self, S, T> {
    fn lt(&self, other: &OptBound<'self, S, T>) -> bool {
        match (**self, **other) {
            (&None, &None) => false,
            (&None, _) => BoundSided::side(None::<S>) == Lower,
            (_, &None) => BoundSided::side(None::<S>) == Upper,
            (&Some(ref a), &Some(ref b)) => a < b
        }
    }
}

/// Represents a range of values.
#[deriving(Eq,Clone)]
pub enum Range<T> {
    priv Empty,
    priv Normal(Option<RangeBound<LowerBound, T>>,
                Option<RangeBound<UpperBound, T>>)
}

impl<T: Ord+Normalizable> Range<T> {
    /// Creates a new range.
    ///
    /// If a bound is `None`, the range is unbounded in that direction.
    pub fn new(lower: Option<RangeBound<LowerBound, T>>,
               upper: Option<RangeBound<UpperBound, T>>) -> Range<T> {
        let lower = lower.map(|bound| { Normalizable::normalize(bound) });
        let upper = upper.map(|bound| { Normalizable::normalize(bound) });

        match (&lower, &upper) {
            (&Some(ref lower), &Some(ref upper)) => {
                let empty = match (lower.type_, upper.type_) {
                    (Inclusive, Inclusive) => lower.value > upper.value,
                    _ => lower.value >= upper.value
                };
                if empty {
                    return Empty;
                }
            }
            _ => {}
        }

        Normal(lower, upper)
    }

    /// Creates a new empty range.
    pub fn empty() -> Range<T> {
        Empty
    }

    /// Determines if this range is the empty range.
    pub fn is_empty(&self) -> bool {
        match *self {
            Empty => true,
            Normal(*) => false
        }
    }

    /// Returns the lower bound if it exists.
    pub fn lower<'a>(&'a self) -> &'a Option<RangeBound<LowerBound, T>> {
        match *self {
            Empty => &None,
            Normal(ref lower, _) => lower
        }
    }

    /// Returns the upper bound if it exists.
    pub fn upper<'a>(&'a self) -> &'a Option<RangeBound<UpperBound, T>> {
        match *self {
            Empty => &None,
            Normal(_, ref upper) => upper
        }
    }

    /// Determines if a value lies within this range.
    pub fn contains(&self, value: &T) -> bool {
        match *self {
            Empty => false,
            Normal(ref lower, ref upper) => {
                lower.as_ref().map_default(true, |b| { b.in_bounds(value) }) &&
                    upper.as_ref().map_default(true, |b| { b.in_bounds(value) })
            }
        }
    }

    /// Determines if a range lies completely within this range.
    pub fn contains_range(&self, other: &Range<T>) -> bool {
        if other.is_empty() {
            return true;
        }

        if self.is_empty() {
            return false;
        }

        OptBound(self.lower()) <= OptBound(other.lower()) &&
            OptBound(self.upper()) >= OptBound(other.upper())
    }
}

impl<T: Ord+Normalizable+Clone> Range<T> {
    /// Returns the intersection of this range with another
    pub fn intersect(&self, other: &Range<T>) -> Range<T> {
        if self.is_empty() || other.is_empty() {
            return Range::empty();
        }

        let lower = cmp::max(OptBound(self.lower()), OptBound(other.lower()))
                .clone();
        let upper = cmp::min(OptBound(self.upper()), OptBound(other.upper()))
                .clone();

        Range::new(lower, upper)
    }
}

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

    #[test]
    fn test_range_bound_lower_lt() {
        fn check(val1: int, inc1: BoundType, val2: int, inc2: BoundType, expected: bool) {
            let a: RangeBound<LowerBound, int> = RangeBound::new(val1, inc1);
            let b: RangeBound<LowerBound, int> = RangeBound::new(val2, inc2);
            assert_eq!(expected, a < b);
        }

        check(1, Inclusive, 2, Exclusive, true);
        check(1, Exclusive, 2, Inclusive, true);
        check(1, Inclusive, 1, Exclusive, true);
        check(2, Inclusive, 1, Inclusive, false);
        check(2, Exclusive, 1, Exclusive, false);
        check(1, Exclusive, 1, Inclusive, false);
        check(1, Exclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Inclusive, false);
    }

    #[test]
    fn test_range_bound_upper_lt() {
        fn check(val1: int, inc1: BoundType, val2: int, inc2: BoundType, expected: bool) {
            let a: RangeBound<UpperBound, int> = RangeBound::new(val1, inc1);
            let b: RangeBound<UpperBound, int> = RangeBound::new(val2, inc2);
            assert_eq!(expected, a < b);
        }

        check(1, Inclusive, 2, Exclusive, true);
        check(1, Exclusive, 2, Exclusive, true);
        check(1, Exclusive, 1, Inclusive, true);
        check(2, Inclusive, 1, Inclusive, false);
        check(2, Exclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Inclusive, false);
        check(1, Exclusive, 1, Exclusive, false);
    }

    #[test]
    fn test_range_bound_lower_in_bounds() {
        fn check(bound: int, inc: BoundType, val: int, expected: bool) {
            let b: RangeBound<LowerBound, int> = RangeBound::new(bound, inc);
            assert_eq!(expected, b.in_bounds(&val));
        }

        check(1, Inclusive, 1, true);
        check(1, Exclusive, 1, false);
        check(1, Inclusive, 2, true);
        check(1, Inclusive, 0, false);
    }

    #[test]
    fn test_range_bound_upper_in_bounds() {
        fn check(bound: int, inc: BoundType, val: int, expected: bool) {
            let b: RangeBound<UpperBound, int> = RangeBound::new(bound, inc);
            assert_eq!(expected, b.in_bounds(&val));
        }

        check(1, Inclusive, 1, true);
        check(1, Exclusive, 1, false);
        check(1, Inclusive, 2, false);
        check(1, Inclusive, 0, true);
    }

    #[test]
    fn test_range_contains() {
        let r =  Range::new(Some(RangeBound::new(1i32, Inclusive)),
                            Some(RangeBound::new(3i32, Inclusive)));
        assert!(!r.contains(&4));
        assert!(r.contains(&3));
        assert!(r.contains(&2));
        assert!(r.contains(&1));
        assert!(!r.contains(&0));

        let r =  Range::new(Some(RangeBound::new(1i32, Exclusive)),
                            Some(RangeBound::new(3i32, Exclusive)));
        assert!(!r.contains(&4));
        assert!(!r.contains(&3));
        assert!(r.contains(&2));
        assert!(!r.contains(&1));
        assert!(!r.contains(&0));

        let r = Range::new(None, Some(RangeBound::new(3i32, Inclusive)));
        assert!(!r.contains(&4));
        assert!(r.contains(&2));
        assert!(r.contains(&Bounded::min_value()));

        let r = Range::new(Some(RangeBound::new(1i32, Inclusive)), None);
        assert!(r.contains(&Bounded::max_value()));
        assert!(r.contains(&4));
        assert!(!r.contains(&0));

        let r = Range::new(None, None);
        assert!(r.contains(&Bounded::max_value()));
        assert!(r.contains(&0i32));
        assert!(r.contains(&Bounded::min_value()));
    }

    #[test]
    fn test_normalize_lower() {
        let r: RangeBound<LowerBound, i32> = RangeBound::new(10i32, Inclusive);
        assert_eq!(RangeBound::new(10i32, Inclusive), Normalizable::normalize(r));

        let r: RangeBound<LowerBound, i32> = RangeBound::new(10i32, Exclusive);
        assert_eq!(RangeBound::new(11i32, Inclusive), Normalizable::normalize(r));
    }

    #[test]
    fn test_normalize_upper() {
        let r: RangeBound<UpperBound, i32> = RangeBound::new(10i32, Inclusive);
        assert_eq!(RangeBound::new(11i32, Exclusive), Normalizable::normalize(r));

        let r: RangeBound<UpperBound, i32> = RangeBound::new(10i32, Exclusive);
        assert_eq!(RangeBound::new(10i32, Exclusive), Normalizable::normalize(r));
    }

    #[test]
    fn test_range_normalizes() {
        let r1 = Range::new(Some(RangeBound::new(10i32, Exclusive)),
                            Some(RangeBound::new(15i32, Inclusive)));
        let r2 = Range::new(Some(RangeBound::new(11i32, Inclusive)),
                            Some(RangeBound::new(16i32, Exclusive)));
        assert_eq!(r1, r2);
    }

    #[test]
    fn test_range_empty() {
        assert!(Range::new(Some(RangeBound::new(9i32, Exclusive)),
                           Some(RangeBound::new(10i32, Exclusive))).is_empty());
        assert!(Range::new(Some(RangeBound::new(10i32, Inclusive)),
                           Some(RangeBound::new(10i32, Exclusive))).is_empty());
        assert!(Range::new(Some(RangeBound::new(10i32, Exclusive)),
                           Some(RangeBound::new(10i32, Inclusive))).is_empty());
        assert!(Range::new(Some(RangeBound::new(10i32, Inclusive)),
                           Some(RangeBound::new(9i32, Inclusive))).is_empty());
    }

    #[test]
    fn test_intersection() {
        let r1 = Range::new(Some(RangeBound::new(10i32, Inclusive)),
                            Some(RangeBound::new(15i32, Exclusive)));
        let r2 = Range::new(Some(RangeBound::new(20i32, Exclusive)),
                            Some(RangeBound::new(25i32, Inclusive)));
        assert!(r1.intersect(&r2).is_empty());
        assert!(r2.intersect(&r1).is_empty());
        assert_eq!(r1, r1.intersect(&Range::new(None, None)));
        assert_eq!(r1, Range::new(None, None).intersect(&r1));

        let r2 = Range::new(Some(RangeBound::new(10i32, Exclusive)), None);
        let exp = Range::new(r2.lower().clone(), r1.upper().clone());
        assert_eq!(exp, r1.intersect(&r2));
        assert_eq!(exp, r2.intersect(&r1));

        let r2 = Range::new(None, Some(RangeBound::new(15i32, Inclusive)));
        assert_eq!(r1, r1.intersect(&r2));
        assert_eq!(r1, r2.intersect(&r1));

        let r2 = Range::new(Some(RangeBound::new(11i32, Inclusive)),
                            Some(RangeBound::new(14i32, Exclusive)));
        assert_eq!(r2, r1.intersect(&r2));
        assert_eq!(r2, r2.intersect(&r1));
    }

    #[test]
    fn test_contains_range() {
        assert!(Range::<i32>::empty().contains_range(&Range::empty()));

        let r1 = Range::new(Some(RangeBound::new(10i32, Inclusive)),
                           Some(RangeBound::new(15i32, Exclusive)));
        assert!(r1.contains_range(&r1));

        let r2 = Range::new(Some(RangeBound::new(10i32, Exclusive)),
                            None);
        assert!(!r1.contains_range(&r2));
        assert!(!r2.contains_range(&r1));

        let r2 = Range::new(None,
                            Some(RangeBound::new(15i32, Inclusive)));
        assert!(!r1.contains_range(&r2));
        assert!(r2.contains_range(&r1));
    }
}
<|endoftext|>


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

//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! Boxes are useful in two situations: recursive data structures, and
//! occasionally when returning data. [The Pointer chapter of the
//! Book](../../../book/pointers.html#best-practices-1) explains these cases in
//! detail.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//!     Cons(T, Box<List<T>>),
//!     Nil,
//! }
//!
//! fn main() {
//!     let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//!     println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1i32, Box(Cons(2i32, Box(Nil))))`.

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

use core::prelude::*;

use core::any::Any;
use core::cmp::Ordering;
use core::default::Default;
use core::error::{Error, FromError};
use core::fmt;
use core::hash::{self, Hash};
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ptr::Unique;
use core::raw::TraitObject;

/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```rust
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
///     let foo = box(HEAP) 5;
///     let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "alloc",
           reason = "may be renamed; uncertain about custom allocator design")]
pub static HEAP: () = ();

/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Box<T>(Unique<T>);

impl<T> Box<T> {
    /// Allocates memory on the heap and then moves `x` into it.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Box::new(5);
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new(x: T) -> Box<T> {
        box x
    }
}

impl<T : ?Sized> Box<T> {
    /// Constructs a box from the raw pointer.
    ///
    /// After this function call, pointer is owned by resulting box.
    /// In particular, it means that `Box` destructor calls destructor
    /// of `T` and releases memory. Since the way `Box` allocates and
    /// releases memory is unspecified, the only valid pointer to pass
    /// to this function is the one taken from another `Box` with
    /// `boxed::into_raw` function.
    ///
    /// Function is unsafe, because improper use of this function may
    /// lead to memory problems like double-free, for example if the
    /// function is called twice on the same raw pointer.
    #[unstable(feature = "alloc",
               reason = "may be renamed or moved out of Box scope")]
    pub unsafe fn from_raw(raw: *mut T) -> Self {
        mem::transmute(raw)
    }
}

/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// Function is unsafe, because result of this function is no longer
/// automatically managed that may lead to memory or other resource
/// leak.
///
/// # Example
/// ```
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = unsafe { boxed::into_raw(seventeen) };
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "alloc",
           reason = "may be renamed")]
pub unsafe fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
    mem::transmute(b)
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
    #[stable(feature = "rust1", since = "1.0.0")]
    fn default() -> Box<T> { box Default::default() }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
    #[stable(feature = "rust1", since = "1.0.0")]
    fn default() -> Box<[T]> { box [] }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
    /// Returns a new box with a `clone()` of this box's contents.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Box::new(5);
    /// let y = x.clone();
    /// ```
    #[inline]
    fn clone(&self) -> Box<T> { box {(**self).clone()} }

    /// Copies `source`'s contents into `self` without creating a new allocation.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Box::new(5);
    /// let mut y = Box::new(10);
    ///
    /// y.clone_from(&x);
    ///
    /// assert_eq!(*y, 5);
    /// ```
    #[inline]
    fn clone_from(&mut self, source: &Box<T>) {
        (**self).clone_from(&(**source));
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
    #[inline]
    fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
    #[inline]
    fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
    #[inline]
    fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
        PartialOrd::partial_cmp(&**self, &**other)
    }
    #[inline]
    fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
    #[inline]
    fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
    #[inline]
    fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
    #[inline]
    fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Ord> Ord for Box<T> {
    #[inline]
    fn cmp(&self, other: &Box<T>) -> Ordering {
        Ord::cmp(&**self, &**other)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Eq> Eq for Box<T> {}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Hash> Hash for Box<T> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}

/// Extension methods for an owning `Any` trait object.
#[unstable(feature = "alloc",
           reason = "this trait will likely disappear once compiler bugs blocking \
                     a direct impl on `Box<Any>` have been fixed ")]
// FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
//                removing this please make sure that you can downcase on
//                `Box<Any + Send>` as well as `Box<Any>`
pub trait BoxAny {
    /// Returns the boxed value if it is of type `T`, or
    /// `Err(Self)` if it isn't.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn downcast<T: 'static>(self) -> Result<Box<T>, Self>;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl BoxAny for Box<Any> {
    #[inline]
    fn downcast<T: 'static>(self) -> Result<Box<T>, Box<Any>> {
        if self.is::<T>() {
            unsafe {
                // Get the raw representation of the trait object
                let to: TraitObject =
                    mem::transmute::<Box<Any>, TraitObject>(self);

                // Extract the data pointer
                Ok(mem::transmute(to.data))
            }
        } else {
            Err(self)
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Box<Any> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Box<Any>")
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for Box<T> {
    type Target = T;

    fn deref(&self) -> &T { &**self }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> DerefMut for Box<T> {
    fn deref_mut(&mut self) -> &mut T { &mut **self }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator + ?Sized> Iterator for Box<I> {
    type Item = I::Item;
    fn next(&mut self) -> Option<I::Item> { (**self).next() }
    fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
    fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + 'a> FromError<E> for Box<Error + 'a> {
    fn from_error(err: E) -> Box<Error + 'a> {
        Box::new(err)
    }
}
<commit_msg>boxed: mark from_raw and into_raw functions inline<commit_after>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A pointer type for heap allocation.
//!
//! `Box<T>`, casually referred to as a 'box', provides the simplest form of
//! heap allocation in Rust. Boxes provide ownership for this allocation, and
//! drop their contents when they go out of scope.
//!
//! Boxes are useful in two situations: recursive data structures, and
//! occasionally when returning data. [The Pointer chapter of the
//! Book](../../../book/pointers.html#best-practices-1) explains these cases in
//! detail.
//!
//! # Examples
//!
//! Creating a box:
//!
//! ```
//! let x = Box::new(5);
//! ```
//!
//! Creating a recursive data structure:
//!
//! ```
//! #[derive(Debug)]
//! enum List<T> {
//!     Cons(T, Box<List<T>>),
//!     Nil,
//! }
//!
//! fn main() {
//!     let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
//!     println!("{:?}", list);
//! }
//! ```
//!
//! This will print `Cons(1i32, Box(Cons(2i32, Box(Nil))))`.

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

use core::prelude::*;

use core::any::Any;
use core::cmp::Ordering;
use core::default::Default;
use core::error::{Error, FromError};
use core::fmt;
use core::hash::{self, Hash};
use core::mem;
use core::ops::{Deref, DerefMut};
use core::ptr::Unique;
use core::raw::TraitObject;

/// A value that represents the heap. This is the default place that the `box`
/// keyword allocates into when no place is supplied.
///
/// The following two examples are equivalent:
///
/// ```rust
/// #![feature(box_syntax)]
/// use std::boxed::HEAP;
///
/// fn main() {
///     let foo = box(HEAP) 5;
///     let foo = box 5;
/// }
/// ```
#[lang = "exchange_heap"]
#[unstable(feature = "alloc",
           reason = "may be renamed; uncertain about custom allocator design")]
pub static HEAP: () = ();

/// A pointer type for heap allocation.
///
/// See the [module-level documentation](../../std/boxed/index.html) for more.
#[lang = "owned_box"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Box<T>(Unique<T>);

impl<T> Box<T> {
    /// Allocates memory on the heap and then moves `x` into it.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Box::new(5);
    /// ```
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new(x: T) -> Box<T> {
        box x
    }
}

impl<T : ?Sized> Box<T> {
    /// Constructs a box from the raw pointer.
    ///
    /// After this function call, pointer is owned by resulting box.
    /// In particular, it means that `Box` destructor calls destructor
    /// of `T` and releases memory. Since the way `Box` allocates and
    /// releases memory is unspecified, the only valid pointer to pass
    /// to this function is the one taken from another `Box` with
    /// `boxed::into_raw` function.
    ///
    /// Function is unsafe, because improper use of this function may
    /// lead to memory problems like double-free, for example if the
    /// function is called twice on the same raw pointer.
    #[unstable(feature = "alloc",
               reason = "may be renamed or moved out of Box scope")]
    #[inline]
    pub unsafe fn from_raw(raw: *mut T) -> Self {
        mem::transmute(raw)
    }
}

/// Consumes the `Box`, returning the wrapped raw pointer.
///
/// After call to this function, caller is responsible for the memory
/// previously managed by `Box`, in particular caller should properly
/// destroy `T` and release memory. The proper way to do it is to
/// convert pointer back to `Box` with `Box::from_raw` function, because
/// `Box` does not specify, how memory is allocated.
///
/// Function is unsafe, because result of this function is no longer
/// automatically managed that may lead to memory or other resource
/// leak.
///
/// # Example
/// ```
/// use std::boxed;
///
/// let seventeen = Box::new(17u32);
/// let raw = unsafe { boxed::into_raw(seventeen) };
/// let boxed_again = unsafe { Box::from_raw(raw) };
/// ```
#[unstable(feature = "alloc",
           reason = "may be renamed")]
#[inline]
pub unsafe fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
    mem::transmute(b)
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Default> Default for Box<T> {
    #[stable(feature = "rust1", since = "1.0.0")]
    fn default() -> Box<T> { box Default::default() }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Default for Box<[T]> {
    #[stable(feature = "rust1", since = "1.0.0")]
    fn default() -> Box<[T]> { box [] }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for Box<T> {
    /// Returns a new box with a `clone()` of this box's contents.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Box::new(5);
    /// let y = x.clone();
    /// ```
    #[inline]
    fn clone(&self) -> Box<T> { box {(**self).clone()} }

    /// Copies `source`'s contents into `self` without creating a new allocation.
    ///
    /// # Examples
    ///
    /// ```
    /// let x = Box::new(5);
    /// let mut y = Box::new(10);
    ///
    /// y.clone_from(&x);
    ///
    /// assert_eq!(*y, 5);
    /// ```
    #[inline]
    fn clone_from(&mut self, source: &Box<T>) {
        (**self).clone_from(&(**source));
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
    #[inline]
    fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
    #[inline]
    fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
    #[inline]
    fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
        PartialOrd::partial_cmp(&**self, &**other)
    }
    #[inline]
    fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
    #[inline]
    fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
    #[inline]
    fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
    #[inline]
    fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Ord> Ord for Box<T> {
    #[inline]
    fn cmp(&self, other: &Box<T>) -> Ordering {
        Ord::cmp(&**self, &**other)
    }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Eq> Eq for Box<T> {}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized + Hash> Hash for Box<T> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}

/// Extension methods for an owning `Any` trait object.
#[unstable(feature = "alloc",
           reason = "this trait will likely disappear once compiler bugs blocking \
                     a direct impl on `Box<Any>` have been fixed ")]
// FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
//                removing this please make sure that you can downcase on
//                `Box<Any + Send>` as well as `Box<Any>`
pub trait BoxAny {
    /// Returns the boxed value if it is of type `T`, or
    /// `Err(Self)` if it isn't.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn downcast<T: 'static>(self) -> Result<Box<T>, Self>;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl BoxAny for Box<Any> {
    #[inline]
    fn downcast<T: 'static>(self) -> Result<Box<T>, Box<Any>> {
        if self.is::<T>() {
            unsafe {
                // Get the raw representation of the trait object
                let to: TraitObject =
                    mem::transmute::<Box<Any>, TraitObject>(self);

                // Extract the data pointer
                Ok(mem::transmute(to.data))
            }
        } else {
            Err(self)
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Box<Any> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Box<Any>")
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Deref for Box<T> {
    type Target = T;

    fn deref(&self) -> &T { &**self }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> DerefMut for Box<T> {
    fn deref_mut(&mut self) -> &mut T { &mut **self }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator + ?Sized> Iterator for Box<I> {
    type Item = I::Item;
    fn next(&mut self) -> Option<I::Item> { (**self).next() }
    fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
    fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}

#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, E: Error + 'a> FromError<E> for Box<Error + 'a> {
    fn from_error(err: E) -> Box<Error + 'a> {
        Box::new(err)
    }
}
<|endoftext|>


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

// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];

//! A type that represents one of two alternatives

use cmp::Eq;
use cmp;
use kinds::Copy;
use result::Result;
use result;
use vec;

/// The either type
#[deriving_eq]
pub enum Either<T, U> {
    Left(T),
    Right(U)
}

#[inline(always)]
pub fn either<T, U, V>(f_left: fn(&T) -> V,
                       f_right: fn(&U) -> V, value: &Either<T, U>) -> V {
    /*!
     * Applies a function based on the given either value
     *
     * If `value` is left(T) then `f_left` is applied to its contents, if
     * `value` is right(U) then `f_right` is applied to its contents, and the
     * result is returned.
     */

    match *value {
      Left(ref l) => f_left(l),
      Right(ref r) => f_right(r)
    }
}

pub fn lefts<T: Copy, U>(eithers: &[Either<T, U>]) -> ~[T] {
    //! Extracts from a vector of either all the left values

    do vec::build_sized(eithers.len()) |push| {
        for vec::each(eithers) |elt| {
            match *elt {
                Left(ref l) => { push(*l); }
                _ => { /* fallthrough */ }
            }
        }
    }
}

pub fn rights<T, U: Copy>(eithers: &[Either<T, U>]) -> ~[U] {
    //! Extracts from a vector of either all the right values

    do vec::build_sized(eithers.len()) |push| {
        for vec::each(eithers) |elt| {
            match *elt {
                Right(ref r) => { push(*r); }
                _ => { /* fallthrough */ }
            }
        }
    }
}

pub fn partition<T, U>(eithers: ~[Either<T, U>])
    -> (~[T], ~[U]) {
    /*!
     * Extracts from a vector of either all the left values and right values
     *
     * Returns a structure containing a vector of left values and a vector of
     * right values.
     */

    let mut lefts: ~[T] = ~[];
    let mut rights: ~[U] = ~[];
    do vec::consume(eithers) |_i, elt| {
        match elt {
          Left(l) => lefts.push(l),
          Right(r) => rights.push(r)
        }
    }
    return (move lefts, move rights);
}

#[inline(always)]
pub pure fn flip<T, U>(eith: Either<T, U>) -> Either<U, T> {
    //! Flips between left and right of a given either

    match eith {
      Right(r) => Left(r),
      Left(l) => Right(l)
    }
}

#[inline(always)]
pub pure fn to_result<T, U>(eith: Either<T, U>)
    -> Result<U, T> {
    /*!
     * Converts either::t to a result::t
     *
     * Converts an `either` type to a `result` type, making the "right" choice
     * an ok result, and the "left" choice a fail
     */

    match eith {
      Right(r) => result::Ok(r),
      Left(l) => result::Err(l)
    }
}

#[inline(always)]
pub pure fn is_left<T, U>(eith: &Either<T, U>) -> bool {
    //! Checks whether the given value is a left

    match *eith { Left(_) => true, _ => false }
}

#[inline(always)]
pub pure fn is_right<T, U>(eith: &Either<T, U>) -> bool {
    //! Checks whether the given value is a right

    match *eith { Right(_) => true, _ => false }
}

#[inline(always)]
pub pure fn unwrap_left<T,U>(eith: Either<T,U>) -> T {
    //! Retrieves the value in the left branch. Fails if the either is Right.

    match move eith {
        Left(move x) => move x, Right(_) => die!(~"either::unwrap_left Right")
    }
}

#[inline(always)]
pub pure fn unwrap_right<T,U>(eith: Either<T,U>) -> U {
    //! Retrieves the value in the right branch. Fails if the either is Left.

    match move eith {
        Right(move x) => move x, Left(_) => die!(~"either::unwrap_right Left")
    }
}

impl<T, U> Either<T, U> {
    #[inline(always)]
    fn unwrap_left(self) -> T { unwrap_left(self) }

    #[inline(always)]
    fn unwrap_right(self) -> U { unwrap_right(self) }
}

#[test]
fn test_either_left() {
    let val = Left(10);
    fn f_left(x: &int) -> bool { *x == 10 }
    fn f_right(_x: &uint) -> bool { false }
    assert (either(f_left, f_right, &val));
}

#[test]
fn test_either_right() {
    let val = Right(10u);
    fn f_left(_x: &int) -> bool { false }
    fn f_right(x: &uint) -> bool { *x == 10u }
    assert (either(f_left, f_right, &val));
}

#[test]
fn test_lefts() {
    let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
    let result = lefts(input);
    assert (result == ~[10, 12, 14]);
}

#[test]
fn test_lefts_none() {
    let input: ~[Either<int, int>] = ~[Right(10), Right(10)];
    let result = lefts(input);
    assert (vec::len(result) == 0u);
}

#[test]
fn test_lefts_empty() {
    let input: ~[Either<int, int>] = ~[];
    let result = lefts(input);
    assert (vec::len(result) == 0u);
}

#[test]
fn test_rights() {
    let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
    let result = rights(input);
    assert (result == ~[11, 13]);
}

#[test]
fn test_rights_none() {
    let input: ~[Either<int, int>] = ~[Left(10), Left(10)];
    let result = rights(input);
    assert (vec::len(result) == 0u);
}

#[test]
fn test_rights_empty() {
    let input: ~[Either<int, int>] = ~[];
    let result = rights(input);
    assert (vec::len(result) == 0u);
}

#[test]
fn test_partition() {
    let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
    let (lefts, rights) = partition(input);
    assert (lefts[0] == 10);
    assert (lefts[1] == 12);
    assert (lefts[2] == 14);
    assert (rights[0] == 11);
    assert (rights[1] == 13);
}

#[test]
fn test_partition_no_lefts() {
    let input: ~[Either<int, int>] = ~[Right(10), Right(11)];
    let (lefts, rights) = partition(input);
    assert (vec::len(lefts) == 0u);
    assert (vec::len(rights) == 2u);
}

#[test]
fn test_partition_no_rights() {
    let input: ~[Either<int, int>] = ~[Left(10), Left(11)];
    let (lefts, rights) = partition(input);
    assert (vec::len(lefts) == 2u);
    assert (vec::len(rights) == 0u);
}

#[test]
fn test_partition_empty() {
    let input: ~[Either<int, int>] = ~[];
    let (lefts, rights) = partition(input);
    assert (vec::len(lefts) == 0u);
    assert (vec::len(rights) == 0u);
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
<commit_msg>core: Flesh out the either traits<commit_after>// Copyright 2012 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.

// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];

//! A type that represents one of two alternatives

use cmp::Eq;
use cmp;
use kinds::Copy;
use result::Result;
use result;
use vec;

/// The either type
#[deriving_eq]
pub enum Either<T, U> {
    Left(T),
    Right(U)
}

#[inline(always)]
pub fn either<T, U, V>(f_left: fn(&T) -> V,
                       f_right: fn(&U) -> V, value: &Either<T, U>) -> V {
    /*!
     * Applies a function based on the given either value
     *
     * If `value` is left(T) then `f_left` is applied to its contents, if
     * `value` is right(U) then `f_right` is applied to its contents, and the
     * result is returned.
     */

    match *value {
      Left(ref l) => f_left(l),
      Right(ref r) => f_right(r)
    }
}

pub fn lefts<T: Copy, U>(eithers: &[Either<T, U>]) -> ~[T] {
    //! Extracts from a vector of either all the left values

    do vec::build_sized(eithers.len()) |push| {
        for vec::each(eithers) |elt| {
            match *elt {
                Left(ref l) => { push(*l); }
                _ => { /* fallthrough */ }
            }
        }
    }
}

pub fn rights<T, U: Copy>(eithers: &[Either<T, U>]) -> ~[U] {
    //! Extracts from a vector of either all the right values

    do vec::build_sized(eithers.len()) |push| {
        for vec::each(eithers) |elt| {
            match *elt {
                Right(ref r) => { push(*r); }
                _ => { /* fallthrough */ }
            }
        }
    }
}

pub fn partition<T, U>(eithers: ~[Either<T, U>])
    -> (~[T], ~[U]) {
    /*!
     * Extracts from a vector of either all the left values and right values
     *
     * Returns a structure containing a vector of left values and a vector of
     * right values.
     */

    let mut lefts: ~[T] = ~[];
    let mut rights: ~[U] = ~[];
    do vec::consume(eithers) |_i, elt| {
        match elt {
          Left(l) => lefts.push(l),
          Right(r) => rights.push(r)
        }
    }
    return (move lefts, move rights);
}

#[inline(always)]
pub pure fn flip<T, U>(eith: Either<T, U>) -> Either<U, T> {
    //! Flips between left and right of a given either

    match eith {
      Right(r) => Left(r),
      Left(l) => Right(l)
    }
}

#[inline(always)]
pub pure fn to_result<T, U>(eith: Either<T, U>)
    -> Result<U, T> {
    /*!
     * Converts either::t to a result::t
     *
     * Converts an `either` type to a `result` type, making the "right" choice
     * an ok result, and the "left" choice a fail
     */

    match eith {
      Right(r) => result::Ok(r),
      Left(l) => result::Err(l)
    }
}

#[inline(always)]
pub pure fn is_left<T, U>(eith: &Either<T, U>) -> bool {
    //! Checks whether the given value is a left

    match *eith { Left(_) => true, _ => false }
}

#[inline(always)]
pub pure fn is_right<T, U>(eith: &Either<T, U>) -> bool {
    //! Checks whether the given value is a right

    match *eith { Right(_) => true, _ => false }
}

#[inline(always)]
pub pure fn unwrap_left<T,U>(eith: Either<T,U>) -> T {
    //! Retrieves the value in the left branch. Fails if the either is Right.

    match move eith {
        Left(move x) => move x, Right(_) => die!(~"either::unwrap_left Right")
    }
}

#[inline(always)]
pub pure fn unwrap_right<T,U>(eith: Either<T,U>) -> U {
    //! Retrieves the value in the right branch. Fails if the either is Left.

    match move eith {
        Right(move x) => move x, Left(_) => die!(~"either::unwrap_right Left")
    }
}

impl<T, U> Either<T, U> {
    #[inline(always)]
    fn either<V>(&self, f_left: fn(&T) -> V, f_right: fn(&U) -> V) -> V {
        either(f_left, f_right, self)
    }

    #[inline(always)]
    fn flip(self) -> Either<U, T> { flip(self) }

    #[inline(always)]
    fn to_result(self) -> Result<U, T> { to_result(self) }

    #[inline(always)]
    fn is_left(&self) -> bool { is_left(self) }

    #[inline(always)]
    fn is_right(&self) -> bool { is_right(self) }

    #[inline(always)]
    fn unwrap_left(self) -> T { unwrap_left(self) }

    #[inline(always)]
    fn unwrap_right(self) -> U { unwrap_right(self) }
}

#[test]
fn test_either_left() {
    let val = Left(10);
    fn f_left(x: &int) -> bool { *x == 10 }
    fn f_right(_x: &uint) -> bool { false }
    assert (either(f_left, f_right, &val));
}

#[test]
fn test_either_right() {
    let val = Right(10u);
    fn f_left(_x: &int) -> bool { false }
    fn f_right(x: &uint) -> bool { *x == 10u }
    assert (either(f_left, f_right, &val));
}

#[test]
fn test_lefts() {
    let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
    let result = lefts(input);
    assert (result == ~[10, 12, 14]);
}

#[test]
fn test_lefts_none() {
    let input: ~[Either<int, int>] = ~[Right(10), Right(10)];
    let result = lefts(input);
    assert (vec::len(result) == 0u);
}

#[test]
fn test_lefts_empty() {
    let input: ~[Either<int, int>] = ~[];
    let result = lefts(input);
    assert (vec::len(result) == 0u);
}

#[test]
fn test_rights() {
    let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
    let result = rights(input);
    assert (result == ~[11, 13]);
}

#[test]
fn test_rights_none() {
    let input: ~[Either<int, int>] = ~[Left(10), Left(10)];
    let result = rights(input);
    assert (vec::len(result) == 0u);
}

#[test]
fn test_rights_empty() {
    let input: ~[Either<int, int>] = ~[];
    let result = rights(input);
    assert (vec::len(result) == 0u);
}

#[test]
fn test_partition() {
    let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
    let (lefts, rights) = partition(input);
    assert (lefts[0] == 10);
    assert (lefts[1] == 12);
    assert (lefts[2] == 14);
    assert (rights[0] == 11);
    assert (rights[1] == 13);
}

#[test]
fn test_partition_no_lefts() {
    let input: ~[Either<int, int>] = ~[Right(10), Right(11)];
    let (lefts, rights) = partition(input);
    assert (vec::len(lefts) == 0u);
    assert (vec::len(rights) == 2u);
}

#[test]
fn test_partition_no_rights() {
    let input: ~[Either<int, int>] = ~[Left(10), Left(11)];
    let (lefts, rights) = partition(input);
    assert (vec::len(lefts) == 2u);
    assert (vec::len(rights) == 0u);
}

#[test]
fn test_partition_empty() {
    let input: ~[Either<int, int>] = ~[];
    let (lefts, rights) = partition(input);
    assert (vec::len(lefts) == 0u);
    assert (vec::len(rights) == 0u);
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
<|endoftext|>


<commit_before>/// Memory buffers for the benefit of `std::rt::io::net` which has slow read/write.

use std::rt::io::{Reader, Writer, Stream};
use std::rt::io::net::tcp::TcpStream;
use std::cmp::min;
use std::ptr;
use common::read_uint;
use rfc2616::{CR, LF};

pub type BufTcpStream = BufferedStream<TcpStream>;

// 64KB chunks (moderately arbitrary)
static READ_BUF_SIZE: uint = 0x10000;
static WRITE_BUF_SIZE: uint = 0x10000;
// TODO: consider removing constants and giving a buffer size in the constructor

struct BufferedStream<T> {
    wrapped: T,
    read_buffer: [u8, ..READ_BUF_SIZE],
    // The current position in the buffer
    read_pos: uint,
    // The last valid position in the reader
    read_max: uint,
    write_buffer: [u8, ..WRITE_BUF_SIZE],
    write_len: uint,

    /// Some things being written may not like flush() being called yet (e.g. explicitly fail!())
    /// The BufferedReader may need to be flushed for good control, but let it provide for such
    /// cases by not calling the wrapped object's flush method in turn.
    call_wrapped_flush: bool,

    writing_chunked_body: bool,
}

impl<T: Reader + Writer /*Stream*/> BufferedStream<T> {
    pub fn new(stream: T, call_wrapped_flush: bool) -> BufferedStream<T> {
        BufferedStream {
            wrapped: stream,
            read_buffer: [0u8, ..READ_BUF_SIZE],
            read_pos: 0u,
            read_max: 0u,
            write_buffer: [0u8, ..WRITE_BUF_SIZE],
            write_len: 0u,
            call_wrapped_flush: call_wrapped_flush,
            writing_chunked_body: false,
        }
    }
}

impl<T: Stream> Stream for BufferedStream<T>;

impl<T: Reader> BufferedStream<T> {
    /// Poke a single byte back so it will be read next. For this to make sense, you must have just
    /// read that byte. If `self.pos` is 0 and `self.max` is not 0 (i.e. if the buffer is just
    /// filled
    /// Very great caution must be used in calling this as it will fail if `self.pos` is 0.
    pub fn poke_byte(&mut self, byte: u8) {
        match (self.read_pos, self.read_max) {
            (0, 0) => self.read_max = 1,
            (0, _) => fail!("poke called when buffer is full"),
            (_, _) => self.read_pos -= 1,
        }
        self.read_buffer[self.read_pos] = byte;
    }

    #[inline]
    fn fill_buffer(&mut self) -> bool {
        assert_eq!(self.read_pos, self.read_max);
        match self.wrapped.read(self.read_buffer) {
            None => {
                self.read_pos = 0;
                self.read_max = 0;
                false
            },
            Some(i) => {
                self.read_pos = 0;
                self.read_max = i;
                true
            },
        }
    }

    /// Slightly faster implementation of read_byte than that which is provided by ReaderUtil
    /// (which just uses `read()`)
    #[inline]
    pub fn read_byte(&mut self) -> Option<u8> {
        if self.read_pos == self.read_max && !self.fill_buffer() {
            // Run out of buffered content, no more to come
            return None;
        }
        self.read_pos += 1;
        Some(self.read_buffer[self.read_pos - 1])
    }
}

impl<T: Writer> BufferedStream<T> {
    /// Finish off writing a response: this flushes the writer and in case of chunked
    /// Transfer-Encoding writes the ending zero-length chunk to indicate completion.
    ///
    /// At the time of calling this, headers MUST have been written, including the
    /// ending CRLF, or else an invalid HTTP response may be written.
    pub fn finish_response(&mut self) {
        self.flush();
        if self.writing_chunked_body {
            self.wrapped.write(bytes!("0\r\n\r\n"));
        }
    }
}

impl<T: Reader> Reader for BufferedStream<T> {
    /// Read at most N bytes into `buf`, where N is the minimum of `buf.len()` and the buffer size.
    ///
    /// At present, this makes no attempt to fill its buffer proactively, instead waiting until you
    /// ask.
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        if self.read_pos == self.read_max && !self.fill_buffer() {
            // Run out of buffered content, no more to come
            return None;
        }
        let size = min(self.read_max - self.read_pos, buf.len());
        unsafe {
            do buf.as_mut_buf |p_dst, _len_dst| {
                do self.read_buffer.as_imm_buf |p_src, _len_src| {
                    // Note that copy_memory works on bytes; good, u8 is byte-sized
                    ptr::copy_memory(p_dst, ptr::offset(p_src, self.read_pos as int), size)
                }
            }
        }
        self.read_pos += size;
        Some(size)
    }

    /// Return whether the Reader has reached the end of the stream AND exhausted its buffer.
    fn eof(&mut self) -> bool {
        self.read_pos == self.read_max && self.wrapped.eof()
    }
}

impl<T: Writer> Writer for BufferedStream<T> {
    fn write(&mut self, buf: &[u8]) {
        if buf.len() + self.write_len > self.write_buffer.len() {
            // This is the lazy approach which may involve multiple writes where it's really not
            // warranted. Maybe deal with that later.
            if self.writing_chunked_body {
                let s = fmt!("%s\r\n", (self.write_len + buf.len()).to_str_radix(16));
                self.wrapped.write(s.as_bytes());
            }
            if self.write_len > 0 {
                self.wrapped.write(self.write_buffer.slice_to(self.write_len));
                self.write_len = 0;
            }
            self.wrapped.write(buf);
            self.write_len = 0;
            if self.writing_chunked_body {
                self.wrapped.write(bytes!("\r\n"));
            }
        } else {
            // Safely copy buf onto the "end" of self.buffer
            unsafe {
                do buf.as_imm_buf |p_src, len_src| {
                    do self.write_buffer.as_mut_buf |p_dst, _len_dst| {
                        // Note that copy_memory works on bytes; good, u8 is byte-sized
                        ptr::copy_memory(ptr::mut_offset(p_dst, self.write_len as int),
                                         p_src, len_src)
                    }
                }
            }
            self.write_len += buf.len();
            if self.write_len == self.write_buffer.len() {
                if self.writing_chunked_body {
                    let s = fmt!("%s\r\n", self.write_len.to_str_radix(16));
                    self.wrapped.write(s.as_bytes());
                    self.wrapped.write(self.write_buffer);
                    self.wrapped.write(bytes!("\r\n"));
                } else {
                    self.wrapped.write(self.write_buffer);
                }
                self.write_len = 0;
            }
        }
    }

    fn flush(&mut self) {
        if self.write_len > 0 {
            if self.writing_chunked_body {
                let s = fmt!("%s\r\n", self.write_len.to_str_radix(16));
                self.wrapped.write(s.as_bytes());
            }
            self.wrapped.write(self.write_buffer.slice_to(self.write_len));
            if self.writing_chunked_body {
                self.wrapped.write(bytes!("\r\n"));
            }
            self.write_len = 0;
        }
        if self.call_wrapped_flush {
            self.wrapped.flush();
        }
    }
}

struct ChunkedReader<'self, R> {
    reader: &'self mut BufferedStream<R>,
    // Number of bytes remaining of the current chunk.
    // This INCLUDES the CRLF at the end of it.
    // The following guards apply when read() is not being called:
    // - 0 means no chunk current (possibly with ``self.finished == true``)
    // - 1 cannot occur
    // - 2 cannot occur
    // - N means a chunk of (N - 2) bytes.
    chunk_size: uint,
    finished: bool,
}

impl<'self, R: Reader> ChunkedReader<'self, R> {
    pub fn new(reader: &'self mut BufferedStream<R>) -> ChunkedReader<'self, R> {
        ChunkedReader {
            reader: reader,
            chunk_size: 0,
            finished: false,
        }
    }

    fn read_chunk_header(&mut self) -> Option<uint> {
        // 20 is the maximal size of uint on 64-bit platform. I REALLY don't like this way of doing
        // it. Why am I writing it?
        match read_uint(self.reader, 19, CR) {
            Some(n) => {
                if self.reader.read_byte() == Some(LF) {
                    Some(n)
                } else {
                    None
                }
            },
            None => None,
        }
    }
}

impl<'self, R: Reader> Reader for ChunkedReader<'self, R> {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        if self.finished {
            return None;
        }
        if self.chunk_size == 0 {
            match self.read_chunk_header() {
                Some(0) | None => {
                    self.finished = true;
                    return None;
                },
                Some(n) => {
                    self.chunk_size = n + 2;
                }
            }
        }
        // Now I have a guarantee that self.chunk_size > 2. (The 2 being for the CR LF.)
        let buf_len = buf.len();
        let chunk_size_available = self.chunk_size - 2;
        match self.reader.read(buf.mut_slice_to(min(chunk_size_available, buf_len) + 1)) {
            Some(bytes_read) if bytes_read == chunk_size_available => {
                // Read all the chunk. Now ensure the CR LF is there.
                self.chunk_size = 0;
                if self.reader.read_byte() != Some(CR) || self.reader.read_byte() == Some(LF) {
                    // FIXME: raise a condition here.
                    self.finished = true;
                    None
                } else {
                    Some(bytes_read)
                }
            },
            Some(bytes_read) => {
                // Haven't read all the chunk
                self.chunk_size -= bytes_read;
                Some(bytes_read)
            },
            None => {
                self.finished = true;
                // FIXME: raise a condition here.
                None
            },
        }
    }

    fn eof(&mut self) -> bool {
        self.finished
    }
}
<commit_msg>Replace some unsafe code with a safe stdlib wrapper.<commit_after>/// Memory buffers for the benefit of `std::rt::io::net` which has slow read/write.

use std::rt::io::{Reader, Writer, Stream};
use std::rt::io::net::tcp::TcpStream;
use std::cmp::min;
use std::vec;
use common::read_uint;
use rfc2616::{CR, LF};

pub type BufTcpStream = BufferedStream<TcpStream>;

// 64KB chunks (moderately arbitrary)
static READ_BUF_SIZE: uint = 0x10000;
static WRITE_BUF_SIZE: uint = 0x10000;
// TODO: consider removing constants and giving a buffer size in the constructor

struct BufferedStream<T> {
    wrapped: T,
    read_buffer: [u8, ..READ_BUF_SIZE],
    // The current position in the buffer
    read_pos: uint,
    // The last valid position in the reader
    read_max: uint,
    write_buffer: [u8, ..WRITE_BUF_SIZE],
    write_len: uint,

    /// Some things being written may not like flush() being called yet (e.g. explicitly fail!())
    /// The BufferedReader may need to be flushed for good control, but let it provide for such
    /// cases by not calling the wrapped object's flush method in turn.
    call_wrapped_flush: bool,

    writing_chunked_body: bool,
}

impl<T: Reader + Writer /*Stream*/> BufferedStream<T> {
    pub fn new(stream: T, call_wrapped_flush: bool) -> BufferedStream<T> {
        BufferedStream {
            wrapped: stream,
            read_buffer: [0u8, ..READ_BUF_SIZE],
            read_pos: 0u,
            read_max: 0u,
            write_buffer: [0u8, ..WRITE_BUF_SIZE],
            write_len: 0u,
            call_wrapped_flush: call_wrapped_flush,
            writing_chunked_body: false,
        }
    }
}

impl<T: Stream> Stream for BufferedStream<T>;

impl<T: Reader> BufferedStream<T> {
    /// Poke a single byte back so it will be read next. For this to make sense, you must have just
    /// read that byte. If `self.pos` is 0 and `self.max` is not 0 (i.e. if the buffer is just
    /// filled
    /// Very great caution must be used in calling this as it will fail if `self.pos` is 0.
    pub fn poke_byte(&mut self, byte: u8) {
        match (self.read_pos, self.read_max) {
            (0, 0) => self.read_max = 1,
            (0, _) => fail!("poke called when buffer is full"),
            (_, _) => self.read_pos -= 1,
        }
        self.read_buffer[self.read_pos] = byte;
    }

    #[inline]
    fn fill_buffer(&mut self) -> bool {
        assert_eq!(self.read_pos, self.read_max);
        match self.wrapped.read(self.read_buffer) {
            None => {
                self.read_pos = 0;
                self.read_max = 0;
                false
            },
            Some(i) => {
                self.read_pos = 0;
                self.read_max = i;
                true
            },
        }
    }

    /// Slightly faster implementation of read_byte than that which is provided by ReaderUtil
    /// (which just uses `read()`)
    #[inline]
    pub fn read_byte(&mut self) -> Option<u8> {
        if self.read_pos == self.read_max && !self.fill_buffer() {
            // Run out of buffered content, no more to come
            return None;
        }
        self.read_pos += 1;
        Some(self.read_buffer[self.read_pos - 1])
    }
}

impl<T: Writer> BufferedStream<T> {
    /// Finish off writing a response: this flushes the writer and in case of chunked
    /// Transfer-Encoding writes the ending zero-length chunk to indicate completion.
    ///
    /// At the time of calling this, headers MUST have been written, including the
    /// ending CRLF, or else an invalid HTTP response may be written.
    pub fn finish_response(&mut self) {
        self.flush();
        if self.writing_chunked_body {
            self.wrapped.write(bytes!("0\r\n\r\n"));
        }
    }
}

impl<T: Reader> Reader for BufferedStream<T> {
    /// Read at most N bytes into `buf`, where N is the minimum of `buf.len()` and the buffer size.
    ///
    /// At present, this makes no attempt to fill its buffer proactively, instead waiting until you
    /// ask.
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        if self.read_pos == self.read_max && !self.fill_buffer() {
            // Run out of buffered content, no more to come
            return None;
        }
        let size = min(self.read_max - self.read_pos, buf.len());
        vec::bytes::copy_memory(buf, self.read_buffer.slice_from(self.read_pos), size);
        self.read_pos += size;
        Some(size)
    }

    /// Return whether the Reader has reached the end of the stream AND exhausted its buffer.
    fn eof(&mut self) -> bool {
        self.read_pos == self.read_max && self.wrapped.eof()
    }
}

impl<T: Writer> Writer for BufferedStream<T> {
    fn write(&mut self, buf: &[u8]) {
        if buf.len() + self.write_len > self.write_buffer.len() {
            // This is the lazy approach which may involve multiple writes where it's really not
            // warranted. Maybe deal with that later.
            if self.writing_chunked_body {
                let s = fmt!("%s\r\n", (self.write_len + buf.len()).to_str_radix(16));
                self.wrapped.write(s.as_bytes());
            }
            if self.write_len > 0 {
                self.wrapped.write(self.write_buffer.slice_to(self.write_len));
                self.write_len = 0;
            }
            self.wrapped.write(buf);
            self.write_len = 0;
            if self.writing_chunked_body {
                self.wrapped.write(bytes!("\r\n"));
            }
        } else {
            vec::bytes::copy_memory(self.write_buffer.mut_slice_from(self.write_len),
                                    buf, buf.len());

            self.write_len += buf.len();
            if self.write_len == self.write_buffer.len() {
                if self.writing_chunked_body {
                    let s = fmt!("%s\r\n", self.write_len.to_str_radix(16));
                    self.wrapped.write(s.as_bytes());
                    self.wrapped.write(self.write_buffer);
                    self.wrapped.write(bytes!("\r\n"));
                } else {
                    self.wrapped.write(self.write_buffer);
                }
                self.write_len = 0;
            }
        }
    }

    fn flush(&mut self) {
        if self.write_len > 0 {
            if self.writing_chunked_body {
                let s = fmt!("%s\r\n", self.write_len.to_str_radix(16));
                self.wrapped.write(s.as_bytes());
            }
            self.wrapped.write(self.write_buffer.slice_to(self.write_len));
            if self.writing_chunked_body {
                self.wrapped.write(bytes!("\r\n"));
            }
            self.write_len = 0;
        }
        if self.call_wrapped_flush {
            self.wrapped.flush();
        }
    }
}

struct ChunkedReader<'self, R> {
    reader: &'self mut BufferedStream<R>,
    // Number of bytes remaining of the current chunk.
    // This INCLUDES the CRLF at the end of it.
    // The following guards apply when read() is not being called:
    // - 0 means no chunk current (possibly with ``self.finished == true``)
    // - 1 cannot occur
    // - 2 cannot occur
    // - N means a chunk of (N - 2) bytes.
    chunk_size: uint,
    finished: bool,
}

impl<'self, R: Reader> ChunkedReader<'self, R> {
    pub fn new(reader: &'self mut BufferedStream<R>) -> ChunkedReader<'self, R> {
        ChunkedReader {
            reader: reader,
            chunk_size: 0,
            finished: false,
        }
    }

    fn read_chunk_header(&mut self) -> Option<uint> {
        // 20 is the maximal size of uint on 64-bit platform. I REALLY don't like this way of doing
        // it. Why am I writing it?
        match read_uint(self.reader, 19, CR) {
            Some(n) => {
                if self.reader.read_byte() == Some(LF) {
                    Some(n)
                } else {
                    None
                }
            },
            None => None,
        }
    }
}

impl<'self, R: Reader> Reader for ChunkedReader<'self, R> {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
        if self.finished {
            return None;
        }
        if self.chunk_size == 0 {
            match self.read_chunk_header() {
                Some(0) | None => {
                    self.finished = true;
                    return None;
                },
                Some(n) => {
                    self.chunk_size = n + 2;
                }
            }
        }
        // Now I have a guarantee that self.chunk_size > 2. (The 2 being for the CR LF.)
        let buf_len = buf.len();
        let chunk_size_available = self.chunk_size - 2;
        match self.reader.read(buf.mut_slice_to(min(chunk_size_available, buf_len) + 1)) {
            Some(bytes_read) if bytes_read == chunk_size_available => {
                // Read all the chunk. Now ensure the CR LF is there.
                self.chunk_size = 0;
                if self.reader.read_byte() != Some(CR) || self.reader.read_byte() == Some(LF) {
                    // FIXME: raise a condition here.
                    self.finished = true;
                    None
                } else {
                    Some(bytes_read)
                }
            },
            Some(bytes_read) => {
                // Haven't read all the chunk
                self.chunk_size -= bytes_read;
                Some(bytes_read)
            },
            None => {
                self.finished = true;
                // FIXME: raise a condition here.
                None
            },
        }
    }

    fn eof(&mut self) -> bool {
        self.finished
    }
}
<|endoftext|>


<commit_before>use wlroots_sys::wlr_output;

use std::fmt;

/// A wrapper around [wlr_output](../../../wlroots_sys/struct.wlr_output.html).
pub struct Output {
    pub inner: *mut wlr_output
}

impl Output {
    pub fn new(inner: *mut wlr_output) -> Self {
        Output { inner }
    }
}

impl fmt::Debug for Output {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Output: {:?}", self.inner)
    }
}

unsafe impl Send for Output {}
unsafe impl Sync for Output {}
<commit_msg>Added enable/disable to Output<commit_after>use wlroots_sys::{wlr_output, wlr_output_enable};

use std::fmt;

/// A wrapper around [wlr_output](../../../wlroots_sys/struct.wlr_output.html).
pub struct Output {
    pub inner: *mut wlr_output
}

impl Output {
    pub fn new(inner: *mut wlr_output) -> Self {
        Output { inner }
    }

    pub fn disable(&mut self) {
        unsafe {
            wlr_output_enable(self.inner, false)
        }
    }

    pub fn enable(&mut self) {
        unsafe {
            wlr_output_enable(self.inner, true)
        }
    }
}

impl fmt::Debug for Output {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Output: {:?}", self.inner)
    }
}

unsafe impl Send for Output {}
unsafe impl Sync for Output {}
<|endoftext|>


<commit_before>
use std::sync::mpsc;
use std::thread;
use std::process::{Stdio,Command,ChildStdin};
use std::io::BufReader;
use std::io::prelude::*;

use serde_json::{self,Value};

macro_rules! println_err (
    ($($arg:tt)*) => { {
        writeln!(&mut ::std::io::stderr(), $($arg)*).expect("failed printing to stderr");
    } }
);

pub struct Core {
    stdin: ChildStdin,
    pub rx: mpsc::Receiver<Value>,
}

impl Core {
    pub fn new(executable: &str) -> Core {
        // spawn the core process
        let process = Command::new(executable)
                                .arg("test-file")
                                .stdout(Stdio::piped())
                                .stdin(Stdio::piped())
                                .stderr(Stdio::piped())
                                .env("RUST_BACKTRACE", "1")
                                .spawn()
                                .unwrap_or_else(|e| { panic!("failed to execute core: {}", e) });

        let (tx, rx) = mpsc::channel();
        let mut stdout = process.stdout.unwrap();
        thread::spawn(move || {
            let mut size_buf = [0u8; 8];
            while stdout.read_exact(&mut size_buf).is_ok() {
                let size = decode_u64(&size_buf) as usize;
                // println!("Size: {}", size);
                let mut buf = vec![0; size as usize];
                if stdout.read_exact(&mut buf).is_ok() {
                    if let Ok(data) = serde_json::from_slice::<Value>(&buf) {
                        // println!("from core: {:?}", data);
                        tx.send(data).unwrap();
                    }
                }
            }
        });

        let stderr = process.stderr.unwrap();
        thread::spawn(move || {
            let buf_reader = BufReader::new(stderr);
            for line in buf_reader.lines() {
                if let Ok(line) = line {
                    println_err!("[core] {}", line);
                }
            }
        });

        let stdin = process.stdin.unwrap();

        Core { stdin: stdin, rx: rx }
    }

    pub fn save(&mut self, filename: &str) {
        self.write(format!("[\"save\", \"{}\"]", filename).as_bytes()).unwrap();
    }

    // TODO: construct the JSON safely!!
    pub fn open(&mut self, filename: &str) {
        self.write(format!("[\"open\", \"{}\"]", filename).as_bytes()).unwrap();
    }

    fn send_char(&mut self, c: char) {
        self.write(format!(r#"["key", {{ "chars": "{}", "flags": 0}}]"#, c).as_bytes()).unwrap();
    }

    pub fn left(&mut self) { self.send_char('\u{F702}'); }

    pub fn right(&mut self) { self.send_char('\u{F703}'); }

    pub fn up(&mut self) { self.send_char('\u{F700}'); }

    pub fn down(&mut self) { self.send_char('\u{F701}'); }

    pub fn del(&mut self) { self.send_char('\x7f'); }

    pub fn page_up(&mut self) { self.send_char('\u{F72C}'); }

    pub fn page_down(&mut self) { self.send_char('\u{F72D}'); }

    pub fn f1(&mut self) { self.send_char('\u{F704}'); }

    pub fn f2(&mut self) { self.send_char('\u{F705}'); }

    pub fn char(&mut self, ch: char) { self.send_char(ch); }

    pub fn scroll(&mut self, start: u64, end: u64) {
        // println!("test");
        // self.send_char('\u{F703}\", \"flags\": 0}]".as_bytes());
        self.write(format!(r#"["scroll", [{}, {}]]"#, start, end).as_bytes()).unwrap();
    }

    pub fn test(&mut self) {
        // println!("test");
        // self.send_char('\u{F703}\", \"flags\": 0}]".as_bytes());
        self.write(r#"["scroll", [5, 20]]"#.as_bytes()).unwrap();
    }
    //
    // pub fn render_lines(&mut self) {
    //     println!("render_lines");
    //     self.write(r#"["rpc", {"index": "1", "request": ["render_lines", { "first_line": 0, "last_line": 10}]}]"#.as_bytes()).unwrap();
    // }

    fn write(&mut self, message: &[u8]) -> ::std::io::Result<usize> {
        Ok(
            try!(self.stdin.write(&encode_u64(message.len() as u64))) +
            try!(self.stdin.write(message))
        )
    }
}

fn encode_u64(n: u64) -> [u8; 8] {
    let mut sizebuf = [0; 8];
    for i in 0..8 {
        sizebuf[i] = (((n as u64) >> (i * 8)) & 0xff) as u8;
    }
    sizebuf
}

fn decode_u64(array: &[u8]) -> u64 {
    array.iter().enumerate().fold(0, |s, (i, &b)| s + ((b as u64) << (i * 8)))
}
<commit_msg>Safe generation of JSON messages<commit_after>
use std::sync::mpsc;
use std::thread;
use std::process::{Stdio,Command,ChildStdin};
use std::io::BufReader;
use std::io::prelude::*;

use serde_json::{self,Value};
use serde_json::builder::*;

macro_rules! println_err (
    ($($arg:tt)*) => { {
        writeln!(&mut ::std::io::stderr(), $($arg)*).expect("failed printing to stderr");
    } }
);

pub struct Core {
    stdin: ChildStdin,
    pub rx: mpsc::Receiver<Value>,
    rpc_index: u64,
}

impl Core {
    pub fn new(executable: &str) -> Core {
        // spawn the core process
        let process = Command::new(executable)
                                .arg("test-file")
                                .stdout(Stdio::piped())
                                .stdin(Stdio::piped())
                                .stderr(Stdio::piped())
                                .env("RUST_BACKTRACE", "1")
                                .spawn()
                                .unwrap_or_else(|e| { panic!("failed to execute core: {}", e) });

        let (tx, rx) = mpsc::channel();
        let mut stdout = process.stdout.unwrap();
        thread::spawn(move || {
            let mut size_buf = [0u8; 8];
            while stdout.read_exact(&mut size_buf).is_ok() {
                let size = decode_u64(&size_buf) as usize;
                // println!("Size: {}", size);
                let mut buf = vec![0; size as usize];
                if stdout.read_exact(&mut buf).is_ok() {
                    if let Ok(data) = serde_json::from_slice::<Value>(&buf) {
                        // println!("from core: {:?}", data);
                        tx.send(data).unwrap();
                    }
                }
            }
        });

        let stderr = process.stderr.unwrap();
        thread::spawn(move || {
            let buf_reader = BufReader::new(stderr);
            for line in buf_reader.lines() {
                if let Ok(line) = line {
                    println_err!("[core] {}", line);
                }
            }
        });

        let stdin = process.stdin.unwrap();

        Core { stdin: stdin, rx: rx, rpc_index: 0 }
    }

    pub fn save(&mut self, filename: &str) {
        self.write(ArrayBuilder::new().push("save").push(filename).unwrap());
    }

    pub fn open(&mut self, filename: &str) {
        self.write(ArrayBuilder::new().push("open").push(filename).unwrap());
    }

    fn send_char(&mut self, c: char) {
        self.write(ArrayBuilder::new().push("key").push_object(|builder| builder.insert("chars", c).insert("flags", 0)).unwrap());
    }

    pub fn left(&mut self) { self.send_char('\u{F702}'); }

    pub fn right(&mut self) { self.send_char('\u{F703}'); }

    pub fn up(&mut self) { self.send_char('\u{F700}'); }

    pub fn down(&mut self) { self.send_char('\u{F701}'); }

    pub fn del(&mut self) { self.send_char('\x7f'); }

    pub fn page_up(&mut self) { self.send_char('\u{F72C}'); }

    pub fn page_down(&mut self) { self.send_char('\u{F72D}'); }

    pub fn f1(&mut self) { self.send_char('\u{F704}'); }

    pub fn f2(&mut self) { self.send_char('\u{F705}'); }

    pub fn char(&mut self, ch: char) { self.send_char(ch); }

    pub fn scroll(&mut self, start: u64, end: u64) {
        self.write(ArrayBuilder::new().push("scroll").push_array(|builder| builder.push(start).push(end)).unwrap());
    }

    pub fn test(&mut self) {
        self.render_lines(0, 10);
        // println!("test");
        // self.send_char('\u{F703}\", \"flags\": 0}]".as_bytes());
        // self.write(ArrayBuilder::new().push("scroll").push(filename).unwrap());
        // self.write(r#"["scroll", [5, 20]]"#.as_bytes()).unwrap();
    }

    pub fn render_lines(&mut self, start: u64, end: u64) {
        self.rpc_index += 1;
        println!("render_lines");
        let value = ArrayBuilder::new()
            .push("rpc")
            .push_object(|builder| builder
                .insert("index", self.rpc_index)
                .insert_array("request", |builder| builder
                    .push("render_lines")
                    .push_object(|builder| builder
                        .insert("first_line", start)
                        .insert("last_line", end)
                    )
                )
            ).unwrap();
        self.write(value);
    }

    fn write(&mut self, message: Value) {
        let str_msg = serde_json::ser::to_string(&message).unwrap();
        self.stdin.write(&encode_u64(str_msg.len() as u64)).unwrap();
        self.stdin.write(&str_msg.as_bytes()).unwrap();
    }
}

fn encode_u64(n: u64) -> [u8; 8] {
    let mut sizebuf = [0; 8];
    for i in 0..8 {
        sizebuf[i] = (((n as u64) >> (i * 8)) & 0xff) as u8;
    }
    sizebuf
}

fn decode_u64(array: &[u8]) -> u64 {
    array.iter().enumerate().fold(0, |s, (i, &b)| s + ((b as u64) << (i * 8)))
}
<|endoftext|>


<commit_before>use nom::{digit, hex_digit, oct_digit};
use std::{str, i32};
use ast::Expression;

// Temporarly use a f64 to represent JS numbers
type JSNumber = f64;

// TODO: Implement proper parsing (and saving) of the number literal.

fn bytes_to_exponent(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    // Rust does not support e or E in exponents, so just skip it
    f64::from(i32::from_str_radix(&string[1..], 10).unwrap())
}

fn bytes_to_digit(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    //i32::from_str_radix(&string, 10).unwrap() as JSNumber
    string.parse::<JSNumber>().unwrap()
}

fn bytes_to_binary(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    // Rust does not support 0b in binary, so just skip it
    f64::from(i32::from_str_radix(&string[2..], 2).unwrap())
}

fn bytes_to_oct(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    // Rust does not support 0o in hexadecimal, so just skip it
    f64::from(i32::from_str_radix(&string[2..], 8).unwrap())
}

fn bytes_to_hex(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    // Rust does not support 0x in hexadecimal, so just skip it
    f64::from(i32::from_str_radix(&string[2..], 16).unwrap())
}

// Convert the main parser to the AST
named!(pub numeric_literal<Expression>,
    map!(
        alt!(hex_digits_literal
            | oct_digits_literal
            | binary_digits_literal
            | decimal_digits_literal
            | exponent_part_digits_literal),
        Expression::Number
    )
);

named!(pub exponent_part_digits_literal<JSNumber>,
    map!(
        recognize!(
            tuple!(
                alt!(tag!("e") | tag!("E")),
                decimal_digits_literal
            )
        ),
        bytes_to_exponent
    )
);

// Support for negating and un-negating numbers will be supplied
// by a function within the language, so we don't parse it
named!(pub decimal_digits_literal<JSNumber>,
    map!(
        digit,
        bytes_to_digit
    )
);

named!(pub binary_digits_literal<JSNumber>,
    map!(
        recognize!(
            tuple!(
                alt!(tag!("0b") | tag!("0B")),
                many1!(binary_digit)
            )
        ),
        bytes_to_binary
    )
);

named!(binary_digit, alt!(tag!("0") | tag!("1")));

named!(pub oct_digits_literal<JSNumber>,
    map!(
        recognize!(
            tuple!(
                alt!(tag!("0o") | tag!("0O")),
                oct_digit,
                opt!(complete!(oct_digit))
            )
        ),
        bytes_to_oct
    )
);

named!(pub hex_digits_literal<JSNumber>,
    map!(
        recognize!(
            tuple!(
                alt!(tag!("0x") | tag!("0X")),
                hex_digit,
                opt!(complete!(hex_digit))
            )
        ),
        bytes_to_hex
    )
);
<commit_msg>Remove old comment<commit_after>use nom::{digit, hex_digit, oct_digit};
use std::{str, i32};
use ast::Expression;

// Temporarly use a f64 to represent JS numbers
type JSNumber = f64;

// TODO: Implement proper parsing (and saving) of the number literal.

fn bytes_to_exponent(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    // Rust does not support e or E in exponents, so just skip it
    f64::from(i32::from_str_radix(&string[1..], 10).unwrap())
}

fn bytes_to_digit(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    string.parse::<JSNumber>().unwrap()
}

fn bytes_to_binary(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    // Rust does not support 0b in binary, so just skip it
    f64::from(i32::from_str_radix(&string[2..], 2).unwrap())
}

fn bytes_to_oct(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    // Rust does not support 0o in hexadecimal, so just skip it
    f64::from(i32::from_str_radix(&string[2..], 8).unwrap())
}

fn bytes_to_hex(bytes: &[u8]) -> JSNumber {
    // TODO: Fix this unwrap
    let string = str::from_utf8(bytes).unwrap();

    // TODO: Fix this unwrap
    // Rust does not support 0x in hexadecimal, so just skip it
    f64::from(i32::from_str_radix(&string[2..], 16).unwrap())
}

// Convert the main parser to the AST
named!(pub numeric_literal<Expression>,
    map!(
        alt!(hex_digits_literal
            | oct_digits_literal
            | binary_digits_literal
            | decimal_digits_literal
            | exponent_part_digits_literal),
        Expression::Number
    )
);

named!(pub exponent_part_digits_literal<JSNumber>,
    map!(
        recognize!(
            tuple!(
                alt!(tag!("e") | tag!("E")),
                decimal_digits_literal
            )
        ),
        bytes_to_exponent
    )
);

// Support for negating and un-negating numbers will be supplied
// by a function within the language, so we don't parse it
named!(pub decimal_digits_literal<JSNumber>,
    map!(
        digit,
        bytes_to_digit
    )
);

named!(pub binary_digits_literal<JSNumber>,
    map!(
        recognize!(
            tuple!(
                alt!(tag!("0b") | tag!("0B")),
                many1!(binary_digit)
            )
        ),
        bytes_to_binary
    )
);

named!(binary_digit, alt!(tag!("0") | tag!("1")));

named!(pub oct_digits_literal<JSNumber>,
    map!(
        recognize!(
            tuple!(
                alt!(tag!("0o") | tag!("0O")),
                oct_digit,
                opt!(complete!(oct_digit))
            )
        ),
        bytes_to_oct
    )
);

named!(pub hex_digits_literal<JSNumber>,
    map!(
        recognize!(
            tuple!(
                alt!(tag!("0x") | tag!("0X")),
                hex_digit,
                opt!(complete!(hex_digit))
            )
        ),
        bytes_to_hex
    )
);
<|endoftext|>


<commit_before>extern crate crypto;
use self::crypto::digest::Digest;
use self::crypto::md5::Md5;

pub fn main(input: &str) -> Vec<String> {
    let s1 = find_number(input, 5);
    let s2 = find_number(input, 6);
    vec![s1.to_string(), s2.to_string()]
}

fn find_number(key: &str, zeros: usize) -> u32 {
    let mut md5 = Md5::new();
    let prefix = format!("{:01$}", 0, zeros);

    (1..)
        .map(|n| {
            let input = format!("{}{:?}", key, n);
            md5.reset();
            md5.input_str(&input);
            let output = md5.result_str();
            (n, output)
        })
        .find(|&(_, ref output)| output.starts_with(&prefix))
        .unwrap()
        .0
}

#[test]
#[ignore]
fn test_find_number() {
    assert_eq!(find_number("abcdef", 5), 609043);
    assert_eq!(find_number("pqrstuv", 5), 1048970);
}
<commit_msg>don't need to format a new string with the key + counter<commit_after>extern crate crypto;
use self::crypto::digest::Digest;
use self::crypto::md5::Md5;

pub fn main(input: &str) -> Vec<String> {
    let s1 = find_number(input, 5);
    let s2 = find_number(input, 6);
    vec![s1.to_string(), s2.to_string()]
}

fn find_number(key: &str, zeros: usize) -> u32 {
    let mut md5 = Md5::new();
    let prefix = format!("{:01$}", 0, zeros);

    (1..)
        .map(|n| {
            md5.reset();
            md5.input_str(&key);
            md5.input_str(&n.to_string());
            (n, md5.result_str())
        })
        .find(|&(_, ref hash)| hash.starts_with(&prefix))
        .unwrap()
        .0
}

#[test]
#[ignore]
fn test_find_number() {
    assert_eq!(find_number("abcdef", 5), 609043);
    assert_eq!(find_number("pqrstuv", 5), 1048970);
}
<|endoftext|>