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

//! Generic hashing support.
//!
//! This module provides a generic way to compute the hash of a value. The
//! simplest way to make a type hashable is to use `#[derive(Hash)]`:
//!
//! # Examples
//!
//! ```rust
//! use std::hash::{Hash, SipHasher, Hasher};
//!
//! #[derive(Hash)]
//! struct Person {
//!     id: u32,
//!     name: String,
//!     phone: u64,
//! }
//!
//! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
//! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
//!
//! assert!(hash(&person1) != hash(&person2));
//!
//! fn hash<T: Hash>(t: &T) -> u64 {
//!     let mut s = SipHasher::new();
//!     t.hash(&mut s);
//!     s.finish()
//! }
//! ```
//!
//! If you need more control over how a value is hashed, you need to implement
//! the trait `Hash`:
//!
//! ```rust
//! use std::hash::{Hash, Hasher, SipHasher};
//!
//! struct Person {
//!     id: u32,
//! # #[allow(dead_code)]
//!     name: String,
//!     phone: u64,
//! }
//!
//! impl Hash for Person {
//!     fn hash<H: Hasher>(&self, state: &mut H) {
//!         self.id.hash(state);
//!         self.phone.hash(state);
//!     }
//! }
//!
//! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
//! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
//!
//! assert_eq!(hash(&person1), hash(&person2));
//!
//! fn hash<T: Hash>(t: &T) -> u64 {
//!     let mut s = SipHasher::new();
//!     t.hash(&mut s);
//!     s.finish()
//! }
//! ```

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

use prelude::v1::*;

use marker;
use mem;

#[stable(feature = "rust1", since = "1.0.0")]
pub use self::sip::SipHasher;

mod sip;

/// A hashable type.
///
/// The `H` type parameter is an abstract hash state that is used by the `Hash`
/// to compute the hash.
///
/// If you are also implementing `Eq`, there is an additional property that
/// is important:
///
/// ```text
/// k1 == k2 -> hash(k1) == hash(k2)
/// ```
///
/// In other words, if two keys are equal, their hashes should also be equal.
/// `HashMap` and `HashSet` both rely on this behavior.
///
/// This trait can be used with `#[derive]`.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Hash {
    /// Feeds this value into the state given, updating the hasher as necessary.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn hash<H: Hasher>(&self, state: &mut H);

    /// Feeds a slice of this type into the state provided.
    #[stable(feature = "hash_slice", since = "1.3.0")]
    fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
        where Self: Sized
    {
        for piece in data {
            piece.hash(state);
        }
    }
}

/// A trait which represents the ability to hash an arbitrary stream of bytes.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Hasher {
    /// Completes a round of hashing, producing the output hash generated.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn finish(&self) -> u64;

    /// Writes some data into this `Hasher`
    #[stable(feature = "rust1", since = "1.0.0")]
    fn write(&mut self, bytes: &[u8]);

    /// Write a single `u8` into this hasher
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_u8(&mut self, i: u8) {
        self.write(&[i])
    }
    /// Write a single `u16` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_u16(&mut self, i: u16) {
        self.write(&unsafe { mem::transmute::<_, [u8; 2]>(i) })
    }
    /// Write a single `u32` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_u32(&mut self, i: u32) {
        self.write(&unsafe { mem::transmute::<_, [u8; 4]>(i) })
    }
    /// Write a single `u64` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_u64(&mut self, i: u64) {
        self.write(&unsafe { mem::transmute::<_, [u8; 8]>(i) })
    }
    /// Write a single `usize` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_usize(&mut self, i: usize) {
        let bytes = unsafe {
            ::slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>())
        };
        self.write(bytes);
    }

    /// Write a single `i8` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_i8(&mut self, i: i8) {
        self.write_u8(i as u8)
    }
    /// Write a single `i16` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_i16(&mut self, i: i16) {
        self.write_u16(i as u16)
    }
    /// Write a single `i32` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_i32(&mut self, i: i32) {
        self.write_u32(i as u32)
    }
    /// Write a single `i64` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_i64(&mut self, i: i64) {
        self.write_u64(i as u64)
    }
    /// Write a single `isize` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_isize(&mut self, i: isize) {
        self.write_usize(i as usize)
    }
}

/// A `BuildHasher` is typically used as a factory for instances of `Hasher`
/// which a `HashMap` can then use to hash keys independently.
///
/// Note that for each instance of `BuildHasher` the create hashers should be
/// identical. That is if the same stream of bytes is fed into each hasher the
/// same output will also be generated.
#[stable(since = "1.7.0", feature = "build_hasher")]
pub trait BuildHasher {
    /// Type of the hasher that will be created.
    #[stable(since = "1.7.0", feature = "build_hasher")]
    type Hasher: Hasher;

    /// Creates a new hasher.
    #[stable(since = "1.7.0", feature = "build_hasher")]
    fn build_hasher(&self) -> Self::Hasher;
}

/// A structure which implements `BuildHasher` for all `Hasher` types which also
/// implement `Default`.
///
/// This struct is 0-sized and does not need construction.
#[stable(since = "1.7.0", feature = "build_hasher")]
pub struct BuildHasherDefault<H>(marker::PhantomData<H>);

#[stable(since = "1.7.0", feature = "build_hasher")]
impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
    type Hasher = H;

    fn build_hasher(&self) -> H {
        H::default()
    }
}

#[stable(since = "1.7.0", feature = "build_hasher")]
impl<H> Clone for BuildHasherDefault<H> {
    fn clone(&self) -> BuildHasherDefault<H> {
        BuildHasherDefault(marker::PhantomData)
    }
}

#[stable(since = "1.7.0", feature = "build_hasher")]
impl<H> Default for BuildHasherDefault<H> {
    fn default() -> BuildHasherDefault<H> {
        BuildHasherDefault(marker::PhantomData)
    }
}

// The HashState trait is super deprecated, but it's here to have the blanket
// impl that goes from HashState -> BuildHasher

/// Deprecated, renamed to `BuildHasher`
#[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear",
           issue = "27713")]
#[rustc_deprecated(since = "1.7.0", reason = "support moved to std::hash and \
                                              renamed to BuildHasher")]
pub trait HashState {
    /// Type of the hasher that will be created.
    type Hasher: Hasher;

    /// Creates a new hasher based on the given state of this object.
    fn hasher(&self) -> Self::Hasher;
}

#[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear",
           issue = "27713")]
#[allow(deprecated)]
impl<T: HashState> BuildHasher for T {
    type Hasher = T::Hasher;
    fn build_hasher(&self) -> T::Hasher { self.hasher() }
}

//////////////////////////////////////////////////////////////////////////////

mod impls {
    use prelude::v1::*;

    use mem;
    use slice;
    use super::*;

    macro_rules! impl_write {
        ($(($ty:ident, $meth:ident),)*) => {$(
            #[stable(feature = "rust1", since = "1.0.0")]
            impl Hash for $ty {
                fn hash<H: Hasher>(&self, state: &mut H) {
                    state.$meth(*self)
                }

                fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
                    let newlen = data.len() * mem::size_of::<$ty>();
                    let ptr = data.as_ptr() as *const u8;
                    state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
                }
            }
        )*}
    }

    impl_write! {
        (u8, write_u8),
        (u16, write_u16),
        (u32, write_u32),
        (u64, write_u64),
        (usize, write_usize),
        (i8, write_i8),
        (i16, write_i16),
        (i32, write_i32),
        (i64, write_i64),
        (isize, write_isize),
    }

    #[stable(feature = "rust1", since = "1.0.0")]
    impl Hash for bool {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write_u8(*self as u8)
        }
    }

    #[stable(feature = "rust1", since = "1.0.0")]
    impl Hash for char {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write_u32(*self as u32)
        }
    }

    #[stable(feature = "rust1", since = "1.0.0")]
    impl Hash for str {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write(self.as_bytes());
            state.write_u8(0xff)
        }
    }

    macro_rules! impl_hash_tuple {
        () => (
            #[stable(feature = "rust1", since = "1.0.0")]
            impl Hash for () {
                fn hash<H: Hasher>(&self, _state: &mut H) {}
            }
        );

        ( $($name:ident)+) => (
            #[stable(feature = "rust1", since = "1.0.0")]
            impl<$($name: Hash),*> Hash for ($($name,)*) {
                #[allow(non_snake_case)]
                fn hash<S: Hasher>(&self, state: &mut S) {
                    let ($(ref $name,)*) = *self;
                    $($name.hash(state);)*
                }
            }
        );
    }

    impl_hash_tuple! {}
    impl_hash_tuple! { A }
    impl_hash_tuple! { A B }
    impl_hash_tuple! { A B C }
    impl_hash_tuple! { A B C D }
    impl_hash_tuple! { A B C D E }
    impl_hash_tuple! { A B C D E F }
    impl_hash_tuple! { A B C D E F G }
    impl_hash_tuple! { A B C D E F G H }
    impl_hash_tuple! { A B C D E F G H I }
    impl_hash_tuple! { A B C D E F G H I J }
    impl_hash_tuple! { A B C D E F G H I J K }
    impl_hash_tuple! { A B C D E F G H I J K L }

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

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

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

    #[stable(feature = "rust1", since = "1.0.0")]
    impl<T> Hash for *const T {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write_usize(*self as usize)
        }
    }

    #[stable(feature = "rust1", since = "1.0.0")]
    impl<T> Hash for *mut T {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write_usize(*self as usize)
        }
    }
}
<commit_msg>doc: insert missing chars<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Generic hashing support.
//!
//! This module provides a generic way to compute the hash of a value. The
//! simplest way to make a type hashable is to use `#[derive(Hash)]`:
//!
//! # Examples
//!
//! ```rust
//! use std::hash::{Hash, SipHasher, Hasher};
//!
//! #[derive(Hash)]
//! struct Person {
//!     id: u32,
//!     name: String,
//!     phone: u64,
//! }
//!
//! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
//! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
//!
//! assert!(hash(&person1) != hash(&person2));
//!
//! fn hash<T: Hash>(t: &T) -> u64 {
//!     let mut s = SipHasher::new();
//!     t.hash(&mut s);
//!     s.finish()
//! }
//! ```
//!
//! If you need more control over how a value is hashed, you need to implement
//! the trait `Hash`:
//!
//! ```rust
//! use std::hash::{Hash, Hasher, SipHasher};
//!
//! struct Person {
//!     id: u32,
//! # #[allow(dead_code)]
//!     name: String,
//!     phone: u64,
//! }
//!
//! impl Hash for Person {
//!     fn hash<H: Hasher>(&self, state: &mut H) {
//!         self.id.hash(state);
//!         self.phone.hash(state);
//!     }
//! }
//!
//! let person1 = Person { id: 5, name: "Janet".to_string(), phone: 555_666_7777 };
//! let person2 = Person { id: 5, name: "Bob".to_string(), phone: 555_666_7777 };
//!
//! assert_eq!(hash(&person1), hash(&person2));
//!
//! fn hash<T: Hash>(t: &T) -> u64 {
//!     let mut s = SipHasher::new();
//!     t.hash(&mut s);
//!     s.finish()
//! }
//! ```

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

