<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
//!
//! To access a single element of a tuple one can use the following
//! methods:
//!
//! * `valN` - returns a value of _N_-th element
//! * `refN` - returns a reference to _N_-th element
//! * `mutN` - returns a mutable reference to _N_-th element
//!
//! Indexing starts from zero, so `val0` returns first value, `val1`
//! returns second value, and so on. In general, a tuple with _S_
//! elements provides aforementioned methods suffixed with numbers
//! from `0` to `S-1`. Traits which contain these methods are
//! implemented for tuples with up to 12 elements.
//!
//! If every type inside a tuple implements one of the following
//! traits, then a tuple itself also implements it.
//!
//! * `Clone`
//! * `PartialEq`
//! * `Eq`
//! * `PartialOrd`
//! * `Ord`
//! * `Default`
//!
//! # Examples
//!
//! Using methods:
//!
//! ```
//! let pair = ("pi", 3.14f64);
//! assert_eq!(pair.val0(), "pi");
//! assert_eq!(pair.val1(), 3.14f64);
//! ```
//!
//! Using traits implemented for tuples:
//!
//! ```
//! use std::default::Default;
//!
//! let a = (1i, 2i);
//! let b = (3i, 4i);
//! assert!(a != b);
//!
//! let c = b.clone();
//! assert!(b == c);
//!
//! let d : (u32, f32) = Default::default();
//! assert_eq!(d, (0u32, 0.0f32));
//! ```

#![doc(primitive = "tuple")]
#![stable]

#[unstable = "this is just a documentation module and should not be part \
              of the public api"]
pub use unit;

use clone::Clone;
use cmp::*;
use default::Default;
use option::Option;
use option::Option::Some;

// FIXME(#19630) Remove this work-around
macro_rules! e {
    ($e:expr) => { $e }
}

// macro for implementing n-ary tuple functions and operations
macro_rules! tuple_impls {
    ($(
        $Tuple:ident {
            $(($valN:ident, $refN:ident, $mutN:ident, $idx:tt) -> $T:ident)+
        }
    )+) => {
        $(
            #[allow(missing_docs)]
            #[deprecated]
            pub trait $Tuple<$($T),+> {
                $(
                    #[deprecated = "use tuple indexing: `tuple.N`"]
                    fn $valN(self) -> $T;
                    #[deprecated = "use tuple indexing: `&tuple.N`"]
                    fn $refN<'a>(&'a self) -> &'a $T;
                    #[deprecated = "use tuple indexing: `&mut tuple.N`"]
                    fn $mutN<'a>(&'a mut self) -> &'a mut $T;
                 )+
            }

            impl<$($T),+> $Tuple<$($T),+> for ($($T,)+) {
                $(
                    #[inline]
                    #[allow(unused_variables)]
                    #[deprecated = "use tuple indexing: `tuple.N`"]
                    fn $valN(self) -> $T {
                        e!(self.$idx)
                    }

                    #[inline]
                    #[allow(unused_variables)]
                    #[deprecated = "use tuple indexing: `&tuple.N`"]
                    fn $refN<'a>(&'a self) -> &'a $T {
                        e!(&self.$idx)
                    }

                    #[inline]
                    #[allow(unused_variables)]
                    #[deprecated = "use tuple indexing: &mut tuple.N"]
                    fn $mutN<'a>(&'a mut self) -> &'a mut $T {
                        e!(&mut self.$idx)
                    }
                )+
            }

            #[unstable = "waiting for Clone to stabilize"]
            impl<$($T:Clone),+> Clone for ($($T,)+) {
                fn clone(&self) -> ($($T,)+) {
                    ($(e!(self.$idx.clone()),)+)
                }
            }

            #[unstable = "waiting for PartialEq to stabilize"]
            impl<$($T:PartialEq),+> PartialEq for ($($T,)+) {
                #[inline]
                fn eq(&self, other: &($($T,)+)) -> bool {
                    e!($(self.$idx == other.$idx)&&+)
                }
                #[inline]
                fn ne(&self, other: &($($T,)+)) -> bool {
                    e!($(self.$idx != other.$idx)||+)
                }
            }

            #[unstable = "waiting for Eq to stabilize"]
            impl<$($T:Eq),+> Eq for ($($T,)+) {}

            #[unstable = "waiting for PartialOrd to stabilize"]
            impl<$($T:PartialOrd + PartialEq),+> PartialOrd for ($($T,)+) {
                #[inline]
                fn partial_cmp(&self, other: &($($T,)+)) -> Option<Ordering> {
                    lexical_partial_cmp!($(self.$idx, other.$idx),+)
                }
                #[inline]
                fn lt(&self, other: &($($T,)+)) -> bool {
                    lexical_ord!(lt, $(self.$idx, other.$idx),+)
                }
                #[inline]
                fn le(&self, other: &($($T,)+)) -> bool {
                    lexical_ord!(le, $(self.$idx, other.$idx),+)
                }
                #[inline]
                fn ge(&self, other: &($($T,)+)) -> bool {
                    lexical_ord!(ge, $(self.$idx, other.$idx),+)
                }
                #[inline]
                fn gt(&self, other: &($($T,)+)) -> bool {
                    lexical_ord!(gt, $(self.$idx, other.$idx),+)
                }
            }

            #[unstable = "waiting for Ord to stabilize"]
            impl<$($T:Ord),+> Ord for ($($T,)+) {
                #[inline]
                fn cmp(&self, other: &($($T,)+)) -> Ordering {
                    lexical_cmp!($(self.$idx, other.$idx),+)
                }
            }

            #[stable]
            impl<$($T:Default),+> Default for ($($T,)+) {
                #[inline]
                fn default() -> ($($T,)+) {
                    ($({ let x: $T = Default::default(); x},)+)
                }
            }
        )+
    }
}

// Constructs an expression that performs a lexical ordering using method $rel.
// The values are interleaved, so the macro invocation for
// `(a1, a2, a3) < (b1, b2, b3)` would be `lexical_ord!(lt, a1, b1, a2, b2,
// a3, b3)` (and similarly for `lexical_cmp`)
macro_rules! lexical_ord {
    ($rel: ident, $a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => {
        if $a != $b { lexical_ord!($rel, $a, $b) }
        else { lexical_ord!($rel, $($rest_a, $rest_b),+) }
    };
    ($rel: ident, $a:expr, $b:expr) => { ($a) . $rel (& $b) };
}

macro_rules! lexical_partial_cmp {
    ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => {
        match ($a).partial_cmp(&$b) {
            Some(Equal) => lexical_partial_cmp!($($rest_a, $rest_b),+),
            ordering   => ordering
        }
    };
    ($a:expr, $b:expr) => { ($a).partial_cmp(&$b) };
}

macro_rules! lexical_cmp {
    ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => {
        match ($a).cmp(&$b) {
            Equal => lexical_cmp!($($rest_a, $rest_b),+),
            ordering   => ordering
        }
    };
    ($a:expr, $b:expr) => { ($a).cmp(&$b) };
}

tuple_impls! {
    Tuple1 {
        (val0, ref0, mut0, 0) -> A
    }
    Tuple2 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
    }
    Tuple3 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
    }
    Tuple4 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
    }
    Tuple5 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
    }
    Tuple6 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
    }
    Tuple7 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
    }
    Tuple8 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
    }
    Tuple9 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
        (val8, ref8, mut8, 8) -> I
    }
    Tuple10 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
        (val8, ref8, mut8, 8) -> I
        (val9, ref9, mut9, 9) -> J
    }
    Tuple11 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
        (val8, ref8, mut8, 8) -> I
        (val9, ref9, mut9, 9) -> J
        (val10, ref10, mut10, 10) -> K
    }
    Tuple12 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
        (val8, ref8, mut8, 8) -> I
        (val9, ref9, mut9, 9) -> J
        (val10, ref10, mut10, 10) -> K
        (val11, ref11, mut11, 11) -> L
    }
}

<commit_msg>libcore: allow deprecated `valN` methods on doc tests<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
//!
//! To access a single element of a tuple one can use the following
//! methods:
//!
//! * `valN` - returns a value of _N_-th element
//! * `refN` - returns a reference to _N_-th element
//! * `mutN` - returns a mutable reference to _N_-th element
//!
//! Indexing starts from zero, so `val0` returns first value, `val1`
//! returns second value, and so on. In general, a tuple with _S_
//! elements provides aforementioned methods suffixed with numbers
//! from `0` to `S-1`. Traits which contain these methods are
//! implemented for tuples with up to 12 elements.
//!
//! If every type inside a tuple implements one of the following
//! traits, then a tuple itself also implements it.
//!
//! * `Clone`
//! * `PartialEq`
//! * `Eq`
//! * `PartialOrd`
//! * `Ord`
//! * `Default`
//!
//! # Examples
//!
//! Using methods:
//!
//! ```
//! #[allow(deprecated)]
//! # fn main() {
//! let pair = ("pi", 3.14f64);
//! assert_eq!(pair.val0(), "pi");
//! assert_eq!(pair.val1(), 3.14f64);
//! # }
//! ```
//!
//! Using traits implemented for tuples:
//!
//! ```
//! use std::default::Default;
//!
//! let a = (1i, 2i);
//! let b = (3i, 4i);
//! assert!(a != b);
//!
//! let c = b.clone();
//! assert!(b == c);
//!
//! let d : (u32, f32) = Default::default();
//! assert_eq!(d, (0u32, 0.0f32));
//! ```

#![doc(primitive = "tuple")]
#![stable]

#[unstable = "this is just a documentation module and should not be part \
              of the public api"]
pub use unit;

use clone::Clone;
use cmp::*;
use default::Default;
use option::Option;
use option::Option::Some;

// FIXME(#19630) Remove this work-around
macro_rules! e {
    ($e:expr) => { $e }
}

