<commit_before>//! Details of the `#[ruma_api(...)]` attributes.

use syn::{
    parse::{Parse, ParseStream},
    Ident, Token,
};

/// Like syn::MetaNameValue, but expects an identifier as the value. Also, we don't care about the
/// the span of the equals sign, so we don't have the `eq_token` field from syn::MetaNameValue.
pub struct MetaNameValue {
    /// The part left of the equals sign
    pub name: Ident,
    /// The part right of the equals sign
    pub value: Ident,
}

/// Like syn::Meta, but only parses ruma_api attributes
pub enum Meta {
    /// A single word, like `query` in `#[ruma_api(query)]`
    Word(Ident),
    /// A name-value pair, like `header = CONTENT_TYPE` in `#[ruma_api(header = CONTENT_TYPE)]`
    NameValue(MetaNameValue),
}

impl Meta {
    /// Check if the given attribute is a ruma_api attribute. If it is, parse it.
    ///
    /// # Panics
    ///
    /// Panics if the given attribute is a ruma_api attribute, but fails to parse.
    pub fn from_attribute(attr: &syn::Attribute) -> Option<Self> {
        match &attr.path {
            syn::Path {
                leading_colon: None,
                segments,
            } => {
                if segments.len() == 1 && segments[0].ident == "ruma_api" {
                    Some(
                        attr.parse_args()
                            .expect("ruma_api! could not parse request field attributes"),
                    )
                } else {
                    None
                }
            }
            _ => None,
        }
    }
}

impl Parse for Meta {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let ident = input.parse()?;

        if input.peek(Token![=]) {
            let _ = input.parse::<Token![=]>();
            Ok(Meta::NameValue(MetaNameValue {
                name: ident,
                value: input.parse()?,
            }))
        } else {
            Ok(Meta::Word(ident))
        }
    }
}
<commit_msg>ruma-api-macros: Slight simplification of api/attribute.rs<commit_after>//! Details of the `#[ruma_api(...)]` attributes.

use syn::{
    parse::{Parse, ParseStream},
    Ident, Token,
};

/// Like syn::MetaNameValue, but expects an identifier as the value. Also, we don't care about the
/// the span of the equals sign, so we don't have the `eq_token` field from syn::MetaNameValue.
pub struct MetaNameValue {
    /// The part left of the equals sign
    pub name: Ident,
    /// The part right of the equals sign
    pub value: Ident,
}

/// Like syn::Meta, but only parses ruma_api attributes
pub enum Meta {
    /// A single word, like `query` in `#[ruma_api(query)]`
    Word(Ident),
    /// A name-value pair, like `header = CONTENT_TYPE` in `#[ruma_api(header = CONTENT_TYPE)]`
    NameValue(MetaNameValue),
}

impl Meta {
    /// Check if the given attribute is a ruma_api attribute. If it is, parse it.
    ///
    /// # Panics
    ///
    /// Panics if the given attribute is a ruma_api attribute, but fails to parse.
    pub fn from_attribute(attr: &syn::Attribute) -> Option<Self> {
        match &attr.path {
            syn::Path {
                leading_colon: None,
                segments,
            } if segments.len() == 1 && segments[0].ident == "ruma_api" => Some(
                attr.parse_args()
                    .expect("ruma_api! could not parse request field attributes"),
            ),
            _ => None,
        }
    }
}

impl Parse for Meta {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let ident = input.parse()?;