use prelude::v1::*;

use marker;
use mem;

#[stable(feature = "rust1", since = "1.0.0")]
pub use self::sip::SipHasher;

mod sip;

/// A hashable type.
///
/// The `H` type parameter is an abstract hash state that is used by the `Hash`
/// to compute the hash.
///
/// If you are also implementing `Eq`, there is an additional property that
/// is important:
///
/// ```text
/// k1 == k2 -> hash(k1) == hash(k2)
/// ```
///
/// In other words, if two keys are equal, their hashes should also be equal.
/// `HashMap` and `HashSet` both rely on this behavior.
///
/// This trait can be used with `#[derive]`.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Hash {
    /// Feeds this value into the state given, updating the hasher as necessary.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn hash<H: Hasher>(&self, state: &mut H);

    /// Feeds a slice of this type into the state provided.
    #[stable(feature = "hash_slice", since = "1.3.0")]
    fn hash_slice<H: Hasher>(data: &[Self], state: &mut H)
        where Self: Sized
    {
        for piece in data {
            piece.hash(state);
        }
    }
}

/// A trait which represents the ability to hash an arbitrary stream of bytes.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Hasher {
    /// Completes a round of hashing, producing the output hash generated.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn finish(&self) -> u64;

    /// Writes some data into this `Hasher`
    #[stable(feature = "rust1", since = "1.0.0")]
    fn write(&mut self, bytes: &[u8]);

    /// Write a single `u8` into this hasher
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_u8(&mut self, i: u8) {
        self.write(&[i])
    }
    /// Write a single `u16` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_u16(&mut self, i: u16) {
        self.write(&unsafe { mem::transmute::<_, [u8; 2]>(i) })
    }
    /// Write a single `u32` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_u32(&mut self, i: u32) {
        self.write(&unsafe { mem::transmute::<_, [u8; 4]>(i) })
    }
    /// Write a single `u64` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_u64(&mut self, i: u64) {
        self.write(&unsafe { mem::transmute::<_, [u8; 8]>(i) })
    }
    /// Write a single `usize` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_usize(&mut self, i: usize) {
        let bytes = unsafe {
            ::slice::from_raw_parts(&i as *const usize as *const u8, mem::size_of::<usize>())
        };
        self.write(bytes);
    }

    /// Write a single `i8` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_i8(&mut self, i: i8) {
        self.write_u8(i as u8)
    }
    /// Write a single `i16` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_i16(&mut self, i: i16) {
        self.write_u16(i as u16)
    }
    /// Write a single `i32` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_i32(&mut self, i: i32) {
        self.write_u32(i as u32)
    }
    /// Write a single `i64` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_i64(&mut self, i: i64) {
        self.write_u64(i as u64)
    }
    /// Write a single `isize` into this hasher.
    #[inline]
    #[stable(feature = "hasher_write", since = "1.3.0")]
    fn write_isize(&mut self, i: isize) {
        self.write_usize(i as usize)
    }
}

/// A `BuildHasher` is typically used as a factory for instances of `Hasher`
/// which a `HashMap` can then use to hash keys independently.
///
/// Note that for each instance of `BuildHasher`, the created hashers should be
/// identical. That is, if the same stream of bytes is fed into each hasher, the
/// same output will also be generated.
#[stable(since = "1.7.0", feature = "build_hasher")]
pub trait BuildHasher {
    /// Type of the hasher that will be created.
    #[stable(since = "1.7.0", feature = "build_hasher")]
    type Hasher: Hasher;

    /// Creates a new hasher.
    #[stable(since = "1.7.0", feature = "build_hasher")]
    fn build_hasher(&self) -> Self::Hasher;
}

/// A structure which implements `BuildHasher` for all `Hasher` types which also
/// implement `Default`.
///
/// This struct is 0-sized and does not need construction.
#[stable(since = "1.7.0", feature = "build_hasher")]
pub struct BuildHasherDefault<H>(marker::PhantomData<H>);

#[stable(since = "1.7.0", feature = "build_hasher")]
impl<H: Default + Hasher> BuildHasher for BuildHasherDefault<H> {
    type Hasher = H;

    fn build_hasher(&self) -> H {
        H::default()
    }
}

#[stable(since = "1.7.0", feature = "build_hasher")]
impl<H> Clone for BuildHasherDefault<H> {
    fn clone(&self) -> BuildHasherDefault<H> {
        BuildHasherDefault(marker::PhantomData)
    }
}

#[stable(since = "1.7.0", feature = "build_hasher")]
impl<H> Default for BuildHasherDefault<H> {
    fn default() -> BuildHasherDefault<H> {
        BuildHasherDefault(marker::PhantomData)
    }
}

// The HashState trait is super deprecated, but it's here to have the blanket
// impl that goes from HashState -> BuildHasher

/// Deprecated, renamed to `BuildHasher`
#[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear",
           issue = "27713")]
#[rustc_deprecated(since = "1.7.0", reason = "support moved to std::hash and \
                                              renamed to BuildHasher")]
pub trait HashState {
    /// Type of the hasher that will be created.
    type Hasher: Hasher;

    /// Creates a new hasher based on the given state of this object.
    fn hasher(&self) -> Self::Hasher;
}

#[unstable(feature = "hashmap_hasher", reason = "hasher stuff is unclear",
           issue = "27713")]
#[allow(deprecated)]
impl<T: HashState> BuildHasher for T {
    type Hasher = T::Hasher;
    fn build_hasher(&self) -> T::Hasher { self.hasher() }
}

//////////////////////////////////////////////////////////////////////////////

mod impls {
    use prelude::v1::*;

    use mem;
    use slice;
    use super::*;

    macro_rules! impl_write {
        ($(($ty:ident, $meth:ident),)*) => {$(
            #[stable(feature = "rust1", since = "1.0.0")]
            impl Hash for $ty {
                fn hash<H: Hasher>(&self, state: &mut H) {
                    state.$meth(*self)
                }

                fn hash_slice<H: Hasher>(data: &[$ty], state: &mut H) {
                    let newlen = data.len() * mem::size_of::<$ty>();
                    let ptr = data.as_ptr() as *const u8;
                    state.write(unsafe { slice::from_raw_parts(ptr, newlen) })
                }
            }
        )*}
    }

    impl_write! {
        (u8, write_u8),
        (u16, write_u16),
        (u32, write_u32),
        (u64, write_u64),
        (usize, write_usize),
        (i8, write_i8),
        (i16, write_i16),
        (i32, write_i32),
        (i64, write_i64),
        (isize, write_isize),
    }

    #[stable(feature = "rust1", since = "1.0.0")]
    impl Hash for bool {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write_u8(*self as u8)
        }
    }

    #[stable(feature = "rust1", since = "1.0.0")]
    impl Hash for char {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write_u32(*self as u32)
        }
    }

    #[stable(feature = "rust1", since = "1.0.0")]
    impl Hash for str {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write(self.as_bytes());
            state.write_u8(0xff)
        }
    }

    macro_rules! impl_hash_tuple {
        () => (
            #[stable(feature = "rust1", since = "1.0.0")]
            impl Hash for () {
                fn hash<H: Hasher>(&self, _state: &mut H) {}
            }
        );

        ( $($name:ident)+) => (
            #[stable(feature = "rust1", since = "1.0.0")]
            impl<$($name: Hash),*> Hash for ($($name,)*) {
                #[allow(non_snake_case)]
                fn hash<S: Hasher>(&self, state: &mut S) {
                    let ($(ref $name,)*) = *self;
                    $($name.hash(state);)*
                }
            }
        );
    }

    impl_hash_tuple! {}
    impl_hash_tuple! { A }
    impl_hash_tuple! { A B }
    impl_hash_tuple! { A B C }
    impl_hash_tuple! { A B C D }
    impl_hash_tuple! { A B C D E }
    impl_hash_tuple! { A B C D E F }
    impl_hash_tuple! { A B C D E F G }
    impl_hash_tuple! { A B C D E F G H }
    impl_hash_tuple! { A B C D E F G H I }
    impl_hash_tuple! { A B C D E F G H I J }
    impl_hash_tuple! { A B C D E F G H I J K }
    impl_hash_tuple! { A B C D E F G H I J K L }

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

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

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

    #[stable(feature = "rust1", since = "1.0.0")]
    impl<T> Hash for *const T {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write_usize(*self as usize)
        }
    }

    #[stable(feature = "rust1", since = "1.0.0")]
    impl<T> Hash for *mut T {
        fn hash<H: Hasher>(&self, state: &mut H) {
            state.write_usize(*self as usize)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Finish implementing instructions.<commit_after><|endoftext|>


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

//! Implementations of things like `Eq` for fixed-length arrays
//! up to a certain length. Eventually we should able to generalize
//! to all lengths.
//!
//! *[See also the array primitive type](../../std/primitive.array.html).*

#![unstable(feature = "fixed_size_array",
            reason = "traits and impls are better expressed through generic \
                      integer constants",
            issue = "27778")]

use borrow::{Borrow, BorrowMut};
use cmp::Ordering;
use convert::TryFrom;
use fmt;
use hash::{Hash, self};
use marker::Unsize;
use slice::{Iter, IterMut};

/// Utility trait implemented only on arrays of fixed size
///
/// This trait can be used to implement other traits on fixed-size arrays
/// without causing much metadata bloat.
///
/// The trait is marked unsafe in order to restrict implementors to fixed-size
/// arrays. User of this trait can assume that implementors have the exact
/// layout in memory of a fixed size array (for example, for unsafe
/// initialization).
///
/// Note that the traits AsRef and AsMut provide similar methods for types that
/// may not be fixed-size arrays. Implementors should prefer those traits
/// instead.
pub unsafe trait FixedSizeArray<T> {
    /// Converts the array to immutable slice
    fn as_slice(&self) -> &[T];
    /// Converts the array to mutable slice
    fn as_mut_slice(&mut self) -> &mut [T];
}

unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
    #[inline]
    fn as_slice(&self) -> &[T] {
        self
    }
    #[inline]
    fn as_mut_slice(&mut self) -> &mut [T] {
        self
    }
}

/// The error type returned when a conversion from a slice to an array fails.
#[unstable(feature = "try_from", issue = "33417")]
#[derive(Debug, Copy, Clone)]
pub struct TryFromSliceError(());