// macro for implementing n-ary tuple functions and operations
macro_rules! tuple_impls {
    ($(
        $Tuple:ident {
            $(($valN:ident, $refN:ident, $mutN:ident, $idx:tt) -> $T:ident)+
        }
    )+) => {
        $(
            #[allow(missing_docs)]
            #[deprecated]
            pub trait $Tuple<$($T),+> {
                $(
                    #[deprecated = "use tuple indexing: `tuple.N`"]
                    fn $valN(self) -> $T;
                    #[deprecated = "use tuple indexing: `&tuple.N`"]
                    fn $refN<'a>(&'a self) -> &'a $T;
                    #[deprecated = "use tuple indexing: `&mut tuple.N`"]
                    fn $mutN<'a>(&'a mut self) -> &'a mut $T;
                 )+
            }

            impl<$($T),+> $Tuple<$($T),+> for ($($T,)+) {
                $(
                    #[inline]
                    #[allow(unused_variables)]
                    #[deprecated = "use tuple indexing: `tuple.N`"]
                    fn $valN(self) -> $T {
                        e!(self.$idx)
                    }

                    #[inline]
                    #[allow(unused_variables)]
                    #[deprecated = "use tuple indexing: `&tuple.N`"]
                    fn $refN<'a>(&'a self) -> &'a $T {
                        e!(&self.$idx)
                    }

                    #[inline]
                    #[allow(unused_variables)]
                    #[deprecated = "use tuple indexing: &mut tuple.N"]
                    fn $mutN<'a>(&'a mut self) -> &'a mut $T {
                        e!(&mut self.$idx)
                    }
                )+
            }

            #[unstable = "waiting for Clone to stabilize"]
            impl<$($T:Clone),+> Clone for ($($T,)+) {
                fn clone(&self) -> ($($T,)+) {
                    ($(e!(self.$idx.clone()),)+)
                }
            }

            #[unstable = "waiting for PartialEq to stabilize"]
            impl<$($T:PartialEq),+> PartialEq for ($($T,)+) {
                #[inline]
                fn eq(&self, other: &($($T,)+)) -> bool {
                    e!($(self.$idx == other.$idx)&&+)
                }
                #[inline]
                fn ne(&self, other: &($($T,)+)) -> bool {
                    e!($(self.$idx != other.$idx)||+)
                }
            }

            #[unstable = "waiting for Eq to stabilize"]
            impl<$($T:Eq),+> Eq for ($($T,)+) {}

            #[unstable = "waiting for PartialOrd to stabilize"]
            impl<$($T:PartialOrd + PartialEq),+> PartialOrd for ($($T,)+) {
                #[inline]
                fn partial_cmp(&self, other: &($($T,)+)) -> Option<Ordering> {
                    lexical_partial_cmp!($(self.$idx, other.$idx),+)
                }
                #[inline]
                fn lt(&self, other: &($($T,)+)) -> bool {
                    lexical_ord!(lt, $(self.$idx, other.$idx),+)
                }
                #[inline]
                fn le(&self, other: &($($T,)+)) -> bool {
                    lexical_ord!(le, $(self.$idx, other.$idx),+)
                }
                #[inline]
                fn ge(&self, other: &($($T,)+)) -> bool {
                    lexical_ord!(ge, $(self.$idx, other.$idx),+)
                }
                #[inline]
                fn gt(&self, other: &($($T,)+)) -> bool {
                    lexical_ord!(gt, $(self.$idx, other.$idx),+)
                }
            }

            #[unstable = "waiting for Ord to stabilize"]
            impl<$($T:Ord),+> Ord for ($($T,)+) {
                #[inline]
                fn cmp(&self, other: &($($T,)+)) -> Ordering {
                    lexical_cmp!($(self.$idx, other.$idx),+)
                }
            }

            #[stable]
            impl<$($T:Default),+> Default for ($($T,)+) {
                #[inline]
                fn default() -> ($($T,)+) {
                    ($({ let x: $T = Default::default(); x},)+)
                }
            }
        )+
    }
}

// Constructs an expression that performs a lexical ordering using method $rel.
// The values are interleaved, so the macro invocation for
// `(a1, a2, a3) < (b1, b2, b3)` would be `lexical_ord!(lt, a1, b1, a2, b2,
// a3, b3)` (and similarly for `lexical_cmp`)
macro_rules! lexical_ord {
    ($rel: ident, $a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => {
        if $a != $b { lexical_ord!($rel, $a, $b) }
        else { lexical_ord!($rel, $($rest_a, $rest_b),+) }
    };
    ($rel: ident, $a:expr, $b:expr) => { ($a) . $rel (& $b) };
}

macro_rules! lexical_partial_cmp {
    ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => {
        match ($a).partial_cmp(&$b) {
            Some(Equal) => lexical_partial_cmp!($($rest_a, $rest_b),+),
            ordering   => ordering
        }
    };
    ($a:expr, $b:expr) => { ($a).partial_cmp(&$b) };
}

macro_rules! lexical_cmp {
    ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => {
        match ($a).cmp(&$b) {
            Equal => lexical_cmp!($($rest_a, $rest_b),+),
            ordering   => ordering
        }
    };
    ($a:expr, $b:expr) => { ($a).cmp(&$b) };
}

tuple_impls! {
    Tuple1 {
        (val0, ref0, mut0, 0) -> A
    }
    Tuple2 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
    }
    Tuple3 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
    }
    Tuple4 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
    }
    Tuple5 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
    }
    Tuple6 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
    }
    Tuple7 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
    }
    Tuple8 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
    }
    Tuple9 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
        (val8, ref8, mut8, 8) -> I
    }
    Tuple10 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
        (val8, ref8, mut8, 8) -> I
        (val9, ref9, mut9, 9) -> J
    }
    Tuple11 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
        (val8, ref8, mut8, 8) -> I
        (val9, ref9, mut9, 9) -> J
        (val10, ref10, mut10, 10) -> K
    }
    Tuple12 {
        (val0, ref0, mut0, 0) -> A
        (val1, ref1, mut1, 1) -> B
        (val2, ref2, mut2, 2) -> C
        (val3, ref3, mut3, 3) -> D
        (val4, ref4, mut4, 4) -> E
        (val5, ref5, mut5, 5) -> F
        (val6, ref6, mut6, 6) -> G
        (val7, ref7, mut7, 7) -> H
        (val8, ref8, mut8, 8) -> I
        (val9, ref9, mut9, 9) -> J
        (val10, ref10, mut10, 10) -> K
        (val11, ref11, mut11, 11) -> L
    }
}

<|endoftext|>


<commit_before><commit_msg>impl Deserialize for m.room.power_levels<commit_after><|endoftext|>


<commit_before>#[doc = "Prunes branches of the document tree that contain no documentation"];

export mk_pass;

fn mk_pass() -> pass {
    run
}

type ctxt = {
    mutable have_docs: bool
};

fn run(
    _srv: astsrv::srv,
    doc: doc::cratedoc
) -> doc::cratedoc {
    let ctxt = {
        mutable have_docs: true
    };
    let fold = fold::fold({
        fold_mod: fold_mod,
        fold_fn: fold_fn,
        fold_const: fold_const,
        fold_enum: fold_enum,
        fold_res: fold_res
        with *fold::default_seq_fold(ctxt)
    });
    fold.fold_crate(fold, doc)
}