        if input.peek(Token![=]) {
            let _ = input.parse::<Token![=]>();
            Ok(Meta::NameValue(MetaNameValue {
                name: ident,
                value: input.parse()?,
            }))
        } else {
            Ok(Meta::Word(ident))
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>program 0003: simple multiplication<commit_after>// product of two numbers
fn main() {
    let a = 5.5;
    let b = 7.5;
    let c;

    c = a * b;
    println!("Value of {} * {} is {} ", a, b, c);
}
<|endoftext|>


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

#[allow(unused_imports)]

mod foo {
    use baz::bar;
    //~^ ERROR import `bar` conflicts with existing submodule
    mod bar {}
}
mod baz { pub mod bar {} }

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add layout for 'inline-block' and other atomic inline-level boxes<commit_after><|endoftext|>


<commit_before><commit_msg>adding tests directory<commit_after>extern crate bittorrent;

use bittorrent::default_handler::*;
use bittorrent::chunk::*;
use bittorrent::peer::*;

#[test]
fn test_nand_slice() {
    let a = vec![0, 0];
    let b = vec![0, 1];
    let c = nand_slice_vbr_len(&a, &b);

    assert_eq!(c, vec![255, 254]);
}

/*#[test]
fn test_unclaimed_fields() {
    let mut handler = DefaultHandler;

    handler.owned = vec![0, 0, 0];
    handler.request_map = vec![1, 0];

    let c = handler.unclaimed_fields();
    assert_eq!(c, vec![254, 255, 255]);
}*/

#[test]
fn test_set_have_singleton_bitfield() {
    let mut state = State::new();

    state.set_bitfield(vec![0]);
    state.set_have(2);

    assert_eq!(state.bitfield[0], 32);
}

#[test]
fn test_set_have_longer_bitfield() {
    let mut state = State::new();

    state.set_bitfield(vec![0, 0, 0, 0]);
    state.set_have(23);

    assert_eq!(state.bitfield[0], 0);
    assert_eq!(state.bitfield[1], 0);
    assert_eq!(state.bitfield[2], 1);
    assert_eq!(state.bitfield[3], 0);
}

#[test]
fn test_set_have_out_of_bounds() {
    let mut state = State::new();

    state.set_bitfield(vec![0, 1]);
    state.set_have(31);

    assert_eq!(state.bitfield[0], 0);
    assert_eq!(state.bitfield[1], 1);
    assert_eq!(state.bitfield[2], 0);
    assert_eq!(state.bitfield[3], 1);
}

#[test]
fn test_get_block_boundaries_1() {
    let piece_length = 300;
    let index = 0;
    let offset = 50;
    let bytes = 1000;
    let block = Piece::from(piece_length, index, offset, bytes);

    assert_eq!(block, Piece::new(Position::new(0, 50), Position::new(3, 150)));
}

#[test]
fn test_get_block_boundaries_2() {
    let piece_length = 5;
    let index = 0;
    let offset = 0;
    let bytes = 5;
    let block = Piece::from(piece_length, index, offset, bytes);

    assert_eq!(block, Piece::new(Position::new(0, 0), Position::new(1, 0)));
}

#[test]
fn test_get_block_boundaries_3() {
    let piece_length = 5;
    let index = 0;
    let offset = 0;
    let bytes = 6;
    let block = Piece::from(piece_length, index, offset, bytes);

    assert_eq!(block, Piece::new(Position::new(0, 0), Position::new(1, 1)));
}

#[test]
fn test_request_block () {
    let mut vec = vec![];
    let piece_length = 5;

    let a = {  //empty case
        let index = 0;
        let offset = 0;
        let bytes = 5;

        let expect = Piece::new(Position::new(index, offset), Position::new(index+1, 0));
        let block = Piece::from(piece_length, index, offset, bytes);
        Piece::add_to_boundary_vec(&mut vec, block);
        assert_eq!(vec[0], expect.clone());

        expect
    };

    let b = {
        let index = 5;
        let offset = 0;
        let bytes = 5;

        let expect = Piece::new(Position::new(index, offset), Position::new(index+1, 0));
        let block = Piece::from(piece_length, index, offset, bytes);
        Piece::add_to_boundary_vec(&mut vec, block);
        assert_eq!(vec, vec![a.clone(), expect.clone()]);

        expect
    };

    let c = {
        let index = 3;
        let offset = 0;
        let bytes = 5;

        let expect = Piece::new(Position::new(index, offset), Position::new(index+1, 0));
        let block = Piece::from(piece_length, index, offset, bytes);
        Piece::add_to_boundary_vec(&mut vec, block);
        assert_eq!(vec, vec![a.clone(), expect.clone(), b.clone()]);

        expect
    };

    let d = {
        let index = 4;
        let offset = 0;
        let bytes = 5;

        let expect = Piece::new(Position::new(index, offset), Position::new(index+1, 0));
        let block = Piece::from(piece_length, index, offset, bytes);
        Piece::add_to_boundary_vec(&mut vec, block);
        assert_eq!(vec, vec![a.clone(), c.clone(), expect.clone(), b.clone()]);

        expect
    };

}

#[test]
fn test_request_block_with_compaction () {
    let mut vec = vec![];
    let piece_length = 5;

    let _ = {
        let index = 0;
        let offset = 0;
        let bytes = 5;

        let expect = Piece::new(Position::new(index, offset), Position::new(index, piece_length - 1));
        let block = Piece::from(piece_length, index, offset, bytes);
        Piece::add_to_boundary_vec(&mut vec, block)
    };

    let index = {
        let index = 1;
        let offset = 0;
        let bytes = 5;

        let expect = Piece::new(Position::new(index, offset), Position::new(index, piece_length - 1));
        let block = Piece::from(piece_length, index, offset, bytes);
        Piece::add_to_boundary_vec(&mut vec, block)
    };

    Piece::compact_if_possible(&mut vec, index);

    assert_eq!(vec, vec![Piece::new(Position::new(0, 0), Position::new(2, 0))]);
}

#[test]
pub fn test_convert_bitfield_to_piece_vec() {
    let p = Piece::convert_bitfield_to_piece_vec(&vec![1, 1]);
    assert_eq!(p, vec![Piece::new(Position::new(7, 0), Position::new(8, 0)),
                      Piece::new(Position::new(15, 0), Position::new(16, 0))]);

    let a = Piece::convert_bitfield_to_piece_vec(&vec![128]);
    assert_eq!(a, vec![Piece::new(Position::new(0, 0), Position::new(1, 0))]);
}

#[test]
pub fn test_trivial_complement() {
    let a = vec![
        Piece::new(Position::new(0, 0), Position::new(3, 0))
        ];

    let b = vec![
        Piece::new(Position::new(0, 0), Position::new(1, 0))
    ];

    let a = Piece::complement(&a, &b);

    assert_eq!(a, vec![Piece::new(Position::new(1, 0), Position::new(3, 0))]);
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #41673 - bitshifter:repr-align-codegen-test, r=arielb1<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.

// compile-flags: -C no-prepopulate-passes
#![crate_type = "lib"]

#![feature(attr_literals)]
#![feature(repr_align)]

#[repr(align(64))]
pub struct Align64(i32);

pub struct Nested64 {
    a: Align64,
    b: i32,
    c: i32,
    d: i8,
}

pub enum Enum64 {
    A(Align64),
    B(i32),
}

// CHECK-LABEL: @align64
#[no_mangle]
pub fn align64(i : i32) -> Align64 {
// CHECK: %a64 = alloca %Align64, align 64
// CHECK: call void @llvm.memcpy.{{.*}}(i8* %{{.*}}, i8* %{{.*}}, i{{[0-9]+}} 64, i32 64, i1 false)
    let a64 = Align64(i);
    a64
}

// CHECK-LABEL: @nested64
#[no_mangle]
pub fn nested64(a: Align64, b: i32, c: i32, d: i8) -> Nested64 {
// CHECK: %n64 = alloca %Nested64, align 64
// CHECK: %a = alloca %Align64, align 64
    let n64 = Nested64 { a, b, c, d };
    n64
}

// CHECK-LABEL: @enum64
#[no_mangle]
pub fn enum64(a: Align64) -> Enum64 {
// CHECK: %e64 = alloca %Enum64, align 64
// CHECK: %a = alloca %Align64, align 64
    let e64 = Enum64::A(a);
    e64
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for issue #16739<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.

#![feature(unboxed_closures)]

// Test that unboxing shim for calling rust-call ABI methods through a
// trait box works and does not cause an ICE

struct Foo { foo: uint }

impl FnOnce<(), uint> for Foo {
    #[rust_call_abi_hack]
    fn call_once(self, _: ()) -> uint { self.foo }
}

impl FnOnce<(uint,), uint> for Foo {
    #[rust_call_abi_hack]
    fn call_once(self, (x,): (uint,)) -> uint { self.foo + x }
}

impl FnOnce<(uint, uint), uint> for Foo {
    #[rust_call_abi_hack]
    fn call_once(self, (x, y): (uint, uint)) -> uint { self.foo + x + y }
}

fn main() {
    let f = box Foo { foo: 42 } as Box<FnOnce<(), uint>>;
    assert_eq!(f.call_once(()), 42);

    let f = box Foo { foo: 40 } as Box<FnOnce<(uint,), uint>>;
    assert_eq!(f.call_once((2,)), 42);

    let f = box Foo { foo: 40 } as Box<FnOnce<(uint, uint), uint>>;
    assert_eq!(f.call_once((1, 1)), 42);
}
<|endoftext|>


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

struct Index;

impl Index {
    fn new() -> Self { Index }
}

fn user() {
    let new = Index::new;

    fn inner() {
        let index = Index::new();
    }

    let index2 = new();
}

fn main() {}
<|endoftext|>


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

use std::marker::{PhantomData, PhantomFn};

pub struct Handle<T, I>(T, I);

impl<T, I> Handle<T, I> {
    pub fn get_info(&self) -> &I {
        let Handle(_, ref info) = *self;
        info
    }
}

pub struct BufferHandle<D: Device, T> {
    raw: RawBufferHandle<D>,
    _marker: PhantomData<T>,
}

impl<D: Device, T> BufferHandle<D, T> {
    pub fn get_info(&self) -> &String {
        self.raw.get_info()
    }
}

pub type RawBufferHandle<D: Device> = Handle<<D as Device>::Buffer, String>;

pub trait Device: PhantomFn<Self> {
    type Buffer;
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add regression test for issue 23699.<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.

fn gimme_a_raw_pointer<T>(_: *const T) { }

fn test<T>(t: T) { }

fn main() {
    // Clearly `pointer` must be of type `*const ()`.
    let pointer = &() as *const _;
    gimme_a_raw_pointer(pointer);

    let t = test as fn (i32);
    t(0i32);
}

<|endoftext|>


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

use util::nodemap::{FxHashMap, FxHashSet};
use ty::context::TyCtxt;
use ty::{AdtDef, VariantDef, FieldDef, Ty, TyS};
use ty::{DefId, Substs};
use ty::{AdtKind, Visibility};
use ty::TypeVariants::*;

pub use self::def_id_forest::DefIdForest;

mod def_id_forest;

// The methods in this module calculate DefIdForests of modules in which a
// AdtDef/VariantDef/FieldDef is visibly uninhabited.
//
// # Example
// ```rust
// enum Void {}
// mod a {
//     pub mod b {
//         pub struct SecretlyUninhabited {
//             _priv: !,
//         }
//     }
// }
//
// mod c {
//     pub struct AlsoSecretlyUninhabited {
//         _priv: Void,
//     }
//     mod d {
//     }
// }
//
// struct Foo {
//     x: a::b::SecretlyUninhabited,
//     y: c::AlsoSecretlyUninhabited,
// }
// ```
// In this code, the type Foo will only be visibly uninhabited inside the
// modules b, c and d. Calling uninhabited_from on Foo or its AdtDef will
// return the forest of modules {b, c->d} (represented in a DefIdForest by the
// set {b, c})
//
// We need this information for pattern-matching on Foo or types that contain
// Foo.
//
// # Example
// ```rust
// let foo_result: Result<T, Foo> = ... ;
// let Ok(t) = foo_result;
// ```
// This code should only compile in modules where the uninhabitedness of Foo is
// visible.

impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
    /// Checks whether a type is visibly uninhabited from a particular module.
    /// # Example
    /// ```rust
    /// enum Void {}
    /// mod a {
    ///     pub mod b {
    ///         pub struct SecretlyUninhabited {
    ///             _priv: !,
    ///         }
    ///     }
    /// }
    ///
    /// mod c {
    ///     pub struct AlsoSecretlyUninhabited {
    ///         _priv: Void,
    ///     }
    ///     mod d {
    ///     }
    /// }
    ///
    /// struct Foo {
    ///     x: a::b::SecretlyUninhabited,
    ///     y: c::AlsoSecretlyUninhabited,
    /// }
    /// ```
    /// In this code, the type `Foo` will only be visibly uninhabited inside the
    /// modules b, c and d. This effects pattern-matching on `Foo` or types that
    /// contain `Foo`.
    ///
    /// # Example
    /// ```rust
    /// let foo_result: Result<T, Foo> = ... ;
    /// let Ok(t) = foo_result;
    /// ```
    /// This code should only compile in modules where the uninhabitedness of Foo is
    /// visible.
    pub fn is_ty_uninhabited_from(self, module: DefId, ty: Ty<'tcx>) -> bool {
        // To check whether this type is uninhabited at all (not just from the
        // given node) you could check whether the forest is empty.
        // ```
        // forest.is_empty()
        // ```
        self.ty_inhabitedness_forest(ty).contains(self, module)
    }

    fn ty_inhabitedness_forest(self, ty: Ty<'tcx>) -> DefIdForest {
        ty.uninhabited_from(&mut FxHashMap(), self)
    }

    pub fn is_enum_variant_uninhabited_from(self,
                                            module: DefId,
                                            variant: &'tcx VariantDef,
                                            substs: &'tcx Substs<'tcx>)
                                            -> bool
    {
        self.variant_inhabitedness_forest(variant, substs).contains(self, module)
    }

    pub fn is_variant_uninhabited_from_all_modules(self,
                                                   variant: &'tcx VariantDef,
                                                   substs: &'tcx Substs<'tcx>)
                                                   -> bool
    {
        !self.variant_inhabitedness_forest(variant, substs).is_empty()
    }

    fn variant_inhabitedness_forest(self, variant: &'tcx VariantDef, substs: &'tcx Substs<'tcx>)
                                    -> DefIdForest {
        // Determine the ADT kind:
        let adt_def_id = self.adt_def_id_of_variant(variant);
        let adt_kind = self.adt_def(adt_def_id).adt_kind();

        // Compute inhabitedness forest:
        variant.uninhabited_from(&mut FxHashMap(), self, substs, adt_kind)
    }
}

impl<'a, 'gcx, 'tcx> AdtDef {
    /// Calculate the forest of DefIds from which this adt is visibly uninhabited.
    fn uninhabited_from(
        &self,
        visited: &mut FxHashMap<DefId, FxHashSet<&'tcx Substs<'tcx>>>,
        tcx: TyCtxt<'a, 'gcx, 'tcx>,
        substs: &'tcx Substs<'tcx>) -> DefIdForest
    {
        DefIdForest::intersection(tcx, self.variants.iter().map(|v| {
            v.uninhabited_from(visited, tcx, substs, self.adt_kind())
        }))
    }
}

impl<'a, 'gcx, 'tcx> VariantDef {
    /// Calculate the forest of DefIds from which this variant is visibly uninhabited.
    fn uninhabited_from(
        &self,
        visited: &mut FxHashMap<DefId, FxHashSet<&'tcx Substs<'tcx>>>,
        tcx: TyCtxt<'a, 'gcx, 'tcx>,
        substs: &'tcx Substs<'tcx>,
        adt_kind: AdtKind) -> DefIdForest
    {
        match adt_kind {
            AdtKind::Union => {
                DefIdForest::intersection(tcx, self.fields.iter().map(|f| {
                    f.uninhabited_from(visited, tcx, substs, false)
                }))
            },
            AdtKind::Struct => {
                DefIdForest::union(tcx, self.fields.iter().map(|f| {
                    f.uninhabited_from(visited, tcx, substs, false)
                }))
            },
            AdtKind::Enum => {
                DefIdForest::union(tcx, self.fields.iter().map(|f| {
                    f.uninhabited_from(visited, tcx, substs, true)
                }))
            },
        }
    }
}

impl<'a, 'gcx, 'tcx> FieldDef {
    /// Calculate the forest of DefIds from which this field is visibly uninhabited.
    fn uninhabited_from(
        &self,
        visited: &mut FxHashMap<DefId, FxHashSet<&'tcx Substs<'tcx>>>,
        tcx: TyCtxt<'a, 'gcx, 'tcx>,
        substs: &'tcx Substs<'tcx>,
        is_enum: bool) -> DefIdForest
    {
        let mut data_uninhabitedness = move || {
            self.ty(tcx, substs).uninhabited_from(visited, tcx)
        };
        // FIXME(canndrew): Currently enum fields are (incorrectly) stored with
        // Visibility::Invisible so we need to override self.vis if we're
        // dealing with an enum.
        if is_enum {
            data_uninhabitedness()
        } else {
            match self.vis {
                Visibility::Invisible => DefIdForest::empty(),
                Visibility::Restricted(from) => {
                    let forest = DefIdForest::from_id(from);
                    let iter = Some(forest).into_iter().chain(Some(data_uninhabitedness()));
                    DefIdForest::intersection(tcx, iter)
                },
                Visibility::Public => data_uninhabitedness(),
            }
        }
    }
}

impl<'a, 'gcx, 'tcx> TyS<'tcx> {
    /// Calculate the forest of DefIds from which this type is visibly uninhabited.
    fn uninhabited_from(
        &self,
        visited: &mut FxHashMap<DefId, FxHashSet<&'tcx Substs<'tcx>>>,
        tcx: TyCtxt<'a, 'gcx, 'tcx>) -> DefIdForest
    {
        match self.sty {
            TyAdt(def, substs) => {
                {
                    let substs_set = visited.entry(def.did).or_insert(FxHashSet::default());
                    if !substs_set.insert(substs) {
                        // We are already calculating the inhabitedness of this type.
                        // The type must contain a reference to itself. Break the
                        // infinite loop.
                        return DefIdForest::empty();
                    }
                    if substs_set.len() >= tcx.sess.recursion_limit.get() / 4 {
                        // We have gone very deep, reinstantiating this ADT inside
                        // itself with different type arguments. We are probably
                        // hitting an infinite loop. For example, it's possible to write:
                        //                a type Foo<T>
                        //      which contains a Foo<(T, T)>
                        //      which contains a Foo<((T, T), (T, T))>
                        //      which contains a Foo<(((T, T), (T, T)), ((T, T), (T, T)))>
                        //      etc.
                        let error = format!("reached recursion limit while checking \
                                             inhabitedness of `{}`", self);
                        tcx.sess.fatal(&error);
                    }
                }
                let ret = def.uninhabited_from(visited, tcx, substs);
                let substs_set = visited.get_mut(&def.did).unwrap();
                substs_set.remove(substs);
                ret
            },

            TyNever => DefIdForest::full(tcx),
            TyTuple(ref tys, _) => {
                DefIdForest::union(tcx, tys.iter().map(|ty| {
                    ty.uninhabited_from(visited, tcx)
                }))
            },
            TyArray(ty, len) => {
                if len.val.to_const_int().and_then(|i| i.to_u64()) == Some(0) {
                    DefIdForest::empty()
                } else {
                    ty.uninhabited_from(visited, tcx)
                }
            }
            TyRef(_, ref tm) => {
                tm.ty.uninhabited_from(visited, tcx)
            }

            _ => DefIdForest::empty(),
        }
    }
}

<commit_msg>add a function for testing if a ty is uninhabited from all modules<commit_after>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use util::nodemap::{FxHashMap, FxHashSet};
use ty::context::TyCtxt;
use ty::{AdtDef, VariantDef, FieldDef, Ty, TyS};
use ty::{DefId, Substs};
use ty::{AdtKind, Visibility};
use ty::TypeVariants::*;

pub use self::def_id_forest::DefIdForest;

mod def_id_forest;

// The methods in this module calculate DefIdForests of modules in which a
// AdtDef/VariantDef/FieldDef is visibly uninhabited.
//
// # Example
// ```rust
// enum Void {}
// mod a {
//     pub mod b {
//         pub struct SecretlyUninhabited {
//             _priv: !,
//         }
//     }
// }
//
// mod c {
//     pub struct AlsoSecretlyUninhabited {
//         _priv: Void,
//     }
//     mod d {
//     }
// }
//
// struct Foo {
//     x: a::b::SecretlyUninhabited,
//     y: c::AlsoSecretlyUninhabited,
// }
// ```
// In this code, the type Foo will only be visibly uninhabited inside the
// modules b, c and d. Calling uninhabited_from on Foo or its AdtDef will
// return the forest of modules {b, c->d} (represented in a DefIdForest by the
// set {b, c})
//
// We need this information for pattern-matching on Foo or types that contain
// Foo.
//
// # Example
// ```rust
// let foo_result: Result<T, Foo> = ... ;
// let Ok(t) = foo_result;
// ```
// This code should only compile in modules where the uninhabitedness of Foo is
// visible.

impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
    /// Checks whether a type is visibly uninhabited from a particular module.
    /// # Example
    /// ```rust
    /// enum Void {}
    /// mod a {
    ///     pub mod b {
    ///         pub struct SecretlyUninhabited {
    ///             _priv: !,
    ///         }
    ///     }
    /// }
    ///
    /// mod c {
    ///     pub struct AlsoSecretlyUninhabited {
    ///         _priv: Void,
    ///     }
    ///     mod d {
    ///     }
    /// }
    ///
    /// struct Foo {
    ///     x: a::b::SecretlyUninhabited,
    ///     y: c::AlsoSecretlyUninhabited,
    /// }
    /// ```
    /// In this code, the type `Foo` will only be visibly uninhabited inside the
    /// modules b, c and d. This effects pattern-matching on `Foo` or types that
    /// contain `Foo`.
    ///
    /// # Example
    /// ```rust
    /// let foo_result: Result<T, Foo> = ... ;
    /// let Ok(t) = foo_result;
    /// ```
    /// This code should only compile in modules where the uninhabitedness of Foo is
    /// visible.
    pub fn is_ty_uninhabited_from(self, module: DefId, ty: Ty<'tcx>) -> bool {
        // To check whether this type is uninhabited at all (not just from the
        // given node) you could check whether the forest is empty.
        // ```
        // forest.is_empty()
        // ```
        self.ty_inhabitedness_forest(ty).contains(self, module)
    }

    pub fn is_ty_uninhabited_from_all_modules(self, ty: Ty<'tcx>) -> bool {
        !self.ty_inhabitedness_forest(ty).is_empty()
    }

    fn ty_inhabitedness_forest(self, ty: Ty<'tcx>) -> DefIdForest {
        ty.uninhabited_from(&mut FxHashMap(), self)
    }

    pub fn is_enum_variant_uninhabited_from(self,
                                            module: DefId,
                                            variant: &'tcx VariantDef,
                                            substs: &'tcx Substs<'tcx>)
                                            -> bool
    {
        self.variant_inhabitedness_forest(variant, substs).contains(self, module)
    }

    pub fn is_variant_uninhabited_from_all_modules(self,
                                                   variant: &'tcx VariantDef,
                                                   substs: &'tcx Substs<'tcx>)
                                                   -> bool
    {
        !self.variant_inhabitedness_forest(variant, substs).is_empty()
    }

    fn variant_inhabitedness_forest(self, variant: &'tcx VariantDef, substs: &'tcx Substs<'tcx>)
                                    -> DefIdForest {
        // Determine the ADT kind:
        let adt_def_id = self.adt_def_id_of_variant(variant);
        let adt_kind = self.adt_def(adt_def_id).adt_kind();

        // Compute inhabitedness forest:
        variant.uninhabited_from(&mut FxHashMap(), self, substs, adt_kind)
    }
}

impl<'a, 'gcx, 'tcx> AdtDef {
    /// Calculate the forest of DefIds from which this adt is visibly uninhabited.
    fn uninhabited_from(
        &self,
        visited: &mut FxHashMap<DefId, FxHashSet<&'tcx Substs<'tcx>>>,
        tcx: TyCtxt<'a, 'gcx, 'tcx>,
        substs: &'tcx Substs<'tcx>) -> DefIdForest
    {
        DefIdForest::intersection(tcx, self.variants.iter().map(|v| {
            v.uninhabited_from(visited, tcx, substs, self.adt_kind())
        }))
    }
}

impl<'a, 'gcx, 'tcx> VariantDef {
    /// Calculate the forest of DefIds from which this variant is visibly uninhabited.
    fn uninhabited_from(
        &self,
        visited: &mut FxHashMap<DefId, FxHashSet<&'tcx Substs<'tcx>>>,
        tcx: TyCtxt<'a, 'gcx, 'tcx>,
        substs: &'tcx Substs<'tcx>,
        adt_kind: AdtKind) -> DefIdForest
    {
        match adt_kind {
            AdtKind::Union => {
                DefIdForest::intersection(tcx, self.fields.iter().map(|f| {
                    f.uninhabited_from(visited, tcx, substs, false)
                }))
            },
            AdtKind::Struct => {
                DefIdForest::union(tcx, self.fields.iter().map(|f| {
                    f.uninhabited_from(visited, tcx, substs, false)
                }))
            },
            AdtKind::Enum => {
                DefIdForest::union(tcx, self.fields.iter().map(|f| {
                    f.uninhabited_from(visited, tcx, substs, true)
                }))
            },
        }
    }
}

impl<'a, 'gcx, 'tcx> FieldDef {
    /// Calculate the forest of DefIds from which this field is visibly uninhabited.
    fn uninhabited_from(
        &self,
        visited: &mut FxHashMap<DefId, FxHashSet<&'tcx Substs<'tcx>>>,
        tcx: TyCtxt<'a, 'gcx, 'tcx>,
        substs: &'tcx Substs<'tcx>,
        is_enum: bool) -> DefIdForest
    {
        let mut data_uninhabitedness = move || {
            self.ty(tcx, substs).uninhabited_from(visited, tcx)
        };
        // FIXME(canndrew): Currently enum fields are (incorrectly) stored with
        // Visibility::Invisible so we need to override self.vis if we're
        // dealing with an enum.
        if is_enum {
            data_uninhabitedness()
        } else {
            match self.vis {
                Visibility::Invisible => DefIdForest::empty(),
                Visibility::Restricted(from) => {
                    let forest = DefIdForest::from_id(from);
                    let iter = Some(forest).into_iter().chain(Some(data_uninhabitedness()));
                    DefIdForest::intersection(tcx, iter)
                },
                Visibility::Public => data_uninhabitedness(),
            }
        }
    }
}