impl fmt::Display for TryFromSliceError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self.__description())
    }
}

impl TryFromSliceError {
    #[unstable(feature = "array_error_internals",
           reason = "available through Error trait and this method should not \
                     be exposed publicly",
           issue = "0")]
    #[inline]
    #[doc(hidden)]
    pub fn __description(&self) -> &str {
        "could not convert slice to array"
    }
}

macro_rules! __impl_slice_eq1 {
    ($Lhs: ty, $Rhs: ty) => {
        __impl_slice_eq1! { $Lhs, $Rhs, Sized }
    };
    ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
        #[stable(feature = "rust1", since = "1.0.0")]
        impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
            #[inline]
            fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
            #[inline]
            fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
        }
    }
}

macro_rules! __impl_slice_eq2 {
    ($Lhs: ty, $Rhs: ty) => {
        __impl_slice_eq2! { $Lhs, $Rhs, Sized }
    };
    ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
        __impl_slice_eq1!($Lhs, $Rhs, $Bound);

        #[stable(feature = "rust1", since = "1.0.0")]
        impl<'a, 'b, A: $Bound, B> PartialEq<$Lhs> for $Rhs where B: PartialEq<A> {
            #[inline]
            fn eq(&self, other: &$Lhs) -> bool { self[..] == other[..] }
            #[inline]
            fn ne(&self, other: &$Lhs) -> bool { self[..] != other[..] }
        }
    }
}

// macro for implementing n-element array functions and operations
macro_rules! array_impls {
    ($($N:expr)+) => {
        $(
            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T> AsRef<[T]> for [T; $N] {
                #[inline]
                fn as_ref(&self) -> &[T] {
                    &self[..]
                }
            }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T> AsMut<[T]> for [T; $N] {
                #[inline]
                fn as_mut(&mut self) -> &mut [T] {
                    &mut self[..]
                }
            }

            #[stable(feature = "array_borrow", since = "1.4.0")]
            impl<T> Borrow<[T]> for [T; $N] {
                fn borrow(&self) -> &[T] {
                    self
                }
            }

            #[stable(feature = "array_borrow", since = "1.4.0")]
            impl<T> BorrowMut<[T]> for [T; $N] {
                fn borrow_mut(&mut self) -> &mut [T] {
                    self
                }
            }

            #[unstable(feature = "try_from", issue = "33417")]
            impl<'a, T> TryFrom<&'a [T]> for &'a [T; $N] {
                type Error = TryFromSliceError;

                fn try_from(slice: &[T]) -> Result<&[T; $N], TryFromSliceError> {
                    if slice.len() == $N {
                        let ptr = slice.as_ptr() as *const [T; $N];
                        unsafe { Ok(&*ptr) }
                    } else {
                        Err(TryFromSliceError(()))
                    }
                }
            }

            #[unstable(feature = "try_from", issue = "33417")]
            impl<'a, T> TryFrom<&'a mut [T]> for &'a mut [T; $N] {
                type Error = TryFromSliceError;

                fn try_from(slice: &mut [T]) -> Result<&mut [T; $N], TryFromSliceError> {
                    if slice.len() == $N {
                        let ptr = slice.as_mut_ptr() as *mut [T; $N];
                        unsafe { Ok(&mut *ptr) }
                    } else {
                        Err(TryFromSliceError(()))
                    }
                }
            }

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

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

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<'a, T> IntoIterator for &'a [T; $N] {
                type Item = &'a T;
                type IntoIter = Iter<'a, T>;

                fn into_iter(self) -> Iter<'a, T> {
                    self.iter()
                }
            }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<'a, T> IntoIterator for &'a mut [T; $N] {
                type Item = &'a mut T;
                type IntoIter = IterMut<'a, T>;

                fn into_iter(self) -> IterMut<'a, T> {
                    self.iter_mut()
                }
            }

            // NOTE: some less important impls are omitted to reduce code bloat
            __impl_slice_eq1! { [A; $N], [B; $N] }
            __impl_slice_eq2! { [A; $N], [B] }
            __impl_slice_eq2! { [A; $N], &'b [B] }
            __impl_slice_eq2! { [A; $N], &'b mut [B] }
            // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
            // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T:Eq> Eq for [T; $N] { }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T:PartialOrd> PartialOrd for [T; $N] {
                #[inline]
                fn partial_cmp(&self, other: &[T; $N]) -> Option<Ordering> {
                    PartialOrd::partial_cmp(&&self[..], &&other[..])
                }
                #[inline]
                fn lt(&self, other: &[T; $N]) -> bool {
                    PartialOrd::lt(&&self[..], &&other[..])
                }
                #[inline]
                fn le(&self, other: &[T; $N]) -> bool {
                    PartialOrd::le(&&self[..], &&other[..])
                }
                #[inline]
                fn ge(&self, other: &[T; $N]) -> bool {
                    PartialOrd::ge(&&self[..], &&other[..])
                }
                #[inline]
                fn gt(&self, other: &[T; $N]) -> bool {
                    PartialOrd::gt(&&self[..], &&other[..])
                }
            }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T:Ord> Ord for [T; $N] {
                #[inline]
                fn cmp(&self, other: &[T; $N]) -> Ordering {
                    Ord::cmp(&&self[..], &&other[..])
                }
            }
        )+
    }
}

array_impls! {
     0  1  2  3  4  5  6  7  8  9
    10 11 12 13 14 15 16 17 18 19
    20 21 22 23 24 25 26 27 28 29
    30 31 32
}

// The Default impls cannot be generated using the array_impls! macro because
// they require array literals.

macro_rules! array_impl_default {
    {$n:expr, $t:ident $($ts:ident)*} => {
        #[stable(since = "1.4.0", feature = "array_default")]
        impl<T> Default for [T; $n] where T: Default {
            fn default() -> [T; $n] {
                [$t::default(), $($ts::default()),*]
            }
        }
        array_impl_default!{($n - 1), $($ts)*}
    };
    {$n:expr,} => {
        #[stable(since = "1.4.0", feature = "array_default")]
        impl<T> Default for [T; $n] {
            fn default() -> [T; $n] { [] }
        }
    };
}

array_impl_default!{32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T}
<commit_msg>Pass formatter in TryFromSliceError Display impl<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Implementations of things like `Eq` for fixed-length arrays
//! up to a certain length. Eventually we should able to generalize
//! to all lengths.
//!
//! *[See also the array primitive type](../../std/primitive.array.html).*

#![unstable(feature = "fixed_size_array",
            reason = "traits and impls are better expressed through generic \
                      integer constants",
            issue = "27778")]

use borrow::{Borrow, BorrowMut};
use cmp::Ordering;
use convert::TryFrom;
use fmt;
use hash::{Hash, self};
use marker::Unsize;
use slice::{Iter, IterMut};

/// Utility trait implemented only on arrays of fixed size
///
/// This trait can be used to implement other traits on fixed-size arrays
/// without causing much metadata bloat.
///
/// The trait is marked unsafe in order to restrict implementors to fixed-size
/// arrays. User of this trait can assume that implementors have the exact
/// layout in memory of a fixed size array (for example, for unsafe
/// initialization).
///
/// Note that the traits AsRef and AsMut provide similar methods for types that
/// may not be fixed-size arrays. Implementors should prefer those traits
/// instead.
pub unsafe trait FixedSizeArray<T> {
    /// Converts the array to immutable slice
    fn as_slice(&self) -> &[T];
    /// Converts the array to mutable slice
    fn as_mut_slice(&mut self) -> &mut [T];
}

unsafe impl<T, A: Unsize<[T]>> FixedSizeArray<T> for A {
    #[inline]
    fn as_slice(&self) -> &[T] {
        self
    }
    #[inline]
    fn as_mut_slice(&mut self) -> &mut [T] {
        self
    }
}

/// The error type returned when a conversion from a slice to an array fails.
#[unstable(feature = "try_from", issue = "33417")]
#[derive(Debug, Copy, Clone)]
pub struct TryFromSliceError(());

impl fmt::Display for TryFromSliceError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self.__description(), f)
    }
}

impl TryFromSliceError {
    #[unstable(feature = "array_error_internals",
           reason = "available through Error trait and this method should not \
                     be exposed publicly",
           issue = "0")]
    #[inline]
    #[doc(hidden)]
    pub fn __description(&self) -> &str {
        "could not convert slice to array"
    }
}

macro_rules! __impl_slice_eq1 {
    ($Lhs: ty, $Rhs: ty) => {
        __impl_slice_eq1! { $Lhs, $Rhs, Sized }
    };
    ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
        #[stable(feature = "rust1", since = "1.0.0")]
        impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
            #[inline]
            fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
            #[inline]
            fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
        }
    }
}

macro_rules! __impl_slice_eq2 {
    ($Lhs: ty, $Rhs: ty) => {
        __impl_slice_eq2! { $Lhs, $Rhs, Sized }
    };
    ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
        __impl_slice_eq1!($Lhs, $Rhs, $Bound);

        #[stable(feature = "rust1", since = "1.0.0")]
        impl<'a, 'b, A: $Bound, B> PartialEq<$Lhs> for $Rhs where B: PartialEq<A> {
            #[inline]
            fn eq(&self, other: &$Lhs) -> bool { self[..] == other[..] }
            #[inline]
            fn ne(&self, other: &$Lhs) -> bool { self[..] != other[..] }
        }
    }
}

