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

//! Operations on tuples

use kinds::Copy;
use vec;

pub use self::inner::*;

pub trait CopyableTuple<T, U> {
    fn first(&self) -> T;
    fn second(&self) -> U;
    fn swap(&self) -> (U, T);
}

impl<T:Copy,U:Copy> CopyableTuple<T, U> for (T, U) {

    /// Return the first element of self
    #[inline(always)]
    fn first(&self) -> T {
        let (t, _) = *self;
        return t;
    }

    /// Return the second element of self
    #[inline(always)]
    fn second(&self) -> U {
        let (_, u) = *self;
        return u;
    }

    /// Return the results of swapping the two elements of self
    #[inline(always)]
    fn swap(&self) -> (U, T) {
        let (t, u) = *self;
        return (u, t);
    }
}

pub trait ImmutableTuple<T, U> {
    fn first_ref<'a>(&'a self) -> &'a T;
    fn second_ref<'a>(&'a self) -> &'a U;
}

impl<T, U> ImmutableTuple<T, U> for (T, U) {
    #[inline(always)]
    fn first_ref<'a>(&'a self) -> &'a T {
        match *self {
            (ref t, _) => t,
        }
    }
    #[inline(always)]
    fn second_ref<'a>(&'a self) -> &'a U {
        match *self {
            (_, ref u) => u,
        }
    }
}

pub trait ExtendedTupleOps<A,B> {
    fn zip(&self) -> ~[(A, B)];
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C];
}

impl<'self,A:Copy,B:Copy> ExtendedTupleOps<A,B> for (&'self [A], &'self [B]) {
    #[inline(always)]
    fn zip(&self) -> ~[(A, B)] {
        match *self {
            (ref a, ref b) => {
                vec::zip_slice(*a, *b)
            }
        }
    }

    #[inline(always)]
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
        match *self {
            (ref a, ref b) => {
                vec::map_zip(*a, *b, f)
            }
        }
    }
}

impl<A:Copy,B:Copy> ExtendedTupleOps<A,B> for (~[A], ~[B]) {

    #[inline(always)]
    fn zip(&self) -> ~[(A, B)] {
        match *self {
            (ref a, ref b) => {
                vec::zip_slice(*a, *b)
            }
        }
    }

    #[inline(always)]
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
        match *self {
            (ref a, ref b) => {
                vec::map_zip(*a, *b, f)
            }
        }
    }
}

// macro for implementing n-ary tuple functions and operations

macro_rules! tuple_impls(
    ($(
        $name:ident {
            $(fn $get_fn:ident -> $T:ident { $get_pattern:pat => $ret:expr })+
        }
    )+) => (
        pub mod inner {
            use clone::Clone;
            #[cfg(not(test))] use cmp::{Eq, Ord};

            $(
                pub trait $name<$($T),+> {
                    $(fn $get_fn<'a>(&'a self) -> &'a $T;)+
                }

                impl<$($T),+> $name<$($T),+> for ($($T),+) {
                    $(
                        #[inline(always)]
                        fn $get_fn<'a>(&'a self) -> &'a $T {
                            match *self {
                                $get_pattern => $ret
                            }
                        }
                    )+
                }

                impl<$($T:Clone),+> Clone for ($($T),+) {
                    fn clone(&self) -> ($($T),+) {
                        ($(self.$get_fn().clone()),+)
                    }
                }

                #[cfg(not(test))]
                impl<$($T:Eq),+> Eq for ($($T),+) {
                    #[inline(always)]
                    fn eq(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() == *other.$get_fn())&&+
                    }

                    #[inline(always)]
                    fn ne(&self, other: &($($T),+)) -> bool {
                        !(*self == *other)
                    }
                }

                #[cfg(not(test))]
                impl<$($T:Ord),+> Ord for ($($T),+) {
                    #[inline(always)]
                    fn lt(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() < *other.$get_fn())&&+
                    }

                    #[inline(always)]
                    fn le(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() <= *other.$get_fn())&&+
                    }

                    #[inline(always)]
                    fn ge(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() >= *other.$get_fn())&&+
                    }

                    #[inline(always)]
                    fn gt(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() > *other.$get_fn())&&+
                    }
                }
            )+
        }
    )
)

tuple_impls!(
    Tuple2 {
        fn n0 -> A { (ref a,_) => a }
        fn n1 -> B { (_,ref b) => b }
    }

    Tuple3 {
        fn n0 -> A { (ref a,_,_) => a }
        fn n1 -> B { (_,ref b,_) => b }
        fn n2 -> C { (_,_,ref c) => c }
    }

    Tuple4 {
        fn n0 -> A { (ref a,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_) => b }
        fn n2 -> C { (_,_,ref c,_) => c }
        fn n3 -> D { (_,_,_,ref d) => d }
    }

    Tuple5 {
        fn n0 -> A { (ref a,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_) => d }
        fn n4 -> E { (_,_,_,_,ref e) => e }
    }

    Tuple6 {
        fn n0 -> A { (ref a,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f) => f }
    }

    Tuple7 {
        fn n0 -> A { (ref a,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g) => g }
    }

    Tuple8 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h) => h }
    }

    Tuple9 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h,_) => h }
        fn n8 -> I { (_,_,_,_,_,_,_,_,ref i) => i }
    }

    Tuple10 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_) => h }
        fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_) => i }
        fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j) => j }
    }

    Tuple11 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_,_) => h }
        fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_,_) => i }
        fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j,_) => j }
        fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,ref k) => k }
    }

    Tuple12 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_,_,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_,_,_) => h }
        fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_,_,_) => i }
        fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j,_,_) => j }
        fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,ref k,_) => k }
        fn n11 -> L { (_,_,_,_,_,_,_,_,_,_,_,ref l) => l }
    }
)

#[test]
fn test_tuple_ref() {
    let x = (~"foo", ~"bar");
    assert_eq!(x.first_ref(), &~"foo");
    assert_eq!(x.second_ref(), &~"bar");
}

#[test]
#[allow(non_implicitly_copyable_typarams)]
fn test_tuple() {
    assert_eq!((948, 4039.48).first(), 948);
    assert_eq!((34.5, ~"foo").second(), ~"foo");
    assert_eq!(('a', 2).swap(), (2, 'a'));
}

#[test]
fn test_clone() {
    let a = (1, ~"2");
    let b = a.clone();
    assert_eq!(a.first(), b.first());
    assert_eq!(a.second(), b.second());
}

#[test]
fn test_n_tuple() {
    let t = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64);
    assert_eq!(*t.n0(), 0u8);
    assert_eq!(*t.n1(), 1u16);
    assert_eq!(*t.n2(), 2u32);
    assert_eq!(*t.n3(), 3u64);
    assert_eq!(*t.n4(), 4u);
    assert_eq!(*t.n5(), 5i8);
    assert_eq!(*t.n6(), 6i16);
    assert_eq!(*t.n7(), 7i32);
    assert_eq!(*t.n8(), 8i64);
    assert_eq!(*t.n9(), 9i);
    assert_eq!(*t.n10(), 10f32);
    assert_eq!(*t.n11(), 11f64);
}
<commit_msg>Use match instead of intermediate variable<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Operations on tuples

use kinds::Copy;
use vec;

pub use self::inner::*;

pub trait CopyableTuple<T, U> {
    fn first(&self) -> T;
    fn second(&self) -> U;
    fn swap(&self) -> (U, T);
}

impl<T:Copy,U:Copy> CopyableTuple<T, U> for (T, U) {
    /// Return the first element of self
    #[inline(always)]
    fn first(&self) -> T {
        match *self {
            (t, _) => t,
        }
    }

    /// Return the second element of self
    #[inline(always)]
    fn second(&self) -> U {
        match *self {
            (_, u) => u,
        }
    }

    /// Return the results of swapping the two elements of self
    #[inline(always)]
    fn swap(&self) -> (U, T) {
        match *self {
            (t, u) => (u, t),
        }
    }
}

pub trait ImmutableTuple<T, U> {
    fn first_ref<'a>(&'a self) -> &'a T;
    fn second_ref<'a>(&'a self) -> &'a U;
}

impl<T, U> ImmutableTuple<T, U> for (T, U) {
    #[inline(always)]
    fn first_ref<'a>(&'a self) -> &'a T {
        match *self {
            (ref t, _) => t,
        }
    }
    #[inline(always)]
    fn second_ref<'a>(&'a self) -> &'a U {
        match *self {
            (_, ref u) => u,
        }
    }
}

pub trait ExtendedTupleOps<A,B> {
    fn zip(&self) -> ~[(A, B)];
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C];
}

impl<'self,A:Copy,B:Copy> ExtendedTupleOps<A,B> for (&'self [A], &'self [B]) {
    #[inline(always)]
    fn zip(&self) -> ~[(A, B)] {
        match *self {
            (ref a, ref b) => {
                vec::zip_slice(*a, *b)
            }
        }
    }

    #[inline(always)]
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
        match *self {
            (ref a, ref b) => {
                vec::map_zip(*a, *b, f)
            }
        }
    }
}

impl<A:Copy,B:Copy> ExtendedTupleOps<A,B> for (~[A], ~[B]) {

    #[inline(always)]
    fn zip(&self) -> ~[(A, B)] {
        match *self {
            (ref a, ref b) => {
                vec::zip_slice(*a, *b)
            }
        }
    }

    #[inline(always)]
    fn map<C>(&self, f: &fn(a: &A, b: &B) -> C) -> ~[C] {
        match *self {
            (ref a, ref b) => {
                vec::map_zip(*a, *b, f)
            }
        }
    }
}

// macro for implementing n-ary tuple functions and operations