impl<'a, 'gcx, 'tcx> TyS<'tcx> {
    /// Calculate the forest of DefIds from which this type is visibly uninhabited.
    fn uninhabited_from(
        &self,
        visited: &mut FxHashMap<DefId, FxHashSet<&'tcx Substs<'tcx>>>,
        tcx: TyCtxt<'a, 'gcx, 'tcx>) -> DefIdForest
    {
        match self.sty {
            TyAdt(def, substs) => {
                {
                    let substs_set = visited.entry(def.did).or_insert(FxHashSet::default());
                    if !substs_set.insert(substs) {
                        // We are already calculating the inhabitedness of this type.
                        // The type must contain a reference to itself. Break the
                        // infinite loop.
                        return DefIdForest::empty();
                    }
                    if substs_set.len() >= tcx.sess.recursion_limit.get() / 4 {
                        // We have gone very deep, reinstantiating this ADT inside
                        // itself with different type arguments. We are probably
                        // hitting an infinite loop. For example, it's possible to write:
                        //                a type Foo<T>
                        //      which contains a Foo<(T, T)>
                        //      which contains a Foo<((T, T), (T, T))>
                        //      which contains a Foo<(((T, T), (T, T)), ((T, T), (T, T)))>
                        //      etc.
                        let error = format!("reached recursion limit while checking \
                                             inhabitedness of `{}`", self);
                        tcx.sess.fatal(&error);
                    }
                }
                let ret = def.uninhabited_from(visited, tcx, substs);
                let substs_set = visited.get_mut(&def.did).unwrap();
                substs_set.remove(substs);
                ret
            },

            TyNever => DefIdForest::full(tcx),
            TyTuple(ref tys, _) => {
                DefIdForest::union(tcx, tys.iter().map(|ty| {
                    ty.uninhabited_from(visited, tcx)
                }))
            },
            TyArray(ty, len) => {
                if len.val.to_const_int().and_then(|i| i.to_u64()) == Some(0) {
                    DefIdForest::empty()
                } else {
                    ty.uninhabited_from(visited, tcx)
                }
            }
            TyRef(_, ref tm) => {
                tm.ty.uninhabited_from(visited, tcx)
            }

            _ => DefIdForest::empty(),
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1599<commit_after>// https://leetcode.com/problems/maximum-profit-of-operating-a-centennial-wheel/
pub fn min_operations_max_profit(
    customers: Vec<i32>,
    boarding_cost: i32,
    running_cost: i32,
) -> i32 {
    todo!()
}

fn main() {
    println!("{}", min_operations_max_profit(vec![8, 3], 5, 6)); // 3
    println!("{}", min_operations_max_profit(vec![10, 9, 6], 6, 4)); // 7
    println!("{}", min_operations_max_profit(vec![3, 4, 0, 5, 1], 1, 92)); // -1
}
<|endoftext|>


<commit_before><commit_msg>imag-bookmark: Replace read with typed read<commit_after><|endoftext|>


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

// error-pattern:thread '<main>' panicked at 'attempted to negate with overflow'
// compile-flags: -C debug-assertions

// (Work around constant-evaluation)
fn value() -> i8 { std::i8::MIN }

fn main() {
    let _x = -value();
}
<|endoftext|>


<commit_before><commit_msg>Adding 1D plotting example using curves from wikipedia<commit_after>extern crate bspline;

use std::iter;

/// Plot a simple 1D quadratic B-spline
fn plot_quadratic() {
    let points = vec![0.0, 0.0, 1.0, 0.0, 0.0];
    let knots = vec![0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0];
    let t_start = knots[0];
    let t_end = knots[knots.len() - 1];

    let plot_w = 80;
    let plot_h = 30;
    let x_scale = plot_w as f32 / knots[knots.len() - 1];
    let y_scale = plot_h as f32 / 1.0;

    let mut plot: Vec<_> = iter::repeat(' ').take(plot_w * plot_h).collect();

    println!("Plotting Quadratic B-spline with:\n\tpoints = {:?}\n\tknots = {:?}",
             points, knots);
    println!("\tStarting at {}, ending at {}", t_start, t_end);
    let spline = bspline::BSpline::new(2, points, knots);

    let step_size = 0.001;
    let steps = ((t_end - t_start) / step_size) as usize;
    for s in 0..steps {
        let t = step_size * s as f32 + t_start;
        let y = spline.point(t);
        let iy = (y * y_scale) as isize;
        let ix = (t * x_scale) as isize;
        if iy >= 0 && iy < plot_h as isize {
            plot[(plot_h - 1 - iy as usize) * plot_w + ix as usize] = 'O';
        }
    }
    for y in 0..plot_h {
        for x in 0..plot_w {
            print!("{}", plot[y * plot_w + x]);
        }
        println!("");
    }
}
/// Plot a simple 1D cubic B-spline
fn plot_cubic() {
    let points = vec![0.0, 0.0, 0.0, 6.0, 0.0, 0.0, 0.0];
    let knots = vec![-2.0, -2.0, -2.0, -2.0, -1.0, 0.0, 1.0, 2.0, 2.0, 2.0, 2.0];
    let t_start = knots[0];
    let t_end = knots[knots.len() - 1];

    let plot_w = 80;
    let plot_h = 30;
    let x_scale = plot_w as f32 / 4.0;
    let x_offset = 2.0;
    let y_scale = plot_h as f32 / 6.0;

    let mut plot: Vec<_> = iter::repeat(' ').take(plot_w * plot_h).collect();

    println!("Plotting Cubic B-spline with:\n\tpoints = {:?}\n\tknots = {:?}",
             points, knots);
    println!("\tStarting at {}, ending at {}", t_start, t_end);
    let spline = bspline::BSpline::new(3, points, knots);

    let step_size = 0.001;
    let steps = ((t_end - t_start) / step_size) as usize;
    for s in 0..steps {
        let t = step_size * s as f32 + t_start;
        let y = spline.point(t);
        let iy = (y * y_scale) as isize;
        let ix = ((t + x_offset) * x_scale) as isize;
        if iy >= 0 && iy < plot_h as isize {
            plot[(plot_h - 1 - iy as usize) * plot_w + ix as usize] = 'O';
        }
    }
    for y in 0..plot_h {
        for x in 0..plot_w {
            print!("{}", plot[y * plot_w + x]);
        }
        println!("");
    }
}
/// Plot a simple 1D quartic B-spline
fn plot_quartic() {
        let points = vec![0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0];
        let knots = vec![0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 5.0, 5.0, 5.0];
    let t_start = knots[0];
    let t_end = knots[knots.len() - 1];

    let plot_w = 80;
    let plot_h = 30;
    let x_scale = plot_w as f32 / 5.0;
    let y_scale = plot_h as f32 / 1.0;

    let mut plot: Vec<_> = iter::repeat(' ').take(plot_w * plot_h).collect();

    println!("Plotting Quartic B-spline with:\n\tpoints = {:?}\n\tknots = {:?}",
             points, knots);
    println!("\tStarting at {}, ending at {}", t_start, t_end);
    let spline = bspline::BSpline::new(4, points, knots);

    let step_size = 0.001;
    let steps = ((t_end - t_start) / step_size) as usize;
    for s in 0..steps {
        let t = step_size * s as f32 + t_start;
        let y = spline.point(t);
        let iy = (y * y_scale) as isize;
        let ix = (t * x_scale) as isize;
        if iy >= 0 && iy < plot_h as isize {
            plot[(plot_h - 1 - iy as usize) * plot_w + ix as usize] = 'O';
        }
    }
    for y in 0..plot_h {
        for x in 0..plot_w {
            print!("{}", plot[y * plot_w + x]);
        }
        println!("");
    }
}

fn main() {
    let divider: String = iter::repeat('-').take(80).collect();
    plot_quadratic();
    println!("{}\n\n{}", divider, divider);
    plot_cubic();
    println!("{}\n\n{}", divider, divider);
    plot_quartic();
}

<|endoftext|>


<commit_before><commit_msg>Add tests<commit_after><|endoftext|>


<commit_before><commit_msg>am 38f79d01: Merge "Make ImageProcessing work." into honeycomb<commit_after><|endoftext|>


<commit_before>use audio::wav::*;

use programs::common::*;

use graphics::bmp::*;

pub struct Sprite {
    point: Point,
    image: BMP
}

impl Sprite {
    pub fn draw(&self, content: &mut Display){
        content.image_alpha(self.point, self.image.data, self.image.size);
    }
}

pub struct Application;

impl SessionItem for Application {
    fn main(&mut self, url: URL){
        let mut window = Window::new(Point::new((rand() % 400 + 50) as isize, (rand() % 300 + 50) as isize), Size::new(640, 480), "Example Game (Loading)".to_string());

        let mut player;
        {
            let mut resource = URL::from_string(&"file:///game/ninjaroofront.bmp".to_string()).open();
            let mut bytes: Vec<u8> = Vec::new();
            resource.read_to_end(&mut bytes);
            player = Sprite {
                point: Point::new(200, 200),
                image: unsafe{ BMP::from_data(bytes.as_ptr() as usize) }
            };
        }

        window.title = "Example Game".to_string();

        let sound;
        {
            let mut resource = URL::from_string(&"file:///game/wilhelm.wav".to_string()).open();
            let mut bytes: Vec<u8> = Vec::new();
            resource.read_to_end(&mut bytes);

            sound = WAV::from_data(&bytes);
        }

        let mut keys: Vec<u8> = Vec::new();
        let mut redraw = true;
        let mut running = true;
        while running {
            loop {
                match window.poll() {
                    EventOption::Key(key_event) => {
                        if key_event.pressed {
                            match key_event.scancode {
                                K_ESC => {
                                    running = false;
                                    break;
                                },
                                K_CTRL => {
                                    let mut resource = URL::from_string(&"audio://".to_string()).open();
                                    resource.write(sound.data.as_slice());
                                },
                                _ => ()
                            }

                            let mut found = false;
                            for key in keys.iter() {
                                if *key == key_event.scancode {
                                    found = true;
                                    break;
                                }
                            }
                            if ! found {
                                keys.push(key_event.scancode);
                            }
                        }else{
                            let mut i = 0;
                            while i < keys.len() {
                                let mut remove = false;
                                if let Option::Some(key) = keys.get(i) {
                                    if *key == key_event.scancode {
                                        remove = true;
                                    }
                                }
                                if remove {
                                    keys.remove(i);
                                }else{
                                    i += 1;
                                }
                            }
                        }
                    },
                    EventOption::None => break,
                    _ => ()
                }
            }

            for key in keys.iter() {
                match *key {
                    K_LEFT => {
                        player.point.x = max(0, player.point.x - 1);
                        redraw = true;
                    },
                    K_RIGHT => {
                        player.point.x = min(window.content.width as isize - 1, player.point.x + 1);
                        redraw = true;
                    },
                    K_UP => {
                        player.point.y = max(0, player.point.y - 1);
                        redraw = true;
                    },
                    K_DOWN => {
                        player.point.y = min(window.content.height as isize - 1, player.point.y + 1);
                        redraw = true;
                    },
                    _ => ()
                }
            }

            if redraw {
                redraw = false;

                let content = &mut window.content;
                content.set(Color::new(128, 128, 255));

                player.draw(content);

                content.flip();

                RedrawEvent {
                    redraw: REDRAW_ALL
                }.trigger();
            }

            Duration::new(0, 1000000000/120).sleep();
        }
    }
}

impl Application {
    pub fn new() -> Application {
        Application
    }
}
<commit_msg>Wait for other audio processes<commit_after>use audio::wav::*;

use programs::common::*;

use graphics::bmp::*;

pub struct Sprite {
    point: Point,
    image: BMP
}

impl Sprite {
    pub fn draw(&self, content: &mut Display){
        content.image_alpha(self.point, self.image.data, self.image.size);
    }
}

pub struct Application;

impl SessionItem for Application {
    fn main(&mut self, url: URL){
        let mut window = Window::new(Point::new((rand() % 400 + 50) as isize, (rand() % 300 + 50) as isize), Size::new(640, 480), "Example Game (Loading)".to_string());
        RedrawEvent { redraw: REDRAW_ALL }.trigger();

        let mut audio = URL::from_string(&"audio://".to_string()).open();

        let mut player;
        {
            let mut resource = URL::from_string(&"file:///game/ninjaroofront.bmp".to_string()).open();
            let mut bytes: Vec<u8> = Vec::new();
            resource.read_to_end(&mut bytes);
            player = Sprite {
                point: Point::new(200, 200),
                image: unsafe{ BMP::from_data(bytes.as_ptr() as usize) }
            };
        }

        let sound;
        {
            let mut resource = URL::from_string(&"file:///game/wilhelm.wav".to_string()).open();
            let mut bytes: Vec<u8> = Vec::new();
            resource.read_to_end(&mut bytes);

            sound = WAV::from_data(&bytes);
        }

        window.title = "Example Game".to_string();
        RedrawEvent { redraw: REDRAW_ALL }.trigger();

        let mut keys: Vec<u8> = Vec::new();
        let mut redraw = true;
        let mut running = true;
        while running {
            loop {
                match window.poll() {
                    EventOption::Key(key_event) => {
                        if key_event.pressed {
                            match key_event.scancode {
                                K_ESC => {
                                    running = false;
                                    break;
                                },
                                K_DEL => {
                                    window.title = "Example Game (Screaming)".to_string();
                                    RedrawEvent { redraw: REDRAW_ALL }.trigger();
                                    audio.write(sound.data.as_slice());
                                    window.title = "Example Game".to_string();
                                    RedrawEvent { redraw: REDRAW_ALL }.trigger();
                                },
                                _ => ()
                            }

                            let mut found = false;
                            for key in keys.iter() {
                                if *key == key_event.scancode {
                                    found = true;
                                    break;
                                }
                            }
                            if ! found {
                                keys.push(key_event.scancode);
                            }
                        }else{
                            let mut i = 0;
                            while i < keys.len() {
                                let mut remove = false;
                                if let Option::Some(key) = keys.get(i) {
                                    if *key == key_event.scancode {
                                        remove = true;
                                    }
                                }
                                if remove {
                                    keys.remove(i);
                                }else{
                                    i += 1;
                                }
                            }
                        }
                    },
                    EventOption::None => break,
                    _ => ()
                }
            }

            for key in keys.iter() {
                match *key {
                    K_LEFT => {
                        player.point.x = max(0, player.point.x - 1);
                        redraw = true;
                    },
                    K_RIGHT => {
                        player.point.x = min(window.content.width as isize - 1, player.point.x + 1);
                        redraw = true;
                    },
                    K_UP => {
                        player.point.y = max(0, player.point.y - 1);
                        redraw = true;
                    },
                    K_DOWN => {
                        player.point.y = min(window.content.height as isize - 1, player.point.y + 1);
                        redraw = true;
                    },
                    _ => ()
                }
            }

            if redraw {
                redraw = false;

                let content = &mut window.content;
                content.set(Color::new(128, 128, 255));

                player.draw(content);

                content.flip();
                RedrawEvent { redraw: REDRAW_ALL }.trigger();
            }

            Duration::new(0, 1000000000/120).sleep();
        }

        window.title = "Example Game (Closing)".to_string();
        RedrawEvent { redraw: REDRAW_ALL }.trigger();

        {
            let mut resource = URL::from_string(&"file:///game/game_over.wav".to_string()).open();
            let mut bytes: Vec<u8> = Vec::new();
            resource.read_to_end(&mut bytes);

            let game_over = WAV::from_data(&bytes);
            audio.write(game_over.data.as_slice());
        }
    }
}

impl Application {
    pub fn new() -> Application {
        Application
    }
}
<|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.

/*!

Operations on the ubiquitous `Option` type.

Type `Option` represents an optional value.

Every `Option<T>` value can either be `Some(T)` or `None`. Where in other
languages you might use a nullable type, in Rust you would use an option
type.

Options are most commonly used with pattern matching to query the presence
of a value and take action, always accounting for the `None` case.

# Example

~~~
let msg = Some(~"howdy");

// Take a reference to the contained string
match msg {
    Some(ref m) => io::println(m),
    None => ()
}

// Remove the contained string, destroying the Option
let unwrapped_msg = match msg {
    Some(m) => m,
    None => ~"default message"
};
~~~

*/

use cmp::{Eq,Ord};
use ops::Add;
use kinds::Copy;
use util;
use num::Zero;
use old_iter::{BaseIter, MutableIter, ExtendedIter};
use old_iter;
use str::StrSlice;
use clone::DeepClone;

#[cfg(test)] use str;

/// The option type
#[deriving(Clone, DeepClone, Eq)]
pub enum Option<T> {
    None,
    Some(T),
}

impl<T:Ord> Ord for Option<T> {
    fn lt(&self, other: &Option<T>) -> bool {
        match (self, other) {
            (&None, &None) => false,
            (&None, &Some(_)) => true,
            (&Some(_), &None) => false,
            (&Some(ref a), &Some(ref b)) => *a < *b
        }
    }

    fn le(&self, other: &Option<T>) -> bool {
        match (self, other) {
            (&None, &None) => true,
            (&None, &Some(_)) => true,
            (&Some(_), &None) => false,
            (&Some(ref a), &Some(ref b)) => *a <= *b
        }
    }

    fn ge(&self, other: &Option<T>) -> bool {
        !(self < other)
    }

    fn gt(&self, other: &Option<T>) -> bool {
        !(self <= other)
    }
}

impl<T: Copy + Add<T,T>> Add<Option<T>, Option<T>> for Option<T> {
    #[inline(always)]
    fn add(&self, other: &Option<T>) -> Option<T> {
        match (*self, *other) {
            (None, None) => None,
            (_, None) => *self,
            (None, _) => *other,
            (Some(ref lhs), Some(ref rhs)) => Some(*lhs + *rhs)
        }
    }
}

impl<T> BaseIter<T> for Option<T> {
    /// Performs an operation on the contained value by reference
    #[inline(always)]
    fn each<'a>(&'a self, f: &fn(x: &'a T) -> bool) -> bool {
        match *self { None => true, Some(ref t) => { f(t) } }
    }

    #[inline(always)]
    fn size_hint(&self) -> Option<uint> {
        if self.is_some() { Some(1) } else { Some(0) }
    }
}

impl<T> MutableIter<T> for Option<T> {
    #[inline(always)]
    fn each_mut<'a>(&'a mut self, f: &fn(&'a mut T) -> bool) -> bool {
        match *self { None => true, Some(ref mut t) => { f(t) } }
    }
}

impl<A> ExtendedIter<A> for Option<A> {
    pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool {
        old_iter::eachi(self, blk)
    }
    pub fn all(&self, blk: &fn(&A) -> bool) -> bool {
        old_iter::all(self, blk)
    }
    pub fn any(&self, blk: &fn(&A) -> bool) -> bool {
        old_iter::any(self, blk)
    }
    pub fn foldl<B>(&self, b0: B, blk: &fn(&B, &A) -> B) -> B {
        old_iter::foldl(self, b0, blk)
    }
    pub fn position(&self, f: &fn(&A) -> bool) -> Option<uint> {
        old_iter::position(self, f)
    }
    fn map_to_vec<B>(&self, op: &fn(&A) -> B) -> ~[B] {
        old_iter::map_to_vec(self, op)
    }
    fn flat_map_to_vec<B,IB:BaseIter<B>>(&self, op: &fn(&A) -> IB)
        -> ~[B] {
        old_iter::flat_map_to_vec(self, op)
    }
}

impl<T> Option<T> {
    /// Returns true if the option equals `none`
    pub fn is_none(&const self) -> bool {
        match *self { None => true, Some(_) => false }
    }

    /// Returns true if the option contains some value
    #[inline(always)]
    pub fn is_some(&const self) -> bool { !self.is_none() }

    /// Update an optional value by optionally running its content through a
    /// function that returns an option.
    #[inline(always)]
    pub fn chain<U>(self, f: &fn(t: T) -> Option<U>) -> Option<U> {
        match self {
            Some(t) => f(t),
            None => None
        }
    }

    /// Returns the leftmost Some() value, or None if both are None.
    #[inline(always)]
    pub fn or(self, optb: Option<T>) -> Option<T> {
        match self {
            Some(opta) => Some(opta),
            _ => optb
        }
    }

    /// Update an optional value by optionally running its content by reference
    /// through a function that returns an option.
    #[inline(always)]
    pub fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option<U>)
                            -> Option<U> {
        match *self {
            Some(ref x) => f(x),
            None => None
        }
    }

    /// Maps a `some` value from one type to another by reference
    #[inline(always)]
    pub fn map<'a, U>(&self, f: &fn(&'a T) -> U) -> Option<U> {
        match *self { Some(ref x) => Some(f(x)), None => None }
    }

    /// As `map`, but consumes the option and gives `f` ownership to avoid
    /// copying.
    #[inline(always)]
    pub fn map_consume<U>(self, f: &fn(v: T) -> U) -> Option<U> {
        match self { None => None, Some(v) => Some(f(v)) }
    }

    /// Applies a function to the contained value or returns a default
    #[inline(always)]
    pub fn map_default<'a, U>(&'a self, def: U, f: &fn(&'a T) -> U) -> U {
        match *self { None => def, Some(ref t) => f(t) }
    }

    /// As `map_default`, but consumes the option and gives `f`
    /// ownership to avoid copying.
    #[inline(always)]
    pub fn map_consume_default<U>(self, def: U, f: &fn(v: T) -> U) -> U {
        match self { None => def, Some(v) => f(v) }
    }

    /// Apply a function to the contained value or do nothing
    pub fn mutate(&mut self, f: &fn(T) -> T) {
        if self.is_some() {
            *self = Some(f(self.swap_unwrap()));
        }
    }

    /// Apply a function to the contained value or set it to a default
    pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) {
        if self.is_some() {
            *self = Some(f(self.swap_unwrap()));
        } else {
            *self = Some(def);
        }
    }