// macro for implementing n-element array functions and operations
macro_rules! array_impls {
    ($($N:expr)+) => {
        $(
            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T> AsRef<[T]> for [T; $N] {
                #[inline]
                fn as_ref(&self) -> &[T] {
                    &self[..]
                }
            }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T> AsMut<[T]> for [T; $N] {
                #[inline]
                fn as_mut(&mut self) -> &mut [T] {
                    &mut self[..]
                }
            }

            #[stable(feature = "array_borrow", since = "1.4.0")]
            impl<T> Borrow<[T]> for [T; $N] {
                fn borrow(&self) -> &[T] {
                    self
                }
            }

            #[stable(feature = "array_borrow", since = "1.4.0")]
            impl<T> BorrowMut<[T]> for [T; $N] {
                fn borrow_mut(&mut self) -> &mut [T] {
                    self
                }
            }

            #[unstable(feature = "try_from", issue = "33417")]
            impl<'a, T> TryFrom<&'a [T]> for &'a [T; $N] {
                type Error = TryFromSliceError;

                fn try_from(slice: &[T]) -> Result<&[T; $N], TryFromSliceError> {
                    if slice.len() == $N {
                        let ptr = slice.as_ptr() as *const [T; $N];
                        unsafe { Ok(&*ptr) }
                    } else {
                        Err(TryFromSliceError(()))
                    }
                }
            }

            #[unstable(feature = "try_from", issue = "33417")]
            impl<'a, T> TryFrom<&'a mut [T]> for &'a mut [T; $N] {
                type Error = TryFromSliceError;

                fn try_from(slice: &mut [T]) -> Result<&mut [T; $N], TryFromSliceError> {
                    if slice.len() == $N {
                        let ptr = slice.as_mut_ptr() as *mut [T; $N];
                        unsafe { Ok(&mut *ptr) }
                    } else {
                        Err(TryFromSliceError(()))
                    }
                }
            }

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

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

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<'a, T> IntoIterator for &'a [T; $N] {
                type Item = &'a T;
                type IntoIter = Iter<'a, T>;

                fn into_iter(self) -> Iter<'a, T> {
                    self.iter()
                }
            }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<'a, T> IntoIterator for &'a mut [T; $N] {
                type Item = &'a mut T;
                type IntoIter = IterMut<'a, T>;

                fn into_iter(self) -> IterMut<'a, T> {
                    self.iter_mut()
                }
            }

            // NOTE: some less important impls are omitted to reduce code bloat
            __impl_slice_eq1! { [A; $N], [B; $N] }
            __impl_slice_eq2! { [A; $N], [B] }
            __impl_slice_eq2! { [A; $N], &'b [B] }
            __impl_slice_eq2! { [A; $N], &'b mut [B] }
            // __impl_slice_eq2! { [A; $N], &'b [B; $N] }
            // __impl_slice_eq2! { [A; $N], &'b mut [B; $N] }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T:Eq> Eq for [T; $N] { }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T:PartialOrd> PartialOrd for [T; $N] {
                #[inline]
                fn partial_cmp(&self, other: &[T; $N]) -> Option<Ordering> {
                    PartialOrd::partial_cmp(&&self[..], &&other[..])
                }
                #[inline]
                fn lt(&self, other: &[T; $N]) -> bool {
                    PartialOrd::lt(&&self[..], &&other[..])
                }
                #[inline]
                fn le(&self, other: &[T; $N]) -> bool {
                    PartialOrd::le(&&self[..], &&other[..])
                }
                #[inline]
                fn ge(&self, other: &[T; $N]) -> bool {
                    PartialOrd::ge(&&self[..], &&other[..])
                }
                #[inline]
                fn gt(&self, other: &[T; $N]) -> bool {
                    PartialOrd::gt(&&self[..], &&other[..])
                }
            }

            #[stable(feature = "rust1", since = "1.0.0")]
            impl<T:Ord> Ord for [T; $N] {
                #[inline]
                fn cmp(&self, other: &[T; $N]) -> Ordering {
                    Ord::cmp(&&self[..], &&other[..])
                }
            }
        )+
    }
}

array_impls! {
     0  1  2  3  4  5  6  7  8  9
    10 11 12 13 14 15 16 17 18 19
    20 21 22 23 24 25 26 27 28 29
    30 31 32
}

// The Default impls cannot be generated using the array_impls! macro because
// they require array literals.

macro_rules! array_impl_default {
    {$n:expr, $t:ident $($ts:ident)*} => {
        #[stable(since = "1.4.0", feature = "array_default")]
        impl<T> Default for [T; $n] where T: Default {
            fn default() -> [T; $n] {
                [$t::default(), $($ts::default()),*]
            }
        }
        array_impl_default!{($n - 1), $($ts)*}
    };
    {$n:expr,} => {
        #[stable(since = "1.4.0", feature = "array_default")]
        impl<T> Default for [T; $n] {
            fn default() -> [T; $n] { [] }
        }
    };
}

array_impl_default!{32, T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T T}
<|endoftext|>


<commit_before><commit_msg>languages/rust/rust-book/test.rs<commit_after><|endoftext|>


<commit_before><commit_msg>pattern/parse.rs: checking in before removal<commit_after>//! Parsing routines for patterns.

use std;
use std::fmt::Debug;
use std::hash::Hash;
use std::boxed::Box;
use std::cmp::{Eq,PartialEq};
use std::collections::HashSet;
use std::iter::{Peekable,FromIterator};

use super::*;
use util::hash::Hashable;

/// Parse interface for concrete pattern types.
///
/// Note that this is *not* object-safe!
trait Parse<T> {
    fn parse(input: &str) -> Self;
}

#[derive(Copy,Clone,Eq,PartialEq)]
#[repr(u8)]
enum PatternType {
    EMPTY,
    SEQUENCE,
    UNION
}

/// Precedence for patterns.  Higher values indicate a higher priority here.
const PATTERN_PRIORITY: [u8; 3]
    = [ 0xFF, 0xFE, 0xFD ];

/// Part of a pattern held in a Builder instance.
#[derive(Clone,Eq,PartialEq)]
enum Partial<T> where T: 'static + Copy + Debug + Hash + Eq + PartialEq<T>{
    Empty,
    Element(Element<T>),
    Builder(Builder<T>)
}

impl<T> Partial<T> where T: 'static + Copy + Debug + Eq + PartialEq + Hash + Hashable {
    pub fn finish(self) -> Element<T> {
        match self {
            Partial::Empty => Element::Empty,
            Partial::Element(elt) => elt,
            Partial::Builder(builder) => builder.finish()
        }
    }
}

/// Concrete syntax tree builder.
#[derive(Clone,Eq,PartialEq)]
struct Builder<T> where T: 'static + Copy + Debug + Hash + Eq + PartialEq<T> {
    pattern_type: PatternType,
    parts: Vec<Partial<T>>,
    push_index: Option<usize>
}

impl<T> Builder<T> where T: Copy + Debug + Hash + Eq + PartialEq<T> {
    pub fn new() -> Builder<T> {
        Builder{pattern_type: PatternType::EMPTY,
                parts: Vec::new(),
                push_index: None}
    }

    pub fn ensure_type(&self, ptype: PatternType) -> Self {
        if let Some(idx) = self.push_index {
            match self.parts[idx] {
                // Cannot set type of a completed pattern!  Clear the push
                // index and fall through.
                Partial::Element(_) => self.push_index = None,
                Partial::Builder(ref b) => { b.ensure_type(ptype);
                                             return *self; }
            }
        }

        if self.pattern_type == ptype {
            *self
        } else if self.pattern_type == PatternType::EMPTY {
            self.pattern_type = ptype;
            *self
        } else {
            // Create a new builder object.
            let mut o = Builder::new();
            o.pattern_type = ptype;

            if PATTERN_PRIORITY[ptype as usize] > PATTERN_PRIORITY[self.pattern_type as usize] {
                // Push the current builder in as a component of the new one.
                o.push(Partial::Builder(*self));
                o
            } else {
                // Append the new builder to the current one, and set the push index to the new index.
                self.push(Partial::Builder(o));
                self.push_index = Some(self.parts.len() - 1);
                *self
            }
        }
    }

    pub fn push(&self, part: Partial<T>) {
        // If we're adding an element to a non-empty builder marked as empty,
        // it's clearly *not* empty -- it's probably a sequence.
        if ! self.parts.is_empty() && self.pattern_type == PatternType::EMPTY {
            self.pattern_type = PatternType::SEQUENCE;
            self.push_index = None;
        }

        match self.push_index {
            Some(idx) =>
            { match self.parts[idx] {
                // Can't push to a completed element.
                Partial::Element(..)
                    => { self.push_index = None;
                         self.parts.push(part); },
                Partial::Builder(ref b)
                    => b.push(part) } },
            None => self.parts.push(part)
        }
    }

    /// Evaluate the builder's contents and produce a pattern.
    pub fn finish(self) -> Element<T> where T: 'static + Copy + Debug + Eq + PartialEq + Hash + Hashable {
        match self.pattern_type.clone() {
            PatternType::EMPTY => {

                match self.parts.len() {
                    0 => Element::Empty,
                    1 => self.parts[0].finish(),
                    _ => panic!("Pattern type MUST be set for non-unit-length Builder instance!")
                } },
            PatternType::SEQUENCE => {
                Element::Pattern(Box::new(Sequence::new(self.parts.map_in_place(move |p| p.finish())))) }
            PatternType::UNION =>
                // Let's figure out these other errors later.
                unimplemented!() // {
            //     let mut s = HashSet::<Element<T>>::new();
            //     for p in self.parts { s.insert(p.finish()) }
            //     Element::Pattern(Box::new(Union::new(s)))
            // }

        }
    }

}

pub struct Parser<'a> {
    input: &'a str,
    iter: Peekable<std::str::Chars<'a>>
}

impl<'a> Parser<'a> {
    pub fn parse(input: &'a str) -> Element<char> {
        Parser::new(input).run()
    }

    pub fn new(input: &'a str) -> Self {
        Parser{input: input, iter: input.chars().peekable()}
    }

    fn next_char(&self) -> char {
        if self.iter.is_empty() { panic!("`next_char()` called with empty buffer") }
        else { self.iter.next().unwrap() }
    }

    pub fn run(&self) -> Element<char> {
        let escaped = false;
        let mut b = Builder::<char>::new();
        let len = self.input.len();

        for c in self.input.chars() {
            if escaped { b.push(Partial::Element(Element::Atom(c))); }
            else {
                match c {
                    '\\' => escaped = true,
                    '|' => b = b.ensure_type(PatternType::UNION),
                    '(' => { let mut s = String::with_capacity(len);

                    },
                    _ => {b.push(Partial::Element(Element::Atom(c)));}
                }
            }
        }
        b.finish()
    }
}

/*impl<'a> Parse<&'a str> for Sequence<char> {
    fn parse(input: &str) -> Sequence<char> {
        Sequence::from_iter(input.chars())
    }
}*/
<|endoftext|>


<commit_before><commit_msg>Added tests for the `Equivalent` trait.<commit_after>use hashbrown::Equivalent;
use hashbrown::HashMap;

use std::hash::Hash;

#[derive(Debug, Hash)]
pub struct Pair<A, B>(pub A, pub B);

impl<A, B, C, D> PartialEq<(A, B)> for Pair<C, D>
where
    C: PartialEq<A>,
    D: PartialEq<B>,
{
    fn eq(&self, rhs: &(A, B)) -> bool {
        self.0 == rhs.0 && self.1 == rhs.1
    }
}

impl<A, B, X> Equivalent<X> for Pair<A, B>
where
    Pair<A, B>: PartialEq<X>,
    A: Hash + Eq,
    B: Hash + Eq,
{
    fn equivalent(&self, other: &X) -> bool {
        *self == *other
    }
}

#[test]
fn test_lookup() {
    let s = String::from;
    let mut map = HashMap::new();
    map.insert((s("a"), s("b")), 1);
    map.insert((s("a"), s("x")), 2);

    assert!(map.contains_key(&Pair("a", "b")));
    assert!(!map.contains_key(&Pair("b", "a")));
}