macro_rules! tuple_impls(
    ($(
        $name:ident {
            $(fn $get_fn:ident -> $T:ident { $get_pattern:pat => $ret:expr })+
        }
    )+) => (
        pub mod inner {
            use clone::Clone;
            #[cfg(not(test))] use cmp::{Eq, Ord};

            $(
                pub trait $name<$($T),+> {
                    $(fn $get_fn<'a>(&'a self) -> &'a $T;)+
                }

                impl<$($T),+> $name<$($T),+> for ($($T),+) {
                    $(
                        #[inline(always)]
                        fn $get_fn<'a>(&'a self) -> &'a $T {
                            match *self {
                                $get_pattern => $ret
                            }
                        }
                    )+
                }

                impl<$($T:Clone),+> Clone for ($($T),+) {
                    fn clone(&self) -> ($($T),+) {
                        ($(self.$get_fn().clone()),+)
                    }
                }

                #[cfg(not(test))]
                impl<$($T:Eq),+> Eq for ($($T),+) {
                    #[inline(always)]
                    fn eq(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() == *other.$get_fn())&&+
                    }

                    #[inline(always)]
                    fn ne(&self, other: &($($T),+)) -> bool {
                        !(*self == *other)
                    }
                }

                #[cfg(not(test))]
                impl<$($T:Ord),+> Ord for ($($T),+) {
                    #[inline(always)]
                    fn lt(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() < *other.$get_fn())&&+
                    }

                    #[inline(always)]
                    fn le(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() <= *other.$get_fn())&&+
                    }

                    #[inline(always)]
                    fn ge(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() >= *other.$get_fn())&&+
                    }

                    #[inline(always)]
                    fn gt(&self, other: &($($T),+)) -> bool {
                        $(*self.$get_fn() > *other.$get_fn())&&+
                    }
                }
            )+
        }
    )
)

tuple_impls!(
    Tuple2 {
        fn n0 -> A { (ref a,_) => a }
        fn n1 -> B { (_,ref b) => b }
    }

    Tuple3 {
        fn n0 -> A { (ref a,_,_) => a }
        fn n1 -> B { (_,ref b,_) => b }
        fn n2 -> C { (_,_,ref c) => c }
    }

    Tuple4 {
        fn n0 -> A { (ref a,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_) => b }
        fn n2 -> C { (_,_,ref c,_) => c }
        fn n3 -> D { (_,_,_,ref d) => d }
    }

    Tuple5 {
        fn n0 -> A { (ref a,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_) => d }
        fn n4 -> E { (_,_,_,_,ref e) => e }
    }

    Tuple6 {
        fn n0 -> A { (ref a,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f) => f }
    }

    Tuple7 {
        fn n0 -> A { (ref a,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g) => g }
    }

    Tuple8 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h) => h }
    }

    Tuple9 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h,_) => h }
        fn n8 -> I { (_,_,_,_,_,_,_,_,ref i) => i }
    }

    Tuple10 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_) => h }
        fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_) => i }
        fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j) => j }
    }

    Tuple11 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_,_) => h }
        fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_,_) => i }
        fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j,_) => j }
        fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,ref k) => k }
    }

    Tuple12 {
        fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_,_,_) => a }
        fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_,_,_) => b }
        fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_,_,_) => c }
        fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_,_,_) => d }
        fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_,_,_) => e }
        fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_,_,_) => f }
        fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_,_,_) => g }
        fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_,_,_) => h }
        fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_,_,_) => i }
        fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j,_,_) => j }
        fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,ref k,_) => k }
        fn n11 -> L { (_,_,_,_,_,_,_,_,_,_,_,ref l) => l }
    }
)

#[test]
fn test_tuple_ref() {
    let x = (~"foo", ~"bar");
    assert_eq!(x.first_ref(), &~"foo");
    assert_eq!(x.second_ref(), &~"bar");
}

#[test]
#[allow(non_implicitly_copyable_typarams)]
fn test_tuple() {
    assert_eq!((948, 4039.48).first(), 948);
    assert_eq!((34.5, ~"foo").second(), ~"foo");
    assert_eq!(('a', 2).swap(), (2, 'a'));
}

#[test]
fn test_clone() {
    let a = (1, ~"2");
    let b = a.clone();
    assert_eq!(a.first(), b.first());
    assert_eq!(a.second(), b.second());
}

#[test]
fn test_n_tuple() {
    let t = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64);
    assert_eq!(*t.n0(), 0u8);
    assert_eq!(*t.n1(), 1u16);
    assert_eq!(*t.n2(), 2u32);
    assert_eq!(*t.n3(), 3u64);
    assert_eq!(*t.n4(), 4u);
    assert_eq!(*t.n5(), 5i8);
    assert_eq!(*t.n6(), 6i16);
    assert_eq!(*t.n7(), 7i32);
    assert_eq!(*t.n8(), 8i64);
    assert_eq!(*t.n9(), 9i);
    assert_eq!(*t.n10(), 10f32);
    assert_eq!(*t.n11(), 11f64);
}
<|endoftext|>


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

//! Base64 binary-to-text encoding

use core::iter;
use core::str;
use core::vec;

pub trait ToBase64 {
    fn to_base64(&self) -> ~str;
}

static CHARS: [char, ..64] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
];

impl<'self> ToBase64 for &'self [u8] {
    /**
     * Turn a vector of `u8` bytes into a base64 string.
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     *
     * fn main () {
     *   let str = [52,32].to_base64();
     *   println(fmt!("%s", str));
     * }
     * ~~~~
     */
    fn to_base64(&self) -> ~str {
        let mut s = ~"";
        unsafe {
            let len = self.len();
            str::reserve(&mut s, ((len + 3u) / 4u) * 3u);

            let mut i = 0u;

            while i < len - (len % 3u) {
                let n = (self[i] as uint) << 16u |
                        (self[i + 1u] as uint) << 8u |
                        (self[i + 2u] as uint);

                // This 24-bit number gets separated into four 6-bit numbers.
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 6u) & 63u]);
                str::push_char(&mut s, CHARS[n & 63u]);

                i += 3u;
            }

            // Heh, would be cool if we knew this was exhaustive
            // (the dream of bounded integer types)
            match len % 3 {
              0 => (),
              1 => {
                let n = (self[i] as uint) << 16u;
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, '=');
                str::push_char(&mut s, '=');
              }
              2 => {
                let n = (self[i] as uint) << 16u |
                    (self[i + 1u] as uint) << 8u;
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 6u) & 63u]);
                str::push_char(&mut s, '=');
              }
              _ => fail!(~"Algebra is broken, please alert the math police")
            }
        }
        s
    }
}

impl<'self> ToBase64 for &'self str {
    /**
     * Convert any string (literal, `@`, `&`, or `~`) to base64 encoding.
     *
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     *
     * fn main () {
     *   let str = "Hello, World".to_base64();
     *   println(fmt!("%s",str));
     * }
     * ~~~~
     *
     */
    fn to_base64(&self) -> ~str {
        str::to_bytes(*self).to_base64()
    }
}

pub trait FromBase64 {
    fn from_base64(&self) -> ~[u8];
}

impl FromBase64 for ~[u8] {
    /**
     * Convert base64 `u8` vector into u8 byte values.
     * Every 4 encoded characters is converted into 3 octets, modulo padding.
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     * use std::base64::FromBase64;
     *
     * fn main () {
     *   let str = [52,32].to_base64();
     *   println(fmt!("%s", str));
     *   let bytes = str.from_base64();
     *   println(fmt!("%?",bytes));
     * }
     * ~~~~
     */
    fn from_base64(&self) -> ~[u8] {
        if self.len() % 4u != 0u { fail!(~"invalid base64 length"); }

        let len = self.len();
        let mut padding = 0u;

        if len != 0u {
            if self[len - 1u] == '=' as u8 { padding += 1u; }
            if self[len - 2u] == '=' as u8 { padding += 1u; }
        }

        let mut r = vec::with_capacity((len / 4u) * 3u - padding);

        unsafe {
            let mut i = 0u;
            while i < len {
                let mut n = 0u;

                for iter::repeat(4u) {
                    let ch = self[i] as char;
                    n <<= 6u;

                    if ch >= 'A' && ch <= 'Z' {
                        n |= (ch as uint) - 0x41u;
                    } else if ch >= 'a' && ch <= 'z' {
                        n |= (ch as uint) - 0x47u;
                    } else if ch >= '0' && ch <= '9' {
                        n |= (ch as uint) + 0x04u;
                    } else if ch == '+' {
                        n |= 0x3Eu;
                    } else if ch == '/' {
                        n |= 0x3Fu;
                    } else if ch == '=' {
                        match len - i {
                          1u => {
                            r.push(((n >> 16u) & 0xFFu) as u8);
                            r.push(((n >> 8u ) & 0xFFu) as u8);
                            return copy r;
                          }
                          2u => {
                            r.push(((n >> 10u) & 0xFFu) as u8);
                            return copy r;
                          }
                          _ => fail!(~"invalid base64 padding")
                        }
                    } else {
                        fail!(~"invalid base64 character");
                    }

                    i += 1u;
                };

                r.push(((n >> 16u) & 0xFFu) as u8);
                r.push(((n >> 8u ) & 0xFFu) as u8);
                r.push(((n       ) & 0xFFu) as u8);
            }
        }
        r
    }
}

impl FromBase64 for ~str {
    /**
     * Convert any base64 encoded string (literal, `@`, `&`, or `~`)
     * to the byte values it encodes.
     *
     * You can use the `from_bytes` function in `core::str`
     * to turn a `[u8]` into a string with characters corresponding to those values.
     *
     * *Example*:
     *
     * This converts a string literal to base64 and back.
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     * use std::base64::FromBase64;
     * use core::str;
     *
     * fn main () {
     *   let hello_str = "Hello, World".to_base64();
     *   println(fmt!("%s",hello_str));
     *   let bytes = hello_str.from_base64();
     *   println(fmt!("%?",bytes));
     *   let result_str = str::from_bytes(bytes);
     *   println(fmt!("%s",result_str));
     * }
     * ~~~~
     */
    fn from_base64(&self) -> ~[u8] {
        str::to_bytes(*self).from_base64()
    }
}

#[cfg(test)]
mod tests {
    use core::str;