    /**
    Gets an immutable reference to the value inside an option.

    # Failure

    Fails if the value equals `None`

    # Safety note

    In general, because this function may fail, its use is discouraged
    (calling `get` on `None` is akin to dereferencing a null pointer).
    Instead, prefer to use pattern matching and handle the `None`
    case explicitly.
     */
    #[inline(always)]
    pub fn get_ref<'a>(&'a self) -> &'a T {
        match *self {
          Some(ref x) => x,
          None => fail!("option::get_ref none")
        }
    }

    /**
    Gets a mutable reference to the value inside an option.

    # Failure

    Fails if the value equals `None`

    # Safety note

    In general, because this function may fail, its use is discouraged
    (calling `get` on `None` is akin to dereferencing a null pointer).
    Instead, prefer to use pattern matching and handle the `None`
    case explicitly.
     */
    #[inline(always)]
    pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
        match *self {
          Some(ref mut x) => x,
          None => fail!("option::get_mut_ref none")
        }
    }

    #[inline(always)]
    pub fn unwrap(self) -> T {
        /*!
        Moves a value out of an option type and returns it.

        Useful primarily for getting strings, vectors and unique pointers out
        of option types without copying them.

        # Failure

        Fails if the value equals `None`.

        # Safety note

        In general, because this function may fail, its use is discouraged.
        Instead, prefer to use pattern matching and handle the `None`
        case explicitly.
         */
        match self {
          Some(x) => x,
          None => fail!("option::unwrap none")
        }
    }

    /**
     * The option dance. Moves a value out of an option type and returns it,
     * replacing the original with `None`.
     *
     * # Failure
     *
     * Fails if the value equals `None`.
     */
    #[inline(always)]
    pub fn swap_unwrap(&mut self) -> T {
        if self.is_none() { fail!("option::swap_unwrap none") }
        util::replace(self, None).unwrap()
    }

    /**
     * Gets the value out of an option, printing a specified message on
     * failure
     *
     * # Failure
     *
     * Fails if the value equals `none`
     */
    #[inline(always)]
    pub fn expect(self, reason: &str) -> T {
        match self {
          Some(val) => val,
          None => fail!(reason.to_owned()),
        }
    }
}