fn fold_mod(
    fold: fold::fold<ctxt>,
    doc: doc::moddoc
) -> doc::moddoc {
    let doc = {
        items: ~vec::filter_map(*doc.items) {|itemtag|
            alt itemtag {
              doc::modtag(moddoc) {
                let doc = fold.fold_mod(fold, moddoc);
                if fold.ctxt.have_docs {
                    some(doc::modtag(doc))
                } else {
                    none
                }
              }
              doc::fntag(fndoc) {
                let doc = fold.fold_fn(fold, fndoc);
                if fold.ctxt.have_docs {
                    some(doc::fntag(doc))
                } else {
                    none
                }
              }
              doc::consttag(constdoc) {
                let doc = fold.fold_const(fold, constdoc);
                if fold.ctxt.have_docs {
                    some(doc::consttag(doc))
                } else {
                    none
                }
              }
              doc::enumtag(enumdoc) {
                let doc = fold.fold_enum(fold, enumdoc);
                if fold.ctxt.have_docs {
                    some(doc::enumtag(doc))
                } else {
                    none
                }
              }
              doc::restag(resdoc) {
                let doc = fold.fold_res(fold, resdoc);
                if fold.ctxt.have_docs {
                    some(doc::restag(doc))
                } else {
                    none
                }
              }
              _ { some(itemtag) }
            }
        }
        with fold::default_seq_fold_mod(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(*doc.items);
    ret doc;
}

fn fold_fn(
    fold: fold::fold<ctxt>,
    doc: doc::fndoc
) -> doc::fndoc {
    let have_arg_docs = false;
    let doc = {
        args: vec::filter_map(doc.args) {|doc|
            if option::is_some(doc.desc) {
                have_arg_docs = true;
                some(doc)
            } else {
                none
            }
        },
        return: {
            ty: if option::is_some(doc.return.desc) {
                doc.return.ty
            } else {
                none
            }
            with doc.return
        }
        with doc
    };

    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || have_arg_docs
        || doc.return.desc != none
        || doc.failure != none;
    ret doc;
}

#[test]
fn should_elide_undocumented_arguments() {
    let source = "#[doc = \"hey\"] fn a(b: int) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.fns()[0].args);
}

#[test]
fn should_not_elide_fns_with_documented_arguments() {
    let source = "#[doc(args(a = \"b\"))] fn a(a: int) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.fns());
}

#[test]
fn should_elide_undocumented_return_values() {
    let source = "#[doc = \"fonz\"] fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = tystr_pass::mk_pass()(srv, doc);
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert doc.topmod.fns()[0].return.ty == none;
}

#[test]
fn should_not_elide_fns_with_documented_failure_conditions() {
    let source = "#[doc(failure = \"yup\")] fn a() { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.fns());
}

#[test]
fn should_elide_undocumented_mods() {
    let source = "mod a { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.mods());
}

#[test]
fn should_not_elide_undocument_mods_with_documented_mods() {
    let source = "mod a { #[doc = \"b\"] mod b { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.mods());
}

#[test]
fn should_not_elide_undocument_mods_with_documented_fns() {
    let source = "mod a { #[doc = \"b\"] fn b() { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.mods());
}

#[test]
fn should_elide_undocumented_fns() {
    let source = "fn a() { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.fns());
}

fn fold_const(
    fold: fold::fold<ctxt>,
    doc: doc::constdoc
) -> doc::constdoc {
    let doc = fold::default_seq_fold_const(fold, doc);
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none;
    ret doc;
}

#[test]
fn should_elide_undocumented_consts() {
    let source = "const a: bool = true;";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.consts());
}

fn fold_enum(fold: fold::fold<ctxt>, doc: doc::enumdoc) -> doc::enumdoc {
    let doc = {
        variants: vec::filter_map(doc.variants) {|variant|
            if variant.desc != none {
                some(variant)
            } else {
                none
            }
        }
        with fold::default_seq_fold_enum(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.variants);
    ret doc;
}

#[test]
fn should_elide_undocumented_enums() {
    let source = "enum a { b }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.enums());
}

#[test]
fn should_elide_undocumented_variants() {
    let source = "#[doc = \"a\"] enum a { b }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.enums()[0].variants);
}

#[test]
fn should_not_elide_enums_with_documented_variants() {
    let source = "enum a { #[doc = \"a\"] b }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.enums());
}

fn fold_res(fold: fold::fold<ctxt>, doc: doc::resdoc) -> doc::resdoc {
    let doc = {
        args: vec::filter_map(doc.args) {|arg|
            if arg.desc != none {
                some(arg)
            } else {
                none
            }
        }
        with fold::default_seq_fold_res(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.args);
    ret doc;
}

#[test]
fn should_elide_undocumented_resources() {
    let source = "resource r(a: bool) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.resources());
}

#[test]
fn should_elide_undocumented_resource_args() {
    let source = "#[doc = \"drunk\"]\
                  resource r(a: bool) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.resources()[0].args);
}

#[test]
fn should_not_elide_resources_with_documented_args() {
    let source = "#[doc(args(a = \"drunk\"))]\
                  resource r(a: bool) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.resources());
}
<commit_msg>rustdoc: Prune undocumented ifaces<commit_after>#[doc = "Prunes branches of the document tree that contain no documentation"];

export mk_pass;

fn mk_pass() -> pass {
    run
}

type ctxt = {
    mutable have_docs: bool
};

fn run(
    _srv: astsrv::srv,
    doc: doc::cratedoc
) -> doc::cratedoc {
    let ctxt = {
        mutable have_docs: true
    };
    let fold = fold::fold({
        fold_mod: fold_mod,
        fold_fn: fold_fn,
        fold_const: fold_const,
        fold_enum: fold_enum,
        fold_res: fold_res,
        fold_iface: fold_iface
        with *fold::default_seq_fold(ctxt)
    });
    fold.fold_crate(fold, doc)
}

fn fold_mod(
    fold: fold::fold<ctxt>,
    doc: doc::moddoc
) -> doc::moddoc {
    let doc = {
        items: ~vec::filter_map(*doc.items) {|itemtag|
            alt itemtag {
              doc::modtag(moddoc) {
                let doc = fold.fold_mod(fold, moddoc);
                if fold.ctxt.have_docs {
                    some(doc::modtag(doc))
                } else {
                    none
                }
              }
              doc::fntag(fndoc) {
                let doc = fold.fold_fn(fold, fndoc);
                if fold.ctxt.have_docs {
                    some(doc::fntag(doc))
                } else {
                    none
                }
              }
              doc::consttag(constdoc) {
                let doc = fold.fold_const(fold, constdoc);
                if fold.ctxt.have_docs {
                    some(doc::consttag(doc))
                } else {
                    none
                }
              }
              doc::enumtag(enumdoc) {
                let doc = fold.fold_enum(fold, enumdoc);
                if fold.ctxt.have_docs {
                    some(doc::enumtag(doc))
                } else {
                    none
                }
              }
              doc::restag(resdoc) {
                let doc = fold.fold_res(fold, resdoc);
                if fold.ctxt.have_docs {
                    some(doc::restag(doc))
                } else {
                    none
                }
              }
              doc::ifacetag(ifacedoc) {
                let doc = fold.fold_iface(fold, ifacedoc);
                if fold.ctxt.have_docs {
                    some(doc::ifacetag(doc))
                } else {
                    none
                }
              }
              _ { some(itemtag) }
            }
        }
        with fold::default_seq_fold_mod(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(*doc.items);
    ret doc;
}

fn fold_fn(
    fold: fold::fold<ctxt>,
    doc: doc::fndoc
) -> doc::fndoc {
    let doc = {
        args: prune_args(doc.args),
        return: prune_return(doc.return)
        with doc
    };

    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.args)
        || doc.return.desc != none
        || doc.failure != none;
    ret doc;
}

fn prune_args(docs: [doc::argdoc]) -> [doc::argdoc] {
    vec::filter_map(docs) {|doc|
        if option::is_some(doc.desc) {
            some(doc)
        } else {
            none
        }
    }
}

fn prune_return(doc: doc::retdoc) -> doc::retdoc {
    {
        ty: if option::is_some(doc.desc) {
            doc.ty
        } else {
            none
        }
        with doc
    }
}

#[test]
fn should_elide_undocumented_arguments() {
    let source = "#[doc = \"hey\"] fn a(b: int) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.fns()[0].args);
}

#[test]
fn should_not_elide_fns_with_documented_arguments() {
    let source = "#[doc(args(a = \"b\"))] fn a(a: int) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.fns());
}

#[test]
fn should_elide_undocumented_return_values() {
    let source = "#[doc = \"fonz\"] fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = tystr_pass::mk_pass()(srv, doc);
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert doc.topmod.fns()[0].return.ty == none;
}

#[test]
fn should_not_elide_fns_with_documented_failure_conditions() {
    let source = "#[doc(failure = \"yup\")] fn a() { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.fns());
}

#[test]
fn should_elide_undocumented_mods() {
    let source = "mod a { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.mods());
}

#[test]
fn should_not_elide_undocument_mods_with_documented_mods() {
    let source = "mod a { #[doc = \"b\"] mod b { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.mods());
}

#[test]
fn should_not_elide_undocument_mods_with_documented_fns() {
    let source = "mod a { #[doc = \"b\"] fn b() { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.mods());
}

#[test]
fn should_elide_undocumented_fns() {
    let source = "fn a() { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.fns());
}

fn fold_const(
    fold: fold::fold<ctxt>,
    doc: doc::constdoc
) -> doc::constdoc {
    let doc = fold::default_seq_fold_const(fold, doc);
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none;
    ret doc;
}

#[test]
fn should_elide_undocumented_consts() {
    let source = "const a: bool = true;";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.consts());
}

fn fold_enum(fold: fold::fold<ctxt>, doc: doc::enumdoc) -> doc::enumdoc {
    let doc = {
        variants: vec::filter_map(doc.variants) {|variant|
            if variant.desc != none {
                some(variant)
            } else {
                none
            }
        }
        with fold::default_seq_fold_enum(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.variants);
    ret doc;
}

#[test]
fn should_elide_undocumented_enums() {
    let source = "enum a { b }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.enums());
}

#[test]
fn should_elide_undocumented_variants() {
    let source = "#[doc = \"a\"] enum a { b }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.enums()[0].variants);
}

#[test]
fn should_not_elide_enums_with_documented_variants() {
    let source = "enum a { #[doc = \"a\"] b }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.enums());
}

fn fold_res(fold: fold::fold<ctxt>, doc: doc::resdoc) -> doc::resdoc {
    let doc = {
        args: vec::filter_map(doc.args) {|arg|
            if arg.desc != none {
                some(arg)
            } else {
                none
            }
        }
        with fold::default_seq_fold_res(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.args);
    ret doc;
}

#[test]
fn should_elide_undocumented_resources() {
    let source = "resource r(a: bool) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.resources());
}

#[test]
fn should_elide_undocumented_resource_args() {
    let source = "#[doc = \"drunk\"]\
                  resource r(a: bool) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.resources()[0].args);
}

#[test]
fn should_not_elide_resources_with_documented_args() {
    let source = "#[doc(args(a = \"drunk\"))]\
                  resource r(a: bool) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.resources());
}

fn fold_iface(
    fold: fold::fold<ctxt>,
    doc: doc::ifacedoc
) -> doc::ifacedoc {
    let doc = fold::default_seq_fold_iface(fold, doc);
    let doc = {
        methods: vec::map(doc.methods) {|doc|
            {
                args: prune_args(doc.args),
                return: prune_return(doc.return)
                with doc
            }
        }
        with doc
    };
    let methods_have_docs = vec::foldl(false, doc.methods) {|accum, doc|
        accum
            || doc.brief != none
            || doc.desc != none
            || vec::is_not_empty(doc.args)
            || doc.return.desc != none
            || doc.failure != none
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || methods_have_docs;
    ret doc;
}

#[test]
fn should_elide_undocumented_ifaces() {
    let source = "iface i { fn a(); }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.ifaces());
}

#[test]
fn should_not_elide_documented_ifaces() {
    let source = "#[doc = \"hey\"] iface i { fn a(); }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.ifaces());
}

#[test]
fn should_not_elide_ifaces_with_documented_methods() {
    let source = "iface i { #[doc = \"hey\"] fn a(); }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.ifaces());
}

#[test]
fn should_not_elide_undocumented_methods() {
    let source = "#[doc = \"hey\"] iface i { fn a(); }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(doc.topmod.ifaces()[0].methods);
}

#[test]
fn should_elide_undocumented_method_args() {
    let source = "#[doc = \"hey\"] iface i { fn a(); }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.ifaces()[0].methods[0].args);
}

#[test]
fn should_elide_undocumented_method_return_values() {
    let source = "#[doc = \"hey\"] iface i { fn a() -> int; }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert doc.topmod.ifaces()[0].methods[0].return.ty == none;
}<|endoftext|>


<commit_before><commit_msg>feat: Subscribe to colored logs<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test for issue 34571<commit_after>// Copyright 2017 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.

#[repr(u8)]
enum Foo {
    Foo(u8),
}

fn main() {
    match Foo::Foo(1) {
        _ => ()
    }
}
<|endoftext|>


<commit_before>

/* -*- mode: rust; indent-tabs-mode: nil -*-
 * Implementation of 'fasta' benchmark from
 * Computer Language Benchmarks Game
 * http://shootout.alioth.debian.org/
 */
use std;
import std::vec;
import std::str;
import std::uint;
import std::int;

fn LINE_LENGTH() -> uint { ret 60u; }

obj myrandom(mutable u32 last) {
    fn next(u32 mx) -> u32 {
        last = (last * 3877u32 + 29573u32) % 139968u32;
        auto ans = mx * last / 139968u32;
        ret ans;
    }
}

type aminoacids = rec(char ch, u32 prob);

fn make_cumulative(vec[aminoacids] aa) -> vec[aminoacids] {
    let u32 cp = 0u32;
    let vec[aminoacids] ans = [];
    for (aminoacids a in aa) { cp += a.prob; ans += [rec(ch=a.ch, prob=cp)]; }
    ret ans;
}

fn select_random(u32 r, vec[aminoacids] genelist) -> char {
    if (r < genelist.(0).prob) { ret genelist.(0).ch; }
    fn bisect(vec[aminoacids] v, uint lo, uint hi, u32 target) -> char {
        if (hi > lo + 1u) {
            let uint mid = lo + (hi - lo) / 2u;
            if (target < v.(mid).prob) {
                be bisect(v, lo, mid, target);
            } else { be bisect(v, mid, hi, target); }
        } else { ret v.(hi).ch; }
    }
    ret bisect(genelist, 0u, vec::len[aminoacids](genelist) - 1u, r);
}

fn make_random_fasta(str id, str desc, vec[aminoacids] genelist, int n) {
    log ">" + id + " " + desc;
    auto rng = myrandom(std::rand::mk_rng().next());
    let str op = "";
    for each (uint i in uint::range(0u, n as uint)) {
        str::push_byte(op, select_random(rng.next(100u32), genelist) as u8);
        if (str::byte_len(op) >= LINE_LENGTH()) { log op; op = ""; }
    }
    if (str::byte_len(op) > 0u) { log op; }
}

fn make_repeat_fasta(str id, str desc, str s, int n) {
    log ">" + id + " " + desc;
    let str op = "";
    let uint sl = str::byte_len(s);
    for each (uint i in uint::range(0u, n as uint)) {
        str::push_byte(op, s.(i % sl));
        if (str::byte_len(op) >= LINE_LENGTH()) { log op; op = ""; }
    }
    if (str::byte_len(op) > 0u) { log op; }
}

fn acid(char ch, u32 prob) { ret rec(ch=ch, prob=prob); }

fn main(vec[str] args) {
    let vec[aminoacids] iub =
        make_cumulative([acid('a', 27u32), acid('c', 12u32), acid('g', 12u32),
                         acid('t', 27u32), acid('B', 2u32), acid('D', 2u32),
                         acid('H', 2u32), acid('K', 2u32), acid('M', 2u32),
                         acid('N', 2u32), acid('R', 2u32), acid('S', 2u32),
                         acid('V', 2u32), acid('W', 2u32), acid('Y', 2u32)]);
    let vec[aminoacids] homosapiens =
        make_cumulative([acid('a', 30u32), acid('c', 20u32), acid('g', 20u32),
                         acid('t', 30u32)]);
    let str alu =
        "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" +
            "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" +
            "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" +
            "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" +
            "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" +
            "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" +
            "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
    let int n = 512;
    make_repeat_fasta("ONE", "Homo sapiens alu", alu, n * 2);
    make_random_fasta("TWO", "IUB ambiguity codes", iub, n * 3);
    make_random_fasta("THREE", "Homo sapiens frequency", homosapiens, n * 5);
}<commit_msg>Fixup test changes<commit_after>

/* -*- mode: rust; indent-tabs-mode: nil -*-
 * Implementation of 'fasta' benchmark from
 * Computer Language Benchmarks Game
 * http://shootout.alioth.debian.org/
 */
use std;
import std::vec;
import std::str;
import std::uint;
import std::int;

fn LINE_LENGTH() -> uint { ret 60u; }

obj myrandom(mutable u32 last) {
    fn next(u32 mx) -> u32 {
        last = (last * 3877u32 + 29573u32) % 139968u32;
        auto ans = mx * last / 139968u32;
        ret ans;
    }
}

type aminoacids = rec(char ch, u32 prob);

fn make_cumulative(vec[aminoacids] aa) -> vec[aminoacids] {
    let u32 cp = 0u32;
    let vec[aminoacids] ans = [];
    for (aminoacids a in aa) { cp += a.prob; ans += [rec(ch=a.ch, prob=cp)]; }
    ret ans;
}

fn select_random(u32 r, vec[aminoacids] genelist) -> char {
    if (r < genelist.(0).prob) { ret genelist.(0).ch; }
    fn bisect(vec[aminoacids] v, uint lo, uint hi, u32 target) -> char {
        if (hi > lo + 1u) {
            let uint mid = lo + (hi - lo) / 2u;
            if (target < v.(mid).prob) {
                be bisect(v, lo, mid, target);
            } else { be bisect(v, mid, hi, target); }
        } else { ret v.(hi).ch; }
    }
    ret bisect(genelist, 0u, vec::len[aminoacids](genelist) - 1u, r);
}

fn make_random_fasta(str id, str desc, vec[aminoacids] genelist, int n) {
    log ">" + id + " " + desc;
    auto rng = myrandom(std::rand::mk_rng().next());
    let str op = "";
    for each (uint i in uint::range(0u, n as uint)) {
        str::push_byte(op, select_random(rng.next(100u32), genelist) as u8);
        if (str::byte_len(op) >= LINE_LENGTH()) { log op; op = ""; }
    }
    if (str::byte_len(op) > 0u) { log op; }
}

fn make_repeat_fasta(str id, str desc, str s, int n) {
    log ">" + id + " " + desc;
    let str op = "";
    let uint sl = str::byte_len(s);
    for each (uint i in uint::range(0u, n as uint)) {
        str::push_byte(op, s.(i % sl));
        if (str::byte_len(op) >= LINE_LENGTH()) { log op; op = ""; }
    }
    if (str::byte_len(op) > 0u) { log op; }
}

fn acid(char ch, u32 prob) -> aminoacids { ret rec(ch=ch, prob=prob); }

fn main(vec[str] args) {
    let vec[aminoacids] iub =
        make_cumulative([acid('a', 27u32), acid('c', 12u32), acid('g', 12u32),
                         acid('t', 27u32), acid('B', 2u32), acid('D', 2u32),
                         acid('H', 2u32), acid('K', 2u32), acid('M', 2u32),
                         acid('N', 2u32), acid('R', 2u32), acid('S', 2u32),
                         acid('V', 2u32), acid('W', 2u32), acid('Y', 2u32)]);
    let vec[aminoacids] homosapiens =
        make_cumulative([acid('a', 30u32), acid('c', 20u32), acid('g', 20u32),
                         acid('t', 30u32)]);
    let str alu =
        "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" +
            "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" +
            "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" +
            "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" +
            "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" +
            "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" +
            "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA";
    let int n = 512;
    make_repeat_fasta("ONE", "Homo sapiens alu", alu, n * 2);
    make_random_fasta("TWO", "IUB ambiguity codes", iub, n * 3);
    make_random_fasta("THREE", "Homo sapiens frequency", homosapiens, n * 5);
}<|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;
use std::io::{Seek, Write, SeekFrom};
use std::fs::OpenOptions;
use std::os::linux::fs::MetadataExt;
use std::os::unix::prelude::AsRawFd;
use std::path::Path;

use nix::sys::stat::{S_IFBLK, S_IFMT};

use devicemapper::consts::SECTOR_SIZE;
use devicemapper::{Bytes, Device, Sectors};

use super::super::errors::{EngineResult, EngineError, ErrorEnum};

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

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

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

/// Write buf at offset length times.
pub fn write_sectors<P: AsRef<Path>>(path: P,
                                     offset: Sectors,
                                     length: Sectors,
                                     buf: &[u8; SECTOR_SIZE])
                                     -> EngineResult<()> {
    let mut f = OpenOptions::new().write(true).open(path)?;

    f.seek(SeekFrom::Start(*offset))?;
    for _ in 0..*length {
        f.write_all(buf)?;
    }

    f.flush()?;
    Ok(())
}

/// Zero sectors at the given offset for length sectors.
pub fn wipe_sectors<P: AsRef<Path>>(path: P, offset: Sectors, length: Sectors) -> EngineResult<()> {
    write_sectors(path, offset, length, &[0u8; SECTOR_SIZE])
}

/// Get a device number from a device node.
/// Return None if the device is not a block device; devicemapper is not
/// interested in other sorts of devices.
pub fn devnode_to_devno(path: &Path) -> EngineResult<Option<u64>> {
    match path.metadata() {
        Ok(metadata) => {
            Ok(if metadata.st_mode() & S_IFMT.bits() == S_IFBLK.bits() {
                   Some(metadata.st_rdev())
               } else {
                   None
               })
        }
        Err(err) => Err(err)?,
    }
}

/// 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]) -> EngineResult<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(EngineError::Engine(ErrorEnum::Invalid, err_msg.into()));
            }
        }
    }
    Ok(map)
}
<commit_msg>Make write_sectors() faster by using BufWriter<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;
use std::io::{BufWriter, Seek, Write, SeekFrom};
use std::fs::OpenOptions;
use std::os::linux::fs::MetadataExt;
use std::os::unix::prelude::AsRawFd;
use std::path::Path;

use nix::sys::stat::{S_IFBLK, S_IFMT};

use devicemapper::consts::SECTOR_SIZE;
use devicemapper::{Bytes, Device, Sectors};

use super::super::consts::IEC;
use super::super::errors::{EngineResult, EngineError, ErrorEnum};

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

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

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

/// Write buf at offset length times.
pub fn write_sectors<P: AsRef<Path>>(path: P,
                                     offset: Sectors,
                                     length: Sectors,
                                     buf: &[u8; SECTOR_SIZE])
                                     -> EngineResult<()> {
    let mut f = BufWriter::with_capacity(IEC::Mi as usize,
                                         OpenOptions::new().write(true).open(path)?);

    f.seek(SeekFrom::Start(*offset))?;
    for _ in 0..*length {
        f.write_all(buf)?;
    }

    f.flush()?;
    Ok(())
}

/// Zero sectors at the given offset for length sectors.
pub fn wipe_sectors<P: AsRef<Path>>(path: P, offset: Sectors, length: Sectors) -> EngineResult<()> {
    write_sectors(path, offset, length, &[0u8; SECTOR_SIZE])
}

/// Get a device number from a device node.
/// Return None if the device is not a block device; devicemapper is not
/// interested in other sorts of devices.
pub fn devnode_to_devno(path: &Path) -> EngineResult<Option<u64>> {
    match path.metadata() {
        Ok(metadata) => {
            Ok(if metadata.st_mode() & S_IFMT.bits() == S_IFBLK.bits() {
                   Some(metadata.st_rdev())
               } else {
                   None
               })
        }
        Err(err) => Err(err)?,
    }
}

/// 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]) -> EngineResult<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(EngineError::Engine(ErrorEnum::Invalid, err_msg.into()));
            }
        }
    }
    Ok(map)
}
<|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::{Metadata, Payload, Done, LoadResponse, LoaderTask, start_sending};