    #[test]
    pub fn test_to_base64() {
        assert!((~"").to_base64()       == ~"");
        assert!((~"f").to_base64()      == ~"Zg==");
        assert!((~"fo").to_base64()     == ~"Zm8=");
        assert!((~"foo").to_base64()    == ~"Zm9v");
        assert!((~"foob").to_base64()   == ~"Zm9vYg==");
        assert!((~"fooba").to_base64()  == ~"Zm9vYmE=");
        assert!((~"foobar").to_base64() == ~"Zm9vYmFy");
    }

    #[test]
    pub fn test_from_base64() {
        assert!((~"").from_base64() == str::to_bytes(~""));
        assert!((~"Zg==").from_base64() == str::to_bytes(~"f"));
        assert!((~"Zm8=").from_base64() == str::to_bytes(~"fo"));
        assert!((~"Zm9v").from_base64() == str::to_bytes(~"foo"));
        assert!((~"Zm9vYg==").from_base64() == str::to_bytes(~"foob"));
        assert!((~"Zm9vYmE=").from_base64() == str::to_bytes(~"fooba"));
        assert!((~"Zm9vYmFy").from_base64() == str::to_bytes(~"foobar"));
    }
}
<commit_msg>update copyright notice on base64.rs<commit_after>// Copyright 2012-2013 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.

//! Base64 binary-to-text encoding

use core::iter;
use core::str;
use core::vec;

pub trait ToBase64 {
    fn to_base64(&self) -> ~str;
}

static CHARS: [char, ..64] = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
];

impl<'self> ToBase64 for &'self [u8] {
    /**
     * Turn a vector of `u8` bytes into a base64 string.
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     *
     * fn main () {
     *   let str = [52,32].to_base64();
     *   println(fmt!("%s", str));
     * }
     * ~~~~
     */
    fn to_base64(&self) -> ~str {
        let mut s = ~"";
        unsafe {
            let len = self.len();
            str::reserve(&mut s, ((len + 3u) / 4u) * 3u);

            let mut i = 0u;

            while i < len - (len % 3u) {
                let n = (self[i] as uint) << 16u |
                        (self[i + 1u] as uint) << 8u |
                        (self[i + 2u] as uint);

                // This 24-bit number gets separated into four 6-bit numbers.
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 6u) & 63u]);
                str::push_char(&mut s, CHARS[n & 63u]);

                i += 3u;
            }

            // Heh, would be cool if we knew this was exhaustive
            // (the dream of bounded integer types)
            match len % 3 {
              0 => (),
              1 => {
                let n = (self[i] as uint) << 16u;
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, '=');
                str::push_char(&mut s, '=');
              }
              2 => {
                let n = (self[i] as uint) << 16u |
                    (self[i + 1u] as uint) << 8u;
                str::push_char(&mut s, CHARS[(n >> 18u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 12u) & 63u]);
                str::push_char(&mut s, CHARS[(n >> 6u) & 63u]);
                str::push_char(&mut s, '=');
              }
              _ => fail!(~"Algebra is broken, please alert the math police")
            }
        }
        s
    }
}

impl<'self> ToBase64 for &'self str {
    /**
     * Convert any string (literal, `@`, `&`, or `~`) to base64 encoding.
     *
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     *
     * fn main () {
     *   let str = "Hello, World".to_base64();
     *   println(fmt!("%s",str));
     * }
     * ~~~~
     *
     */
    fn to_base64(&self) -> ~str {
        str::to_bytes(*self).to_base64()
    }
}

pub trait FromBase64 {
    fn from_base64(&self) -> ~[u8];
}

impl FromBase64 for ~[u8] {
    /**
     * Convert base64 `u8` vector into u8 byte values.
     * Every 4 encoded characters is converted into 3 octets, modulo padding.
     *
     * *Example*:
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     * use std::base64::FromBase64;
     *
     * fn main () {
     *   let str = [52,32].to_base64();
     *   println(fmt!("%s", str));
     *   let bytes = str.from_base64();
     *   println(fmt!("%?",bytes));
     * }
     * ~~~~
     */
    fn from_base64(&self) -> ~[u8] {
        if self.len() % 4u != 0u { fail!(~"invalid base64 length"); }

        let len = self.len();
        let mut padding = 0u;

        if len != 0u {
            if self[len - 1u] == '=' as u8 { padding += 1u; }
            if self[len - 2u] == '=' as u8 { padding += 1u; }
        }

        let mut r = vec::with_capacity((len / 4u) * 3u - padding);

        unsafe {
            let mut i = 0u;
            while i < len {
                let mut n = 0u;

                for iter::repeat(4u) {
                    let ch = self[i] as char;
                    n <<= 6u;

                    if ch >= 'A' && ch <= 'Z' {
                        n |= (ch as uint) - 0x41u;
                    } else if ch >= 'a' && ch <= 'z' {
                        n |= (ch as uint) - 0x47u;
                    } else if ch >= '0' && ch <= '9' {
                        n |= (ch as uint) + 0x04u;
                    } else if ch == '+' {
                        n |= 0x3Eu;
                    } else if ch == '/' {
                        n |= 0x3Fu;
                    } else if ch == '=' {
                        match len - i {
                          1u => {
                            r.push(((n >> 16u) & 0xFFu) as u8);
                            r.push(((n >> 8u ) & 0xFFu) as u8);
                            return copy r;
                          }
                          2u => {
                            r.push(((n >> 10u) & 0xFFu) as u8);
                            return copy r;
                          }
                          _ => fail!(~"invalid base64 padding")
                        }
                    } else {
                        fail!(~"invalid base64 character");
                    }

                    i += 1u;
                };

                r.push(((n >> 16u) & 0xFFu) as u8);
                r.push(((n >> 8u ) & 0xFFu) as u8);
                r.push(((n       ) & 0xFFu) as u8);
            }
        }
        r
    }
}

impl FromBase64 for ~str {
    /**
     * Convert any base64 encoded string (literal, `@`, `&`, or `~`)
     * to the byte values it encodes.
     *
     * You can use the `from_bytes` function in `core::str`
     * to turn a `[u8]` into a string with characters corresponding to those values.
     *
     * *Example*:
     *
     * This converts a string literal to base64 and back.
     *
     * ~~~~
     * extern mod std;
     * use std::base64::ToBase64;
     * use std::base64::FromBase64;
     * use core::str;
     *
     * fn main () {
     *   let hello_str = "Hello, World".to_base64();
     *   println(fmt!("%s",hello_str));
     *   let bytes = hello_str.from_base64();
     *   println(fmt!("%?",bytes));
     *   let result_str = str::from_bytes(bytes);
     *   println(fmt!("%s",result_str));
     * }
     * ~~~~
     */
    fn from_base64(&self) -> ~[u8] {
        str::to_bytes(*self).from_base64()
    }
}

#[cfg(test)]
mod tests {
    use core::str;

    #[test]
    pub fn test_to_base64() {
        assert!((~"").to_base64()       == ~"");
        assert!((~"f").to_base64()      == ~"Zg==");
        assert!((~"fo").to_base64()     == ~"Zm8=");
        assert!((~"foo").to_base64()    == ~"Zm9v");
        assert!((~"foob").to_base64()   == ~"Zm9vYg==");
        assert!((~"fooba").to_base64()  == ~"Zm9vYmE=");
        assert!((~"foobar").to_base64() == ~"Zm9vYmFy");
    }

    #[test]
    pub fn test_from_base64() {
        assert!((~"").from_base64() == str::to_bytes(~""));
        assert!((~"Zg==").from_base64() == str::to_bytes(~"f"));
        assert!((~"Zm8=").from_base64() == str::to_bytes(~"fo"));
        assert!((~"Zm9v").from_base64() == str::to_bytes(~"foo"));
        assert!((~"Zm9vYg==").from_base64() == str::to_bytes(~"foob"));
        assert!((~"Zm9vYmE=").from_base64() == str::to_bytes(~"fooba"));
        assert!((~"Zm9vYmFy").from_base64() == str::to_bytes(~"foobar"));
    }
}
<|endoftext|>


<commit_before>use alloc::boxed::Box;

use schemes::{Result, KScheme, Resource, Url, VecResource};

pub struct InterruptScheme;

impl KScheme for InterruptScheme {
    fn scheme(&self) -> &str {
        "interrupt"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        let mut string = format!("{:<6}{:<16}", "INT", "COUNT");

        {
            let interrupts = ::env().interrupts.lock();
            for interrupt in 0..interrupts.len() {
                let count = interrupts[interrupt];

                if count > 0 {
                    string = string + "\n" + &format!("{:<6X}{:<16}", interrupt, count);
                }
            }
        }

        Ok(box VecResource::new(Url::from_str("interrupt:"), string.into_bytes()))
    }
}
<commit_msg>Add interrupt description to interrupt:<commit_after>use alloc::boxed::Box;

use schemes::{Result, KScheme, Resource, Url, VecResource};

pub struct InterruptScheme;

impl KScheme for InterruptScheme {
    fn scheme(&self) -> &str {
        "interrupt"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        let mut string = format!("{:<6}{:<16}{}", "INT", "COUNT", "DESCRIPTION");

        {
            let interrupts = ::env().interrupts.lock();
            for interrupt in 0..interrupts.len() {
                let count = interrupts[interrupt];

                if count > 0 {
                    let description = match interrupt {
                        0x20 => "Programmable Interrupt Timer",
                        0x21 => "Keyboard",
                        0x22 => "Cascade",
                        0x23 => "Serial 2 and 4",
                        0x24 => "Serial 1 and 3",
                        0x25 => "Parallel 2",
                        0x26 => "Floppy",
                        0x27 => "Parallel 1",
                        0x28 => "Realtime Clock",
                        0x29 => "PCI 1",
                        0x2A => "PCI 2",
                        0x2B => "PCI 3",
                        0x2C => "Mouse",
                        0x2D => "Coprocessor",
                        0x2E => "IDE Primary",
                        0x2F => "IDE Secondary",
                        0x80 => "System Call",
                        0x0 => "Divide by zero exception",
                        0x1 => "Debug exception",
                        0x2 => "Non-maskable interrupt",
                        0x3 => "Breakpoint exception",
                        0x4 => "Overflow exception",
                        0x5 => "Bound range exceeded exception",
                        0x6 => "Invalid opcode exception",
                        0x7 => "Device not available exception",
                        0x8 => "Double fault",
                        0xA => "Invalid TSS exception",
                        0xB => "Segment not present exception",
                        0xC => "Stack-segment fault",
                        0xD => "General protection fault",
                        0xE => "Page fault",
                        0x10 => "x87 floating-point exception",
                        0x11 => "Alignment check exception",
                        0x12 => "Machine check exception",
                        0x13 => "SIMD floating-point exception",
                        0x14 => "Virtualization exception",
                        0x1E => "Security exception",
                        _ => "Unknown Interrupt",
                    };

                    string = string + "\n" + &format!("{:<6X}{:<16}{}", interrupt, count, description);
                }
            }
        }

        Ok(box VecResource::new(Url::from_str("interrupt:"), string.into_bytes()))
    }
}
<|endoftext|>