impl<T:Copy> Option<T> {
    /**
    Gets the value out of an option

    # Failure

    Fails if the value equals `None`

    # Safety note

    In general, because this function may fail, its use is discouraged
    (calling `get` on `None` is akin to dereferencing a null pointer).
    Instead, prefer to use pattern matching and handle the `None`
    case explicitly.
    */
    #[inline(always)]
    pub fn get(self) -> T {
        match self {
          Some(x) => return x,
          None => fail!("option::get none")
        }
    }

    /// Returns the contained value or a default
    #[inline(always)]
    pub fn get_or_default(self, def: T) -> T {
        match self { Some(x) => x, None => def }
    }

    /// Applies a function zero or more times until the result is none.
    #[inline(always)]
    pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
        let mut opt = self;
        while opt.is_some() {
            opt = blk(opt.unwrap());
        }
    }
}

impl<T:Copy + Zero> Option<T> {
    /// Returns the contained value or zero (for this type)
    #[inline(always)]
    pub fn get_or_zero(self) -> T {
        match self {
            Some(x) => x,
            None => Zero::zero()
        }
    }
}

#[test]
fn test_unwrap_ptr() {
    unsafe {
        let x = ~0;
        let addr_x: *int = ::cast::transmute(&*x);
        let opt = Some(x);
        let y = opt.unwrap();
        let addr_y: *int = ::cast::transmute(&*y);
        assert_eq!(addr_x, addr_y);
    }
}

#[test]
fn test_unwrap_str() {
    let x = ~"test";
    let addr_x = str::as_buf(x, |buf, _len| buf);
    let opt = Some(x);
    let y = opt.unwrap();
    let addr_y = str::as_buf(y, |buf, _len| buf);
    assert_eq!(addr_x, addr_y);
}

#[test]
fn test_unwrap_resource() {
    struct R {
       i: @mut int,
    }

    #[unsafe_destructor]
    impl ::ops::Drop for R {
       fn finalize(&self) { *(self.i) += 1; }
    }

    fn R(i: @mut int) -> R {
        R {
            i: i
        }
    }

    let i = @mut 0;
    {
        let x = R(i);
        let opt = Some(x);
        let _y = opt.unwrap();
    }
    assert_eq!(*i, 1);
}