use collections::hashmap::HashSet;
use http::client::{RequestWriter, NetworkStream};
use http::method::Get;
use http::headers::HeaderEnum;
use std::io::Reader;
use std::slice;
use servo_util::task::spawn_named;
use url::Url;

pub fn factory() -> LoaderTask {
    let f: LoaderTask = proc(url, start_chan) {
        spawn_named("http_loader", proc() load(url, start_chan))
    };
    f
}

fn send_error(url: Url, err: ~str, start_chan: Sender<LoadResponse>) {
    start_sending(start_chan, Metadata::default(url)).send(Done(Err(err)));
}

fn load(mut url: Url, start_chan: Sender<LoadResponse>) {
    // FIXME: At the time of writing this FIXME, servo didn't have any central
    //        location for configuration. If you're reading this and such a
    //        repository DOES exist, please update this constant to use it.
    let max_redirects = 50u;
    let mut iters = 0u;

    let mut redirected_to = HashSet::new();

    // Loop to handle redirects.
    loop {
        iters = iters + 1;

        if iters > max_redirects {
            send_error(url, "too many redirects".to_owned(), start_chan);
            return;
        }

        if redirected_to.contains(&url) {
            send_error(url, "redirect loop".to_owned(), start_chan);
            return;
        }

        redirected_to.insert(url.clone());

        if "http" != url.scheme {
            let s = format!("{:s} request, but we don't support that scheme", url.scheme);
            send_error(url, s, start_chan);
            return;
        }

        info!("requesting {:s}", url.to_str());

        let request = RequestWriter::<NetworkStream>::new(Get, url.clone());
        let writer = match request {
            Ok(w) => ~w,
            Err(e) => {
                send_error(url, e.desc.to_owned(), start_chan);
                return;
            }
        };
        let mut response = match writer.read_response() {
            Ok(r) => r,
            Err((_, e)) => {
                send_error(url, e.desc.to_owned(), start_chan);
                return;
            }
        };

        // Dump headers, but only do the iteration if info!() is enabled.
        info!("got HTTP response {:s}, headers:", response.status.to_str());
        info!("{:?}",
            for header in response.headers.iter() {
                info!(" - {:s}: {:s}", header.header_name(), header.header_value());
            });

        if 3 == (response.status.code() / 100) {
            match response.headers.location {
                Some(new_url) => {
                    info!("redirecting to {:s}", new_url.to_str());
                    url = new_url;
                    continue;
                }
                None => ()
            }
        }

        let mut metadata = Metadata::default(url);
        metadata.set_content_type(&response.headers.content_type);

        let progress_chan = start_sending(start_chan, metadata);
        loop {
            let mut buf = slice::with_capacity(1024);

            unsafe { buf.set_len(1024); }
            match response.read(buf) {
                Ok(len) => {
                    unsafe { buf.set_len(len); }
                    let buf: ~[u8] = buf;
                    progress_chan.send(Payload(buf.move_iter().collect()));
                }
                Err(_) => {
                    progress_chan.send(Done(Ok(())));
                    break;
                }
            }
        }

        // We didn't get redirected.
        break;
    }
}
<commit_msg>auto merge of #2406 : Ms2ger/servo/http_loader-load, r=jdm<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::{Metadata, Payload, Done, LoadResponse, LoaderTask, start_sending};