<commit_before><commit_msg>Start on some tests around ingestion.<commit_after><|endoftext|>


<commit_before><commit_msg>add benchmarks<commit_after>#![feature(test)]
extern crate test;
extern crate getrandom;

#[bench]
fn bench_64(b: &mut test::Bencher) {
    let mut buf = [0u8; 64];
    b.iter(|| {
        getrandom::getrandom(&mut buf[..]).unwrap();
        test::black_box(&buf);
    });
    b.bytes = buf.len() as u64;
}

#[bench]
fn bench_65536(b: &mut test::Bencher) {
    let mut buf = [0u8; 65536];
    b.iter(|| {
        getrandom::getrandom(&mut buf[..]).unwrap();
        test::black_box(&buf);
    });
    b.bytes = buf.len() as u64;
}

<|endoftext|>


<commit_before><commit_msg>Add Cmp1 for binary composition<commit_after><|endoftext|>


<commit_before><commit_msg>Only request a meta extension if meta_request is > MIN_META_SEGMENT_SIZE<commit_after><|endoftext|>


<commit_before><commit_msg>Print the version on startup<commit_after><|endoftext|>


<commit_before><commit_msg>Protobuf generated file for interacting with protobuf messages.<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor primary command buffer submit to use the new submit() method<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for `Ipv6Addr` methods in a const context<commit_after>// run-pass

#![feature(ip)]
#![feature(const_ipv6)]

use std::net::{Ipv4Addr, Ipv6Addr, Ipv6MulticastScope};

fn main() {
    const IP_ADDRESS : Ipv6Addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
    assert_eq!(IP_ADDRESS, Ipv6Addr::LOCALHOST);

    const SEGMENTS : [u16; 8] = IP_ADDRESS.segments();
    assert_eq!(SEGMENTS, [0 ,0 ,0 ,0 ,0 ,0 ,0, 1]);

    const OCTETS : [u8; 16] = IP_ADDRESS.octets();
    assert_eq!(OCTETS, [0 ,0 ,0 ,0 ,0 ,0 ,0, 0 ,0 ,0 ,0 ,0 ,0 ,0, 0, 1]);

    const IS_UNSPECIFIED : bool = IP_ADDRESS.is_unspecified();
    assert!(!IS_UNSPECIFIED);

    const IS_LOOPBACK : bool = IP_ADDRESS.is_loopback();
    assert!(IS_LOOPBACK);

    const IS_GLOBAL : bool = IP_ADDRESS.is_global();
    assert!(!IS_GLOBAL);

    const IS_UNIQUE_LOCAL : bool = IP_ADDRESS.is_unique_local();
    assert!(!IS_UNIQUE_LOCAL);

    const IS_UNICAST_LINK_LOCAL_STRICT : bool = IP_ADDRESS.is_unicast_link_local_strict();
    assert!(!IS_UNICAST_LINK_LOCAL_STRICT);

    const IS_UNICAST_LINK_LOCAL : bool = IP_ADDRESS.is_unicast_link_local();
    assert!(!IS_UNICAST_LINK_LOCAL);

    const IS_UNICAST_SITE_LOCAL : bool = IP_ADDRESS.is_unicast_site_local();
    assert!(!IS_UNICAST_SITE_LOCAL);

    const IS_DOCUMENTATION : bool = IP_ADDRESS.is_documentation();
    assert!(!IS_DOCUMENTATION);

    const IS_UNICAST_GLOBAL : bool = IP_ADDRESS.is_unicast_global();
    assert!(!IS_UNICAST_GLOBAL);

    const MULTICAST_SCOPE : Option<Ipv6MulticastScope> = IP_ADDRESS.multicast_scope();
    assert_eq!(MULTICAST_SCOPE, None);

    const IS_MULTICAST : bool = IP_ADDRESS.is_multicast();
    assert!(!IS_MULTICAST);

    const IP_V4 : Option<Ipv4Addr> = IP_ADDRESS.to_ipv4();
    assert_eq!(IP_V4.unwrap(), Ipv4Addr::new(0, 0, 0, 1));
}<|endoftext|>


<commit_before><commit_msg>Shift opcodes - Like I said, it was probably wrong<commit_after><|endoftext|>


<commit_before><commit_msg>practice rust<commit_after>fn main() {
    println!("Hello, world!");
}
<|endoftext|>


<commit_before><commit_msg>Add first test<commit_after>extern crate capstone_sys;
extern crate libc;

use libc::{c_char, size_t};
use capstone_sys::*;

const X86_CODE16: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE32: &'static [u8] = b"\x8d\x4c\x32\x08\x01\xd8\x81\xc6\x34\x12\x00\x00\x05\x23\x01\x00\x00\x36\x8b\x84\x91\x23\x01\x00\x00\x41\x8d\x84\x39\x89\x67\x00\x00\x8d\x87\x89\x67\x00\x00\xb4\xc6";
const X86_CODE64: &'static [u8] = b"\x55\x48\x8b\x05\xb8\x13\x00\x00";

fn to_str(raw: &[c_char]) -> &str {
    unsafe {
        ::std::ffi::CStr::from_ptr(raw.as_ptr()).to_str().expect("invalid UTF-8")
    }
}

fn generic(arch: cs_arch, mode: cs_mode, code: &[u8], expected_size: size_t, expected_first: (&str, &str)) {
    let mut handle: csh = 0;
    let err = unsafe { cs_open(arch, mode, &mut handle) };
    assert_eq!(err, CS_ERR_OK);

    let mut instrs: *mut cs_insn = ::std::ptr::null_mut();
    let size = unsafe { cs_disasm(handle, code.as_ptr(), code.len(), 0, 0 /* read as much as possible */, &mut instrs) };
    assert_eq!(size, expected_size);
    assert!(!instrs.is_null());

    let instr = unsafe { &*instrs };
    let (mnemonic, op_str) = expected_first;
    assert_eq!(to_str(&instr.mnemonic), mnemonic);
    assert_eq!(to_str(&instr.op_str), op_str);

    unsafe {
        cs_close(&mut handle);
    }
}

#[test]
fn test_x86_16() {
    generic(CS_ARCH_X86, CS_MODE_16, X86_CODE16, 15, ("lea", "cx, word ptr [si + 0x32]"));
}

#[test]
fn test_x86_32() {
    generic(CS_ARCH_X86, CS_MODE_32, X86_CODE32, 9, ("lea", "ecx, dword ptr [edx + esi + 8]"));
}

#[test]
fn test_x86_64() {
    generic(CS_ARCH_X86, CS_MODE_64, X86_CODE64, 2, ("push", "rbp"));
}
<|endoftext|>


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


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

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

    if let Err(_e) = io::stdin().read_line(&mut input_a){}
    if let Err(_e) = io::stdin().read_line(&mut input_b){}

    let a: i32 = input_a.trim().parse().unwrap();
    let b: i32 = input_b.trim().parse().unwrap();

    println!("SOMA = {}", a + b);
}
<|endoftext|>


<commit_before><commit_msg>#1 Added 3_derive.rs<commit_after>#[derive(Debug, PartialEq, PartialOrd, Clone, Copy)]
struct User {
    age: i32,
    score: f64
}

fn main() {
    let mut user1 = User {
        age: 30,
        score: 3.14
    };
    let user2 = User {
        age: 22,
        score: 4.1
    };
    // comparison
    if user1 > user2 {
        println!("user1: {:?} > user2: {:?}", user1, user2);
    } else {
        println!("user2: {:?} > user1: {:?}", user2, user1);
    }
    // use of moved value
    {
        let mut same_user1 = user1;
        same_user1.age = 7;
        println!("The same user1 - {:?}", same_user1);
    }
    // print of moved value
    println!("{:?}", user1);
    println!("{:?}", user2);
}<|endoftext|>


<commit_before><commit_msg>Started brainstorming a new API<commit_after>

trait TimeStewardModificationReverter {
  fn revert (event: ?????)->invalidated stuff etc., like the return value of the original modify functions;
}
trait TimeStewardDataThingy {
  // query functions, which take an accessor and possibly a prediction handle, which may be stored in self for future invalidation
  // modify functions, which take a mutator and
  // - possibly return invalidated prediction handles
  // – possibly return spawned predictions, as from creating a new entity
  // - assuming this is for a full TimeSteward, return a StewardRc <TimeStewardModificationReverter> (which, for the simple case, may be a Self). This makes each potential reversion take at least a fat-pointer to store, unless we can make StewardRc be a thin pointer with the vtable at the destination.
}