#[test]
fn test_string_str() {
    let s = String::from;
    let mut map = HashMap::new();
    map.insert(s("a"), 1);
    map.insert(s("b"), 2);
    map.insert(s("x"), 3);
    map.insert(s("y"), 4);

    assert!(map.contains_key("a"));
    assert!(!map.contains_key("z"));
    assert_eq!(map.remove("b"), Some(2));
}
<|endoftext|>


<commit_before><commit_msg>tests: FlagSubCommand<commit_after>use clap::{App, Arg, FlagSubCommand};

#[test]
fn flag_subcommand_normal() {
    let matches = App::new("test")
        .subcommand(
            FlagSubCommand::new('S', "some").arg(
                Arg::new("test")
                    .short('t')
                    .long("test")
                    .about("testing testing"),
            ),
        )
        .get_matches_from(vec!["myprog", "some", "--test"]);
    assert_eq!(matches.subcommand_name().unwrap(), "some");
    let sub_matches = matches.subcommand_matches("some").unwrap();
    assert!(sub_matches.is_present("test"));
}

#[test]
fn flag_subcommand_normal_with_alias() {
    let matches = App::new("test")
        .subcommand(
            FlagSubCommand::new('S', "some")
                .arg(
                    Arg::new("test")
                        .short('t')
                        .long("test")
                        .about("testing testing"),
                )
                .alias("result"),
        )
        .get_matches_from(vec!["myprog", "result", "--test"]);
    assert_eq!(matches.subcommand_name().unwrap(), "some");
    let sub_matches = matches.subcommand_matches("some").unwrap();
    assert!(sub_matches.is_present("test"));
}

#[test]
fn flag_subcommand_short() {
    let matches = App::new("test")
        .subcommand(
            FlagSubCommand::new_short("some", 'S').arg(
                Arg::new("test")
                    .short('t')
                    .long("test")
                    .about("testing testing"),
            ),
        )
        .get_matches_from(vec!["myprog", "-S", "--test"]);
    assert_eq!(matches.subcommand_name().unwrap(), "some");
    let sub_matches = matches.subcommand_matches("some").unwrap();
    assert!(sub_matches.is_present("test"));
}

#[test]
fn flag_subcommand_short_with_args() {
    let matches = App::new("test")
        .subcommand(
            FlagSubCommand::new_short("some", 'S').arg(
                Arg::new("test")
                    .short('t')
                    .long("test")
                    .about("testing testing"),
            ),
        )
        .get_matches_from(vec!["myprog", "-St"]);
    assert_eq!(matches.subcommand_name().unwrap(), "some");
    let sub_matches = matches.subcommand_matches("some").unwrap();
    assert!(sub_matches.is_present("test"));
}

#[test]
fn flag_subcommand_short_with_alias() {
    let matches = App::new("test")
        .subcommand(
            FlagSubCommand::new_short("some", 'S')
                .arg(
                    Arg::new("test")
                        .short('t')
                        .long("test")
                        .about("testing testing"),
                )
                .alias("M")
                .alias("B"),
        )
        .get_matches_from(vec!["myprog", "-Bt"]);
    assert_eq!(matches.subcommand_name().unwrap(), "some");
    let sub_matches = matches.subcommand_matches("some").unwrap();
    assert!(sub_matches.is_present("test"));
}

#[test]
fn flag_subcommand_long() {
    let matches = App::new("test")
        .subcommand(
            FlagSubCommand::new_long("some", "some").arg(
                Arg::new("test")
                    .short('t')
                    .long("test")
                    .about("testing testing"),
            ),
        )
        .get_matches_from(vec!["myprog", "--some", "--test"]);
    assert_eq!(matches.subcommand_name().unwrap(), "some");
    let sub_matches = matches.subcommand_matches("some").unwrap();
    assert!(sub_matches.is_present("test"));
}

#[test]
fn flag_subcommand_long_with_alias() {
    let matches = App::new("test")
        .subcommand(
            FlagSubCommand::new_long("some", "some")
                .arg(
                    Arg::new("test")
                        .short('t')
                        .long("test")
                        .about("testing testing"),
                )
                .alias("result"),
        )
        .get_matches_from(vec!["myprog", "--result", "--test"]);
    assert_eq!(matches.subcommand_name().unwrap(), "some");
    let sub_matches = matches.subcommand_matches("some").unwrap();
    assert!(sub_matches.is_present("test"));
}

#[test]
fn flag_subcommand_multiple() {
    let matches = App::new("test")
        .subcommand(
            FlagSubCommand::new('S', "some")
                .arg(Arg::from("-f, --flag 'some flag'"))
                .arg(Arg::from("-p, --print 'print something'"))
                .subcommand(
                    FlagSubCommand::new('R', "result")
                        .arg(Arg::from("-f, --flag 'some flag'"))
                        .arg(Arg::from("-p, --print 'print something'")),
                ),
        )
        .get_matches_from(vec!["myprog", "-SfpRfp"]);
    assert_eq!(matches.subcommand_name().unwrap(), "some");
    let sub_matches = matches.subcommand_matches("some").unwrap();
    assert!(sub_matches.is_present("flag"));
    assert!(sub_matches.is_present("print"));
    assert_eq!(sub_matches.subcommand_name().unwrap(), "result");
    let result_matches = sub_matches.subcommand_matches("result").unwrap();
    assert!(result_matches.is_present("flag"));
    assert!(result_matches.is_present("print"));
}
<|endoftext|>


<commit_before><commit_msg>Formatting<commit_after><|endoftext|>


<commit_before>// FIXME: With recursive object types, we could implement binary methods like
//        union, intersection, and difference. At that point, we could write
//        an optimizing version of this module that produces a different obj
//        for the case where nbits <= 32.

// FIXME: Almost all the functions in this module should be state fns, but the
//        effect system isn't currently working correctly.

state type t = rec(vec[mutable uint] storage, uint nbits);

// FIXME: this should be a constant once they work
fn uint_bits() -> uint {
    ret 32u + ((1u << 32u) >> 27u);
}

fn create(uint nbits, bool init) -> t {
    auto elt;
    if (init) {
        elt = ~0u;
    } else {
        elt = 0u;
    }

    auto storage = vec::init_elt_mut[uint](elt, nbits / uint_bits() + 1u);
    ret rec(storage = storage, nbits = nbits);
}

fn process(&fn(uint, uint) -> uint op, &t v0, &t v1) -> bool {
    auto len = vec::len(v1.storage);

    assert (vec::len(v0.storage) == len);
    assert (v0.nbits == v1.nbits);

    auto changed = false;

    for each (uint i in uint::range(0u, len)) {
        auto w0 = v0.storage.(i);
        auto w1 = v1.storage.(i);

        auto w = op(w0, w1);
        if (w0 != w) {
            changed = true;
            v0.storage.(i) = w;
        }
    }

    ret changed;
}

fn lor(uint w0, uint w1) -> uint {
    ret w0 | w1;
}

fn union(&t v0, &t v1) -> bool {
    auto sub = lor;
    ret process(sub, v0, v1);
}

fn land(uint w0, uint w1) -> uint {
    ret w0 & w1;
}

fn intersect(&t v0, &t v1) -> bool {
    auto sub = land;
    ret process(sub, v0, v1);
}

fn right(uint w0, uint w1) -> uint {
    ret w1;
}

fn copy(&t v0, t v1) -> bool {
    auto sub = right;
    ret process(sub, v0, v1);
}

fn clone(t v) -> t {
    auto storage = vec::init_elt_mut[uint](0u, v.nbits / uint_bits() + 1u);
    auto len = vec::len(v.storage);
    for each (uint i in uint::range(0u, len)) {
        storage.(i) = v.storage.(i);
    }
    ret rec(storage = storage, nbits = v.nbits);
}

fn get(&t v, uint i) -> bool {
    assert (i < v.nbits);

    auto bits = uint_bits();

    auto w = i / bits;
    auto b = i % bits;
    auto x = 1u & (v.storage.(w) >> b);
    ret x == 1u;
}

fn equal(&t v0, &t v1) -> bool {
    // FIXME: when we can break or return from inside an iterator loop,
    //        we can eliminate this painful while-loop
    auto len = vec::len(v1.storage);
    auto i = 0u;
    while (i < len) {
        if (v0.storage.(i) != v1.storage.(i)) {
            ret false;
        }
        i = i + 1u;
    }
    ret true;
}

fn clear(&t v) {
    for each (uint i in uint::range(0u, vec::len(v.storage))) {
        v.storage.(i) = 0u;
    }
}

fn invert(&t v) {
    for each (uint i in uint::range(0u, vec::len(v.storage))) {
        v.storage.(i) = ~v.storage.(i);
    }
}

/* v0 = v0 - v1 */
fn difference(&t v0, &t v1) -> bool {
    invert(v1);
    auto b = intersect(v0, v1);
    invert(v1);
    ret b;
}

fn set(&t v, uint i, bool x) {
    assert (i < v.nbits);

    auto bits = uint_bits();

    auto w = i / bits;
    auto b = i % bits;
    auto w0 = v.storage.(w);
    auto flag = 1u << b;
    if (x) {
        v.storage.(w) = v.storage.(w) | flag;
    } else {
        v.storage.(w) = v.storage.(w) & ~flag;
    }
}

/* true if all bits are 1 */
fn is_true(&t v) -> bool {
    for (uint i in to_vec(v)) {
        if (i != 1u) {
            ret false;
        }
    }

    ret true;
}

/* true if all bits are non-1 */
fn is_false(&t v) -> bool {
    for (uint i in to_vec(v)) {
        if (i == 1u) {
            ret false;
        }
    }

    ret true;
}

fn init_to_vec(t v, uint i) -> uint {
    if (get(v, i)) {
        ret 1u;
    } else {
        ret 0u;
    }
}

fn to_vec(&t v) -> vec[uint] {
    auto sub = bind init_to_vec(v, _);
    ret vec::init_fn[uint](sub, v.nbits);
}

fn to_str(&t v) -> str {
    auto res = "";

    for (uint i in bitv::to_vec(v)) {
        if (i == 1u) {
            res += "1";
        }
        else {
            res += "0";
        }
    }

    ret res;
}