use collections::hashmap::HashSet;
use http::client::{RequestWriter, NetworkStream};
use http::method::Get;
use http::headers::HeaderEnum;
use std::io::Reader;
use servo_util::task::spawn_named;
use url::Url;

pub fn factory() -> LoaderTask {
    let f: LoaderTask = proc(url, start_chan) {
        spawn_named("http_loader", proc() load(url, start_chan))
    };
    f
}

fn send_error(url: Url, err: ~str, start_chan: Sender<LoadResponse>) {
    start_sending(start_chan, Metadata::default(url)).send(Done(Err(err)));
}

fn load(mut url: Url, start_chan: Sender<LoadResponse>) {
    // FIXME: At the time of writing this FIXME, servo didn't have any central
    //        location for configuration. If you're reading this and such a
    //        repository DOES exist, please update this constant to use it.
    let max_redirects = 50u;
    let mut iters = 0u;

    let mut redirected_to = HashSet::new();

    // Loop to handle redirects.
    loop {
        iters = iters + 1;

        if iters > max_redirects {
            send_error(url, "too many redirects".to_owned(), start_chan);
            return;
        }

        if redirected_to.contains(&url) {
            send_error(url, "redirect loop".to_owned(), start_chan);
            return;
        }

        redirected_to.insert(url.clone());

        if "http" != url.scheme {
            let s = format!("{:s} request, but we don't support that scheme", url.scheme);
            send_error(url, s, start_chan);
            return;
        }

        info!("requesting {:s}", url.to_str());

        let request = RequestWriter::<NetworkStream>::new(Get, url.clone());
        let writer = match request {
            Ok(w) => ~w,
            Err(e) => {
                send_error(url, e.desc.to_owned(), start_chan);
                return;
            }
        };
        let mut response = match writer.read_response() {
            Ok(r) => r,
            Err((_, e)) => {
                send_error(url, e.desc.to_owned(), start_chan);
                return;
            }
        };

        // Dump headers, but only do the iteration if info!() is enabled.
        info!("got HTTP response {:s}, headers:", response.status.to_str());
        info!("{:?}",
            for header in response.headers.iter() {
                info!(" - {:s}: {:s}", header.header_name(), header.header_value());
            });

        if 3 == (response.status.code() / 100) {
            match response.headers.location {
                Some(new_url) => {
                    info!("redirecting to {:s}", new_url.to_str());
                    url = new_url;
                    continue;
                }
                None => ()
            }
        }

        let mut metadata = Metadata::default(url);
        metadata.set_content_type(&response.headers.content_type);

        let progress_chan = start_sending(start_chan, metadata);
        loop {
            let mut buf = Vec::with_capacity(1024);

            unsafe { buf.set_len(1024); }
            match response.read(buf.as_mut_slice()) {
                Ok(len) => {
                    unsafe { buf.set_len(len); }
                    progress_chan.send(Payload(buf));
                }
                Err(_) => {
                    progress_chan.send(Done(Ok(())));
                    break;
                }
            }
        }

        // We didn't get redirected.
        break;
    }
}
<|endoftext|>


<commit_before><commit_msg>Create a example PPM program<commit_after>extern crate scratchapixel;

use std::fs::File;

use scratchapixel::ppm::rgb::RGB;
use scratchapixel::ppm::format::PPM;

fn main() {
    let white = RGB { r: 255, g: 255, b: 255 };
    let black = RGB { r: 0, g: 0, b: 0 };
    let red   = RGB { r: 255, g: 0, b: 0 };
    let mut image: PPM = PPM::new(64, 64);
    for y in 0..64 {
        let parity_y = (y / 8) % 2;
        for x in 0..64 {
            let parity_x = (x / 8) % 2;
            let color = match (parity_y + parity_x) % 2 {
                0 => black,
                1 => white,
                _ => red
            };
            image.set_pixel(x, y, color);
        }
    }

    match File::create("resources/example.use_ppm.ppm") {
        Ok(file) => {
            match image.write_file(file) {
                Ok(_) => println!("wrote file"),
                Err(_) => println!("could not write file")
            }
        }
        Err(_) => println!("could not create file")
    }
}
<|endoftext|>


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

// ignore-pretty

mod mod_dir_simple {
    #[path = "test.rs"]
    pub mod syrup;
}

pub fn main() {
    assert_eq!(mod_dir_simple::syrup::foo(), 10);
}
<commit_msg>Add regression test.<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.

// ignore-pretty

mod mod_dir_simple {
    #[path = "test.rs"]
    pub mod syrup;
}