trait EntityHistory {
  type Steward: Steward;
  fn get (m: & Steward::Mutator) {
}
struct TypedEntityHistory<E:Entity, S: Steward> {
  data: Steward::EntityHistory;
}
impl TypedEntityHistory {
  fn get (m: & S::Mutator) {self.data.get (m).downcast_ref().expect()}
}

trait Entity {
  type Varying = Self;
  type Constants = ();
}

trait Mutator : ??? + Rng {
  type Steward: Steward;
  fn create <E: Entity> (&mut self, constants: E::Constants)->TypedEntityHistory <E, B::S>;
  fn get <E: Entity> (&self, t: TypedEntityHistory <E, B::S>)->E::Varying {t.data.get (...).downcast_ref().expect()}
  ;
}

trait Steward {
  type Mutator: Mutator <Steward = Self>;
  type EntityHistory: EntityHistory <Steward = Self>;
}

impl Event for Struct {
  ...
  fn call <M: Mutator <...>> (& self, mutator: M) {
    let history: TypedEntityHistory <MyType, M::Steward> = self.entity_history;
    let value: &MyType = history.get (mutator);

    let new_history = mutator.create <MyType>(constants);
  }
}

<|endoftext|>


<commit_before><commit_msg>rust helllo<commit_after>//a tradicional program to show u hello man
//with Rush

fn main()
{   //print the text to the COnsole
    println!("Hello man")

}<|endoftext|>


<commit_before><commit_msg>Replace deprecated functioncall<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor(cryptoutil): break get_hmac into two functions<commit_after><|endoftext|>


<commit_before><commit_msg>Cubes - refactored the node graph<commit_after><|endoftext|>


<commit_before><commit_msg>test nested comments in rust<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use resource_task::{ProgressMsg, Payload, Done, LoaderTask};

use std::cell::Cell;
use std::vec;
use extra::url::Url;
use http::client::RequestWriter;
use http::method::Get;
use http::headers::HeaderEnum;
use std::rt::io::Reader;
use std::rt::io::net::ip::SocketAddr;

pub fn factory() -> LoaderTask {
	let f: LoaderTask = |url, progress_chan| {
        let url = Cell::new(url);
        let progress_chan = Cell::new(progress_chan);
        spawn(|| load(url.take(), progress_chan.take()))
	};
	f
}

fn load(url: Url, progress_chan: Chan<ProgressMsg>) {
	assert!(url.scheme == ~"http");

    info!("requesting %s", url.to_str());

    let mut request = ~RequestWriter::new(Get, url.clone());
    request.remote_addr = Some(url_to_socket_addr(&url));
    let mut response = match request.read_response() {
        Ok(r) => r,
        Err(_) => {
            progress_chan.send(Done(Err(())));
            return;
        }
    };

    loop {
        for header in response.headers.iter() {
            info!(" - %s: %s", header.header_name(), header.header_value());
        }

        let mut buf = vec::with_capacity(1024);
        unsafe { vec::raw::set_len(&mut buf, 1024) };
        match response.read(buf) {
            Some(len) => {
                unsafe { vec::raw::set_len(&mut buf, len) };
            }
            None => {
                progress_chan.send(Done(Ok(())));
                return;
            }
        }
        progress_chan.send(Payload(buf));
    }
}

// FIXME: Quick hack to convert ip addresses to SocketAddr
fn url_to_socket_addr(url: &Url) -> SocketAddr {
    let host_and_port = fmt!("%s:%s", url.host, url.port.clone().unwrap_or_default(~"80"));
    FromStr::from_str(host_and_port).expect("couldn't parse host as IP address")
}
<commit_msg>auto merge of #870 : brson/servo/http, r=metajack<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use resource_task::{ProgressMsg, Payload, Done, LoaderTask};

use std::cell::Cell;
use std::vec;
use extra::url::Url;
use http::client::RequestWriter;
use http::method::Get;
use http::headers::HeaderEnum;
use std::rt::io::Reader;
use std::rt::io::net::ip::SocketAddr;

pub fn factory() -> LoaderTask {
	let f: LoaderTask = |url, progress_chan| {
        let url = Cell::new(url);
        let progress_chan = Cell::new(progress_chan);
        spawn(|| load(url.take(), progress_chan.take()))
	};
	f
}

fn load(url: Url, progress_chan: Chan<ProgressMsg>) {
	assert!(url.scheme == ~"http");

    info!("requesting %s", url.to_str());

    let mut request = ~RequestWriter::new(Get, url.clone());
    request.remote_addr = Some(url_to_socket_addr(&url));
    let mut response = match request.read_response() {
        Ok(r) => r,
        Err(_) => {
            progress_chan.send(Done(Err(())));
            return;
        }
    };

    for header in response.headers.iter() {
        info!(" - %s: %s", header.header_name(), header.header_value());
    }

    loop {
        let mut buf = vec::with_capacity(1024);

        unsafe { vec::raw::set_len(&mut buf, 1024) };
        match response.read(buf) {
            Some(len) => {
                unsafe { vec::raw::set_len(&mut buf, len) };
            }
            None => {
                progress_chan.send(Done(Ok(())));
                return;
            }
        }
        progress_chan.send(Payload(buf));
    }
    progress_chan.send(Done(Ok(())));
}

// FIXME: Quick hack to convert ip addresses to SocketAddr
fn url_to_socket_addr(url: &Url) -> SocketAddr {
    let host_and_port = fmt!("%s:%s", url.host, url.port.clone().unwrap_or_default(~"80"));
    FromStr::from_str(host_and_port).expect("couldn't parse host as IP address")
}
<|endoftext|>


<commit_before><commit_msg>add missing file<commit_after>// Copyright © 2016, Canal TP and/or its affiliates. All rights reserved.
//
// This file is part of Navitia,
//     the software to build cool stuff with public transport.
//
// Hope you'll enjoy and contribute to this project,
//     powered by Canal TP (www.canaltp.fr).
// Help us simplify mobility and open public transport:
//     a non ending quest to the responsive locomotion way of traveling!
//
// LICENCE: This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU Affero General Public
// License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
// Stay tuned using
// twitter @navitia
// IRC #navitia on freenode
// https://groups.google.com/d/forum/navitia
// www.navitia.io

use std::process::Command;

/// Simple call to a BANO load into ES base
/// Checks that we are able to find one object (a specific address)
pub fn osm2mimir_bano2mimir_test(es_wrapper: ::ElasticSearchWrapper) {
    let osm2mimir = concat!(env!("OUT_DIR"), "/../../../osm2mimir");
    let status = Command::new(osm2mimir)
                     .args(&["--input=./tests/fixtures/rues_trois_communes.osm.pbf".into(),
                             "--import-way".into(),
                             "--import-admin".into(),
                             "--level=8".into(),
                             format!("--connection-string={}", es_wrapper.host())])
                     .status()
                     .unwrap();
    assert!(status.success(), "`bano2mimir` failed {}", &status);

    let bano2mimir = concat!(env!("OUT_DIR"), "/../../../bano2mimir");
    info!("Launching {}", bano2mimir);
    let status = Command::new(bano2mimir)
                     .args(&["--input=./tests/fixtures/bano-trois_communes.csv".into(),
                             format!("--connection-string={}", es_wrapper.host())])
                     .status()
                     .unwrap();
    assert!(status.success(), "`bano2mimir` failed {}", &status);

    es_wrapper.refresh();

	// TODO: more tests will be written here
}
<|endoftext|>


<commit_before>use std::slice;
use std::io;

use image;
use image::ImageResult;
use image::ImageDecoder;
use color;

use super::lzw::LZWReader;

macro_rules! io_try(
    ($e: expr) => (
        match $e {
            Ok(e) => e,
            Err(err) => return Err(image::IoError(err))
        }
    )
)

const IMAGEDESCRIPTOR: u8 = 0x2C;
const EXTENSION: u8 = 0x21;
const APPLICATION: u8 = 0xFF;
const GRAPHICCONTROL: u8 = 0xF9;
const COMMENT: u8 = 0xFE;
const TRAILER: u8 = 0x3B;

/// The Representation of a GIF decoder
pub struct GIFDecoder <R> {
    r: R,

    width: u16,
    height: u16,

    global_table: [(u8, u8, u8), ..256],
    local_table: Option<Vec<(u8, u8, u8)>>,

    delay: u16,
    image: Vec<u8>,

    global_backgroud_index: Option<u8>,
    local_transparent_index: Option<u8>,

    have_header: bool,
    decoded_rows: u32,
}

impl<R: Reader> GIFDecoder<R> {
    /// Create a new GIFDecoder from the Reader ```r```.
    /// This function takes ownership of the Reader.
    pub fn new(r: R) -> GIFDecoder<R> {
        GIFDecoder {
            r: r,

            width: 0,
            height: 0,

            global_table: [(0u8, 0u8, 0u8), ..256],
            local_table: None,

            delay: 0,
            image: Vec::new(),

            global_backgroud_index: None,
            local_transparent_index: None,

            have_header: false,
            decoded_rows: 0,
        }
    }

    ///Returns the display delay in 100th's of a second for the currently
    ///decoded image.
    pub fn delay(&mut self) -> ImageResult<u16> {

        let _ = try!(self.read_metadata());

        Ok(self.delay)
    }

    fn read_header(&mut self) -> ImageResult<()> {
        let signature = io_try!(self.r.read_exact(3));
        let version   = io_try!(self.r.read_exact(3));

        if signature.as_slice() != "GIF".as_bytes() {
            Err(image::FormatError("GIF signature not found.".to_string()))
        } else if version.as_slice() != "87a".as_bytes() &&
                  version.as_slice() != "89a".as_bytes() {
            Err(image::UnsupportedError(
                format!("GIF version {} is not supported.", version)
            ))
        } else {
            Ok(())
        }
    }

    fn read_block(&mut self) -> io::IoResult<Vec<u8>> {
        let size = try!(self.r.read_u8());
        Ok(try!(self.r.read_exact(size as uint)))
    }

    fn read_image_data(&mut self) -> ImageResult<Vec<u8>> {
        let minimum_code_size = io_try!(self.r.read_u8());

        if minimum_code_size > 8 {
            return Err(image::FormatError(format!("Invalid code size {}.", minimum_code_size)))
        }

        let mut data = Vec::new();
        loop {
            let b = io_try!(self.read_block());

            if b.len() == 0 {
                break
            }

            data = data + b;
        }

        let m = io::MemReader::new(data);
        let mut lzw = LZWReader::new(m, minimum_code_size);
        let b = lzw.read_to_end().unwrap();

        Ok(b)
    }