#[test]
fn test_option_dance() {
    let x = Some(());
    let mut y = Some(5);
    let mut y2 = 0;
    for x.each |_x| {
        y2 = y.swap_unwrap();
    }
    assert_eq!(y2, 5);
    assert!(y.is_none());
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_option_too_much_dance() {
    let mut y = Some(util::NonCopyable::new());
    let _y2 = y.swap_unwrap();
    let _y3 = y.swap_unwrap();
}

#[test]
fn test_option_while_some() {
    let mut i = 0;
    do Some(10).while_some |j| {
        i += 1;
        if (j > 0) {
            Some(j-1)
        } else {
            None
        }
    }
    assert_eq!(i, 11);
}

#[test]
fn test_get_or_zero() {
    let some_stuff = Some(42);
    assert_eq!(some_stuff.get_or_zero(), 42);
    let no_stuff: Option<int> = None;
    assert_eq!(no_stuff.get_or_zero(), 0);
}
<commit_msg>add Iterator implementations for Option<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.

/*!

Operations on the ubiquitous `Option` type.

Type `Option` represents an optional value.

Every `Option<T>` value can either be `Some(T)` or `None`. Where in other
languages you might use a nullable type, in Rust you would use an option
type.

Options are most commonly used with pattern matching to query the presence
of a value and take action, always accounting for the `None` case.

# Example

~~~
let msg = Some(~"howdy");

// Take a reference to the contained string
match msg {
    Some(ref m) => io::println(m),
    None => ()
}

// Remove the contained string, destroying the Option
let unwrapped_msg = match msg {
    Some(m) => m,
    None => ~"default message"
};
~~~

*/

use cmp::{Eq,Ord};
use ops::Add;
use kinds::Copy;
use util;
use num::Zero;
use old_iter::{BaseIter, MutableIter, ExtendedIter};
use old_iter;
use iterator::Iterator;
use str::StrSlice;
use clone::DeepClone;

#[cfg(test)] use str;

/// The option type
#[deriving(Clone, DeepClone, Eq)]
pub enum Option<T> {
    None,
    Some(T),
}

impl<T:Ord> Ord for Option<T> {
    fn lt(&self, other: &Option<T>) -> bool {
        match (self, other) {
            (&None, &None) => false,
            (&None, &Some(_)) => true,
            (&Some(_), &None) => false,
            (&Some(ref a), &Some(ref b)) => *a < *b
        }
    }

    fn le(&self, other: &Option<T>) -> bool {
        match (self, other) {
            (&None, &None) => true,
            (&None, &Some(_)) => true,
            (&Some(_), &None) => false,
            (&Some(ref a), &Some(ref b)) => *a <= *b
        }
    }

    fn ge(&self, other: &Option<T>) -> bool {
        !(self < other)
    }

    fn gt(&self, other: &Option<T>) -> bool {
        !(self <= other)
    }
}

impl<T: Copy + Add<T,T>> Add<Option<T>, Option<T>> for Option<T> {
    #[inline(always)]
    fn add(&self, other: &Option<T>) -> Option<T> {
        match (*self, *other) {
            (None, None) => None,
            (_, None) => *self,
            (None, _) => *other,
            (Some(ref lhs), Some(ref rhs)) => Some(*lhs + *rhs)
        }
    }
}

impl<T> BaseIter<T> for Option<T> {
    /// Performs an operation on the contained value by reference
    #[inline(always)]
    fn each<'a>(&'a self, f: &fn(x: &'a T) -> bool) -> bool {
        match *self { None => true, Some(ref t) => { f(t) } }
    }

    #[inline(always)]
    fn size_hint(&self) -> Option<uint> {
        if self.is_some() { Some(1) } else { Some(0) }
    }
}

impl<T> MutableIter<T> for Option<T> {
    #[inline(always)]
    fn each_mut<'a>(&'a mut self, f: &fn(&'a mut T) -> bool) -> bool {
        match *self { None => true, Some(ref mut t) => { f(t) } }
    }
}

impl<A> ExtendedIter<A> for Option<A> {
    pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool {
        old_iter::eachi(self, blk)
    }
    pub fn all(&self, blk: &fn(&A) -> bool) -> bool {
        old_iter::all(self, blk)
    }
    pub fn any(&self, blk: &fn(&A) -> bool) -> bool {
        old_iter::any(self, blk)
    }
    pub fn foldl<B>(&self, b0: B, blk: &fn(&B, &A) -> B) -> B {
        old_iter::foldl(self, b0, blk)
    }
    pub fn position(&self, f: &fn(&A) -> bool) -> Option<uint> {
        old_iter::position(self, f)
    }
    fn map_to_vec<B>(&self, op: &fn(&A) -> B) -> ~[B] {
        old_iter::map_to_vec(self, op)
    }
    fn flat_map_to_vec<B,IB:BaseIter<B>>(&self, op: &fn(&A) -> IB)
        -> ~[B] {
        old_iter::flat_map_to_vec(self, op)
    }
}

impl<T> Option<T> {
    #[inline]
    pub fn iter<'r>(&'r self) -> OptionIterator<'r, T> {
        match *self {
            Some(ref x) => OptionIterator{opt: Some(x)},
            None => OptionIterator{opt: None}
        }
    }

    #[inline]
    pub fn mut_iter<'r>(&'r mut self) -> OptionMutIterator<'r, T> {
        match *self {
            Some(ref mut x) => OptionMutIterator{opt: Some(x)},
            None => OptionMutIterator{opt: None}
        }
    }

    /// Returns true if the option equals `none`
    #[inline]
    pub fn is_none(&const self) -> bool {
        match *self { None => true, Some(_) => false }
    }

    /// Returns true if the option contains some value
    #[inline(always)]
    pub fn is_some(&const self) -> bool { !self.is_none() }

    /// Update an optional value by optionally running its content through a
    /// function that returns an option.
    #[inline(always)]
    pub fn chain<U>(self, f: &fn(t: T) -> Option<U>) -> Option<U> {
        match self {
            Some(t) => f(t),
            None => None
        }
    }

    /// Returns the leftmost Some() value, or None if both are None.
    #[inline(always)]
    pub fn or(self, optb: Option<T>) -> Option<T> {
        match self {
            Some(opta) => Some(opta),
            _ => optb
        }
    }

    /// Update an optional value by optionally running its content by reference
    /// through a function that returns an option.
    #[inline(always)]
    pub fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option<U>)
                            -> Option<U> {
        match *self {
            Some(ref x) => f(x),
            None => None
        }
    }

    /// Maps a `some` value from one type to another by reference
    #[inline(always)]
    pub fn map<'a, U>(&self, f: &fn(&'a T) -> U) -> Option<U> {
        match *self { Some(ref x) => Some(f(x)), None => None }
    }

    /// As `map`, but consumes the option and gives `f` ownership to avoid
    /// copying.
    #[inline(always)]
    pub fn map_consume<U>(self, f: &fn(v: T) -> U) -> Option<U> {
        match self { None => None, Some(v) => Some(f(v)) }
    }

    /// Applies a function to the contained value or returns a default
    #[inline(always)]
    pub fn map_default<'a, U>(&'a self, def: U, f: &fn(&'a T) -> U) -> U {
        match *self { None => def, Some(ref t) => f(t) }
    }

    /// As `map_default`, but consumes the option and gives `f`
    /// ownership to avoid copying.
    #[inline(always)]
    pub fn map_consume_default<U>(self, def: U, f: &fn(v: T) -> U) -> U {
        match self { None => def, Some(v) => f(v) }
    }

    /// Apply a function to the contained value or do nothing
    pub fn mutate(&mut self, f: &fn(T) -> T) {
        if self.is_some() {
            *self = Some(f(self.swap_unwrap()));
        }
    }

    /// Apply a function to the contained value or set it to a default
    pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) {
        if self.is_some() {
            *self = Some(f(self.swap_unwrap()));
        } else {
            *self = Some(def);
        }
    }

    /**
    Gets an immutable reference to the value inside an option.

    # Failure

    Fails if the value equals `None`

    # Safety note

    In general, because this function may fail, its use is discouraged
    (calling `get` on `None` is akin to dereferencing a null pointer).
    Instead, prefer to use pattern matching and handle the `None`
    case explicitly.
     */
    #[inline(always)]
    pub fn get_ref<'a>(&'a self) -> &'a T {
        match *self {
          Some(ref x) => x,
          None => fail!("option::get_ref none")
        }
    }

    /**
    Gets a mutable reference to the value inside an option.

    # Failure

    Fails if the value equals `None`

    # Safety note

    In general, because this function may fail, its use is discouraged
    (calling `get` on `None` is akin to dereferencing a null pointer).
    Instead, prefer to use pattern matching and handle the `None`
    case explicitly.
     */
    #[inline(always)]
    pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
        match *self {
          Some(ref mut x) => x,
          None => fail!("option::get_mut_ref none")
        }
    }

    #[inline(always)]
    pub fn unwrap(self) -> T {
        /*!
        Moves a value out of an option type and returns it.

        Useful primarily for getting strings, vectors and unique pointers out
        of option types without copying them.

        # Failure

        Fails if the value equals `None`.

        # Safety note

        In general, because this function may fail, its use is discouraged.
        Instead, prefer to use pattern matching and handle the `None`
        case explicitly.
         */
        match self {
          Some(x) => x,
          None => fail!("option::unwrap none")
        }
    }

    /**
     * The option dance. Moves a value out of an option type and returns it,
     * replacing the original with `None`.
     *
     * # Failure
     *
     * Fails if the value equals `None`.
     */
    #[inline(always)]
    pub fn swap_unwrap(&mut self) -> T {
        if self.is_none() { fail!("option::swap_unwrap none") }
        util::replace(self, None).unwrap()
    }

    /**
     * Gets the value out of an option, printing a specified message on
     * failure
     *
     * # Failure
     *
     * Fails if the value equals `none`
     */
    #[inline(always)]
    pub fn expect(self, reason: &str) -> T {
        match self {
          Some(val) => val,
          None => fail!(reason.to_owned()),
        }
    }
}

impl<T:Copy> Option<T> {
    /**
    Gets the value out of an option

    # Failure

    Fails if the value equals `None`

    # Safety note

    In general, because this function may fail, its use is discouraged
    (calling `get` on `None` is akin to dereferencing a null pointer).
    Instead, prefer to use pattern matching and handle the `None`
    case explicitly.
    */
    #[inline(always)]
    pub fn get(self) -> T {
        match self {
          Some(x) => return x,
          None => fail!("option::get none")
        }
    }

    /// Returns the contained value or a default
    #[inline(always)]
    pub fn get_or_default(self, def: T) -> T {
        match self { Some(x) => x, None => def }
    }

    /// Applies a function zero or more times until the result is none.
    #[inline(always)]
    pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
        let mut opt = self;
        while opt.is_some() {
            opt = blk(opt.unwrap());
        }
    }
}

impl<T:Copy + Zero> Option<T> {
    /// Returns the contained value or zero (for this type)
    #[inline(always)]
    pub fn get_or_zero(self) -> T {
        match self {
            Some(x) => x,
            None => Zero::zero()
        }
    }
}

pub struct OptionIterator<'self, A> {
    priv opt: Option<&'self A>
}

impl<'self, A> Iterator<&'self A> for OptionIterator<'self, A> {
    fn next(&mut self) -> Option<&'self A> {
        util::replace(&mut self.opt, None)
    }
}

pub struct OptionMutIterator<'self, A> {
    priv opt: Option<&'self mut A>
}

impl<'self, A> Iterator<&'self mut A> for OptionMutIterator<'self, A> {
    fn next(&mut self) -> Option<&'self mut A> {
        util::replace(&mut self.opt, None)
    }
}

#[test]
fn test_unwrap_ptr() {
    unsafe {
        let x = ~0;
        let addr_x: *int = ::cast::transmute(&*x);
        let opt = Some(x);
        let y = opt.unwrap();
        let addr_y: *int = ::cast::transmute(&*y);
        assert_eq!(addr_x, addr_y);
    }
}

#[test]
fn test_unwrap_str() {
    let x = ~"test";
    let addr_x = str::as_buf(x, |buf, _len| buf);
    let opt = Some(x);
    let y = opt.unwrap();
    let addr_y = str::as_buf(y, |buf, _len| buf);
    assert_eq!(addr_x, addr_y);
}