pub fn main() {
    assert_eq!(mod_dir_simple::syrup::foo(), 10);

    #[path = "auxiliary"]
    mod foo {
        mod two_macros;
    }

    #[path = "auxiliary"]
    mod bar {
        macro_rules! m { () => { mod two_macros; } }
        m!();
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for #133.<commit_after>use std::mem::size_of;

struct S<U, V> {
    _u: U,
    size_of_u: usize,
    _v: V,
    size_of_v: usize
}

impl<U, V> S<U, V> {
    fn new(u: U, v: V) -> Self {
        S {
            _u: u,
            size_of_u: size_of::<U>(),
            _v: v,
            size_of_v: size_of::<V>()
        }
    }
}

impl<V, U> Drop for S<U, V> {
    fn drop(&mut self) {
        assert_eq!(size_of::<U>(), self.size_of_u);
        assert_eq!(size_of::<V>(), self.size_of_v);
    }
}

fn main() {
    S::new(0u8, 1u16);
}
<|endoftext|>


<commit_before><commit_msg>Add Some Benchmarks<commit_after>#![feature(test)]
extern crate test;
extern crate regex;

extern crate betabear;

use test::Bencher;

static DICTIONARY: &'static str = include_str!("/usr/share/dict/words");

#[bench]
fn build_1(b: &mut Bencher) {
    let given_letters = "noraanoraanoraa";
    let word = "aaronaaronaaron";

    b.iter(|| {
        let mut given_letters = given_letters.chars().collect::<Vec<char>>();
        given_letters.sort(); // For binary_search down the road

        for letter in word.chars() {
            if let Ok(index) = given_letters.binary_search(&letter) {
                given_letters.remove(index);
            } else {
                return false;
            }
        }

        true
    })
}

#[bench]
fn build_1_prepare_first(b: &mut Bencher) {
    let word = "aaronaaronaaron";
    let given_letters = "noraanoraanoraa";

    let mut given_letters = given_letters.chars().collect::<Vec<char>>();
    given_letters.sort(); // For binary_search down the road

    b.iter(|| {
        let mut given_letters = given_letters.clone();
        for letter in word.chars() {
            if let Ok(index) = given_letters.binary_search(&letter) {
                given_letters.remove(index);
            } else {
                return false;
            }
        }

        true
    })
}

#[bench]
fn build_1_check_len_first(b: &mut Bencher) {
    let given_letters = "noraanoraanoraa";
    let word = "aaronaaronaaron";

    b.iter(|| {
        let mut given_letters = given_letters.chars().collect::<Vec<char>>();

        if given_letters.len() < word.chars().count() {
            return false;
        }

        given_letters.sort(); // For binary_search down the road

        for letter in word.chars() {
            if let Ok(index) = given_letters.binary_search(&letter) {
                given_letters.remove(index);
            } else {
                return false;
            }
        }

        true
    })
}

#[bench]
fn build_no_binary_search(b: &mut Bencher) {
    let given_letters = "noraanoraanoraa";
    let word = "aaronaaronaaron";

    b.iter(|| {
        let mut given_letters = given_letters.chars().collect::<Vec<char>>();

        for letter in word.chars() {
            if let Some(index) = given_letters.iter().position(|&x| x == letter) {
                given_letters.remove(index);
            } else {
                return false;
            }
        }

        true
    })
}

#[bench]
fn build_no_binary_search_prepared(b: &mut Bencher) {
    let given_letters = "noraanoraanoraa";
    let word = "aaronaaronaaron";

    let given_letters = given_letters.chars().collect::<Vec<char>>();

    b.iter(|| {
        let mut given_letters = given_letters.clone();

        for letter in word.chars() {
            if let Some(index) = given_letters.iter().position(|&x| x == letter) {
                given_letters.remove(index);
            } else {
                return false;
            }
        }

        true
    })
}

#[bench]
fn build_no_binary_search_prepared_and_sorted(b: &mut Bencher) {
    let given_letters = "noraanoraanoraa";
    let word = "aaronaaronaaron";

    let mut given_letters = given_letters.chars().collect::<Vec<char>>();
    given_letters.sort();

    b.iter(|| {
        let mut given_letters = given_letters.clone();

        for letter in word.chars() {
            if let Some(index) = given_letters.iter().position(|&x| x == letter) {
                given_letters.remove(index);
            } else {
                return false;
            }
        }

        true
    })
}

#[bench]
#[ignore]
fn search_1(b: &mut Bencher) {
    let letters = "noraa";
    let letters = letters.trim().chars().collect::<Vec<char>>();

    b.iter(|| {
        let mut matches = DICTIONARY.lines()
                                    .filter(|word| betabear::build_with_letters(&letters, word))
                                    .map(|word| (word, word.chars().count()))
                                    .collect::<Vec<(&str, usize)>>();

        matches.sort_by(|a, b| b.1.cmp(&a.1));

        matches
    })
}

#[bench]
#[ignore]
fn search_1_with_regex(b: &mut Bencher) {
    let letters = "noraa";

    let regex = regex::Regex::new(&format!("^[{}]+$", letters))
                    .expect("String of given letters is malformed.");

    let letters = letters.trim().chars().collect::<Vec<char>>();

    b.iter(|| {
        let mut matches = DICTIONARY.lines()
                                    .filter(|word| regex.is_match(word))
                                    .filter(|word| betabear::build_with_letters(&letters, word))
                                    .map(|word| (word, word.chars().count()))
                                    .collect::<Vec<(&str, usize)>>();

        matches.sort_by(|a, b| b.1.cmp(&a.1));

        matches
    })
}
<|endoftext|>


<commit_before><commit_msg>SparkleComponent is now sparkle_component<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.

use std::num::NonZeroU32;
use std::u32;

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct NodeIndex {
    index: NonZeroU32,
}

impl NodeIndex {
    pub fn new(value: usize) -> NodeIndex {
        assert!(value < (u32::MAX as usize));
        NodeIndex { index: NonZeroU32::new((value as u32) + 1).unwrap() }
    }

    pub fn get(self) -> usize {
        (self.index.get() - 1) as usize
    }
}
<commit_msg>Inline `NodeIndex` methods.<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.

use std::num::NonZeroU32;
use std::u32;

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct NodeIndex {
    index: NonZeroU32,
}

impl NodeIndex {
    #[inline]
    pub fn new(value: usize) -> NodeIndex {
        assert!(value < (u32::MAX as usize));
        NodeIndex { index: NonZeroU32::new((value as u32) + 1).unwrap() }
    }

    #[inline]
    pub fn get(self) -> usize {
        (self.index.get() - 1) as usize
    }
}
<|endoftext|>


<commit_before><commit_msg>Added segment on type-parameterized traits.<commit_after><|endoftext|>


<commit_before><commit_msg>Don't add resources to the manager when they are already present<commit_after><|endoftext|>


<commit_before><commit_msg>Missing file added.<commit_after>//! A data structure for a sequence of small integers with a few big integers.
//! Small ints are stored in type S (e.g. a byte), big ints are stored separately (in type B) in a BTree.
//!
//! # Example
//!
//! ```
//! use bio::data_structures::smallints::SmallInts;
//! let mut smallints: SmallInts<u8, usize> = SmallInts::new();
//! smallints.push(3);
//! smallints.push(4);
//! smallints.push(255);
//! smallints.push(305093);
//! assert_eq!(smallints.get(0).unwrap(), 3);
//! smallints.set(0, 50000);
//! let values: Vec<usize> = smallints.iter().collect();
//! assert_eq!(values, [50000, 4, 255, 305093]);
//! ```

use std::num::{Int, NumCast, FromPrimitive, cast};
use std::iter::{Enumerate, repeat};
use std::mem::size_of;
use std::collections::BTreeMap;
use std::slice;

pub struct SmallInts<S: Int + NumCast + FromPrimitive, B: Int + NumCast> {
    smallints: Vec<S>,
    bigints: BTreeMap<usize, B>
}

impl<S: Int + NumCast + FromPrimitive, B: Int + NumCast> SmallInts<S, B> {
    pub fn new() -> Self {
        assert!(size_of::<S>() < size_of::<B>(), "S has to be smaller than B");
        SmallInts { smallints: Vec::new(), bigints: BTreeMap::new() }
    }

    pub fn with_capacity(n: usize) -> Self {
        assert!(size_of::<S>() < size_of::<B>(), "S has to be smaller than B");
        SmallInts { smallints: Vec::with_capacity(n), bigints: BTreeMap::new() }
    }

    pub fn from_elem(v: S, n: usize) -> Self {
        assert!(size_of::<S>() < size_of::<B>(), "S has to be smaller than B");
        if v > FromPrimitive::from_int(0).unwrap() {
            assert!(v < Int::max_value(), "v has to be smaller than maximum value");
        }

        SmallInts { smallints: repeat(v).take(n).collect(), bigints: BTreeMap::new() }
    }

    pub fn get(&self, i: usize) -> Option<B> {
        if i < self.smallints.len() {
            self.real_value(i, self.smallints[i])
        }
        else {
            None
        }
    }

    pub fn push(&mut self, v: B) {
        let maxv: S = Int::max_value();
        match cast(v) {
            Some(v) if v < maxv => self.smallints.push(v),
            _                   => {
                let i = self.smallints.len();
                self.smallints.push(maxv);
                self.bigints.insert(i, v);
            }
        }
    }

    pub fn set(&mut self, i: usize, v: B) {
        let maxv: S = Int::max_value();
        match cast(v) {
            Some(v) if v < maxv => self.smallints[i] = v,
            _                   => {
                self.smallints[i] = maxv;
                self.bigints.insert(i, v);
            }
        }
    }

    pub fn iter<'a>(&'a self) -> Iter<S, B> {
        Iter { smallints: &self, items: self.smallints.iter().enumerate() }
    }

    pub fn decompress(&self) -> Vec<B> {
        self.iter().collect()
    }

    fn real_value(&self, i: usize, v: S) -> Option<B> {
        if v < Int::max_value() {
            cast(v)
        }
        else {
            self.bigints.get(&i).cloned()
        }
    }
}

pub struct Iter<'a, S: 'a + Int + NumCast + FromPrimitive, B: 'a + Int + NumCast> {
    smallints: &'a SmallInts<S, B>,
    items: Enumerate<slice::Iter<'a, S>>
}