// FIXME: can we just use structural equality on to_vec?
fn eq_vec(&t v0, &vec[uint] v1) -> bool {
    assert (v0.nbits == vec::len[uint](v1));
    auto len = v0.nbits;
    auto i = 0u;
    while (i < len) {
        auto w0 = get(v0, i);
        auto w1 = v1.(i);
        if ((!w0 && w1 != 0u) || (w0 && w1 == 0u)) {
            ret false;
        }
        i = i + 1u;
    }
    ret true;
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<commit_msg>Add a set_all function in bitv that's the inverse of clear<commit_after>// FIXME: With recursive object types, we could implement binary methods like
//        union, intersection, and difference. At that point, we could write
//        an optimizing version of this module that produces a different obj
//        for the case where nbits <= 32.

// FIXME: Almost all the functions in this module should be state fns, but the
//        effect system isn't currently working correctly.
state type t = rec(vec[mutable uint] storage, uint nbits);

// FIXME: this should be a constant once they work
fn uint_bits() -> uint {
    ret 32u + ((1u << 32u) >> 27u);
}

fn create(uint nbits, bool init) -> t {
    auto elt;
    if (init) {
        elt = ~0u;
    } else {
        elt = 0u;
    }

    auto storage = vec::init_elt_mut[uint](elt, nbits / uint_bits() + 1u);
    ret rec(storage = storage, nbits = nbits);
}

fn process(&fn(uint, uint) -> uint op, &t v0, &t v1) -> bool {
    auto len = vec::len(v1.storage);

    assert (vec::len(v0.storage) == len);
    assert (v0.nbits == v1.nbits);

    auto changed = false;

    for each (uint i in uint::range(0u, len)) {
        auto w0 = v0.storage.(i);
        auto w1 = v1.storage.(i);

        auto w = op(w0, w1);
        if (w0 != w) {
            changed = true;
            v0.storage.(i) = w;
        }
    }

    ret changed;
}

fn lor(uint w0, uint w1) -> uint {
    ret w0 | w1;
}

fn union(&t v0, &t v1) -> bool {
    auto sub = lor;
    ret process(sub, v0, v1);
}

fn land(uint w0, uint w1) -> uint {
    ret w0 & w1;
}

fn intersect(&t v0, &t v1) -> bool {
    auto sub = land;
    ret process(sub, v0, v1);
}

fn right(uint w0, uint w1) -> uint {
    ret w1;
}

fn copy(&t v0, t v1) -> bool {
    auto sub = right;
    ret process(sub, v0, v1);
}

fn clone(t v) -> t {
    auto storage = vec::init_elt_mut[uint](0u, v.nbits / uint_bits() + 1u);
    auto len = vec::len(v.storage);
    for each (uint i in uint::range(0u, len)) {
        storage.(i) = v.storage.(i);
    }
    ret rec(storage = storage, nbits = v.nbits);
}

fn get(&t v, uint i) -> bool {
    assert (i < v.nbits);

    auto bits = uint_bits();

    auto w = i / bits;
    auto b = i % bits;
    auto x = 1u & (v.storage.(w) >> b);
    ret x == 1u;
}

fn equal(&t v0, &t v1) -> bool {
    // FIXME: when we can break or return from inside an iterator loop,
    //        we can eliminate this painful while-loop
    auto len = vec::len(v1.storage);
    auto i = 0u;
    while (i < len) {
        if (v0.storage.(i) != v1.storage.(i)) {
            ret false;
        }
        i = i + 1u;
    }
    ret true;
}

fn clear(&t v) {
    for each (uint i in uint::range(0u, vec::len(v.storage))) {
        v.storage.(i) = 0u;
    }
}

fn set_all(&t v) {
    for each (uint i in _uint::range(0u, v.nbits)) {
        set(v, i, true);
    }
}

fn invert(&t v) {
    for each (uint i in uint::range(0u, vec::len(v.storage))) {
        v.storage.(i) = ~v.storage.(i);
    }
}

/* v0 = v0 - v1 */
fn difference(&t v0, &t v1) -> bool {
    invert(v1);
    auto b = intersect(v0, v1);
    invert(v1);
    ret b;
}

fn set(&t v, uint i, bool x) {
    assert (i < v.nbits);

    auto bits = uint_bits();

    auto w = i / bits;
    auto b = i % bits;
    auto w0 = v.storage.(w);
    auto flag = 1u << b;
    if (x) {
        v.storage.(w) = v.storage.(w) | flag;
    } else {
        v.storage.(w) = v.storage.(w) & ~flag;
    }
}

/* true if all bits are 1 */
fn is_true(&t v) -> bool {
    for (uint i in to_vec(v)) {
        if (i != 1u) {
            ret false;
        }
    }

    ret true;
}

/* true if all bits are non-1 */
fn is_false(&t v) -> bool {
    for (uint i in to_vec(v)) {
        if (i == 1u) {
            ret false;
        }
    }

    ret true;
}

fn init_to_vec(t v, uint i) -> uint {
    if (get(v, i)) {
        ret 1u;
    } else {
        ret 0u;
    }
}

fn to_vec(&t v) -> vec[uint] {
    auto sub = bind init_to_vec(v, _);
    ret vec::init_fn[uint](sub, v.nbits);
}

fn to_str(&t v) -> str {
    auto res = "";

    for (uint i in bitv::to_vec(v)) {
        if (i == 1u) {
            res += "1";
        }
        else {
            res += "0";
        }
    }

    ret res;
}

// FIXME: can we just use structural equality on to_vec?
fn eq_vec(&t v0, &vec[uint] v1) -> bool {
    assert (v0.nbits == vec::len[uint](v1));
    auto len = v0.nbits;
    auto i = 0u;
    while (i < len) {
        auto w0 = get(v0, i);
        auto w1 = v1.(i);
        if ((!w0 && w1 != 0u) || (w0 && w1 == 0u)) {
            ret false;
        }
        i = i + 1u;
    }
    ret true;
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<|endoftext|>


<commit_before><commit_msg>think building blocks, not algorithms<commit_after><|endoftext|>


<commit_before><commit_msg>first try for simple log in rust<commit_after>use std::fs::OpenOptions;
use std::io::prelude::*;
use std::time::SystemTime;

/**
 * mod loggy; // for the separate file
 * use loggy::loggy; // use loggy() in loggy.rs
 *
 * loggy(line!(), String::from("hi"));
 * loggy(line!(), format!("tuple{:?}", (3,4)));
 */
pub fn loggy(line :u32, msg :String) {
    // TODO move to diff dir, and diff module

    let mut file = OpenOptions::new()
        .write(true)
        .append(true)
        .create(true)
        .open("z.log")
        .unwrap();
    let unix_epoch :u64;
    match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
        Ok(n) => unix_epoch = n.as_secs(),
        Err(_) => panic!("SystemTime before UNIX EPOCH!"),
    }
    /*
    x /* nested comment */
    // always commented, can end multiline comment */
    if let Err(e) = writeln!(file, "{} {} {} {}",
            unix_epoch,
            std::process::id(),
            line,
            msg) {

        eprintln!("Couldn't write to file: {}", e);
    }
}
<|endoftext|>


<commit_before><commit_msg>test: Add a test for mods inside functions. Closes #493<commit_after>fn f() -> int {
    mod m {
        fn g() -> int { 720 }
    }

    m::g()
}

fn main() {
    assert f() == 720;
}<|endoftext|>


<commit_before><commit_msg>Add problem #123<commit_after>#[crate_type = "rlib"];

extern mod math;

use std::iter;
use math::arith;
use math::prime::Prime;

pub static EXPECTED_ANSWER: &'static str = "21035";

// from problem 120
// f(n) := (p[n]-1)^n + (p[n]+1)^n
//
// if n is even:
//   f(n) ≡ 1  f   mod p[n]^2
// if n is odd:
//   f(n) ≡ 2np[n] mod p[n]^2

fn get_mod(n: uint, pn: uint) -> uint {
    if n.is_even() {
        1
    } else {
        (2 * n * pn) % (pn * pn)
    }
}

pub fn solve() -> ~str {
    let limit = arith::pow(10, 10);

    let ps = Prime::new();
    iter::count(1, 1u)
        .zip(ps.iter())
        .find(|&(n, pn)| get_mod(n, pn) > limit)
        .unwrap()
        .n0()
        .to_str()
}
<|endoftext|>


<commit_before><commit_msg>feat(tests): Enable logging in the tests<commit_after><|endoftext|>


<commit_before><commit_msg>Wrote some tests<commit_after>extern crate difflib;

use difflib::sequencematcher::{SequenceMatcher, Match};

#[test]
fn test_longest_match()
{
	let matcher = SequenceMatcher::new(" abcd", "abcd abcd");
    let m =  matcher.find_longest_match(0, 5, 0, 9);
    assert_eq!(m.first_start, 0);
    assert_eq!(m.second_start, 4);
    assert_eq!(m.size, 5);
}

#[test]
fn test_all_matches()
{
	let mut matcher = SequenceMatcher::new("abxcd", "abcd");
	let result = matcher.get_matching_blocks();
    let mut expected_result = Vec::new();
    expected_result.push(Match{
    	first_start: 0,
    	second_start: 0,
    	size: 2
    });
    expected_result.push(Match{
    	first_start: 3,
    	second_start: 2,
    	size: 2
    });
    expected_result.push(Match{
    	first_start: 5,
    	second_start: 4,
    	size: 0
    });
    assert_eq!(result, expected_result);
}<|endoftext|>


<commit_before><commit_msg>initial commit of Array_concatenation solution<commit_after>// http://rosettacode.org/wiki/Array_concatenation

fn main() {
    let a_vec: Vec<i32> = vec![1, 2, 3, 4, 5];
    let b_vec: Vec<i32> = vec![6; 5];

    assert!(a_vec[0] == 1i32);
    assert!(b_vec[0] == 6i32);

    let c_vec = concatenate_arrays::<i32>(a_vec.as_slice(), b_vec.as_slice());

    println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec);
}

fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
    let mut concat: Vec<T> = vec![x[0].clone(); x.len()];

    concat.clone_from_slice(x);
    concat.extend_from_slice(y);

    concat
}

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

    #[derive(Clone, Debug, PartialEq)]
    struct Dummy {
        a: f64,
        b: &'static str,
    }

    #[test]
    fn test_concatenation_int() {
        let a_vec: Vec<u64> = vec![0, 1, 2, 3, 4];
        let b_vec: Vec<u64> = vec![5; 5];
        let c_vec = concatenate_arrays::<u64>(a_vec.as_slice(), b_vec.as_slice());

        assert_eq!(c_vec, [0, 1, 2, 3, 4, 5, 5, 5, 5, 5]);
    }

    #[test]
    fn test_concatenation_str() {
        let a_vec: Vec<&str> = vec!["hay", "ye", "eye", "owe", "you"];
        let b_vec: Vec<&str> = vec!["why"];
        let c_vec = concatenate_arrays::<&str>(a_vec.as_slice(), b_vec.as_slice());

        assert_eq!(c_vec, ["hay", "ye", "eye", "owe", "you", "why"]);
    }

    #[test]
    fn test_concatenation_tuple() {
        let a_vec: Vec<(i32, &str)> = vec![(0, "hay"), (1, "ye"), (2, "eye")];
        let b_vec: Vec<(i32, &str)> = vec![(3, "owe"), (4, "you")];
        let c_vec = concatenate_arrays::<(i32, &str)>(a_vec.as_slice(), b_vec.as_slice());

        assert_eq!(c_vec, [(0, "hay"), (1, "ye"), (2, "eye"), (3, "owe"), (4, "you")]);
    }

    #[test]
    fn test_concatenation_struct() {
        let a_vec: Vec<Dummy> = vec![
            Dummy { a: 0.0, b: "hay"},
            Dummy { a: 1.1, b: "ye"},
            Dummy { a: 2.2, b: "eye"}
        ];
        let b_vec: Vec<Dummy> = vec![
            Dummy { a: 3.3, b: "owe"},
            Dummy { a: 4.4, b: "you"},
        ];

        let c_vec = concatenate_arrays::<Dummy>(a_vec.as_slice(), b_vec.as_slice());

        assert_eq!(c_vec, [
            Dummy { a: 0.0, b: "hay"},
            Dummy { a: 1.1, b: "ye"},
            Dummy { a: 2.2, b: "eye"},
            Dummy { a: 3.3, b: "owe"},
            Dummy { a: 4.4, b: "you"},
        ]);
    }
}<|endoftext|>


<commit_before><commit_msg>Adding explanations and examples for the bounded type parameter.<commit_after><|endoftext|>


<commit_before><commit_msg>refactor(tmux): Make errors more readable<commit_after><|endoftext|>


<commit_before><commit_msg>Deprecate Garbage<commit_after><|endoftext|>


<commit_before>use libimagstore::storeid::StoreId;
use libimagstore::store::Entry;
use libimagstore::store::EntryHeader;
use libimagstore::store::Result as StoreResult;

use error::{LinkError, LinkErrorKind};
use result::Result;

use toml::Value;

pub type Link = String;

pub trait InternalLinker {

    /// Get the internal links from the implementor object
    fn get_internal_links(&self) -> Result<Vec<Link>>;

    /// Set the internal links for the implementor object
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>>;

    /// Add an internal link to the implementor object
    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()>;

    /// Remove an internal link from the implementor object
    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()>;

}

impl InternalLinker for Entry {

    fn get_internal_links(&self) -> Result<Vec<Link>> {
        process_rw_result(self.get_header().read("imag.links"))
    }

    /// Set the links in a header and return the old links, if any.
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>> {
        let self_location = self.get_location().clone();
        let mut new_links = vec![];

        for link in links {
            if let Err(e) = add_foreign_link(link, self_location.clone()) {
                return Err(e);
            }
            let link = link.get_location().clone();
            let link = link.to_str();
            if link.is_none() {
                return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
            }
            let link = link.unwrap();

            new_links.push(Value::String(String::from(link)));
        }

        process_rw_result(self.get_header_mut().set("imag.links", Value::Array(new_links)))
    }

    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let new_link = link.get_location().clone();
        let new_link = new_link.to_str();
        if new_link.is_none() {
            return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
        }
        let new_link = new_link.unwrap();

        add_foreign_link(link, self.get_location().clone())
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|mut links| {
                        links.push(String::from(new_link));
                        let links = links.into_iter().map(|s| Value::String(s)).collect();
                        let process = self.get_header_mut().set("imag.links", Value::Array(links));
                        process_rw_result(process)
                            .map(|_| ())
                    })
            })
    }

    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let own_loc = link.get_location().clone();
        let own_loc = own_loc.to_str();
        if own_loc.is_none() {
            return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
        }
        let own_loc = own_loc.unwrap();

        let other_loc = link.get_location().clone();
        let other_loc = other_loc.to_str();
        if other_loc.is_none() {
            return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
        }
        let other_loc = other_loc.unwrap();

        link.get_internal_links()
            .and_then(|mut links| {
                let links = links.into_iter()
                    .filter(|l| l.clone() != own_loc)
                    .map(|s| Value::String(s))
                    .collect();
                process_rw_result(link.get_header_mut().set("imag.links", Value::Array(links)))
                    .map(|_| ())
            })
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|mut links| {
                        let links = links
                            .into_iter()
                            .filter(|l| l.clone() != other_loc)
                            .map(|s| Value::String(s))
                            .collect();
                        process_rw_result(self.get_header_mut().set("imag.links", Value::Array(links)))
                            .map(|_| ())
                    })
            })
    }

}

/// When Linking A -> B, the specification wants us to link back B -> A.
/// This is a helper function which does this.
fn add_foreign_link(target: &mut Entry, from: StoreId) -> Result<()> {
    let from = from.to_str();
    if from.is_none() {
        debug!("Cannot convert pathbuf '{:?}' to String", from);
        return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
    }
    let from = from.unwrap();

    target.get_internal_links()
        .and_then(|mut links| {
            links.push(String::from(from));
            let links = links.into_iter().map(|s| Value::String(s)).collect();
            process_rw_result(target.get_header_mut().set("imag.links", Value::Array(links)))
                .map(|_| ())
        })
}

fn process_rw_result(links: StoreResult<Option<Value>>) -> Result<Vec<Link>> {
    if links.is_err() {
        let lerr  = LinkError::new(LinkErrorKind::EntryHeaderReadError,
                                   Some(Box::new(links.err().unwrap())));
        return Err(lerr);
    }
    let links = links.unwrap();

    if links.iter().any(|l| match l { &Value::String(_) => true, _ => false }) {
        return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
    }

    let links : Vec<Link> = links.into_iter()
        .map(|link| {
            match link {
                Value::String(s) => String::from(s),
                _ => unreachable!(),
            }
        })
        .collect();

    Ok(links)
}

<commit_msg>Rewrite internal linking to use StoreId instead of String as Link type<commit_after>use libimagstore::storeid::StoreId;
use libimagstore::store::Entry;
use libimagstore::store::Result as StoreResult;

use error::{LinkError, LinkErrorKind};
use result::Result;

use toml::Value;

pub type Link = StoreId;

pub trait InternalLinker {

    /// Get the internal links from the implementor object
    fn get_internal_links(&self) -> Result<Vec<Link>>;

    /// Set the internal links for the implementor object
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>>;

    /// Add an internal link to the implementor object
    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()>;

    /// Remove an internal link from the implementor object
    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()>;

}

impl InternalLinker for Entry {

    fn get_internal_links(&self) -> Result<Vec<Link>> {
        process_rw_result(self.get_header().read("imag.links"))
    }

    /// Set the links in a header and return the old links, if any.
    fn set_internal_links(&mut self, links: Vec<&mut Entry>) -> Result<Vec<Link>> {
        let self_location = self.get_location().clone();
        let mut new_links = vec![];

        for link in links {
            if let Err(e) = add_foreign_link(link, self_location.clone()) {
                return Err(e);
            }
            let link = link.get_location().clone();
            let link = link.to_str();
            if link.is_none() {
                return Err(LinkError::new(LinkErrorKind::InternalConversionError, None));
            }
            let link = link.unwrap();

            new_links.push(Value::String(String::from(link)));
        }

        process_rw_result(self.get_header_mut().set("imag.links", Value::Array(new_links)))
    }

    fn add_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let new_link = link.get_location().clone();

        add_foreign_link(link, self.get_location().clone())
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|mut links| {
                        links.push(new_link);

                        // try to convert them to str so we can put them back into the header
                        let links : Vec<Option<Value>> = links
                            .into_iter()
                            .map(|s| s.to_str().map(|s| Value::String(String::from(s))))
                            .collect();

                        if links.iter().any(|o| o.is_none()) {
                            // if any type convert failed we fail as well
                            Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
                        } else {
                            // I know it is ugly
                            let links = links.into_iter().map(|opt| opt.unwrap()).collect();
                            let process = self.get_header_mut().set("imag.links", Value::Array(links));
                            process_rw_result(process)
                                .map(|_| ())
                        }
                    })
            })
    }

    fn remove_internal_link(&mut self, link: &mut Entry) -> Result<()> {
        let own_loc   = link.get_location().clone();
        let other_loc = link.get_location().clone();

        link.get_internal_links()
            .and_then(|links| {
                let links : Vec<Option<Value>> = links.into_iter()
                    .filter(|l| l.clone() != own_loc)
                    .map(|s| {
                        match s.to_str() {
                            Some(s) => Some(Value::String(String::from(s))),
                            _ => None
                        }
                    })
                    .collect();

                if links.iter().any(|o| o.is_none()) {
                    Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
                } else {
                    let links = links.into_iter().map(|opt| opt.unwrap()).collect();
                    process_rw_result(self.get_header_mut().set("imag.links", Value::Array(links)))
                        .map(|_| ())
                }
            })
            .and_then(|_| {
                self.get_internal_links()
                    .and_then(|links| {
                        let links : Vec<Option<Value>> = links
                            .into_iter()
                            .filter(|l| l.clone() != other_loc)
                            .map(|s| {
                                match s.to_str() {
                                    Some(s) => Some(Value::String(String::from(s))),
                                    _ => None
                                }
                            })
                            .collect();
                        if links.iter().any(|o| o.is_none()) {
                            Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
                        } else {
                            let links = links.into_iter().map(|opt| opt.unwrap()).collect();
                            process_rw_result(link.get_header_mut().set("imag.links", Value::Array(links)))
                                .map(|_| ())
                        }
                    })
            })
    }

}

/// When Linking A -> B, the specification wants us to link back B -> A.
/// This is a helper function which does this.
fn add_foreign_link(target: &mut Entry, from: StoreId) -> Result<()> {
    target.get_internal_links()
        .and_then(|mut links| {
            links.push(from);
            let links : Vec<Option<Value>> = links
                .into_iter()
                .map(|s| {
                    match s.to_str() {
                        Some(s) => Some(Value::String(String::from(s))),
                        _ => None
                    }
                })
                .collect();
            if links.iter().any(|o| o.is_none()) {
                Err(LinkError::new(LinkErrorKind::InternalConversionError, None))
            } else {
                let links = links.into_iter().map(|opt| opt.unwrap()).collect();
                process_rw_result(target.get_header_mut().set("imag.links", Value::Array(links)))
                    .map(|_| ())
            }
        })
}