    fn read_image_descriptor(&mut self) -> ImageResult<()> {
        let image_left   = io_try!(self.r.read_le_u16());
        let image_top    = io_try!(self.r.read_le_u16());
        let image_width  = io_try!(self.r.read_le_u16());
        let image_height = io_try!(self.r.read_le_u16());

        let fields = io_try!(self.r.read_u8());

        let local_table = fields & 80 != 0;
        let interlace   = fields & 40 != 0;
        let table_size  = fields & 7;

        if interlace {
            return Err(image::UnsupportedError("Interlaced images are not supported.".to_string()))
        }

        if local_table {
            let n   = 1 << (table_size + 1) as uint;
            let buf = io_try!(self.r.read_exact(3 * n));
            let mut b = Vec::from_elem(n, (0u8, 0u8, 0u8));

            for (i, rgb) in buf.as_slice().chunks(3).enumerate() {
                b.as_mut_slice()[i] = (rgb[0], rgb[1], rgb[2]);
            }

            self.local_table = Some(b);
        }

        let indices = try!(self.read_image_data());

        {

            let trans_index = if self.local_transparent_index.is_some() {
                self.local_transparent_index
            } else {
                self.global_backgroud_index
            };

            let table = if self.local_table.is_some() {
                self.local_table.as_ref().unwrap().as_slice()
            } else {
                self.global_table.as_slice()
            };

            expand_image(
                table,
                indices.as_slice(),
                image_top as uint,
                image_left as uint,
                image_width as uint,
                image_height as uint,
                self.width as uint * 3,
                trans_index,
                self.image.as_mut_slice()
            );
        }

        self.local_table = None;
        self.local_transparent_index = None;

        Ok(())
    }

    fn read_extension(&mut self) -> ImageResult<()> {
        let identifier = io_try!(self.r.read_u8());

        match identifier {
            APPLICATION    => try!(self.read_application_extension()),
            GRAPHICCONTROL => try!(self.read_graphic_control_extension()),
            COMMENT 	   => try!(self.read_comment_extension()),
            _              => return Err(image::UnsupportedError(
                                  format!("Identifier {} is not supported.", identifier))
                              )
        }

        Ok(())
    }

    fn read_comment_extension(&mut self) -> ImageResult<()> {
        loop {
            let b = io_try!(self.read_block());

            if b.len() == 0 {
                break
            }
        }

        Ok(())
    }

    fn read_graphic_control_extension(&mut self) -> ImageResult<()> {
        let size   = io_try!(self.r.read_u8());
        assert!(size == 4);

        let fields = io_try!(self.r.read_u8());
        self.delay = io_try!(self.r.read_le_u16());
        let trans  = io_try!(self.r.read_u8());

        if fields & 1 != 0 {
            self.local_transparent_index = Some(trans);
        }

        let _disposal = (fields & 0x1C) >> 2;
        let _term = io_try!(self.r.read_u8());

        Ok(())
    }

    fn read_application_extension(&mut self) -> ImageResult<()> {
        let size = io_try!(self.r.read_u8());
        let _ = io_try!(self.r.read_exact(size as uint));

        loop {
            let b = io_try!(self.read_block());

            if b.len() == 0 {
                break
            }
        }

        Ok(())
    }

    fn read_logical_screen_descriptor(&mut self) -> ImageResult<()> {
        self.width  = io_try!(self.r.read_le_u16());
        self.height = io_try!(self.r.read_le_u16());
        self.image  = Vec::from_elem(self.width as uint * self.height as uint * 3, 0u8);

        let fields = io_try!(self.r.read_u8());

        let global_table = fields & 0x80 != 0;

        let entries = if global_table {
            1 << ((fields & 7) + 1) as uint
        } else {
            0u
        };

        if global_table {
        let b = io_try!(self.r.read_u8());
            self.global_backgroud_index = Some(b);
        }

        let _aspect_ratio = io_try!(self.r.read_u8());

        let buf = io_try!(self.r.read_exact(3 * entries));

        for (i, rgb) in buf.as_slice().chunks(3).enumerate() {
            self.global_table.as_mut_slice()[i] = (rgb[0], rgb[1], rgb[2]);
        }

        Ok(())
    }

    fn read_metadata(&mut self) -> ImageResult<()> {
        if !self.have_header {
            let _ = try!(self.read_header());
            let _ = try!(self.read_logical_screen_descriptor());
            self.have_header = true;
        }

        Ok(())
    }
}

impl<R: Reader> ImageDecoder for GIFDecoder<R> {
    fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
        let _ = try!(self.read_metadata());
        Ok((self.width as u32, self.height as u32))
    }

    fn colortype(&mut self) -> ImageResult<color::ColorType> {
        let _ = try!(self.read_metadata());
        Ok(color::RGB(8))
    }

    fn row_len(&mut self) -> ImageResult<uint> {
        let _ = try!(self.read_metadata());
        Ok(3 * self.width as uint)
    }

    fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> {
        let _ = try!(self.read_metadata());
        if self.decoded_rows == self.height as u32 || self.image.len() == 0 {
            let _ = try!(self.read_image());
        }

        let rlen  = buf.len();
        let slice = self.image.slice(self.decoded_rows as uint * rlen,
        self.decoded_rows as uint * rlen + rlen);

        slice::bytes::copy_memory(buf, slice);
        self.decoded_rows += 1;

        Ok(self.decoded_rows)
    }

    fn read_image(&mut self) -> ImageResult<Vec<u8>> {
        let _ = try!(self.read_metadata());
        loop {
            let block = io_try!(self.r.read_u8());

            match block {
                EXTENSION => try!(self.read_extension()),
                IMAGEDESCRIPTOR => {
                    let _ = try!(self.read_image_descriptor());
                    return Ok(self.image.clone())
                }
                TRAILER => break,
                _       => return Err(image::UnsupportedError(
                            format!("Block type {} is not supported.", block))
                        )
            }
        }

        Err(image::ImageEnd)
    }
}

fn expand_image(palete: &[(u8, u8, u8)],
                indices: &[u8],
                y0: uint,
                x0: uint,
                width: uint,
                height: uint,
                stride: uint,
                trans_index: Option<u8>,
                image: &mut [u8]) {

    for y in range(0, height) {
        for x in range(0, width) {
            let index = indices[y * width + x];

            if trans_index == Some(index) {
                continue
            }

            let (r, g, b) = palete[index as uint];

            image[(y0 + y) * stride + x0 * 3 + x * 3 + 0] = r;
            image[(y0 + y) * stride + x0 * 3 + x * 3 + 1] = g;
            image[(y0 + y) * stride + x0 * 3 + x * 3 + 2] = b;
        }
    }
}
<commit_msg>Fix typo<commit_after>use std::slice;
use std::io;

use image;
use image::ImageResult;
use image::ImageDecoder;
use color;

use super::lzw::LZWReader;

macro_rules! io_try(
    ($e: expr) => (
        match $e {
            Ok(e) => e,
            Err(err) => return Err(image::IoError(err))
        }
    )
)

const IMAGEDESCRIPTOR: u8 = 0x2C;
const EXTENSION: u8 = 0x21;
const APPLICATION: u8 = 0xFF;
const GRAPHICCONTROL: u8 = 0xF9;
const COMMENT: u8 = 0xFE;
const TRAILER: u8 = 0x3B;

/// The Representation of a GIF decoder
pub struct GIFDecoder <R> {
    r: R,

    width: u16,
    height: u16,

    global_table: [(u8, u8, u8), ..256],
    local_table: Option<Vec<(u8, u8, u8)>>,

    delay: u16,
    image: Vec<u8>,

    global_backgroud_index: Option<u8>,
    local_transparent_index: Option<u8>,

    have_header: bool,
    decoded_rows: u32,
}

impl<R: Reader> GIFDecoder<R> {
    /// Create a new GIFDecoder from the Reader ```r```.
    /// This function takes ownership of the Reader.
    pub fn new(r: R) -> GIFDecoder<R> {
        GIFDecoder {
            r: r,

            width: 0,
            height: 0,

            global_table: [(0u8, 0u8, 0u8), ..256],
            local_table: None,

            delay: 0,
            image: Vec::new(),

            global_backgroud_index: None,
            local_transparent_index: None,

            have_header: false,
            decoded_rows: 0,
        }
    }

    ///Returns the display delay in 100th's of a second for the currently
    ///decoded image.
    pub fn delay(&mut self) -> ImageResult<u16> {

        let _ = try!(self.read_metadata());

        Ok(self.delay)
    }

    fn read_header(&mut self) -> ImageResult<()> {
        let signature = io_try!(self.r.read_exact(3));
        let version   = io_try!(self.r.read_exact(3));

        if signature.as_slice() != "GIF".as_bytes() {
            Err(image::FormatError("GIF signature not found.".to_string()))
        } else if version.as_slice() != "87a".as_bytes() &&
                  version.as_slice() != "89a".as_bytes() {
            Err(image::UnsupportedError(
                format!("GIF version {} is not supported.", version)
            ))
        } else {
            Ok(())
        }
    }

    fn read_block(&mut self) -> io::IoResult<Vec<u8>> {
        let size = try!(self.r.read_u8());
        Ok(try!(self.r.read_exact(size as uint)))
    }

    fn read_image_data(&mut self) -> ImageResult<Vec<u8>> {
        let minimum_code_size = io_try!(self.r.read_u8());

        if minimum_code_size > 8 {
            return Err(image::FormatError(format!("Invalid code size {}.", minimum_code_size)))
        }

        let mut data = Vec::new();
        loop {
            let b = io_try!(self.read_block());

            if b.len() == 0 {
                break
            }

            data = data + b;
        }

        let m = io::MemReader::new(data);
        let mut lzw = LZWReader::new(m, minimum_code_size);
        let b = lzw.read_to_end().unwrap();

        Ok(b)
    }