impl<'a, S: 'a + Int + NumCast + FromPrimitive, B: 'a + Int + NumCast> Iterator for Iter<'a, S, B> {
    type Item = B;

    fn next(&mut self) -> Option<B> {
        match self.items.next() {
            Some((i, &v)) => self.smallints.real_value(i, v),
            None => None
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement XOR, LShift & RShift in Calc<commit_after><|endoftext|>


<commit_before><commit_msg>tests: add regression test for #74614<commit_after>// build-pass

fn test<T>() {
    std::mem::size_of::<T>();
}

pub fn foo<T>(_: T) -> &'static fn() {
    &(test::<T> as fn())
}

fn outer<T>() {
    foo(|| ());
}

fn main() {
    outer::<u8>();
}
<|endoftext|>


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

#![feature(drop_types_in_const)]

struct A(i32);

impl Drop for A {
    fn drop(&mut self) {}
}

static FOO: A = A(123);

fn main() {
    println!("{}", &FOO.0);
}
<|endoftext|>


<commit_before><commit_msg>:art: Make possible to deserialize with serde<commit_after><|endoftext|>


<commit_before><commit_msg>Can't quite say it compiles...crashes the compiler!<commit_after>extern mod rust_fuse;

use std::libc::{
    S_IFDIR,
    S_IFREG,
    ENOENT,
    EACCES,
    O_RDONLY,
    stat,
    off_t,
    size_t,
    c_int
};

use std::cmp::min;
use rust_fuse::*;
use std::os;
use std::path::stat::arch::default_stat;
use std::vec::MutableCloneableVector;

static HELLO_STR:&'static str = "Hello rusty world!\n";
static HELLO_FILE_FULLPATH:&'static str = "/hello_from_rust";

struct HelloFs;

impl FuseOperations for HelloFs {
    fn getattr(&self, path:&str) -> ErrorOrResult<errno, stat> {
        match path {
            "/" => Result({
                    let mut st = default_stat();
                    // 493: octal 755.  Rust lacks octal literals
                    st.st_mode = (S_IFDIR | 493) as u32;
                    st.st_nlink = 2;
                    st
                }),
            HELLO_FILE_FULLPATH => Result({
                    let mut st = default_stat();
                    // 292: octal 0444
                    st.st_mode = (S_IFREG | 292) as u32;
                    st.st_nlink = 1;
                    st.st_size = HELLO_STR.len() as i64;
                    st
                }),
            _ => Error(ENOENT)
        }
    }

    fn readdir(&self, path:&str, filler: fuse_fill_dir_func,
               _offset: off_t, _info: &fuse_file_info) -> ErrorOrResult<errno, ()> {
        match path {
            "/" => Result({
                    filler(".", None, 0);
                    filler("..", None, 0);
                    filler(HELLO_FILE_FULLPATH.slice_from(1), None, 0);
                }),
            _ => Error(ENOENT)
        }
    }

    fn open(&self, path:&str, info: &fuse_file_info) -> ErrorOrResult<errno, filehandle> {
        match path {
            HELLO_FILE_FULLPATH =>
                if info.flags & 3 != O_RDONLY { Error(EACCES) } else { Result(0) },
            _ => Error(ENOENT)
        }
    }

    fn read(&self, path:&str, buf:&mut [u8], size: size_t, offset: off_t,
            _info: &fuse_file_info) -> ErrorOrResult<errno, c_int> {
        if path != HELLO_FILE_FULLPATH {
            return Error(ENOENT)
        };

        let slice_to_read = HELLO_STR.slice(offset as uint,
                                            min(HELLO_STR.len(),size as uint));
        Result(buf.copy_from(slice_to_read.as_bytes()) as c_int)
    }
}

fn main() {
    std::os::set_exit_status(fuse_main(os::args(), ~HelloFs))
}
<|endoftext|>


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

/*!

The `ToStr` trait for converting to strings

*/

use str::OwnedStr;
use hashmap::HashMap;
use hashmap::HashSet;
use iterator::IteratorUtil;
use hash::Hash;
use cmp::Eq;
use vec::ImmutableVector;

/// A generic trait for converting a value to a string
pub trait ToStr {
    /// Converts the value of `self` to an owned string
    fn to_str(&self) -> ~str;
}

/// Trait for converting a type to a string, consuming it in the process.
pub trait ToStrConsume {
    /// Cosume and convert to a string.
    fn into_str(self) -> ~str;
}

impl ToStr for () {
    #[inline]
    fn to_str(&self) -> ~str { ~"()" }
}

impl<A:ToStr> ToStr for (A,) {
    #[inline]
    fn to_str(&self) -> ~str {
        match *self {
            (ref a,) => {
                fmt!("(%s,)", (*a).to_str())
            }
        }
    }
}

impl<A:ToStr+Hash+Eq, B:ToStr+Hash+Eq> ToStr for HashMap<A, B> {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"{", true);
        for self.iter().advance |(key, value)| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(key.to_str());
            acc.push_str(": ");
            acc.push_str(value.to_str());
        }
        acc.push_char('}');
        acc
    }
}

impl<A:ToStr+Hash+Eq> ToStr for HashSet<A> {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"{", true);
        for self.iter().advance |element| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(element.to_str());
        }
        acc.push_char('}');
        acc
    }
}

impl<A:ToStr,B:ToStr> ToStr for (A, B) {
    #[inline]
    fn to_str(&self) -> ~str {
        // FIXME(#4653): this causes an llvm assertion
        //let &(ref a, ref b) = self;
        match *self {
            (ref a, ref b) => {
                fmt!("(%s, %s)", (*a).to_str(), (*b).to_str())
            }
        }
    }
}

impl<A:ToStr,B:ToStr,C:ToStr> ToStr for (A, B, C) {
    #[inline]
    fn to_str(&self) -> ~str {
        // FIXME(#4653): this causes an llvm assertion
        //let &(ref a, ref b, ref c) = self;
        match *self {
            (ref a, ref b, ref c) => {
                fmt!("(%s, %s, %s)",
                    (*a).to_str(),
                    (*b).to_str(),
                    (*c).to_str()
                )
            }
        }
    }
}

impl<'self,A:ToStr> ToStr for &'self [A] {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"[", true);
        for self.iter().advance |elt| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(elt.to_str());
        }
        acc.push_char(']');
        acc
    }
}

impl<A:ToStr> ToStr for ~[A] {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"[", true);
        for self.iter().advance |elt| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(elt.to_str());
        }
        acc.push_char(']');
        acc
    }
}

impl<A:ToStr> ToStr for @[A] {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"[", true);
        for self.iter().advance |elt| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(elt.to_str());
        }
        acc.push_char(']');
        acc
    }
}

#[cfg(test)]
#[allow(non_implicitly_copyable_typarams)]
mod tests {
    use hashmap::HashMap;
    use hashmap::HashSet;
    use container::Set;
    #[test]
    fn test_simple_types() {
        assert_eq!(1i.to_str(), ~"1");
        assert_eq!((-1i).to_str(), ~"-1");
        assert_eq!(200u.to_str(), ~"200");
        assert_eq!(2u8.to_str(), ~"2");
        assert_eq!(true.to_str(), ~"true");
        assert_eq!(false.to_str(), ~"false");
        assert_eq!(().to_str(), ~"()");
        assert_eq!((~"hi").to_str(), ~"hi");
        assert_eq!((@"hi").to_str(), ~"hi");
    }

    #[test]
    fn test_tuple_types() {
        assert_eq!((1, 2).to_str(), ~"(1, 2)");
        assert_eq!((~"a", ~"b", false).to_str(), ~"(a, b, false)");
        assert_eq!(((), ((), 100)).to_str(), ~"((), ((), 100))");
    }

    #[test]
    fn test_vectors() {
        let x: ~[int] = ~[];
        assert_eq!(x.to_str(), ~"[]");
        assert_eq!((~[1]).to_str(), ~"[1]");
        assert_eq!((~[1, 2, 3]).to_str(), ~"[1, 2, 3]");
        assert!((~[~[], ~[1], ~[1, 1]]).to_str() ==
               ~"[[], [1], [1, 1]]");
    }

    #[test]
    fn test_hashmap() {
        let mut table: HashMap<int, int> = HashMap::new();
        let empty: HashMap<int, int> = HashMap::new();

        table.insert(3, 4);
        table.insert(1, 2);

        let table_str = table.to_str();

        assert!(table_str == ~"{1: 2, 3: 4}" || table_str == ~"{3: 4, 1: 2}");
        assert_eq!(empty.to_str(), ~"{}");
    }

    #[test]
    fn test_hashset() {
        let mut set: HashSet<int> = HashSet::new();
        let empty_set: HashSet<int> = HashSet::new();

        set.insert(1);
        set.insert(2);

        let set_str = set.to_str();

        assert!(set_str == ~"{1, 2}" || set_str == ~"{2, 1}");
        assert_eq!(empty_set.to_str(), ~"{}");
    }
}
<commit_msg>Add missing import to tests<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.

/*!

The `ToStr` trait for converting to strings

*/

use str::OwnedStr;
use hashmap::HashMap;
use hashmap::HashSet;
use iterator::IteratorUtil;
use hash::Hash;
use cmp::Eq;
use vec::ImmutableVector;

/// A generic trait for converting a value to a string
pub trait ToStr {
    /// Converts the value of `self` to an owned string
    fn to_str(&self) -> ~str;
}

/// Trait for converting a type to a string, consuming it in the process.
pub trait ToStrConsume {
    /// Cosume and convert to a string.
    fn into_str(self) -> ~str;
}