fn process_rw_result(links: StoreResult<Option<Value>>) -> Result<Vec<Link>> {
    if links.is_err() {
        let lerr  = LinkError::new(LinkErrorKind::EntryHeaderReadError,
                                   Some(Box::new(links.err().unwrap())));
        return Err(lerr);
    }
    let links = links.unwrap();

    if links.iter().any(|l| match l { &Value::String(_) => true, _ => false }) {
        return Err(LinkError::new(LinkErrorKind::ExistingLinkTypeWrong, None));
    }

    let links : Vec<Link> = links.into_iter()
        .map(|link| {
            match link {
                Value::String(s) => StoreId::from(s),
                _ => unreachable!(),
            }
        })
        .collect();

    Ok(links)
}

<|endoftext|>


<commit_before><commit_msg>Solved first problem for day 7<commit_after><|endoftext|>


<commit_before><commit_msg>handler numbers & ids<commit_after><|endoftext|>


<commit_before><commit_msg>task/simple_executor: init<commit_after>use super::Task;
use alloc::collections::VecDeque;

pub struct SimpleExecutor {
    task_queue: VecDeque<Task>,
}

impl SimpleExecutor {
    pub fn new() -> SimpleExecutor {
        SimpleExecutor {
            task_queue: VecDeque::new(),
        }
    }

    pub fn spawn(&mut self, task: Task) { self.task_queue.push_back(task) }
}
<|endoftext|>


<commit_before><commit_msg>Solve Difference in rust<commit_after>use std::io;

fn main() {
    let mut input_a = String::new();
    let mut input_b = String::new();
    let mut input_c = String::new();
    let mut input_d = String::new();

    if let Err(_e) = io::stdin().read_line(&mut input_a){}
    let a: i32 = input_a.trim().parse().unwrap();

    if let Err(_e) = io::stdin().read_line(&mut input_b){}
    let b: i32 = input_b.trim().parse().unwrap();

    if let Err(_e) = io::stdin().read_line(&mut input_c){}
    let c: i32 = input_c.trim().parse().unwrap();

    if let Err(_e) = io::stdin().read_line(&mut input_d){}
    let d: i32 = input_d.trim().parse().unwrap();

    println!("DIFERENCA = {}", a * b - c * d);
}
<|endoftext|>


<commit_before><commit_msg>sep. file for prefixes, suffixes<commit_after>use std;

// prefixes, smallest first
fn prefixes(ss: str) -> [str] unsafe {
   let vv = [];

   vec::push(vv, "");
   str::chars_iteri(ss) {|ii, _bb|
      vec::push(vv, str::slice(ss, 0u, ii+1u));
   }

   ret vv;
}

#[test]
fn test_prefs() {
   assert ["", "a", "ab", "abc", "abcd"] == prefixes("abcd");
   assert [""] == prefixes("");
}

// suffixes, largest first
fn suffixes(ss: str) -> [str] unsafe {
   let vv = [];
   let lim = str::len(ss);

   str::chars_iteri(ss) {|ii, _bb|
      vec::push(vv, str::slice(ss, ii, lim));
   }
   vec::push(vv, "");

   ret vv;
}

#[test]
fn test_sufs() {
   assert ["abcd", "bcd", "cd", "d", ""] == suffixes("abcd");
   assert [""] == suffixes("");
}

<|endoftext|>


<commit_before><commit_msg>laying down foundational stuff<commit_after>extern crate rand;
use std::hash::Hash;
use std::collections::HashMap;
use rand::distributions::{IndependentSample, Range};

#[derive(Debug)]
enum Occupation {
    Unemployed,
    Student,
    Programmer,
}

#[derive(Eq, PartialEq, Hash)]
enum Vars {
    Age,
    Income,
    Occupation,
}

struct Datum {
    age: u8,
    income: usize,
    occupation: Occupation,
}

struct Dataset<T: Eq + PartialEq + Hash> {
    // map var to col index
    cols: HashMap<T, usize>,
    rows: Vec<Vec<Var>>,
}

impl<T: Eq + PartialEq + Hash> Dataset<T> {
    pub fn new<F, D>(mut data: Vec<D>, to_row: F, mut cols: Vec<T>) -> Dataset<T>
        where F: Fn(D) -> Vec<Var>
    {
        let n_cols = cols.len();
        Dataset::<T> {
            cols: cols.drain(..).zip((0..n_cols)).collect(),
            rows: data.drain(..).map(to_row).collect(),
        }
    }

    // Group rows in the dataset by a column.
    // Pass in a binning function, which returns the group a given row belongs to.
    fn group_by<F>(&self, var: T, bins: F) -> HashMap<usize, Vec<Vec<Var>>>
        where F: Fn(&Var) -> usize
    {
        let mut groups = HashMap::<usize, Vec<Vec<Var>>>::new();
        let idx = *self.cols.get(&var).unwrap();
        self.rows.iter().map(|r| {
            let group = bins(&r[idx]);
            groups.entry(group).or_insert(vec![]).push(r.to_vec());
        });
        groups // TODO
    }
}

// random variable
// either categorical or continuous
// TODO extend this, a bit wasteful e.g. if you only need uints
#[derive(Clone)]
enum Var {
    Int(i64),
    Float(f64),
}

struct BNet<T: Eq + PartialEq + Hash> {
    graph: HashMap<T, T>,
}

impl<T: Eq + PartialEq + Hash> BNet<T> {
    pub fn new() -> BNet<T> {
        BNet { graph: HashMap::new() }
    }

    // Add an edge from one variable A to another B,
    // indicating that A influences B.
    pub fn add_edge(&mut self, from: T, to: T) {
        self.graph.insert(from, to);
    }
}

// need to:
// [X] specify graph
// [X] group/bin data by variable

fn main() {
    // a row of is a column_name->variable hashmap
    // let row = HashMap::<str, Var>::new();

    // generate a dataset
    let mut rng = rand::thread_rng();
    let ages = Range::new(1, 100);
    let low_income = Range::new(0, 20000);
    let mid_income = Range::new(10000, 30000);
    let hii_income = Range::new(60000, 100000);
    let pop: Vec<Datum> = (0..10000)
        .map(|_| {
            let age = ages.ind_sample(&mut rng);
            let occupation = if age <= 14 {
                Occupation::Unemployed
            } else if age <= 24 {
                let os = vec![Occupation::Student, Occupation::Programmer];
                rand::sample(&mut rng, os, 1).pop().unwrap()
            } else if age <= 60 {
                Occupation::Programmer
            } else {
                Occupation::Unemployed
            };
            let income = match occupation {
                Occupation::Unemployed => low_income.ind_sample(&mut rng),
                Occupation::Student => mid_income.ind_sample(&mut rng),
                Occupation::Programmer => hii_income.ind_sample(&mut rng),
            };
            // println!("{:?}", age);
            // println!("{:?}", occupation);
            // println!("{:?}", income);
            Datum {
                age: age,
                income: 0,
                occupation: Occupation::Unemployed,
            }
        })
        .collect();

    // need to convert the data into "rows"
    let dataset = Dataset::<Vars>::new(pop,
                                       |d| {
                                           vec![Var::Int(d.age as i64),
                                                Var::Int(d.income as i64),
                                                Var::Int(d.occupation as i64)]
                                       },
                                       vec![Vars::Age, Vars::Income, Vars::Occupation]);
    println!("{:?}", dataset.rows.len());

    let mut graph = BNet::new();
    graph.add_edge(Vars::Age, Vars::Occupation);
    graph.add_edge(Vars::Occupation, Vars::Income);
}
<|endoftext|>


<commit_before><commit_msg>Added an example. Is this the correct way?<commit_after>extern crate sdl2;
extern crate sdl2_sys;
extern crate libc;

mod start;
mod vid;

use vid::*;

fn main() {
    let mut rend_contx = start::bootstrap(1280, 720, "Hello world!");
    let (mut renderer, mut pump) = rend_contx;

    unsafe {sdl2_sys::mouse::SDL_SetRelativeMouseMode(1);}

    let screen_w = 1280/2;
    let screen_h = 720/2;

    let mut camera_x = 0.0;
    let mut camera_y = 0.0;
    let mut camera_z = 3.0;

    let mut camera_x_z = 0.0;
    let mut camera_y_z = 0.0;
    let mut camera_x_y = 0.0;

    let mut cubes = vec![Cube::gen_new(0.0, 0.0, 4.0, 0.5, 0.5, 0.5),
                         Cube::gen_new(0.0, 0.0, 1.0, 2.5, 0.5, 0.5),
                         Cube::gen_new(0.0, 0.0, 1.0, 0.5, 0.5, 0.5),
                         /*Cube::gen_new(1.0, 1.0, 1.0, 0.5, 0.5, 0.5),*/];

    'game_loop: loop {
        use sdl2::pixels::Color::RGB;

        std::thread::sleep(std::time::Duration::from_millis(33));

        for event in pump.poll_iter() {
            use sdl2::event::Event::*;
            use sdl2::keyboard::Keycode::*;

            match event {
                Quit {..} => {break 'game_loop;},
                KeyDown {keycode, ..} => {
                    match keycode {
                        Some(Up) => {
                            let z = camera_z;
                            camera_z = z - 0.05;
                        },
                        Some(Down) => {
                            let z = camera_z;
                            camera_z = z + 0.05;
                        },
                        Some(Left) => {
                            let x = camera_x;
                            camera_x = x + 0.05;
                        },
                        Some(Right) => {
                            let x = camera_x;
                            camera_x = x - 0.05;
                        },
                        Some(RCtrl) => {
                            let y = camera_y;
                            camera_y = y + 0.05;
                        },
                        Some(RShift) => {
                            let y = camera_y;
                            camera_y = y - 0.05;
                        },
                        Some(Q) => {
                            camera_x_y += 0.1;
                        },
                        Some(E) => {
                            camera_x_y -= 0.1;
                        },
                        Some(Escape) => {
                            break 'game_loop;
                        }
                        _ => {println!("{:?}", keycode);}
                    }
                },
                MouseMotion {xrel, yrel, ..} => {
                    camera_x_z = (xrel as f64)/30.0;
                    //camera_y_z = (yrel as f64)/30.0;
                }
                _ => {}
            }
        }

        renderer.set_draw_color(RGB(20, 40, 60));
        renderer.clear();
        renderer.set_draw_color(RGB(200, 200, 200));

        // KNOWN BUG: IF A POINT IS OFF SCREEN THEN THE WHOLE LINE ISNT DRAWN AND IT STARTS GOING TO WRONG POINT
        for cube in &mut cubes {
            use std::f64;

            cube.flat(screen_w, screen_h, &mut renderer,
                      camera_x, camera_y, camera_z,
                      camera_x_y, camera_x_z, camera_y_z);

        }

        // Reset relative mouse move back to 0 as everything was already moved
        camera_x_z = 0.0;
        camera_y_z = 0.0;
        camera_x_y = 0.0;

        renderer.present();
    }
}
<|endoftext|>