#[test]
fn test_unwrap_resource() {
    struct R {
       i: @mut int,
    }

    #[unsafe_destructor]
    impl ::ops::Drop for R {
       fn finalize(&self) { *(self.i) += 1; }
    }

    fn R(i: @mut int) -> R {
        R {
            i: i
        }
    }

    let i = @mut 0;
    {
        let x = R(i);
        let opt = Some(x);
        let _y = opt.unwrap();
    }
    assert_eq!(*i, 1);
}

#[test]
fn test_option_dance() {
    let x = Some(());
    let mut y = Some(5);
    let mut y2 = 0;
    for x.each |_x| {
        y2 = y.swap_unwrap();
    }
    assert_eq!(y2, 5);
    assert!(y.is_none());
}
#[test] #[should_fail] #[ignore(cfg(windows))]
fn test_option_too_much_dance() {
    let mut y = Some(util::NonCopyable::new());
    let _y2 = y.swap_unwrap();
    let _y3 = y.swap_unwrap();
}

#[test]
fn test_option_while_some() {
    let mut i = 0;
    do Some(10).while_some |j| {
        i += 1;
        if (j > 0) {
            Some(j-1)
        } else {
            None
        }
    }
    assert_eq!(i, 11);
}

#[test]
fn test_get_or_zero() {
    let some_stuff = Some(42);
    assert_eq!(some_stuff.get_or_zero(), 42);
    let no_stuff: Option<int> = None;
    assert_eq!(no_stuff.get_or_zero(), 0);
}
<|endoftext|>


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

//! A type representing either success or failure

#[allow(missing_doc)];

use clone::Clone;
use cmp::Eq;
use either;
use either::Either;
use iterator::IteratorUtil;
use option::{None, Option, Some};
use vec;
use vec::{OwnedVector, ImmutableVector};
use container::Container;

/// The result type
#[deriving(Clone, Eq)]
pub enum Result<T, U> {
    /// Contains the successful result value
    Ok(T),
    /// Contains the error value
    Err(U)
}

impl<T, E> Result<T, E> {
    /**
     * Convert to the `either` type
     *
     * `Ok` result variants are converted to `either::Right` variants, `Err`
     * result variants are converted to `either::Left`.
     */
    #[inline]
    pub fn to_either(self)-> Either<E, T>{
        match self {
            Ok(t) => either::Right(t),
            Err(e) => either::Left(e),
        }
    }

    /**
     * Get a reference to the value out of a successful result
     *
     * # Failure
     *
     * If the result is an error
     */
    #[inline]
    pub fn get_ref<'a>(&'a self) -> &'a T {
        match *self {
            Ok(ref t) => t,
            Err(ref e) => fail!("get_ref called on `Err` result: %?", *e),
        }
    }

    /// Returns true if the result is `Ok`
    #[inline]
    pub fn is_ok(&self) -> bool {
        match *self {
            Ok(_) => true,
            Err(_) => false
        }
    }

    /// Returns true if the result is `Err`
    #[inline]
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Ok` then the value is extracted and passed to `op`
     * whereupon `op`s result is returned. if `self` is `Err` then it is
     * immediately returned. This function can be used to compose the results
     * of two functions.
     *
     * Example:
     *
     *     do read_file(file).iter |buf| {
     *         print_buf(buf)
     *     }
     */
    #[inline]
    pub fn iter(&self, f: &fn(&T)) {
        match *self {
            Ok(ref t) => f(t),
            Err(_) => (),
        }
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Err` then the value is extracted and passed to `op`
     * whereupon `op`s result is returned. if `self` is `Ok` then it is
     * immediately returned.  This function can be used to pass through a
     * successful result while handling an error.
     */
    #[inline]
    pub fn iter_err(&self, f: &fn(&E)) {
        match *self {
            Ok(_) => (),
            Err(ref e) => f(e),
        }
    }

    /// Unwraps a result, assuming it is an `Ok(T)`
    #[inline]
    pub fn unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(_) => fail!("unwrap called on an `Err` result"),
        }
    }

    /// Unwraps a result, assuming it is an `Err(U)`
    #[inline]
    pub fn unwrap_err(self) -> E {
        match self {
            Err(e) => e,
            Ok(_) => fail!("unwrap called on an `Ok` result"),
        }
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Ok` then the value is extracted and passed to `op`
     * whereupon `op`s result is returned. if `self` is `Err` then it is
     * immediately returned. This function can be used to compose the results
     * of two functions.
     *
     * Example:
     *
     *     let res = do read_file(file) |buf| {
     *         Ok(parse_bytes(buf))
     *     };
     */
    #[inline]
    pub fn chain<U>(self, op: &fn(T) -> Result<U, E>) -> Result<U, E> {
        match self {
            Ok(t) => op(t),
            Err(e) => Err(e),
        }
    }

    /**
     * Call a function based on a previous result
     *
     * If `self` is `Err` then the value is extracted and passed to `op`
     * whereupon `op`s result is returned. if `self` is `Ok` then it is
     * immediately returned.  This function can be used to pass through a
     * successful result while handling an error.
     */
    #[inline]
    pub fn chain_err<F>(self, op: &fn(E) -> Result<T, F>) -> Result<T, F> {
        match self {
            Ok(t) => Ok(t),
            Err(e) => op(e),
        }
    }
}

impl<T: Clone, E> Result<T, E> {
    /**
     * Get the value out of a successful result
     *
     * # Failure
     *
     * If the result is an error
     */
    #[inline]
    pub fn get(&self) -> T {
        match *self {
            Ok(ref t) => t.clone(),
            Err(ref e) => fail!("get called on `Err` result: %?", *e),
        }
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Err` then the value is extracted and passed to `op`
     * whereupon `op`s result is wrapped in an `Err` and returned. if `self` is
     * `Ok` then it is immediately returned.  This function can be used to pass
     * through a successful result while handling an error.
     */
    #[inline]
    pub fn map_err<F:Clone>(&self, op: &fn(&E) -> F) -> Result<T,F> {
        match *self {
            Ok(ref t) => Ok(t.clone()),
            Err(ref e) => Err(op(e))
        }
    }
}