    fn read_image_descriptor(&mut self) -> ImageResult<()> {
        let image_left   = io_try!(self.r.read_le_u16());
        let image_top    = io_try!(self.r.read_le_u16());
        let image_width  = io_try!(self.r.read_le_u16());
        let image_height = io_try!(self.r.read_le_u16());

        let fields = io_try!(self.r.read_u8());

        let local_table = fields & 80 != 0;
        let interlace   = fields & 40 != 0;
        let table_size  = fields & 7;

        if interlace {
            return Err(image::UnsupportedError("Interlaced images are not supported.".to_string()))
        }

        if local_table {
            let n   = 1 << (table_size + 1) as uint;
            let buf = io_try!(self.r.read_exact(3 * n));
            let mut b = Vec::from_elem(n, (0u8, 0u8, 0u8));

            for (i, rgb) in buf.as_slice().chunks(3).enumerate() {
                b.as_mut_slice()[i] = (rgb[0], rgb[1], rgb[2]);
            }

            self.local_table = Some(b);
        }

        let indices = try!(self.read_image_data());

        {

            let trans_index = if self.local_transparent_index.is_some() {
                self.local_transparent_index
            } else {
                self.global_backgroud_index
            };

            let table = if self.local_table.is_some() {
                self.local_table.as_ref().unwrap().as_slice()
            } else {
                self.global_table.as_slice()
            };

            expand_image(
                table,
                indices.as_slice(),
                image_top as uint,
                image_left as uint,
                image_width as uint,
                image_height as uint,
                self.width as uint * 3,
                trans_index,
                self.image.as_mut_slice()
            );
        }

        self.local_table = None;
        self.local_transparent_index = None;

        Ok(())
    }

    fn read_extension(&mut self) -> ImageResult<()> {
        let identifier = io_try!(self.r.read_u8());

        match identifier {
            APPLICATION    => try!(self.read_application_extension()),
            GRAPHICCONTROL => try!(self.read_graphic_control_extension()),
            COMMENT 	   => try!(self.read_comment_extension()),
            _              => return Err(image::UnsupportedError(
                                  format!("Identifier {} is not supported.", identifier))
                              )
        }

        Ok(())
    }

    fn read_comment_extension(&mut self) -> ImageResult<()> {
        loop {
            let b = io_try!(self.read_block());

            if b.len() == 0 {
                break
            }
        }

        Ok(())
    }

    fn read_graphic_control_extension(&mut self) -> ImageResult<()> {
        let size   = io_try!(self.r.read_u8());
        assert!(size == 4);

        let fields = io_try!(self.r.read_u8());
        self.delay = io_try!(self.r.read_le_u16());
        let trans  = io_try!(self.r.read_u8());

        if fields & 1 != 0 {
            self.local_transparent_index = Some(trans);
        }

        let _disposal = (fields & 0x1C) >> 2;
        let _term = io_try!(self.r.read_u8());

        Ok(())
    }

    fn read_application_extension(&mut self) -> ImageResult<()> {
        let size = io_try!(self.r.read_u8());
        let _ = io_try!(self.r.read_exact(size as uint));

        loop {
            let b = io_try!(self.read_block());

            if b.len() == 0 {
                break
            }
        }

        Ok(())
    }

    fn read_logical_screen_descriptor(&mut self) -> ImageResult<()> {
        self.width  = io_try!(self.r.read_le_u16());
        self.height = io_try!(self.r.read_le_u16());
        self.image  = Vec::from_elem(self.width as uint * self.height as uint * 3, 0u8);

        let fields = io_try!(self.r.read_u8());

        let global_table = fields & 0x80 != 0;

        let entries = if global_table {
            1 << ((fields & 7) + 1) as uint
        } else {
            0u
        };

        if global_table {
        let b = io_try!(self.r.read_u8());
            self.global_backgroud_index = Some(b);
        }

        let _aspect_ratio = io_try!(self.r.read_u8());

        let buf = io_try!(self.r.read_exact(3 * entries));

        for (i, rgb) in buf.as_slice().chunks(3).enumerate() {
            self.global_table.as_mut_slice()[i] = (rgb[0], rgb[1], rgb[2]);
        }

        Ok(())
    }

    fn read_metadata(&mut self) -> ImageResult<()> {
        if !self.have_header {
            let _ = try!(self.read_header());
            let _ = try!(self.read_logical_screen_descriptor());
            self.have_header = true;
        }

        Ok(())
    }
}

impl<R: Reader> ImageDecoder for GIFDecoder<R> {
    fn dimensions(&mut self) -> ImageResult<(u32, u32)> {
        let _ = try!(self.read_metadata());
        Ok((self.width as u32, self.height as u32))
    }

    fn colortype(&mut self) -> ImageResult<color::ColorType> {
        let _ = try!(self.read_metadata());
        Ok(color::RGB(8))
    }

    fn row_len(&mut self) -> ImageResult<uint> {
        let _ = try!(self.read_metadata());
        Ok(3 * self.width as uint)
    }

    fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32> {
        let _ = try!(self.read_metadata());
        if self.decoded_rows == self.height as u32 || self.image.len() == 0 {
            let _ = try!(self.read_image());
        }

        let rlen  = buf.len();
        let slice = self.image.slice(self.decoded_rows as uint * rlen,
        self.decoded_rows as uint * rlen + rlen);

        slice::bytes::copy_memory(buf, slice);
        self.decoded_rows += 1;

        Ok(self.decoded_rows)
    }

    fn read_image(&mut self) -> ImageResult<Vec<u8>> {
        let _ = try!(self.read_metadata());
        loop {
            let block = io_try!(self.r.read_u8());

            match block {
                EXTENSION => try!(self.read_extension()),
                IMAGEDESCRIPTOR => {
                    let _ = try!(self.read_image_descriptor());
                    return Ok(self.image.clone())
                }
                TRAILER => break,
                _       => return Err(image::UnsupportedError(
                            format!("Block type {} is not supported.", block))
                        )
            }
        }

        Err(image::ImageEnd)
    }
}