impl ToStr for () {
    #[inline]
    fn to_str(&self) -> ~str { ~"()" }
}

impl<A:ToStr> ToStr for (A,) {
    #[inline]
    fn to_str(&self) -> ~str {
        match *self {
            (ref a,) => {
                fmt!("(%s,)", (*a).to_str())
            }
        }
    }
}

impl<A:ToStr+Hash+Eq, B:ToStr+Hash+Eq> ToStr for HashMap<A, B> {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"{", true);
        for self.iter().advance |(key, value)| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(key.to_str());
            acc.push_str(": ");
            acc.push_str(value.to_str());
        }
        acc.push_char('}');
        acc
    }
}

impl<A:ToStr+Hash+Eq> ToStr for HashSet<A> {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"{", true);
        for self.iter().advance |element| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(element.to_str());
        }
        acc.push_char('}');
        acc
    }
}

impl<A:ToStr,B:ToStr> ToStr for (A, B) {
    #[inline]
    fn to_str(&self) -> ~str {
        // FIXME(#4653): this causes an llvm assertion
        //let &(ref a, ref b) = self;
        match *self {
            (ref a, ref b) => {
                fmt!("(%s, %s)", (*a).to_str(), (*b).to_str())
            }
        }
    }
}

impl<A:ToStr,B:ToStr,C:ToStr> ToStr for (A, B, C) {
    #[inline]
    fn to_str(&self) -> ~str {
        // FIXME(#4653): this causes an llvm assertion
        //let &(ref a, ref b, ref c) = self;
        match *self {
            (ref a, ref b, ref c) => {
                fmt!("(%s, %s, %s)",
                    (*a).to_str(),
                    (*b).to_str(),
                    (*c).to_str()
                )
            }
        }
    }
}

impl<'self,A:ToStr> ToStr for &'self [A] {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"[", true);
        for self.iter().advance |elt| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(elt.to_str());
        }
        acc.push_char(']');
        acc
    }
}

impl<A:ToStr> ToStr for ~[A] {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"[", true);
        for self.iter().advance |elt| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(elt.to_str());
        }
        acc.push_char(']');
        acc
    }
}

impl<A:ToStr> ToStr for @[A] {
    #[inline]
    fn to_str(&self) -> ~str {
        let mut (acc, first) = (~"[", true);
        for self.iter().advance |elt| {
            if first {
                first = false;
            }
            else {
                acc.push_str(", ");
            }
            acc.push_str(elt.to_str());
        }
        acc.push_char(']');
        acc
    }
}

#[cfg(test)]
#[allow(non_implicitly_copyable_typarams)]
mod tests {
    use hashmap::HashMap;
    use hashmap::HashSet;
    use container::{Set,Map};
    #[test]
    fn test_simple_types() {
        assert_eq!(1i.to_str(), ~"1");
        assert_eq!((-1i).to_str(), ~"-1");
        assert_eq!(200u.to_str(), ~"200");
        assert_eq!(2u8.to_str(), ~"2");
        assert_eq!(true.to_str(), ~"true");
        assert_eq!(false.to_str(), ~"false");
        assert_eq!(().to_str(), ~"()");
        assert_eq!((~"hi").to_str(), ~"hi");
        assert_eq!((@"hi").to_str(), ~"hi");
    }

    #[test]
    fn test_tuple_types() {
        assert_eq!((1, 2).to_str(), ~"(1, 2)");
        assert_eq!((~"a", ~"b", false).to_str(), ~"(a, b, false)");
        assert_eq!(((), ((), 100)).to_str(), ~"((), ((), 100))");
    }

    #[test]
    fn test_vectors() {
        let x: ~[int] = ~[];
        assert_eq!(x.to_str(), ~"[]");
        assert_eq!((~[1]).to_str(), ~"[1]");
        assert_eq!((~[1, 2, 3]).to_str(), ~"[1, 2, 3]");
        assert!((~[~[], ~[1], ~[1, 1]]).to_str() ==
               ~"[[], [1], [1, 1]]");
    }

    #[test]
    fn test_hashmap() {
        let mut table: HashMap<int, int> = HashMap::new();
        let empty: HashMap<int, int> = HashMap::new();

        table.insert(3, 4);
        table.insert(1, 2);

        let table_str = table.to_str();

        assert!(table_str == ~"{1: 2, 3: 4}" || table_str == ~"{3: 4, 1: 2}");
        assert_eq!(empty.to_str(), ~"{}");
    }

    #[test]
    fn test_hashset() {
        let mut set: HashSet<int> = HashSet::new();
        let empty_set: HashSet<int> = HashSet::new();

        set.insert(1);
        set.insert(2);

        let set_str = set.to_str();

        assert!(set_str == ~"{1, 2}" || set_str == ~"{2, 1}");
        assert_eq!(empty_set.to_str(), ~"{}");
    }
}
<|endoftext|>


<commit_before><commit_msg>remove macro file<commit_after><|endoftext|>


<commit_before><commit_msg>Document segments and debug env var in codegen.<commit_after><|endoftext|>


<commit_before><commit_msg>parse strings<commit_after><|endoftext|>


<commit_before><commit_msg>test checking full stderr output, with new message, resulting from a "did you mean"<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: "status" subcommand might not be present<commit_after><|endoftext|>


<commit_before><commit_msg>Range error messages<commit_after><|endoftext|>


<commit_before><commit_msg>renamed the vertex testing file<commit_after>extern crate thunderdome;

#[cfg(test)]
mod vertex_tests {
    use thunderdome::graph::*;
    use thunderdome::vertex::*;

    #[test]
    fn test_vertex_edge_traversals() {
        let mut g = Graph::new();
        let mut vertex = g.add_vertex();
        let mut vertex2 = g.add_vertex();

        vertex.add_edge(&mut vertex2, "test");

        let result = vertex.outE();
        assert_eq!(1, result.len());

        let result = vertex.inE();
        assert_eq!(0, result.len());

        let result = vertex2.outE();
        assert_eq!(0, result.len());

        let result = vertex2.inE();
        assert_eq!(1, result.len());
    }

    #[test]
    fn test_deref() {
        let mut g = Graph::new();
        let v1 = g.add_vertex();
        let vertex = &*v1;
        assert!(vertex.id == 1);
    }

    #[test]
    fn test_new_vertex() {
        let mut g = Graph::new();
        let v1 = g.add_vertex();

        assert_eq!(v1.id, 1);

        unsafe {
            let vertex = &*v1;
            assert_eq!((*v1).id, 1);
        }

        let v2 = g.add_vertex();
        assert!(v2.id == 2);
    }

}
<|endoftext|>


<commit_before><commit_msg>10以上のところに当たってなかった可能性<commit_after><|endoftext|>


<commit_before><commit_msg>Add error docs.<commit_after><|endoftext|>


<commit_before><commit_msg>Add GitError algebraic data type<commit_after>use std::fmt;

pub enum GitError {
    CorruptedRepository(&'static str),
    CorruptedCommit(&'static str)
}

impl fmt::Show for GitError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            CorruptedCommit(s) => write!(f, "CorruptedCommit: {}", s),
            CorruptedRepository(s) => write!(f, "CorruptedRepository: {}", s),
        }
    }
}<|endoftext|>


<commit_before><commit_msg>Day 19 in rust<commit_after><|endoftext|>


<commit_before><commit_msg>Add module-level constants documentation<commit_after><|endoftext|>


<commit_before><commit_msg>fibonacci nth term in Rust<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: CReader uses the new Bytes extension trait<commit_after><|endoftext|>


<commit_before><commit_msg>Add r -> c -> r using r2c<commit_after>
extern crate fftw3;
extern crate num_traits;

use fftw3::*;
use num_traits::Zero;

#[test]
fn r2c2r() {
    let n = 128;
    let mut in_ = vec![0.0; n];
    let mut out = vec![c64::zero(); n / 2 + 1];
    let mut plan = Plan::r2c_1d(&mut in_, &mut out, FLAG::FFTW_ESTIMATE);
    for (i, val) in plan.field.iter_mut().enumerate() {
        *val = (i + 1) as f64;
    }
    plan.forward();
    plan.backward();
    for (i, val) in plan.field.iter().enumerate() {
        let ans = (i + 1) as f64;
        if (ans - *val).abs() / ans.abs() > 1e-7 {
            panic!("Not equal: ans={:?}/val={:?}", ans, val);
        }
    }
}

#[test]
fn c2r2c() {
    let n = 128;
    let mut in_ = vec![0.0; n];
    let mut out = vec![c64::zero(); n / 2 + 1];
    let mut plan = Plan::r2c_1d(&mut in_, &mut out, FLAG::FFTW_ESTIMATE);
    for (i, val) in plan.coef.iter_mut().enumerate() {
        *val = c64::new((i + 1) as f64, (i + 2) as f64);
    }
    plan.backward();
    plan.forward();
    for (i, val) in plan.coef.iter().enumerate() {
        let mut ans = c64::new((i + 1) as f64, (i + 2) as f64);
        if i == 0 || i == n / 2 {
            ans[1] = 0.0;
        }
        if (ans - *val).abs() / ans.abs() > 1e-7 {
            panic!("Not equal: i={}, ans={:?}/val={:?}", i, ans, val);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Make exported trait public<commit_after><|endoftext|>


<commit_before><commit_msg>Remove extraneous 0<commit_after><|endoftext|>


<commit_before><commit_msg>Add declaration example<commit_after>fn main() {
    // Declare a variable binding
    let a_binding;

    {
        let x = 2;

        // Initialize the binding
        a_binding = x * x;
    }

    println!("a binding: {}", a_binding);

    let another_binding;

    // Error! Use of uninitialized binding
    // println!("another binding: {}", another_binding);
    // FIXME ^ Comment out this line

    another_binding = 1;

    println!("another binding: {}", another_binding);
}
<|endoftext|>