impl<T, E: Clone> Result<T, E> {
    /**
     * Get the value out of an error result
     *
     * # Failure
     *
     * If the result is not an error
     */
    #[inline]
    pub fn get_err(&self) -> E {
        match *self {
            Err(ref e) => e.clone(),
            Ok(_) => fail!("get_err called on `Ok` result")
        }
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Ok` then the value is extracted and passed to `op`
     * whereupon `op`s result is wrapped in `Ok` and returned. if `self` is
     * `Err` then it is immediately returned.  This function can be used to
     * compose the results of two functions.
     *
     * Example:
     *
     *     let res = do read_file(file).map |buf| {
     *         parse_bytes(buf)
     *     };
     */
    #[inline]
    pub fn map<U:Clone>(&self, op: &fn(&T) -> U) -> Result<U,E> {
        match *self {
            Ok(ref t) => Ok(op(t)),
            Err(ref e) => Err(e.clone())
        }
    }
}

/**
 * Maps each element in the vector `ts` using the operation `op`.  Should an
 * error occur, no further mappings are performed and the error is returned.
 * Should no error occur, a vector containing the result of each map is
 * returned.
 *
 * Here is an example which increments every integer in a vector,
 * checking for overflow:
 *
 *     fn inc_conditionally(x: uint) -> result<uint,str> {
 *         if x == uint::max_value { return Err("overflow"); }
 *         else { return Ok(x+1u); }
 *     }
 *     map(~[1u, 2u, 3u], inc_conditionally).chain {|incd|
 *         assert!(incd == ~[2u, 3u, 4u]);
 *     }
 */
#[inline]
pub fn map_vec<T,U,V>(ts: &[T], op: &fn(&T) -> Result<V,U>)
                      -> Result<~[V],U> {
    let mut vs: ~[V] = vec::with_capacity(ts.len());
    for ts.iter().advance |t| {
        match op(t) {
          Ok(v) => vs.push(v),
          Err(u) => return Err(u)
        }
    }
    return Ok(vs);
}

#[inline]
#[allow(missing_doc)]
pub fn map_opt<T,
               U,
               V>(
               o_t: &Option<T>,
               op: &fn(&T) -> Result<V,U>)
               -> Result<Option<V>,U> {
    match *o_t {
        None => Ok(None),
        Some(ref t) => match op(t) {
            Ok(v) => Ok(Some(v)),
            Err(e) => Err(e)
        }
    }
}

/**
 * Same as map, but it operates over two parallel vectors.
 *
 * A precondition is used here to ensure that the vectors are the same
 * length.  While we do not often use preconditions in the standard
 * library, a precondition is used here because result::t is generally
 * used in 'careful' code contexts where it is both appropriate and easy
 * to accommodate an error like the vectors being of different lengths.
 */
#[inline]
pub fn map_vec2<S,T,U,V>(ss: &[S], ts: &[T],
                op: &fn(&S,&T) -> Result<V,U>) -> Result<~[V],U> {

    assert!(vec::same_length(ss, ts));
    let n = ts.len();
    let mut vs = vec::with_capacity(n);
    let mut i = 0u;
    while i < n {
        match op(&ss[i],&ts[i]) {
          Ok(v) => vs.push(v),
          Err(u) => return Err(u)
        }
        i += 1u;
    }
    return Ok(vs);
}

/**
 * Applies op to the pairwise elements from `ss` and `ts`, aborting on
 * error.  This could be implemented using `map_zip()` but it is more efficient
 * on its own as no result vector is built.
 */
#[inline]
pub fn iter_vec2<S,T,U>(ss: &[S], ts: &[T],
                         op: &fn(&S,&T) -> Result<(),U>) -> Result<(),U> {

    assert!(vec::same_length(ss, ts));
    let n = ts.len();
    let mut i = 0u;
    while i < n {
        match op(&ss[i],&ts[i]) {
          Ok(()) => (),
          Err(u) => return Err(u)
        }
        i += 1u;
    }
    return Ok(());
}

#[cfg(test)]
mod tests {
    use result::{Err, Ok, Result};
    use result;
    use either;

    pub fn op1() -> result::Result<int, ~str> { result::Ok(666) }

    pub fn op2(i: int) -> result::Result<uint, ~str> {
        result::Ok(i as uint + 1u)
    }

    pub fn op3() -> result::Result<int, ~str> { result::Err(~"sadface") }

    #[test]
    pub fn chain_success() {
        assert_eq!(op1().chain(op2).get(), 667u);
    }

    #[test]
    pub fn chain_failure() {
        assert_eq!(op3().chain( op2).get_err(), ~"sadface");
    }

    #[test]
    pub fn test_impl_iter() {
        let mut valid = false;
        Ok::<~str, ~str>(~"a").iter(|_x| valid = true);
        assert!(valid);

        Err::<~str, ~str>(~"b").iter(|_x| valid = false);
        assert!(valid);
    }

    #[test]
    pub fn test_impl_iter_err() {
        let mut valid = true;
        Ok::<~str, ~str>(~"a").iter_err(|_x| valid = false);
        assert!(valid);

        valid = false;
        Err::<~str, ~str>(~"b").iter_err(|_x| valid = true);
        assert!(valid);
    }

    #[test]
    pub fn test_impl_map() {
        assert_eq!(Ok::<~str, ~str>(~"a").map(|_x| ~"b"), Ok(~"b"));
        assert_eq!(Err::<~str, ~str>(~"a").map(|_x| ~"b"), Err(~"a"));
    }

    #[test]
    pub fn test_impl_map_err() {
        assert_eq!(Ok::<~str, ~str>(~"a").map_err(|_x| ~"b"), Ok(~"a"));
        assert_eq!(Err::<~str, ~str>(~"a").map_err(|_x| ~"b"), Err(~"b"));
    }

    #[test]
    pub fn test_get_ref_method() {
        let foo: Result<int, ()> = Ok(100);
        assert_eq!(*foo.get_ref(), 100);
    }

    #[test]
    pub fn test_to_either() {
        let r: Result<int, ()> = Ok(100);
        let err: Result<(), int> = Err(404);

        assert_eq!(r.to_either(), either::Right(100));
        assert_eq!(err.to_either(), either::Left(404));
    }
}
<commit_msg>std: cleanup imports in result::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.

//! A type representing either success or failure

#[allow(missing_doc)];

use clone::Clone;
use cmp::Eq;
use either;
use iterator::IteratorUtil;
use option::{None, Option, Some};
use vec;
use vec::{OwnedVector, ImmutableVector};
use container::Container;

/// The result type
#[deriving(Clone, Eq)]
pub enum Result<T, U> {
    /// Contains the successful result value
    Ok(T),
    /// Contains the error value
    Err(U)
}

impl<T, E> Result<T, E> {
    /**
     * Convert to the `either` type
     *
     * `Ok` result variants are converted to `either::Right` variants, `Err`
     * result variants are converted to `either::Left`.
     */
    #[inline]
    pub fn to_either(self)-> either::Either<E, T>{
        match self {
            Ok(t) => either::Right(t),
            Err(e) => either::Left(e),
        }
    }

    /**
     * Get a reference to the value out of a successful result
     *
     * # Failure
     *
     * If the result is an error
     */
    #[inline]
    pub fn get_ref<'a>(&'a self) -> &'a T {
        match *self {
            Ok(ref t) => t,
            Err(ref e) => fail!("get_ref called on `Err` result: %?", *e),
        }
    }

    /// Returns true if the result is `Ok`
    #[inline]
    pub fn is_ok(&self) -> bool {
        match *self {
            Ok(_) => true,
            Err(_) => false
        }
    }

    /// Returns true if the result is `Err`
    #[inline]
    pub fn is_err(&self) -> bool {
        !self.is_ok()
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Ok` then the value is extracted and passed to `op`
     * whereupon `op`s result is returned. if `self` is `Err` then it is
     * immediately returned. This function can be used to compose the results
     * of two functions.
     *
     * Example:
     *
     *     do read_file(file).iter |buf| {
     *         print_buf(buf)
     *     }
     */
    #[inline]
    pub fn iter(&self, f: &fn(&T)) {
        match *self {
            Ok(ref t) => f(t),
            Err(_) => (),
        }
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Err` then the value is extracted and passed to `op`
     * whereupon `op`s result is returned. if `self` is `Ok` then it is
     * immediately returned.  This function can be used to pass through a
     * successful result while handling an error.
     */
    #[inline]
    pub fn iter_err(&self, f: &fn(&E)) {
        match *self {
            Ok(_) => (),
            Err(ref e) => f(e),
        }
    }

    /// Unwraps a result, assuming it is an `Ok(T)`
    #[inline]
    pub fn unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(_) => fail!("unwrap called on an `Err` result"),
        }
    }

    /// Unwraps a result, assuming it is an `Err(U)`
    #[inline]
    pub fn unwrap_err(self) -> E {
        match self {
            Err(e) => e,
            Ok(_) => fail!("unwrap called on an `Ok` result"),
        }
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Ok` then the value is extracted and passed to `op`
     * whereupon `op`s result is returned. if `self` is `Err` then it is
     * immediately returned. This function can be used to compose the results
     * of two functions.
     *
     * Example:
     *
     *     let res = do read_file(file) |buf| {
     *         Ok(parse_bytes(buf))
     *     };
     */
    #[inline]
    pub fn chain<U>(self, op: &fn(T) -> Result<U, E>) -> Result<U, E> {
        match self {
            Ok(t) => op(t),
            Err(e) => Err(e),
        }
    }

    /**
     * Call a function based on a previous result
     *
     * If `self` is `Err` then the value is extracted and passed to `op`
     * whereupon `op`s result is returned. if `self` is `Ok` then it is
     * immediately returned.  This function can be used to pass through a
     * successful result while handling an error.
     */
    #[inline]
    pub fn chain_err<F>(self, op: &fn(E) -> Result<T, F>) -> Result<T, F> {
        match self {
            Ok(t) => Ok(t),
            Err(e) => op(e),
        }
    }
}

impl<T: Clone, E> Result<T, E> {
    /**
     * Get the value out of a successful result
     *
     * # Failure
     *
     * If the result is an error
     */
    #[inline]
    pub fn get(&self) -> T {
        match *self {
            Ok(ref t) => t.clone(),
            Err(ref e) => fail!("get called on `Err` result: %?", *e),
        }
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Err` then the value is extracted and passed to `op`
     * whereupon `op`s result is wrapped in an `Err` and returned. if `self` is
     * `Ok` then it is immediately returned.  This function can be used to pass
     * through a successful result while handling an error.
     */
    #[inline]
    pub fn map_err<F:Clone>(&self, op: &fn(&E) -> F) -> Result<T,F> {
        match *self {
            Ok(ref t) => Ok(t.clone()),
            Err(ref e) => Err(op(e))
        }
    }
}

impl<T, E: Clone> Result<T, E> {
    /**
     * Get the value out of an error result
     *
     * # Failure
     *
     * If the result is not an error
     */
    #[inline]
    pub fn get_err(&self) -> E {
        match *self {
            Err(ref e) => e.clone(),
            Ok(_) => fail!("get_err called on `Ok` result")
        }
    }

    /**
     * Call a method based on a previous result
     *
     * If `self` is `Ok` then the value is extracted and passed to `op`
     * whereupon `op`s result is wrapped in `Ok` and returned. if `self` is
     * `Err` then it is immediately returned.  This function can be used to
     * compose the results of two functions.
     *
     * Example:
     *
     *     let res = do read_file(file).map |buf| {
     *         parse_bytes(buf)
     *     };
     */
    #[inline]
    pub fn map<U:Clone>(&self, op: &fn(&T) -> U) -> Result<U,E> {
        match *self {
            Ok(ref t) => Ok(op(t)),
            Err(ref e) => Err(e.clone())
        }
    }
}

/**
 * Maps each element in the vector `ts` using the operation `op`.  Should an
 * error occur, no further mappings are performed and the error is returned.
 * Should no error occur, a vector containing the result of each map is
 * returned.
 *
 * Here is an example which increments every integer in a vector,
 * checking for overflow:
 *
 *     fn inc_conditionally(x: uint) -> result<uint,str> {
 *         if x == uint::max_value { return Err("overflow"); }
 *         else { return Ok(x+1u); }
 *     }
 *     map(~[1u, 2u, 3u], inc_conditionally).chain {|incd|
 *         assert!(incd == ~[2u, 3u, 4u]);
 *     }
 */
#[inline]
pub fn map_vec<T,U,V>(ts: &[T], op: &fn(&T) -> Result<V,U>)
                      -> Result<~[V],U> {
    let mut vs: ~[V] = vec::with_capacity(ts.len());
    for ts.iter().advance |t| {
        match op(t) {
          Ok(v) => vs.push(v),
          Err(u) => return Err(u)
        }
    }
    return Ok(vs);
}

#[inline]
#[allow(missing_doc)]
pub fn map_opt<T,
               U,
               V>(
               o_t: &Option<T>,
               op: &fn(&T) -> Result<V,U>)
               -> Result<Option<V>,U> {
    match *o_t {
        None => Ok(None),
        Some(ref t) => match op(t) {
            Ok(v) => Ok(Some(v)),
            Err(e) => Err(e)
        }
    }
}

/**
 * Same as map, but it operates over two parallel vectors.
 *
 * A precondition is used here to ensure that the vectors are the same
 * length.  While we do not often use preconditions in the standard
 * library, a precondition is used here because result::t is generally
 * used in 'careful' code contexts where it is both appropriate and easy
 * to accommodate an error like the vectors being of different lengths.
 */
#[inline]
pub fn map_vec2<S,T,U,V>(ss: &[S], ts: &[T],
                op: &fn(&S,&T) -> Result<V,U>) -> Result<~[V],U> {

    assert!(vec::same_length(ss, ts));
    let n = ts.len();
    let mut vs = vec::with_capacity(n);
    let mut i = 0u;
    while i < n {
        match op(&ss[i],&ts[i]) {
          Ok(v) => vs.push(v),
          Err(u) => return Err(u)
        }
        i += 1u;
    }
    return Ok(vs);
}

/**
 * Applies op to the pairwise elements from `ss` and `ts`, aborting on
 * error.  This could be implemented using `map_zip()` but it is more efficient
 * on its own as no result vector is built.
 */
#[inline]
pub fn iter_vec2<S,T,U>(ss: &[S], ts: &[T],
                         op: &fn(&S,&T) -> Result<(),U>) -> Result<(),U> {

    assert!(vec::same_length(ss, ts));
    let n = ts.len();
    let mut i = 0u;
    while i < n {
        match op(&ss[i],&ts[i]) {
          Ok(()) => (),
          Err(u) => return Err(u)
        }
        i += 1u;
    }
    return Ok(());
}

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

    pub fn op1() -> Result<int, ~str> { Ok(666) }

    pub fn op2(i: int) -> Result<uint, ~str> {
        Ok(i as uint + 1u)
    }

    pub fn op3() -> Result<int, ~str> { Err(~"sadface") }

    #[test]
    pub fn chain_success() {
        assert_eq!(op1().chain(op2).get(), 667u);
    }

    #[test]
    pub fn chain_failure() {
        assert_eq!(op3().chain( op2).get_err(), ~"sadface");
    }

    #[test]
    pub fn test_impl_iter() {
        let mut valid = false;
        Ok::<~str, ~str>(~"a").iter(|_x| valid = true);
        assert!(valid);

        Err::<~str, ~str>(~"b").iter(|_x| valid = false);
        assert!(valid);
    }

    #[test]
    pub fn test_impl_iter_err() {
        let mut valid = true;
        Ok::<~str, ~str>(~"a").iter_err(|_x| valid = false);
        assert!(valid);

        valid = false;
        Err::<~str, ~str>(~"b").iter_err(|_x| valid = true);
        assert!(valid);
    }

    #[test]
    pub fn test_impl_map() {
        assert_eq!(Ok::<~str, ~str>(~"a").map(|_x| ~"b"), Ok(~"b"));
        assert_eq!(Err::<~str, ~str>(~"a").map(|_x| ~"b"), Err(~"a"));
    }

    #[test]
    pub fn test_impl_map_err() {
        assert_eq!(Ok::<~str, ~str>(~"a").map_err(|_x| ~"b"), Ok(~"a"));
        assert_eq!(Err::<~str, ~str>(~"a").map_err(|_x| ~"b"), Err(~"b"));
    }

    #[test]
    pub fn test_get_ref_method() {
        let foo: Result<int, ()> = Ok(100);
        assert_eq!(*foo.get_ref(), 100);
    }

    #[test]
    pub fn test_to_either() {
        let r: Result<int, ()> = Ok(100);
        let err: Result<(), int> = Err(404);

        assert_eq!(r.to_either(), either::Right(100));
        assert_eq!(err.to_either(), either::Left(404));
    }
}
<|endoftext|>