fn expand_image(palette: &[(u8, u8, u8)],
                indices: &[u8],
                y0: uint,
                x0: uint,
                width: uint,
                height: uint,
                stride: uint,
                trans_index: Option<u8>,
                image: &mut [u8]) {

    for y in range(0, height) {
        for x in range(0, width) {
            let index = indices[y * width + x];

            if trans_index == Some(index) {
                continue
            }

            let (r, g, b) = palette[index as uint];

            image[(y0 + y) * stride + x0 * 3 + x * 3 + 0] = r;
            image[(y0 + y) * stride + x0 * 3 + x * 3 + 1] = g;
            image[(y0 + y) * stride + x0 * 3 + x * 3 + 2] = b;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>examples require both audio and video permissions<commit_after><|endoftext|>


<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// Functions for dealing with devices.

use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::os::unix::prelude::AsRawFd;
use std::path::Path;

use devicemapper::{devnode_to_devno, Bytes, Device};
use stratis::{ErrorEnum, StratisError, StratisResult};

use super::super::super::types::{DevUuid, PoolUuid};
use super::metadata::StaticHeader;
use super::util::get_udev_block_device;

ioctl!(read blkgetsize64 with 0x12, 114; u64);

pub fn blkdev_size(file: &File) -> StratisResult<Bytes> {
    let mut val: u64 = 0;

    match unsafe { blkgetsize64(file.as_raw_fd(), &mut val) } {
        Err(x) => Err(StratisError::Nix(x)),
        Ok(_) => Ok(Bytes(val)),
    }
}

/// Resolve a list of Paths of some sort to a set of unique Devices.
/// Return an IOError if there was a problem resolving any particular device.
/// The set of devices maps each device to one of the paths passed.
/// Returns an error if any path does not correspond to a block device.
pub fn resolve_devices<'a>(paths: &'a [&Path]) -> StratisResult<HashMap<Device, &'a Path>> {
    let mut map = HashMap::new();
    for path in paths {
        match devnode_to_devno(path)? {
            Some(devno) => {
                let _ = map.insert(Device::from(devno), *path);
            }
            None => {
                let err_msg = format!("path {} does not refer to a block device", path.display());
                return Err(StratisError::Engine(ErrorEnum::Invalid, err_msg));
            }
        }
    }
    Ok(map)
}

#[derive(Debug, PartialEq, Eq)]
pub enum DevOwnership {
    Ours(PoolUuid, DevUuid),
    Unowned,
    Theirs(String), // String is something useful to give back to end user about what's on device
}

/// Returns true if a device has no signature, yes this is a bit convoluted.  Logic gleaned from
/// blivet library.
fn empty(device: &HashMap<String, String>) -> bool {
    !((device.contains_key("ID_PART_TABLE_TYPE") && !device.contains_key("ID_PART_ENTRY_DISK"))
        || device.contains_key("ID_FS_USAGE"))
}

/// Generate some kind of human readable text about what's on a device.
fn signature(device: &HashMap<String, String>) -> String {
    if empty(device) {
        String::from("empty")
    } else {
        device
            .iter()
            .filter(|&(k, _)| k.contains("ID_FS_") || k.contains("ID_PART_TABLE_"))
            .map(|(k, v)| format!("{}={}", k, v))
            .collect::<Vec<String>>()
            .join(" ")
    }
}

/// Determine what a block device is used for.
pub fn identify(devnode: &Path) -> StratisResult<DevOwnership> {
    if let Some(device) = get_udev_block_device(devnode)? {
        if empty(&device) {
            // The device is either really empty or we are running on a distribution that hasn't
            // picked up the latest libblkid, lets read down to the device and find out for sure.
            // TODO: At some point in the future we can remove this and just return Unowned.
            if let Some((pool_uuid, device_uuid)) = StaticHeader::device_identifiers(
                &mut OpenOptions::new().read(true).open(&devnode)?,
            )? {
                Ok(DevOwnership::Ours(pool_uuid, device_uuid))
            } else {
                Ok(DevOwnership::Unowned)
            }
        } else if device.contains_key("ID_FS_TYPE") && device["ID_FS_TYPE"] == "stratis" {
            // Device is ours, but we don't get everything we need from udev db, lets go to disk.
            if let Some((pool_uuid, device_uuid)) = StaticHeader::device_identifiers(
                &mut OpenOptions::new().read(true).open(&devnode)?,
            )? {
                Ok(DevOwnership::Ours(pool_uuid, device_uuid))
            } else {
                // In this case the udev db says it's ours, but our check says otherwise.  We should
                // trust ourselves.  Should we raise an error here?
                Ok(DevOwnership::Theirs(String::from(
                    "Udev db says stratis, disk meta says no",
                )))
            }
        } else {
            Ok(DevOwnership::Theirs(signature(&device)))
        }
    } else {
        Err(StratisError::Engine(
            ErrorEnum::NotFound,
            format!(
                "We expected to find the block device {:?} \
                 in the udev db",
                devnode
            ),
        ))
    }
}

/// Determine if devnode is a Stratis device. Return the device's Stratis
/// pool UUID if it belongs to Stratis.
pub fn is_stratis_device(devnode: &Path) -> StratisResult<Option<PoolUuid>> {
    match identify(devnode)? {
        DevOwnership::Ours(pool_uuid, _) => Ok(Some(pool_uuid)),
        _ => Ok(None),
    }
}

#[cfg(test)]
mod test {
    use std::path::Path;

    use super::super::super::cmd::{create_ext3_fs, udev_settle};
    use super::super::super::tests::{loopbacked, real};

    use super::super::device;

    /// Verify that the device is not stratis by creating a device with XFS fs.
    fn test_other_ownership(paths: &[&Path]) {
        create_ext3_fs(paths[0]).unwrap();

        udev_settle().unwrap();

        assert_eq!(device::is_stratis_device(paths[0]).unwrap(), None);

        assert!(match device::identify(paths[0]).unwrap() {
            device::DevOwnership::Theirs(identity) => {
                assert!(identity.contains("ID_FS_USAGE=filesystem"));
                assert!(identity.contains("ID_FS_TYPE=ext3"));
                assert!(identity.contains("ID_FS_UUID"));
                true
            }
            _ => false,
        });
    }

    /// Test a blank device and ensure it comes up as device::Usage::Unowned
    fn test_empty(paths: &[&Path]) {
        udev_settle().unwrap();

        assert_eq!(device::is_stratis_device(paths[0]).unwrap(), None);

        assert!(match device::identify(paths[0]).unwrap() {
            device::DevOwnership::Unowned => true,
            _ => false,
        });

        assert_eq!(device::is_stratis_device(paths[0]).unwrap(), None);
    }

    #[test]
    pub fn loop_test_device_other_ownership() {
        loopbacked::test_with_spec(
            loopbacked::DeviceLimits::Range(1, 3, None),
            test_other_ownership,
        );
    }

    #[test]
    pub fn real_test_device_other_ownership() {
        real::test_with_spec(
            real::DeviceLimits::AtLeast(1, None, None),
            test_other_ownership,
        );
    }

    #[test]
    pub fn loop_test_device_empty() {
        loopbacked::test_with_spec(loopbacked::DeviceLimits::Range(1, 3, None), test_empty);
    }

    #[test]
    pub fn real_test_device_empty() {
        real::test_with_spec(real::DeviceLimits::AtLeast(1, None, None), test_empty);
    }
}
<commit_msg>turn off rustfmt on one spot<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// Functions for dealing with devices.

use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::os::unix::prelude::AsRawFd;
use std::path::Path;

use devicemapper::{devnode_to_devno, Bytes, Device};
use stratis::{ErrorEnum, StratisError, StratisResult};

use super::super::super::types::{DevUuid, PoolUuid};
use super::metadata::StaticHeader;
use super::util::get_udev_block_device;

ioctl!(read blkgetsize64 with 0x12, 114; u64);

pub fn blkdev_size(file: &File) -> StratisResult<Bytes> {
    let mut val: u64 = 0;

    match unsafe { blkgetsize64(file.as_raw_fd(), &mut val) } {
        Err(x) => Err(StratisError::Nix(x)),
        Ok(_) => Ok(Bytes(val)),
    }
}

/// Resolve a list of Paths of some sort to a set of unique Devices.
/// Return an IOError if there was a problem resolving any particular device.
/// The set of devices maps each device to one of the paths passed.
/// Returns an error if any path does not correspond to a block device.
pub fn resolve_devices<'a>(paths: &'a [&Path]) -> StratisResult<HashMap<Device, &'a Path>> {
    let mut map = HashMap::new();
    for path in paths {
        match devnode_to_devno(path)? {
            Some(devno) => {
                let _ = map.insert(Device::from(devno), *path);
            }
            None => {
                let err_msg = format!("path {} does not refer to a block device", path.display());
                return Err(StratisError::Engine(ErrorEnum::Invalid, err_msg));
            }
        }
    }
    Ok(map)
}

#[derive(Debug, PartialEq, Eq)]
pub enum DevOwnership {
    Ours(PoolUuid, DevUuid),
    Unowned,
    Theirs(String), // String is something useful to give back to end user about what's on device
}

/// Returns true if a device has no signature, yes this is a bit convoluted.  Logic gleaned from
/// blivet library.
fn empty(device: &HashMap<String, String>) -> bool {
    !((device.contains_key("ID_PART_TABLE_TYPE") && !device.contains_key("ID_PART_ENTRY_DISK"))
        || device.contains_key("ID_FS_USAGE"))
}

/// Generate some kind of human readable text about what's on a device.
fn signature(device: &HashMap<String, String>) -> String {
    if empty(device) {
        String::from("empty")
    } else {
        device
            .iter()
            .filter(|&(k, _)| k.contains("ID_FS_") || k.contains("ID_PART_TABLE_"))
            .map(|(k, v)| format!("{}={}", k, v))
            .collect::<Vec<String>>()
            .join(" ")
    }
}

/// Determine what a block device is used for.
pub fn identify(devnode: &Path) -> StratisResult<DevOwnership> {
    if let Some(device) = get_udev_block_device(devnode)? {
        if empty(&device) {
            // The device is either really empty or we are running on a distribution that hasn't
            // picked up the latest libblkid, lets read down to the device and find out for sure.
            // TODO: At some point in the future we can remove this and just return Unowned.
            if let Some((pool_uuid, device_uuid)) = StaticHeader::device_identifiers(
                &mut OpenOptions::new().read(true).open(&devnode)?,
            )? {
                Ok(DevOwnership::Ours(pool_uuid, device_uuid))
            } else {
                Ok(DevOwnership::Unowned)
            }
        } else if device.contains_key("ID_FS_TYPE") && device["ID_FS_TYPE"] == "stratis" {
            // Device is ours, but we don't get everything we need from udev db, lets go to disk.
            if let Some((pool_uuid, device_uuid)) = StaticHeader::device_identifiers(
                &mut OpenOptions::new().read(true).open(&devnode)?,
            )? {
                Ok(DevOwnership::Ours(pool_uuid, device_uuid))
            } else {
                // In this case the udev db says it's ours, but our check says otherwise.  We should
                // trust ourselves.  Should we raise an error here?
                Ok(DevOwnership::Theirs(String::from(
                    "Udev db says stratis, disk meta says no",
                )))
            }
        } else {
            Ok(DevOwnership::Theirs(signature(&device)))
        }
    } else {
        Err(StratisError::Engine(
            ErrorEnum::NotFound,
            format!(
                "We expected to find the block device {:?} \
                 in the udev db",
                devnode
            ),
        ))
    }
}

/// Determine if devnode is a Stratis device. Return the device's Stratis
/// pool UUID if it belongs to Stratis.
pub fn is_stratis_device(devnode: &Path) -> StratisResult<Option<PoolUuid>> {
    match identify(devnode)? {
        DevOwnership::Ours(pool_uuid, _) => Ok(Some(pool_uuid)),
        _ => Ok(None),
    }
}

#[cfg(test)]
// rustfmt bug requires this?
#[cfg_attr(rustfmt, rustfmt_skip)]
mod test {
    use std::path::Path;

    use super::super::super::cmd::{create_ext3_fs, udev_settle};
    use super::super::super::tests::{loopbacked, real};

    use super::super::device;

    /// Verify that the device is not stratis by creating a device with XFS fs.
    fn test_other_ownership(paths: &[&Path]) {
        create_ext3_fs(paths[0]).unwrap();

        udev_settle().unwrap();

        assert_eq!(device::is_stratis_device(paths[0]).unwrap(), None);

        assert!(match device::identify(paths[0]).unwrap() {
            device::DevOwnership::Theirs(identity) => {
                assert!(identity.contains("ID_FS_USAGE=filesystem"));
                assert!(identity.contains("ID_FS_TYPE=ext3"));
                assert!(identity.contains("ID_FS_UUID"));
                true
            }
            _ => false,
        });
    }

    /// Test a blank device and ensure it comes up as device::Usage::Unowned
    fn test_empty(paths: &[&Path]) {
        udev_settle().unwrap();

        assert_eq!(device::is_stratis_device(paths[0]).unwrap(), None);

        assert!(match device::identify(paths[0]).unwrap() {
            device::DevOwnership::Unowned => true,
            _ => false,
        });

        assert_eq!(device::is_stratis_device(paths[0]).unwrap(), None);
    }

    #[test]
    pub fn loop_test_device_other_ownership() {
        loopbacked::test_with_spec(
            loopbacked::DeviceLimits::Range(1, 3, None),
            test_other_ownership,
        );
    }

    #[test]
    pub fn real_test_device_other_ownership() {
        real::test_with_spec(
            real::DeviceLimits::AtLeast(1, None, None),
            test_other_ownership,
        );
    }

    #[test]
    pub fn loop_test_device_empty() {
        loopbacked::test_with_spec(loopbacked::DeviceLimits::Range(1, 3, None), test_empty);
    }

    #[test]
    pub fn real_test_device_empty() {
        real::test_with_spec(real::DeviceLimits::AtLeast(1, None, None), test_empty);
    }
}
<|endoftext|>


<commit_before><commit_msg>Commit the missing db.rs file.<commit_after><|endoftext|>


<commit_before><commit_msg>Add Vulkan event support<commit_after><|endoftext|>