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

//! Replaces 128-bit operators with lang item calls

use rustc::hir::def_id::DefId;
use rustc::middle::lang_items::LangItem;
use rustc::mir::*;
use rustc::ty::{Slice, Ty, TyCtxt, TypeVariants};
use rustc_data_structures::indexed_vec::{Idx};
use transform::{MirPass, MirSource};
use syntax;

pub struct Lower128Bit;

impl MirPass for Lower128Bit {
    fn run_pass<'a, 'tcx>(&self,
                          tcx: TyCtxt<'a, 'tcx, 'tcx>,
                          _src: MirSource,
                          mir: &mut Mir<'tcx>) {
        let debugging_override = tcx.sess.opts.debugging_opts.lower_128bit_ops;
        let target_default = tcx.sess.host.options.i128_lowering;
        if !debugging_override.unwrap_or(target_default) {
            return
        }

        self.lower_128bit_ops(tcx, mir);
    }
}

impl Lower128Bit {
    fn lower_128bit_ops<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, mir: &mut Mir<'tcx>) {
        let mut new_blocks = Vec::new();
        let cur_len = mir.basic_blocks().len();

        let (basic_blocks, local_decls) = mir.basic_blocks_and_local_decls_mut();
        for block in basic_blocks.iter_mut() {
            for i in (0..block.statements.len()).rev() {
                let (lang_item, rhs_kind) =
                    if let Some((lang_item, rhs_kind)) =
                        lower_to(&block.statements[i], local_decls, tcx)
                    {
                        (lang_item, rhs_kind)
                    } else {
                        continue;
                    };

                let rhs_override_ty = rhs_kind.ty(tcx);
                let cast_local =
                    match rhs_override_ty {
                        None => None,
                        Some(ty) => {
                            let local_decl = LocalDecl::new_internal(
                                ty, block.statements[i].source_info.span);
                            Some(local_decls.push(local_decl))
                        },
                    };

                let storage_dead = cast_local.map(|local| {
                    Statement {
                        source_info: block.statements[i].source_info,
                        kind: StatementKind::StorageDead(local),
                    }
                });
                let after_call = BasicBlockData {
                    statements: storage_dead.into_iter()
                        .chain(block.statements.drain((i+1)..)).collect(),
                    is_cleanup: block.is_cleanup,
                    terminator: block.terminator.take(),
                };

                let bin_statement = block.statements.pop().unwrap();
                let (source_info, place, lhs, mut rhs) = match bin_statement {
                    Statement {
                        source_info,
                        kind: StatementKind::Assign(
                            place,
                            Rvalue::BinaryOp(_, lhs, rhs))
                    } => (source_info, place, lhs, rhs),
                    Statement {
                        source_info,
                        kind: StatementKind::Assign(
                            place,
                            Rvalue::CheckedBinaryOp(_, lhs, rhs))
                    } => (source_info, place, lhs, rhs),
                    _ => bug!("Statement doesn't match pattern any more?"),
                };

                if let Some(local) = cast_local {
                    block.statements.push(Statement {
                        source_info: source_info,
                        kind: StatementKind::StorageLive(local),
                    });
                    block.statements.push(Statement {
                        source_info: source_info,
                        kind: StatementKind::Assign(
                            Place::Local(local),
                            Rvalue::Cast(
                                CastKind::Misc,
                                rhs,
                                rhs_override_ty.unwrap())),
                    });
                    rhs = Operand::Move(Place::Local(local));
                }

                let call_did = check_lang_item_type(
                    lang_item, &place, &lhs, &rhs, local_decls, tcx);

                let bb = BasicBlock::new(cur_len + new_blocks.len());
                new_blocks.push(after_call);

                block.terminator =
                    Some(Terminator {
                        source_info,
                        kind: TerminatorKind::Call {
                            func: Operand::function_handle(tcx, call_did,
                                Slice::empty(), source_info.span),
                            args: vec![lhs, rhs],
                            destination: Some((place, bb)),
                            cleanup: None,
                        },
                    });
            }
        }

        basic_blocks.extend(new_blocks);
    }
}

fn check_lang_item_type<'a, 'tcx, D>(
    lang_item: LangItem,
    place: &Place<'tcx>,
    lhs: &Operand<'tcx>,
    rhs: &Operand<'tcx>,
    local_decls: &D,
    tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> DefId
    where D: HasLocalDecls<'tcx>
{
    let did = tcx.require_lang_item(lang_item);
    let poly_sig = tcx.fn_sig(did);
    let sig = poly_sig.no_late_bound_regions().unwrap();
    let lhs_ty = lhs.ty(local_decls, tcx);
    let rhs_ty = rhs.ty(local_decls, tcx);
    let place_ty = place.ty(local_decls, tcx).to_ty(tcx);
    let expected = [lhs_ty, rhs_ty, place_ty];
    assert_eq!(sig.inputs_and_output[..], expected,
        "lang item {}", tcx.def_symbol_name(did));
    did
}

fn lower_to<'a, 'tcx, D>(statement: &Statement<'tcx>, local_decls: &D, tcx: TyCtxt<'a, 'tcx, 'tcx>)
    -> Option<(LangItem, RhsKind)>
    where D: HasLocalDecls<'tcx>
{
    match statement.kind {
        StatementKind::Assign(_, Rvalue::BinaryOp(bin_op, ref lhs, _)) => {
            let ty = lhs.ty(local_decls, tcx);
            if let Some(is_signed) = sign_of_128bit(ty) {
                return item_for_op(bin_op, is_signed);
            }
        },
        StatementKind::Assign(_, Rvalue::CheckedBinaryOp(bin_op, ref lhs, _)) => {
            let ty = lhs.ty(local_decls, tcx);
            if let Some(is_signed) = sign_of_128bit(ty) {
                return item_for_checked_op(bin_op, is_signed);
            }
        },
        _ => {},
    }
    None
}

#[derive(Copy, Clone)]
enum RhsKind {
    Unchanged,
    ForceU128,
    ForceU32,
}

impl RhsKind {
    fn ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Ty<'tcx>> {
        match *self {
            RhsKind::Unchanged => None,
            RhsKind::ForceU128 => Some(tcx.types.u128),
            RhsKind::ForceU32 => Some(tcx.types.u32),
        }
    }
}

fn sign_of_128bit(ty: Ty) -> Option<bool> {
    match ty.sty {
        TypeVariants::TyInt(syntax::ast::IntTy::I128) => Some(true),
        TypeVariants::TyUint(syntax::ast::UintTy::U128) => Some(false),
        _ => None,
    }
}

fn item_for_op(bin_op: BinOp, is_signed: bool) -> Option<(LangItem, RhsKind)> {
    let i = match (bin_op, is_signed) {
        (BinOp::Add, true) => (LangItem::I128AddFnLangItem, RhsKind::Unchanged),
        (BinOp::Add, false) => (LangItem::U128AddFnLangItem, RhsKind::Unchanged),
        (BinOp::Sub, true) => (LangItem::I128SubFnLangItem, RhsKind::Unchanged),
        (BinOp::Sub, false) => (LangItem::U128SubFnLangItem, RhsKind::Unchanged),
        (BinOp::Mul, true) => (LangItem::I128MulFnLangItem, RhsKind::Unchanged),
        (BinOp::Mul, false) => (LangItem::U128MulFnLangItem, RhsKind::Unchanged),
        (BinOp::Div, true) => (LangItem::I128DivFnLangItem, RhsKind::Unchanged),
        (BinOp::Div, false) => (LangItem::U128DivFnLangItem, RhsKind::Unchanged),
        (BinOp::Rem, true) => (LangItem::I128RemFnLangItem, RhsKind::Unchanged),
        (BinOp::Rem, false) => (LangItem::U128RemFnLangItem, RhsKind::Unchanged),
        (BinOp::Shl, true) => (LangItem::I128ShlFnLangItem, RhsKind::ForceU32),
        (BinOp::Shl, false) => (LangItem::U128ShlFnLangItem, RhsKind::ForceU32),
        (BinOp::Shr, true) => (LangItem::I128ShrFnLangItem, RhsKind::ForceU32),
        (BinOp::Shr, false) => (LangItem::U128ShrFnLangItem, RhsKind::ForceU32),
        _ => return None,
    };
    Some(i)
}

fn item_for_checked_op(bin_op: BinOp, is_signed: bool) -> Option<(LangItem, RhsKind)> {
    let i = match (bin_op, is_signed) {
        (BinOp::Add, true) => (LangItem::I128AddoFnLangItem, RhsKind::Unchanged),
        (BinOp::Add, false) => (LangItem::U128AddoFnLangItem, RhsKind::Unchanged),
        (BinOp::Sub, true) => (LangItem::I128SuboFnLangItem, RhsKind::Unchanged),
        (BinOp::Sub, false) => (LangItem::U128SuboFnLangItem, RhsKind::Unchanged),
        (BinOp::Mul, true) => (LangItem::I128MuloFnLangItem, RhsKind::Unchanged),
        (BinOp::Mul, false) => (LangItem::U128MuloFnLangItem, RhsKind::Unchanged),
        (BinOp::Shl, true) => (LangItem::I128ShloFnLangItem, RhsKind::ForceU128),
        (BinOp::Shl, false) => (LangItem::U128ShloFnLangItem, RhsKind::ForceU128),
        (BinOp::Shr, true) => (LangItem::I128ShroFnLangItem, RhsKind::ForceU128),
        (BinOp::Shr, false) => (LangItem::U128ShroFnLangItem, RhsKind::ForceU128),
        _ => bug!("That should be all the checked ones?"),
    };
    Some(i)
}
<commit_msg>Rollup merge of #48727 - leodasvacas:refactor-contrived-match, r=rkruppe<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Replaces 128-bit operators with lang item calls

use rustc::hir::def_id::DefId;
use rustc::middle::lang_items::LangItem;
use rustc::mir::*;
use rustc::ty::{Slice, Ty, TyCtxt, TypeVariants};
use rustc_data_structures::indexed_vec::{Idx};
use transform::{MirPass, MirSource};
use syntax;

pub struct Lower128Bit;

impl MirPass for Lower128Bit {
    fn run_pass<'a, 'tcx>(&self,
                          tcx: TyCtxt<'a, 'tcx, 'tcx>,
                          _src: MirSource,
                          mir: &mut Mir<'tcx>) {
        let debugging_override = tcx.sess.opts.debugging_opts.lower_128bit_ops;
        let target_default = tcx.sess.host.options.i128_lowering;
        if !debugging_override.unwrap_or(target_default) {
            return
        }

        self.lower_128bit_ops(tcx, mir);
    }
}

impl Lower128Bit {
    fn lower_128bit_ops<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, mir: &mut Mir<'tcx>) {
        let mut new_blocks = Vec::new();
        let cur_len = mir.basic_blocks().len();

        let (basic_blocks, local_decls) = mir.basic_blocks_and_local_decls_mut();
        for block in basic_blocks.iter_mut() {
            for i in (0..block.statements.len()).rev() {
                let (lang_item, rhs_kind) =
                    if let Some((lang_item, rhs_kind)) =
                        lower_to(&block.statements[i], local_decls, tcx)
                    {
                        (lang_item, rhs_kind)
                    } else {
                        continue;
                    };

                let rhs_override_ty = rhs_kind.ty(tcx);
                let cast_local =
                    match rhs_override_ty {
                        None => None,
                        Some(ty) => {
                            let local_decl = LocalDecl::new_internal(
                                ty, block.statements[i].source_info.span);
                            Some(local_decls.push(local_decl))
                        },
                    };

                let storage_dead = cast_local.map(|local| {
                    Statement {
                        source_info: block.statements[i].source_info,
                        kind: StatementKind::StorageDead(local),
                    }
                });
                let after_call = BasicBlockData {
                    statements: storage_dead.into_iter()
                        .chain(block.statements.drain((i+1)..)).collect(),
                    is_cleanup: block.is_cleanup,
                    terminator: block.terminator.take(),
                };

                let bin_statement = block.statements.pop().unwrap();
                let source_info = bin_statement.source_info;
                let (place, lhs, mut rhs) = match bin_statement.kind {
                    StatementKind::Assign(place, Rvalue::BinaryOp(_, lhs, rhs))
                    | StatementKind::Assign(place, Rvalue::CheckedBinaryOp(_, lhs, rhs)) => {
                        (place, lhs, rhs)
                    }
                    _ => bug!("Statement doesn't match pattern any more?"),
                };

                if let Some(local) = cast_local {
                    block.statements.push(Statement {
                        source_info: source_info,
                        kind: StatementKind::StorageLive(local),
                    });
                    block.statements.push(Statement {
                        source_info: source_info,
                        kind: StatementKind::Assign(
                            Place::Local(local),
                            Rvalue::Cast(
                                CastKind::Misc,
                                rhs,
                                rhs_override_ty.unwrap())),
                    });
                    rhs = Operand::Move(Place::Local(local));
                }

                let call_did = check_lang_item_type(
                    lang_item, &place, &lhs, &rhs, local_decls, tcx);

                let bb = BasicBlock::new(cur_len + new_blocks.len());
                new_blocks.push(after_call);

                block.terminator =
                    Some(Terminator {
                        source_info,
                        kind: TerminatorKind::Call {
                            func: Operand::function_handle(tcx, call_did,
                                Slice::empty(), source_info.span),
                            args: vec![lhs, rhs],
                            destination: Some((place, bb)),
                            cleanup: None,
                        },
                    });
            }
        }

        basic_blocks.extend(new_blocks);
    }
}

fn check_lang_item_type<'a, 'tcx, D>(
    lang_item: LangItem,
    place: &Place<'tcx>,
    lhs: &Operand<'tcx>,
    rhs: &Operand<'tcx>,
    local_decls: &D,
    tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> DefId
    where D: HasLocalDecls<'tcx>
{
    let did = tcx.require_lang_item(lang_item);
    let poly_sig = tcx.fn_sig(did);
    let sig = poly_sig.no_late_bound_regions().unwrap();
    let lhs_ty = lhs.ty(local_decls, tcx);
    let rhs_ty = rhs.ty(local_decls, tcx);
    let place_ty = place.ty(local_decls, tcx).to_ty(tcx);
    let expected = [lhs_ty, rhs_ty, place_ty];
    assert_eq!(sig.inputs_and_output[..], expected,
        "lang item {}", tcx.def_symbol_name(did));
    did
}

fn lower_to<'a, 'tcx, D>(statement: &Statement<'tcx>, local_decls: &D, tcx: TyCtxt<'a, 'tcx, 'tcx>)
    -> Option<(LangItem, RhsKind)>
    where D: HasLocalDecls<'tcx>
{
    match statement.kind {
        StatementKind::Assign(_, Rvalue::BinaryOp(bin_op, ref lhs, _)) => {
            let ty = lhs.ty(local_decls, tcx);
            if let Some(is_signed) = sign_of_128bit(ty) {
                return item_for_op(bin_op, is_signed);
            }
        },
        StatementKind::Assign(_, Rvalue::CheckedBinaryOp(bin_op, ref lhs, _)) => {
            let ty = lhs.ty(local_decls, tcx);
            if let Some(is_signed) = sign_of_128bit(ty) {
                return item_for_checked_op(bin_op, is_signed);
            }
        },
        _ => {},
    }
    None
}

#[derive(Copy, Clone)]
enum RhsKind {
    Unchanged,
    ForceU128,
    ForceU32,
}

impl RhsKind {
    fn ty<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Ty<'tcx>> {
        match *self {
            RhsKind::Unchanged => None,
            RhsKind::ForceU128 => Some(tcx.types.u128),
            RhsKind::ForceU32 => Some(tcx.types.u32),
        }
    }
}

fn sign_of_128bit(ty: Ty) -> Option<bool> {
    match ty.sty {
        TypeVariants::TyInt(syntax::ast::IntTy::I128) => Some(true),
        TypeVariants::TyUint(syntax::ast::UintTy::U128) => Some(false),
        _ => None,
    }
}

fn item_for_op(bin_op: BinOp, is_signed: bool) -> Option<(LangItem, RhsKind)> {
    let i = match (bin_op, is_signed) {
        (BinOp::Add, true) => (LangItem::I128AddFnLangItem, RhsKind::Unchanged),
        (BinOp::Add, false) => (LangItem::U128AddFnLangItem, RhsKind::Unchanged),
        (BinOp::Sub, true) => (LangItem::I128SubFnLangItem, RhsKind::Unchanged),
        (BinOp::Sub, false) => (LangItem::U128SubFnLangItem, RhsKind::Unchanged),
        (BinOp::Mul, true) => (LangItem::I128MulFnLangItem, RhsKind::Unchanged),
        (BinOp::Mul, false) => (LangItem::U128MulFnLangItem, RhsKind::Unchanged),
        (BinOp::Div, true) => (LangItem::I128DivFnLangItem, RhsKind::Unchanged),
        (BinOp::Div, false) => (LangItem::U128DivFnLangItem, RhsKind::Unchanged),
        (BinOp::Rem, true) => (LangItem::I128RemFnLangItem, RhsKind::Unchanged),
        (BinOp::Rem, false) => (LangItem::U128RemFnLangItem, RhsKind::Unchanged),
        (BinOp::Shl, true) => (LangItem::I128ShlFnLangItem, RhsKind::ForceU32),
        (BinOp::Shl, false) => (LangItem::U128ShlFnLangItem, RhsKind::ForceU32),
        (BinOp::Shr, true) => (LangItem::I128ShrFnLangItem, RhsKind::ForceU32),
        (BinOp::Shr, false) => (LangItem::U128ShrFnLangItem, RhsKind::ForceU32),
        _ => return None,
    };
    Some(i)
}

fn item_for_checked_op(bin_op: BinOp, is_signed: bool) -> Option<(LangItem, RhsKind)> {
    let i = match (bin_op, is_signed) {
        (BinOp::Add, true) => (LangItem::I128AddoFnLangItem, RhsKind::Unchanged),
        (BinOp::Add, false) => (LangItem::U128AddoFnLangItem, RhsKind::Unchanged),
        (BinOp::Sub, true) => (LangItem::I128SuboFnLangItem, RhsKind::Unchanged),
        (BinOp::Sub, false) => (LangItem::U128SuboFnLangItem, RhsKind::Unchanged),
        (BinOp::Mul, true) => (LangItem::I128MuloFnLangItem, RhsKind::Unchanged),
        (BinOp::Mul, false) => (LangItem::U128MuloFnLangItem, RhsKind::Unchanged),
        (BinOp::Shl, true) => (LangItem::I128ShloFnLangItem, RhsKind::ForceU128),
        (BinOp::Shl, false) => (LangItem::U128ShloFnLangItem, RhsKind::ForceU128),
        (BinOp::Shr, true) => (LangItem::I128ShroFnLangItem, RhsKind::ForceU128),
        (BinOp::Shr, false) => (LangItem::U128ShroFnLangItem, RhsKind::ForceU128),
        _ => bug!("That should be all the checked ones?"),
    };
    Some(i)
}
<|endoftext|>


<commit_before>//! Tests for build.rs rerun-if-env-changed and rustc-env

use cargo_test_support::basic_manifest;
use cargo_test_support::project;
use cargo_test_support::sleep_ms;

#[cargo_test]
fn rerun_if_env_changes() {
    let p = project()
        .file("src/main.rs", "fn main() {}")
        .file(
            "build.rs",
            r#"
                fn main() {
                    println!("cargo:rerun-if-env-changed=FOO");
                }
            "#,
        )
        .build();

    p.cargo("build")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "bar")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "baz")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "baz")
        .with_stderr("[FINISHED] [..]")
        .run();
    p.cargo("build")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
}

#[cargo_test]
fn rerun_if_env_or_file_changes() {
    let p = project()
        .file("src/main.rs", "fn main() {}")
        .file(
            "build.rs",
            r#"
                fn main() {
                    println!("cargo:rerun-if-env-changed=FOO");
                    println!("cargo:rerun-if-changed=foo");
                }
            "#,
        )
        .file("foo", "")
        .build();

    p.cargo("build")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "bar")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "bar")
        .with_stderr("[FINISHED] [..]")
        .run();
    sleep_ms(1000);
    p.change_file("foo", "");
    p.cargo("build")
        .env("FOO", "bar")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
}

#[cargo_test]
fn rustc_bootstrap() {
    let build_rs = r#"
        fn main() {
            println!("cargo:rustc-env=RUSTC_BOOTSTRAP=1");
        }
    "#;
    let p = project()
        .file("Cargo.toml", &basic_manifest("has-dashes", "0.0.1"))
        .file("src/lib.rs", "#![feature(rustc_attrs)]")
        .file("build.rs", build_rs)
        .build();
    // RUSTC_BOOTSTRAP unset on stable should error
    p.cargo("build")
        .with_stderr_contains("error: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .with_stderr_contains(
            "help: [..] set the environment variable `RUSTC_BOOTSTRAP=has_dashes` [..]",
        )
        .with_status(101)
        .run();
    // nightly should warn whether or not RUSTC_BOOTSTRAP is set
    p.cargo("build")
        .masquerade_as_nightly_cargo(&["RUSTC_BOOTSTRAP"])
        // NOTE: uses RUSTC_BOOTSTRAP so it will be propagated to rustc
        // (this matters when tests are being run with a beta or stable cargo)
        .env("RUSTC_BOOTSTRAP", "1")
        .with_stderr_contains("warning: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .run();
    // RUSTC_BOOTSTRAP set to the name of the library should warn
    p.cargo("build")
        .env("RUSTC_BOOTSTRAP", "has_dashes")
        .with_stderr_contains("warning: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .run();
    // RUSTC_BOOTSTRAP set to some random value should error
    p.cargo("build")
        .env("RUSTC_BOOTSTRAP", "bar")
        .with_stderr_contains("error: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .with_stderr_contains(
            "help: [..] set the environment variable `RUSTC_BOOTSTRAP=has_dashes` [..]",
        )
        .with_status(101)
        .run();

    // Tests for binaries instead of libraries
    let p = project()
        .file("Cargo.toml", &basic_manifest("foo", "0.0.1"))
        .file("src/main.rs", "#![feature(rustc_attrs)] fn main() {}")
        .file("build.rs", build_rs)
        .build();
    // nightly should warn when there's no library whether or not RUSTC_BOOTSTRAP is set
    p.cargo("build")
        .masquerade_as_nightly_cargo(&["RUSTC_BOOTSTRAP"])
        // NOTE: uses RUSTC_BOOTSTRAP so it will be propagated to rustc
        // (this matters when tests are being run with a beta or stable cargo)
        .env("RUSTC_BOOTSTRAP", "1")
        .with_stderr_contains("warning: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .run();
    // RUSTC_BOOTSTRAP conditionally set when there's no library should error (regardless of the value)
    p.cargo("build")
        .env("RUSTC_BOOTSTRAP", "foo")
        .with_stderr_contains("error: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .with_stderr_contains("help: [..] set the environment variable `RUSTC_BOOTSTRAP=1` [..]")
        .with_status(101)
        .run();
}
<commit_msg>add failing test for CARGO_CFG_TARGET_FEATURE<commit_after>//! Tests for build.rs rerun-if-env-changed and rustc-env

use cargo_test_support::basic_manifest;
use cargo_test_support::project;
use cargo_test_support::sleep_ms;

#[cargo_test]
fn rerun_if_env_changes() {
    let p = project()
        .file("src/main.rs", "fn main() {}")
        .file(
            "build.rs",
            r#"
                fn main() {
                    println!("cargo:rerun-if-env-changed=FOO");
                }
            "#,
        )
        .build();

    p.cargo("build")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "bar")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "baz")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "baz")
        .with_stderr("[FINISHED] [..]")
        .run();
    p.cargo("build")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
}

#[cargo_test]
fn rerun_if_env_or_file_changes() {
    let p = project()
        .file("src/main.rs", "fn main() {}")
        .file(
            "build.rs",
            r#"
                fn main() {
                    println!("cargo:rerun-if-env-changed=FOO");
                    println!("cargo:rerun-if-changed=foo");
                }
            "#,
        )
        .file("foo", "")
        .build();

    p.cargo("build")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "bar")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
    p.cargo("build")
        .env("FOO", "bar")
        .with_stderr("[FINISHED] [..]")
        .run();
    sleep_ms(1000);
    p.change_file("foo", "");
    p.cargo("build")
        .env("FOO", "bar")
        .with_stderr(
            "\
[COMPILING] foo v0.0.1 ([..])
[FINISHED] [..]
",
        )
        .run();
}

#[cargo_test]
fn rustc_bootstrap() {
    let build_rs = r#"
        fn main() {
            println!("cargo:rustc-env=RUSTC_BOOTSTRAP=1");
        }
    "#;
    let p = project()
        .file("Cargo.toml", &basic_manifest("has-dashes", "0.0.1"))
        .file("src/lib.rs", "#![feature(rustc_attrs)]")
        .file("build.rs", build_rs)
        .build();
    // RUSTC_BOOTSTRAP unset on stable should error
    p.cargo("build")
        .with_stderr_contains("error: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .with_stderr_contains(
            "help: [..] set the environment variable `RUSTC_BOOTSTRAP=has_dashes` [..]",
        )
        .with_status(101)
        .run();
    // nightly should warn whether or not RUSTC_BOOTSTRAP is set
    p.cargo("build")
        .masquerade_as_nightly_cargo(&["RUSTC_BOOTSTRAP"])
        // NOTE: uses RUSTC_BOOTSTRAP so it will be propagated to rustc
        // (this matters when tests are being run with a beta or stable cargo)
        .env("RUSTC_BOOTSTRAP", "1")
        .with_stderr_contains("warning: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .run();
    // RUSTC_BOOTSTRAP set to the name of the library should warn
    p.cargo("build")
        .env("RUSTC_BOOTSTRAP", "has_dashes")
        .with_stderr_contains("warning: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .run();
    // RUSTC_BOOTSTRAP set to some random value should error
    p.cargo("build")
        .env("RUSTC_BOOTSTRAP", "bar")
        .with_stderr_contains("error: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .with_stderr_contains(
            "help: [..] set the environment variable `RUSTC_BOOTSTRAP=has_dashes` [..]",
        )
        .with_status(101)
        .run();

    // Tests for binaries instead of libraries
    let p = project()
        .file("Cargo.toml", &basic_manifest("foo", "0.0.1"))
        .file("src/main.rs", "#![feature(rustc_attrs)] fn main() {}")
        .file("build.rs", build_rs)
        .build();
    // nightly should warn when there's no library whether or not RUSTC_BOOTSTRAP is set
    p.cargo("build")
        .masquerade_as_nightly_cargo(&["RUSTC_BOOTSTRAP"])
        // NOTE: uses RUSTC_BOOTSTRAP so it will be propagated to rustc
        // (this matters when tests are being run with a beta or stable cargo)
        .env("RUSTC_BOOTSTRAP", "1")
        .with_stderr_contains("warning: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .run();
    // RUSTC_BOOTSTRAP conditionally set when there's no library should error (regardless of the value)
    p.cargo("build")
        .env("RUSTC_BOOTSTRAP", "foo")
        .with_stderr_contains("error: Cannot set `RUSTC_BOOTSTRAP=1` [..]")
        .with_stderr_contains("help: [..] set the environment variable `RUSTC_BOOTSTRAP=1` [..]")
        .with_status(101)
        .run();
}

#[cargo_test]
#[cfg(target_arch = "x86_64")]
fn build_script_sees_cfg_target_feature() {
    let build_rs = r#"
        fn main() {
            let cfg = std::env::var("CARGO_CFG_TARGET_FEATURE").unwrap();
            eprintln!("CARGO_CFG_TARGET_FEATURE={cfg}");
        }
    "#;

    let configs = [
        r#"
            [build]
            rustflags = ["-Ctarget-feature=+sse4.1,+sse4.2"]
        "#,
        r#"
            [target.'cfg(target_arch = "x86_64")']
            rustflags = ["-Ctarget-feature=+sse4.1,+sse4.2"]
        "#,
    ];

    for config in configs {
        let p = project()
            .file(".cargo/config.toml", config)
            .file("src/lib.rs", r#""#)
            .file("build.rs", build_rs)
            .build();

        p.cargo("build -vv")
            .with_stderr_contains("[foo 0.0.1] CARGO_CFG_TARGET_FEATURE=[..]sse4.2[..]")
            .with_stderr_contains("[..]-Ctarget-feature=[..]+sse4.2[..]")
            .run();
    }
}
<|endoftext|>


<commit_before><commit_msg>Use 'format' in 'raw_upload' example instead of checking Content-Type directly.<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #32<commit_after>extern mod std;
use std::sort::{ merge_sort };
use std::map::{ HashMap, set_add };

// possible num of digits combinations
// 1 x 1 = 7 : NG 10 * 10
// 1 x 2 = 6 : NG 10 * 100
// 1 x 3 = 5 : NG 10 * 1000 = 10000
// 1 x 4 = 4 : OK
// 2 x 2 = 5 : NG 100 * 100 = 10000
// 2 x 3 = 4 : OK
// 3 x 3 = 3 : NG

pure fn num_to_digits(n: uint) -> ~[uint] {
    let buf = [mut
               0, 0, 0, 0,  0, 0, 0, 0,
               0, 0, 0, 0,  0, 0, 0, 0,
               0, 0, 0, 0,  0, 0, 0, 0,
               0, 0, 0, 0,  0, 0, 0, 0,

               0, 0, 0, 0,  0, 0, 0, 0,
               0, 0, 0, 0,  0, 0, 0, 0,
               0, 0, 0, 0,  0, 0, 0, 0,
               0, 0, 0, 0,  0, 0, 0, 0
              ]/64;
    let mut filled_idx = buf.len();
    let mut itr = n;
    while itr != 0 {
        buf[filled_idx - 1] = itr % 10;
        filled_idx -= 1;
        itr /= 10;
    }
    return vec::from_slice(vec::view(buf, filled_idx, buf.len()));
}

pure fn digits_to_num(v: &[uint]) -> uint {
    let mut num = 0;
    for v.each |n| {
        num *= 10;
        num += *n;
    }
    return num;
}

pure fn fill_zero(v: &[uint], n: uint) -> ~[uint] {
    assert n >= v.len();
    vec::from_elem(n - v.len(), 0) + v
}

pure fn permutate_num(digits: &[uint], len: uint, min: uint, max: uint,
                      f: fn(uint, &[uint])->bool) {
    let min_vec = fill_zero(num_to_digits(min), len);
    let max_vec = fill_zero(num_to_digits(max), len);
    perm_sub(digits, len, to_some(min_vec), to_some(max_vec), f);

    pure fn to_some(v: &a/[uint]) -> Option<&a/[uint]> { Some(v) }

    pure fn perm_sub(digits: &[uint], len: uint, min: Option<&[uint]>, max: Option<&[uint]>,
                     f: fn(uint, &[uint])->bool) {
        if len == 0 {
            f(0, digits);
            return;
        }

        let unit = {
            let mut tmp = 1;
            for (len-1).times { tmp *= 10 }
            tmp
        };

        let buf = vec::to_mut(vec::from_elem(digits.len() - 1, 0));

        for digits.eachi |i, np| {
            let n = *np;

            let min_vec = match min {
                Some(v) if n <  v[0] => loop,
                Some(v) if n == v[0] => Some(vec::view(v, 1, v.len())),
                _ => None
            };
            let max_vec = match max {
                Some(v) if n >  v[0] => loop,
                Some(v) if n == v[0] => Some(vec::view(v, 1, v.len())),
                _ => None
            };

            for uint::range(0, i)         |j| { buf[j] = digits[j]; }
            for uint::range(i, buf.len()) |j| { buf[j] = digits[j + 1]; }
            for perm_sub(buf, len - 1, min_vec, max_vec) |num, ds| {
                if !f(num + n * unit, ds) { return; }
            }
        }
    }
}

fn main() {
    let digits = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
    let mut answer = HashMap::<uint, ()>();

    // 1 x 4 = 4
    // a b = c
    // 1 < a < 10
    // 1000 < b < 10000
    // 1000 < c = ab < 10000 => 1000 / a < b < 10000 / a
    //  => 1000 < b < 10000 / a
    for permutate_num(digits, 1, 0, 9) |a, ds| {
        for permutate_num(ds, 4, 1000, 9999 / a) |b, ds| {
            let c = a * b;
            let c_digits = merge_sort(|a, b| a <= b, num_to_digits(c));
            if vec::eq(c_digits, ds) { set_add(answer, c); }
        }
    }

    // 2 x 3 = 4
    // a b = c
    // 10   < a < 100
    // 100  < b < 1000
    // 1000 < c = ab < 10000 => 1000 / a < b < 10000 / a
    // => 100 < b < 10000 / a
    for permutate_num(digits, 2, 10, 99) |a, ds| {
        for permutate_num(ds, 3, 100, 9999 / a) |b, ds| {
            let c = a * b;
            let c_digits = merge_sort(|a, b| a <= b, num_to_digits(c));
            if vec::eq(c_digits, ds) { set_add(answer, c); }
        }
    }

    let mut sum = 0;
    for answer.each_key |c| {
        sum += c;
    }
    io::println(fmt!("%u", sum));
}
<|endoftext|>


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

use LinkerFlavor;
use std::io;
use std::process::Command;
use target::{LinkArgs, TargetOptions};

use self::Arch::*;

#[allow(non_camel_case_types)]
#[derive(Copy, Clone)]
pub enum Arch {
    Armv7,
    Armv7s,
    Arm64,
    I386,
    X86_64
}

impl Arch {
    pub fn to_string(&self) -> &'static str {
        match self {
            &Armv7 => "armv7",
            &Armv7s => "armv7s",
            &Arm64 => "arm64",
            &I386 => "i386",
            &X86_64 => "x86_64"
        }
    }
}

pub fn get_sdk_root(sdk_name: &str) -> Result<String, String> {
    let res = Command::new("xcrun")
                      .arg("--show-sdk-path")
                      .arg("-sdk")
                      .arg(sdk_name)
                      .output()
                      .and_then(|output| {
                          if output.status.success() {
                              Ok(String::from_utf8(output.stdout).unwrap())
                          } else {
                              let error = String::from_utf8(output.stderr);
                              let error = format!("process exit with error: {}",
                                                  error.unwrap());
                              Err(io::Error::new(io::ErrorKind::Other,
                                                 &error[..]))
                          }
                      });

    match res {
        Ok(output) => Ok(output.trim().to_string()),
        Err(e) => Err(format!("failed to get {} SDK path: {}", sdk_name, e))
    }
}

fn build_pre_link_args(arch: Arch) -> Result<LinkArgs, String> {
    let sdk_name = match arch {
        Armv7 | Armv7s | Arm64 => "iphoneos",
        I386 | X86_64 => "iphonesimulator"
    };

    let arch_name = arch.to_string();

    let sdk_root = get_sdk_root(sdk_name)?;

    let mut args = LinkArgs::new();
    args.insert(LinkerFlavor::Gcc,
                vec!["-arch".to_string(),
                     arch_name.to_string(),
                     "-Wl,-syslibroot".to_string(),
                     sdk_root]);

    Ok(args)
}

fn target_cpu(arch: Arch) -> String {
    match arch {
        Armv7 => "cortex-a8", // iOS7 is supported on iPhone 4 and higher
        Armv7s => "cortex-a9",
        Arm64 => "cyclone",
        I386 => "yonah",
        X86_64 => "core2",
    }.to_string()
}

pub fn opts(arch: Arch) -> Result<TargetOptions, String> {
    let pre_link_args = build_pre_link_args(arch)?;
    Ok(TargetOptions {
        cpu: target_cpu(arch),
        dynamic_linking: false,
        executables: true,
        pre_link_args,
        has_elf_tls: false,
        .. super::apple_base::opts()
    })
}
<commit_msg>disable jemalloc on exectuable for ios targets<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use LinkerFlavor;
use std::io;
use std::process::Command;
use target::{LinkArgs, TargetOptions};

use self::Arch::*;

#[allow(non_camel_case_types)]
#[derive(Copy, Clone)]
pub enum Arch {
    Armv7,
    Armv7s,
    Arm64,
    I386,
    X86_64
}

impl Arch {
    pub fn to_string(&self) -> &'static str {
        match self {
            &Armv7 => "armv7",
            &Armv7s => "armv7s",
            &Arm64 => "arm64",
            &I386 => "i386",
            &X86_64 => "x86_64"
        }
    }
}

pub fn get_sdk_root(sdk_name: &str) -> Result<String, String> {
    let res = Command::new("xcrun")
                      .arg("--show-sdk-path")
                      .arg("-sdk")
                      .arg(sdk_name)
                      .output()
                      .and_then(|output| {
                          if output.status.success() {
                              Ok(String::from_utf8(output.stdout).unwrap())
                          } else {
                              let error = String::from_utf8(output.stderr);
                              let error = format!("process exit with error: {}",
                                                  error.unwrap());
                              Err(io::Error::new(io::ErrorKind::Other,
                                                 &error[..]))
                          }
                      });

    match res {
        Ok(output) => Ok(output.trim().to_string()),
        Err(e) => Err(format!("failed to get {} SDK path: {}", sdk_name, e))
    }
}

fn build_pre_link_args(arch: Arch) -> Result<LinkArgs, String> {
    let sdk_name = match arch {
        Armv7 | Armv7s | Arm64 => "iphoneos",
        I386 | X86_64 => "iphonesimulator"
    };

    let arch_name = arch.to_string();

    let sdk_root = get_sdk_root(sdk_name)?;

    let mut args = LinkArgs::new();
    args.insert(LinkerFlavor::Gcc,
                vec!["-arch".to_string(),
                     arch_name.to_string(),
                     "-Wl,-syslibroot".to_string(),
                     sdk_root]);

    Ok(args)
}

fn target_cpu(arch: Arch) -> String {
    match arch {
        Armv7 => "cortex-a8", // iOS7 is supported on iPhone 4 and higher
        Armv7s => "cortex-a9",
        Arm64 => "cyclone",
        I386 => "yonah",
        X86_64 => "core2",
    }.to_string()
}

pub fn opts(arch: Arch) -> Result<TargetOptions, String> {
    let pre_link_args = build_pre_link_args(arch)?;
    Ok(TargetOptions {
        cpu: target_cpu(arch),
        dynamic_linking: false,
        executables: true,
        pre_link_args,
        has_elf_tls: false,
        exe_allocation_crate: None,
        .. super::apple_base::opts()
    })
}
<|endoftext|>


<commit_before><commit_msg>Use or_else() instead of or()<commit_after><|endoftext|>


<commit_before><commit_msg>start new<commit_after>fn make_squares_list(n: i32) -> Vec<i32> {
    let mut re: Vec<i32> = vec![];
    for i in 0..n {
        let temp = i * i;
        if temp > n {
            break;
        } else {
            re.push(temp);
        }
    }

    re
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>lexer: fix case when an identifier is terminated by a comment<commit_after><|endoftext|>


<commit_before><commit_msg>adjust time source start time when coming out of the debugger<commit_after><|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

// NB: transitionary, de-mode-ing.

#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];

use cmp::Eq;
use either::Either;

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

/**
 * Get the value out of a successful result
 *
 * # Failure
 *
 * If the result is an error
 */
pub pure fn get<T: Copy, U>(res: &Result<T, U>) -> T {
    match *res {
      Ok(copy t) => t,
      Err(ref the_err) => unsafe {
        fail fmt!("get called on error result: %?", *the_err)
      }
    }
}

/**
 * Get a reference to the value out of a successful result
 *
 * # Failure
 *
 * If the result is an error
 */
pub pure fn get_ref<T, U>(res: &a/Result<T, U>) -> &a/T {
    match *res {
        Ok(ref t) => t,
        Err(ref the_err) => unsafe {
            fail fmt!("get_ref called on error result: %?", *the_err)
        }
    }
}

/**
 * Get the value out of an error result
 *
 * # Failure
 *
 * If the result is not an error
 */
pub pure fn get_err<T, U: Copy>(res: &Result<T, U>) -> U {
    match *res {
      Err(copy u) => u,
      Ok(_) => fail ~"get_err called on ok result"
    }
}

/// Returns true if the result is `ok`
pub pure fn is_ok<T, U>(res: &Result<T, U>) -> bool {
    match *res {
      Ok(_) => true,
      Err(_) => false
    }
}

/// Returns true if the result is `err`
pub pure fn is_err<T, U>(res: &Result<T, U>) -> bool {
    !is_ok(res)
}

/**
 * Convert to the `either` type
 *
 * `ok` result variants are converted to `either::right` variants, `err`
 * result variants are converted to `either::left`.
 */
pub pure fn to_either<T: Copy, U: Copy>(res: &Result<U, T>)
    -> Either<T, U> {
    match *res {
      Ok(copy res) => either::Right(res),
      Err(copy fail_) => either::Left(fail_)
    }
}

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

/**
 * Call a function based on a previous result
 *
 * If `res` is `err` then the value is extracted and passed to `op`
 * whereupon `op`s result is returned. if `res` is `ok` then it is
 * immediately returned.  This function can be used to pass through a
 * successful result while handling an error.
 */
pub pure fn chain_err<T, U, V>(
    res: Result<T, V>,
    op: fn(t: V) -> Result<T, U>)
    -> Result<T, U> {
    match move res {
      Ok(move t) => Ok(move t),
      Err(move v) => op(move v)
    }
}

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

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

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

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

impl<T, E> Result<T, E> {
    #[inline(always)]
    pure fn get_ref(&self) -> &self/T { get_ref(self) }

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

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

    #[inline(always)]
    pure fn iter(&self, f: fn(&T)) { iter(self, f) }

    #[inline(always)]
    pure fn iter_err(&self, f: fn(&E)) { iter_err(self, f) }

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

    #[inline(always)]
    pure fn unwrap_err(self) -> T { unwrap(self) }

    #[inline(always)]
    pure fn chain<U>(self, op: fn(T) -> Result<U,E>) -> Result<U,E> {
        chain(self, op)
    }

    #[inline(always)]
    pure fn chain_err<F>(self, op: fn(E) -> Result<T,F>) -> Result<T,F> {
        chain_err(self, op)
    }
}

impl<T: Copy, E> Result<T, E> {
    #[inline(always)]
    pure fn get(&self) -> T { get(self) }

    #[inline(always)]
    pure fn map_err<F:Copy>(&self, op: fn(&E) -> F) -> Result<T,F> {
        map_err(self, op)
    }
}

impl<T, E: Copy> Result<T, E> {
    #[inline(always)]
    pure fn get_err(&self) -> E { get_err(self) }

    #[inline(always)]
    pure fn map<U:Copy>(&self, op: fn(&T) -> U) -> Result<U,E> {
        map(self, op)
    }
}

/**
 * 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];
 *     }
 */
pub fn map_vec<T,U:Copy,V:Copy>(
    ts: &[T], op: fn(&T) -> Result<V,U>) -> Result<~[V],U> {

    let mut vs: ~[V] = vec::with_capacity(vec::len(ts));
    for vec::each(ts) |t| {
        match op(t) {
          Ok(copy v) => vs.push(v),
          Err(copy u) => return Err(u)
        }
    }
    return Ok(move vs);
}

pub fn map_opt<T,U:Copy,V:Copy>(
    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(copy v) => Ok(Some(v)),
        Err(copy 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.
 */
pub fn map_vec2<S,T,U:Copy,V:Copy>(ss: &[S], ts: &[T],
                op: fn(&S,&T) -> Result<V,U>) -> Result<~[V],U> {

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

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

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

/// Unwraps a result, assuming it is an `ok(T)`
#[inline(always)]
pub pure fn unwrap<T, U>(res: Result<T, U>) -> T {
    match move res {
      Ok(move t) => move t,
      Err(_) => fail ~"unwrap called on an err result"
    }
}

/// Unwraps a result, assuming it is an `err(U)`
#[inline(always)]
pub pure fn unwrap_err<T, U>(res: Result<T, U>) -> U {
    match move res {
      Err(move u) => move u,
      Ok(_) => fail ~"unwrap called on an ok result"
    }
}

#[cfg(test)]
#[allow(non_implicitly_copyable_typarams)]
mod tests {
    #[legacy_exports];
    fn op1() -> result::Result<int, ~str> { result::Ok(666) }

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

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

    #[test]
    fn chain_success() {
        assert get(&chain(op1(), op2)) == 667u;
    }

    #[test]
    fn chain_failure() {
        assert get_err(&chain(op3(), op2)) == ~"sadface";
    }

    #[test]
    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]
    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]
    fn test_impl_map() {
        assert Ok::<~str, ~str>(~"a").map(|_x| ~"b") == Ok(~"b");
        assert Err::<~str, ~str>(~"a").map(|_x| ~"b") == Err(~"a");
    }

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

    #[test]
    fn test_get_ref_method() {
        let foo: Result<int, ()> = Ok(100);
        assert *foo.get_ref() == 100;
    }
}
<commit_msg>Fix Option::unwrap_err.<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

// NB: transitionary, de-mode-ing.

#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];

use cmp::Eq;
use either::Either;

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

/**
 * Get the value out of a successful result
 *
 * # Failure
 *
 * If the result is an error
 */
pub pure fn get<T: Copy, U>(res: &Result<T, U>) -> T {
    match *res {
      Ok(copy t) => t,
      Err(ref the_err) => unsafe {
        fail fmt!("get called on error result: %?", *the_err)
      }
    }
}

/**
 * Get a reference to the value out of a successful result
 *
 * # Failure
 *
 * If the result is an error
 */
pub pure fn get_ref<T, U>(res: &a/Result<T, U>) -> &a/T {
    match *res {
        Ok(ref t) => t,
        Err(ref the_err) => unsafe {
            fail fmt!("get_ref called on error result: %?", *the_err)
        }
    }
}

/**
 * Get the value out of an error result
 *
 * # Failure
 *
 * If the result is not an error
 */
pub pure fn get_err<T, U: Copy>(res: &Result<T, U>) -> U {
    match *res {
      Err(copy u) => u,
      Ok(_) => fail ~"get_err called on ok result"
    }
}

/// Returns true if the result is `ok`
pub pure fn is_ok<T, U>(res: &Result<T, U>) -> bool {
    match *res {
      Ok(_) => true,
      Err(_) => false
    }
}

/// Returns true if the result is `err`
pub pure fn is_err<T, U>(res: &Result<T, U>) -> bool {
    !is_ok(res)
}

/**
 * Convert to the `either` type
 *
 * `ok` result variants are converted to `either::right` variants, `err`
 * result variants are converted to `either::left`.
 */
pub pure fn to_either<T: Copy, U: Copy>(res: &Result<U, T>)
    -> Either<T, U> {
    match *res {
      Ok(copy res) => either::Right(res),
      Err(copy fail_) => either::Left(fail_)
    }
}

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

/**
 * Call a function based on a previous result
 *
 * If `res` is `err` then the value is extracted and passed to `op`
 * whereupon `op`s result is returned. if `res` is `ok` then it is
 * immediately returned.  This function can be used to pass through a
 * successful result while handling an error.
 */
pub pure fn chain_err<T, U, V>(
    res: Result<T, V>,
    op: fn(t: V) -> Result<T, U>)
    -> Result<T, U> {
    match move res {
      Ok(move t) => Ok(move t),
      Err(move v) => op(move v)
    }
}

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

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

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

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

impl<T, E> Result<T, E> {
    #[inline(always)]
    pure fn get_ref(&self) -> &self/T { get_ref(self) }

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

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

    #[inline(always)]
    pure fn iter(&self, f: fn(&T)) { iter(self, f) }

    #[inline(always)]
    pure fn iter_err(&self, f: fn(&E)) { iter_err(self, f) }

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

    #[inline(always)]
    pure fn unwrap_err(self) -> E { unwrap_err(self) }

    #[inline(always)]
    pure fn chain<U>(self, op: fn(T) -> Result<U,E>) -> Result<U,E> {
        chain(self, op)
    }

    #[inline(always)]
    pure fn chain_err<F>(self, op: fn(E) -> Result<T,F>) -> Result<T,F> {
        chain_err(self, op)
    }
}

impl<T: Copy, E> Result<T, E> {
    #[inline(always)]
    pure fn get(&self) -> T { get(self) }

    #[inline(always)]
    pure fn map_err<F:Copy>(&self, op: fn(&E) -> F) -> Result<T,F> {
        map_err(self, op)
    }
}

impl<T, E: Copy> Result<T, E> {
    #[inline(always)]
    pure fn get_err(&self) -> E { get_err(self) }

    #[inline(always)]
    pure fn map<U:Copy>(&self, op: fn(&T) -> U) -> Result<U,E> {
        map(self, op)
    }
}

/**
 * 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];
 *     }
 */
pub fn map_vec<T,U:Copy,V:Copy>(
    ts: &[T], op: fn(&T) -> Result<V,U>) -> Result<~[V],U> {

    let mut vs: ~[V] = vec::with_capacity(vec::len(ts));
    for vec::each(ts) |t| {
        match op(t) {
          Ok(copy v) => vs.push(v),
          Err(copy u) => return Err(u)
        }
    }
    return Ok(move vs);
}

pub fn map_opt<T,U:Copy,V:Copy>(
    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(copy v) => Ok(Some(v)),
        Err(copy 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.
 */
pub fn map_vec2<S,T,U:Copy,V:Copy>(ss: &[S], ts: &[T],
                op: fn(&S,&T) -> Result<V,U>) -> Result<~[V],U> {

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

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

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

/// Unwraps a result, assuming it is an `ok(T)`
#[inline(always)]
pub pure fn unwrap<T, U>(res: Result<T, U>) -> T {
    match move res {
      Ok(move t) => move t,
      Err(_) => fail ~"unwrap called on an err result"
    }
}

/// Unwraps a result, assuming it is an `err(U)`
#[inline(always)]
pub pure fn unwrap_err<T, U>(res: Result<T, U>) -> U {
    match move res {
      Err(move u) => move u,
      Ok(_) => fail ~"unwrap called on an ok result"
    }
}

#[cfg(test)]
#[allow(non_implicitly_copyable_typarams)]
mod tests {
    #[legacy_exports];
    fn op1() -> result::Result<int, ~str> { result::Ok(666) }

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

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

    #[test]
    fn chain_success() {
        assert get(&chain(op1(), op2)) == 667u;
    }

    #[test]
    fn chain_failure() {
        assert get_err(&chain(op3(), op2)) == ~"sadface";
    }

    #[test]
    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]
    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]
    fn test_impl_map() {
        assert Ok::<~str, ~str>(~"a").map(|_x| ~"b") == Ok(~"b");
        assert Err::<~str, ~str>(~"a").map(|_x| ~"b") == Err(~"a");
    }

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

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


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

use programs::common::*;
use graphics::point::*;
use graphics::size::*;
use graphics::window::*;
use common::string::*;
use common::resource::*;

use core::ops::DerefMut;

pub struct WindowScheme {
    pub current_window: *mut Window,
}

pub struct WindowResource {
    pub active_window: Box<Window>,
}

impl Resource for WindowResource {
     //Required functions
    /// Return the url of this resource
    fn url(&self) -> URL {
        return URL::from_string(&("window://test".to_string()));
    }
    /// Return the type of this resource
    fn stat(&self) -> ResourceType {
        return ResourceType::Window;
    }
    /// Read data to buffer
    fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        //TODO implement
        return Option::None;
    }
    /// Write to resource
    fn write(&mut self, buf: &[u8]) -> Option<usize> {
        //TODO implement
        return Option::None;
    }
    /// Seek
    fn seek(&mut self, pos: ResourceSeek) -> Option<usize> {
        return Option::None; //TODO implement
    }
    /// Sync the resource
    fn sync(&mut self) -> bool {
        return true;
    }
}

impl SessionItem for WindowScheme {
    fn scheme(&self) -> String {
        return "window".to_string();
    }

    fn open(&mut self, url: &URL) -> Box<Resource> {
        let scheme :String;
        let mut pointx :isize;
        let mut pointy :isize;
        let mut size_width :usize;
        let mut size_height :usize;
        let mut title :String;

        //window://host/path/path/path is the path type we're working with.
        let mut url_path = url.path_parts();
        pointx = match url_path.get(0) {
            Some(x) => x.to_num_signed(),
            None    => 0,
        };
        pointy = match url_path.get(1) {
            Some(y) => y.to_num_signed(),
            None    => 0,
        };
        size_width = match url_path.get(2) {
            Some(w) =>  w.to_num(),
            None    =>  10,
        };
        size_height = match url_path.get(3) {
            Some(h) =>  h.to_num(),
            None    =>  10,
        };
        title = match url_path.get(4) {
            Some(t) =>  t.clone(),
            None    =>  "Fail".to_string(),
        };
        let mut p: Point = Point::new(pointx, pointy);
        let mut s: Size = Size::new(size_width, size_height);

        let mut newWin  = Window::new(p, s, title);
        unsafe {
            newWin.ptr = newWin.deref_mut();
            self.current_window = newWin.ptr;
            //self.raw_current = Box::into_raw(newWin);
            if newWin.ptr as usize > 0 {
                (*::session_ptr).add_window(self.current_window);
            }
        }

        return box WindowResource {
            active_window : newWin,
        };
        //return box VecResource::new(URL::from_str("window://"),
        //                            ResourceType::File,
        //                            newWin);
    }
}

impl Drop for WindowScheme {
   fn drop(&mut self) {
       unsafe {
           (*::session_ptr).remove_window(self.current_window);
       }
   }
}
<commit_msg>rebasing<commit_after>use alloc::boxed::Box;

use programs::common::*;
use graphics::point::*;
use graphics::size::*;
use graphics::window::*;
use common::string::*;
use common::resource::*;

use core::ops::DerefMut;

pub struct WindowScheme {
    pub current_window: *mut Window,
}

pub struct WindowResource {
    pub active_window: Box<Window>,
}

impl Resource for WindowResource {
     //Required functions
    /// Return the url of this resource
    fn url(&self) -> URL {
        return URL::from_string(&("window://test".to_string()));
    }
    /// Return the type of this resource
    fn stat(&self) -> ResourceType {
        return ResourceType::Window;
    }
    /// Read data to buffer
    fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        //TODO implement
        return Option::None;
    }
    /// Write to resource
    fn write(&mut self, buf: &[u8]) -> Option<usize> {
        //TODO implement
        return Option::None;
    }
    /// Seek
    fn seek(&mut self, pos: ResourceSeek) -> Option<usize> {
        return Option::None; //TODO implement
    }
    /// Sync the resource
    fn sync(&mut self) -> bool {
        return true;
    }
}

impl SessionItem for WindowScheme {
    fn scheme(&self) -> String {
        return "window".to_string();
    }

    fn open(&mut self, url: &URL) -> Box<Resource> {
        let scheme :String;
        let mut pointx :isize;
        let mut pointy :isize;
        let mut size_width :usize;
        let mut size_height :usize;
        let mut title :String;

        //window://host/path/path/path is the path type we're working with.
        let mut url_path = url.path_parts();
        pointx = match url_path.get(0) {
            Some(x) => x.to_num_signed(),
            None    => 0,
        };
        pointy = match url_path.get(1) {
            Some(y) => y.to_num_signed(),
            None    => 0,
        };
        size_width = match url_path.get(2) {
            Some(w) =>  w.to_num(),
            None    =>  10,
        };
        size_height = match url_path.get(3) {
            Some(h) =>  h.to_num(),
            None    =>  10,
        };
        title = match url_path.get(4) {
            Some(t) =>  t.clone(),
            None    =>  "Fail".to_string(),
        };
        let mut p: Point = Point::new(pointx, pointy);
        let mut s: Size = Size::new(size_width, size_height);
        let mut newWin  = Window::new(p, s, title);
        unsafe {
            newWin.ptr = newWin.deref_mut();
            self.current_window = newWin.ptr;
            //self.raw_current = Box::into_raw(newWin);
            if newWin.ptr as usize > 0 {
                (*::session_ptr).add_window(self.current_window);
            }
        }

        return box WindowResource {
            active_window : newWin,
        };
        //return box VecResource::new(URL::from_str("window://"),
        //                            ResourceType::File,
        //                            newWin);
    }
}

impl Drop for WindowScheme {
   fn drop(&mut self) {
       unsafe {
           (*::session_ptr).remove_window(self.current_window);
       }
   }
}
<|endoftext|>


<commit_before>// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers

// Copyright (c) 2013-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in
//   the documentation and/or other materials provided with the
//   distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
//   the name of "The Computer Language Shootout Benchmarks" nor the
//   names of its contributors may be used to endorse or promote
//   products derived from this software without specific prior
//   written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

// ignore-pretty very bad with line comments
// ignore-android doesn't terminate?

#![feature(slicing_syntax)]

use std::iter::range_step;
use std::io::{stdin, stdout, File};

static LINE_LEN: uint = 60;

fn make_complements() -> [u8, ..256] {
    let transforms = [
        ('A', 'T'), ('C', 'G'), ('G', 'C'), ('T', 'A'),
        ('U', 'A'), ('M', 'K'), ('R', 'Y'), ('W', 'W'),
        ('S', 'S'), ('Y', 'R'), ('K', 'M'), ('V', 'B'),
        ('H', 'D'), ('D', 'H'), ('B', 'V'), ('N', 'N'),
        ('\n', '\n')];
    let mut complements: [u8, ..256] = [0, ..256];
    for (i, c) in complements.iter_mut().enumerate() {
        *c = i as u8;
    }
    let lower = 'A' as u8 - 'a' as u8;
    for &(from, to) in transforms.iter() {
        complements[from as uint] = to as u8;
        complements[(from as u8 - lower) as uint] = to as u8;
    }
    complements
}

fn main() {
    let complements = make_complements();
    let data = if std::os::getenv("RUST_BENCH").is_some() {
        File::open(&Path::new("shootout-k-nucleotide.data")).read_to_end()
    } else {
        stdin().read_to_end()
    };
    let mut data = data.unwrap();

    for seq in data.as_mut_slice().split_mut(|c| *c == '>' as u8) {
        // skip header and last \n
        let begin = match seq.iter().position(|c| *c == '\n' as u8) {
            None => continue,
            Some(c) => c
        };
        let len = seq.len();
        let seq = seq[mut begin+1..len-1];

        // arrange line breaks
        let len = seq.len();
        let off = LINE_LEN - len % (LINE_LEN + 1);
        for i in range_step(LINE_LEN, len, LINE_LEN + 1) {
            for j in std::iter::count(i, -1).take(off) {
                seq[j] = seq[j - 1];
            }
            seq[i - off] = '\n' as u8;
        }

        // reverse complement, as
        //    seq.reverse(); for c in seq.iter_mut() {*c = complements[*c]}
        // but faster:
        let mut it = seq.iter_mut();
        loop {
            match (it.next(), it.next_back()) {
                (Some(front), Some(back)) => {
                    let tmp = complements[*front as uint];
                    *front = complements[*back as uint];
                    *back = tmp;
                }
                (Some(last), None) => *last = complements[*last as uint], // last element
                _ => break // vector exhausted.
            }
        }
    }

    stdout().write(data.as_slice()).unwrap();
}
<commit_msg>auto merge of #18056 : TeXitoi/rust/shootout-reverse-complement-improvement, r=alexcrichton<commit_after>// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers

// Copyright (c) 2013-2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
//   notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
//   notice, this list of conditions and the following disclaimer in
//   the documentation and/or other materials provided with the
//   distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
//   the name of "The Computer Language Shootout Benchmarks" nor the
//   names of its contributors may be used to endorse or promote
//   products derived from this software without specific prior
//   written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

// ignore-pretty very bad with line comments
// ignore-android doesn't terminate?

#![feature(slicing_syntax)]

use std::iter::range_step;
use std::io::{stdin, stdout, File};

static LINE_LEN: uint = 60;

fn make_complements() -> [u8, ..256] {
    let transforms = [
        ('A', 'T'), ('C', 'G'), ('G', 'C'), ('T', 'A'),
        ('U', 'A'), ('M', 'K'), ('R', 'Y'), ('W', 'W'),
        ('S', 'S'), ('Y', 'R'), ('K', 'M'), ('V', 'B'),
        ('H', 'D'), ('D', 'H'), ('B', 'V'), ('N', 'N'),
        ('\n', '\n')];
    let mut complements: [u8, ..256] = [0, ..256];
    for (i, c) in complements.iter_mut().enumerate() {
        *c = i as u8;
    }
    let lower = 'A' as u8 - 'a' as u8;
    for &(from, to) in transforms.iter() {
        complements[from as uint] = to as u8;
        complements[(from as u8 - lower) as uint] = to as u8;
    }
    complements
}

fn main() {
    let complements = make_complements();
    let data = if std::os::getenv("RUST_BENCH").is_some() {
        File::open(&Path::new("shootout-k-nucleotide.data")).read_to_end()
    } else {
        stdin().read_to_end()
    };
    let mut data = data.unwrap();

    for seq in data.as_mut_slice().split_mut(|c| *c == '>' as u8) {
        // skip header and last \n
        let begin = match seq.iter().position(|c| *c == '\n' as u8) {
            None => continue,
            Some(c) => c
        };
        let len = seq.len();
        let seq = seq[mut begin+1..len-1];

        // arrange line breaks
        let len = seq.len();
        let off = LINE_LEN - len % (LINE_LEN + 1);
        for i in range_step(LINE_LEN, len, LINE_LEN + 1) {
            for j in std::iter::count(i, -1).take(off) {
                seq[j] = seq[j - 1];
            }
            seq[i - off] = '\n' as u8;
        }

        // reverse complement, as
        //    seq.reverse(); for c in seq.iter_mut() { *c = complements[*c] }
        // but faster:
        for (front, back) in two_side_iter(seq) {
            let tmp = complements[*front as uint];
            *front = complements[*back as uint];
            *back = tmp;
        }
        if seq.len() % 2 == 1 {
            let middle = &mut seq[seq.len() / 2];
            *middle = complements[*middle as uint];
        }
    }

    stdout().write(data.as_slice()).unwrap();
}

pub struct TwoSideIter<'a, T: 'a> {
    first: *mut T,
    last: *mut T,
    marker: std::kinds::marker::ContravariantLifetime<'a>,
    marker2: std::kinds::marker::NoCopy
}

pub fn two_side_iter<'a, T>(slice: &'a mut [T]) -> TwoSideIter<'a, T> {
    let len = slice.len();
    let first = slice.as_mut_ptr();
    let last = if len == 0 {
        first
    } else {
        unsafe { first.offset(len as int - 1) }
    };

    TwoSideIter {
        first: first,
        last: last,
        marker: std::kinds::marker::ContravariantLifetime,
        marker2: std::kinds::marker::NoCopy
    }
}

impl<'a, T> Iterator<(&'a mut T, &'a mut T)> for TwoSideIter<'a, T> {
    fn next(&mut self) -> Option<(&'a mut T, &'a mut T)> {
        if self.first < self.last {
            let result = unsafe { (&mut *self.first, &mut *self.last) };
            self.first = unsafe { self.first.offset(1) };
            self.last = unsafe { self.last.offset(-1) };
            Some(result)
        } else {
            None
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #1506 - RalfJung:test-isolation, r=RalfJung<commit_after>// ignore-windows: File handling is not implemented yet
// error-pattern: `open` not available when isolation is enabled

fn main() {
    let _file = std::fs::File::open("file.txt").unwrap();
}
<|endoftext|>


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

fn is_copy<T: ::std::marker<i32>::Copy>() {}
//~^ ERROR type parameters are not allowed on this type [E0109]
fn main() {}
<|endoftext|>


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

fn transmute_lifetime<'a, 'b, T>(t: &'a (T,)) -> &'b T {
    match (&t,) { //~ ERROR cannot infer an appropriate lifetime
        ((u,),) => u,
    }
}

fn main() {
    let x = {
        let y = Box::new((42,));
        transmute_lifetime(&y)
    };

    println!("{}", x);
}
<|endoftext|>


<commit_before><commit_msg>add an idle_loop example<commit_after>extern crate rustbox;
extern crate tiny;

use std::borrow::Borrow;

use tiny::tui::{TUI, TUIRet};

fn loop_() -> Option<String> {
    let mut tui = TUI::new();

    loop {
        match tui.idle_loop() {
            TUIRet::SendMsg(cmd) => {
                tui.show_outgoing_msg(cmd.into_iter().collect::<String>().borrow());
            },
            TUIRet::Abort => {
                return None;
            },
            _ => {}
        }
    }
}

fn main() {
    loop_().map(|err| println!("{}", err));
}
<|endoftext|>


<commit_before><commit_msg>First part of new unified service.<commit_after>//! Service for DNS.

use std::io;
use std::mem;
use std::time::Duration;
use futures::{Async, Future, Poll};
use futures::stream::{Peekable, Stream};
use tokio_core::reactor;
use tokio_core::channel::Receiver;
use super::conf::{ServerConf, TransportMode};
use super::request::ServiceRequest;

//------------ Transport -----------------------------------------------------

/// Something that can send and receive DNS messages.
pub trait Transport: io::Read + io::Write { }

//------------ TransportFactory ----------------------------------------------

/// Something that can make a new `Transport`.
pub trait TransportFactory {
    /// The type of transport created by this factory.
    type Transport: Transport;

    /// The type of future resolved while making a new transport.
    type Future: Future<Item=Self::Transport, Error=io::Error>;

    /// Starts creating a new transport atop a given reactor.
    fn create(&self, reactor: &reactor::Handle) -> io::Result<Self::Future>;
}

//------------ ServiceMode ---------------------------------------------------

/// The mode a service will run in.
///
/// This is essentially `conf::TransportMode` stripped of the variants that a
/// real service can’t have.
pub enum ServiceMode {
    SingleRequest,
    Sequential,
    Multiplex,
}

impl ServiceMode {
    pub fn from_transport_mode(t: TransportMode, default: ServiceMode)
                               -> Option<Self> {
        match t {
            TransportMode::None => None,
            TransportMode::Default => Some(default),
            TransportMode::SingleRequest => Some(ServiceMode::SingleRequest),
            TransportMode::Sequential => Some(ServiceMode::Sequential),
            TransportMode::Multiplex => Some(ServiceMode::Multiplex)
        }
    }
}

//------------ Service -------------------------------------------------------

/// A service processes DNS requests.
pub struct Service<T: TransportFactory>(TrueService<T>);

enum TrueService<T: TransportFactory> {
    Single(SingleService<T>),
    Sequential(Expiring<T, SequentialService<T>>),
    Multiplex(Expiring<T, MultiplexService<T>>)
}

impl<T: TransportFactory> Service<T> {
    /// Creates a new service.
    fn new(receiver: Receiver<ServiceRequest>, factory: T,
           reactor: reactor::Handle, mode: ServiceMode, conf: &ServerConf)
           -> Self {
        match mode {
            ServiceMode::SingleRequest => {
                Service(
                    TrueService::Single(
                        SingleService::new(receiver, factory, reactor, conf)
                    )
                )
            }
            ServiceMode::Sequential => {
                Service(
                    TrueService::Sequential(
                        Expiring::new(receiver, factory, reactor, conf)
                    )
                )
            }
            ServiceMode::Multiplex => {
                Service(
                    TrueService::Multiplex(
                        Expiring::new(receiver, factory, reactor, conf)
                    )
                )
            }
        }
    }
}

//--- Future

impl<T: TransportFactory> Future for Service<T> {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<(), io::Error> {
        match self.0 {
            TrueService::Single(ref mut s) => s.poll(),
            TrueService::Sequential(ref mut s) => s.poll(),
            TrueService::Multiplex(ref mut s) => s.poll()
        }
    }
}

//------------ SingleService -------------------------------------------------

/// A service in single request mode.
struct SingleService<T: TransportFactory> {
    receiver: Receiver<ServiceRequest>,
    factory: T,
    reactor: reactor::Handle,
}

impl<T: TransportFactory> SingleService<T> {
    fn new(receiver: Receiver<ServiceRequest>, factory: T,
           reactor: reactor::Handle, conf: &ServerConf) -> Self {
        unimplemented!()
    }
}

//--- Future

impl<T: TransportFactory> Future for SingleService<T> {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<(), io::Error> {
        unimplemented!()
    }
}

//------------ ExpiringService -----------------------------------------------

/// The service underneath `Expiring`.
///
/// Implementors need to be a stream of `()`, returning an item every time
/// the timeout needs to be refreshed. When they are done streaming, they
/// will be destroyed via their `finalize()` method, thereby retrieving the
/// receiver if it still exists.
trait ExpiringService<T: TransportFactory>: Stream<Item=(), Error=io::Error> {
    fn create(sock: T::Future, receiver: Peekable<Receiver<ServiceRequest>>,
              request_timeout: Duration) -> Self;
    fn finalize(self) -> Option<Peekable<Receiver<ServiceRequest>>>;
}

//------------ Expiring ------------------------------------------------------

/// A wrapper for a service that will expire if nothing happens for too long.
struct Expiring<T: TransportFactory, S: ExpiringService<T>> {
    state: State<S>,
    factory: T,
    reactor: reactor::Handle,
    request_timeout: Duration,
    keep_alive: Duration,
}

enum State<S> {
    Idle(Peekable<Receiver<ServiceRequest>>),
    Active {
        service: S,
        timeout: Option<reactor::Timeout>
    },
    Dead
}

impl<T: TransportFactory, S: ExpiringService<T>> Expiring<T, S> {
    fn new(receiver: Receiver<ServiceRequest>, factory: T,
           reactor: reactor::Handle, conf: &ServerConf) -> Self {
        Expiring {
            state: State::Idle(receiver.peekable()),
            factory: factory,
            reactor: reactor,
            request_timeout: conf.request_timeout,
            keep_alive: conf.keep_alive
        }
    }
}

//--- Future

impl<T: TransportFactory, S: ExpiringService<T>> Future for Expiring<T, S> {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<(), io::Error> {
        match self.state {
            State::Idle(ref mut receiver) => {
                try_ready!(receiver.peek());
            }
            State::Active{ref mut service, ref mut timeout} => {
                if let Some(ref mut timeout) = *timeout {
                    match timeout.poll() {
                        Ok(Async::Ready(())) => { }
                        other => return other
                    }
                }
                if let Some(()) = try_ready!(service.poll()) {
                    *timeout = reactor::Timeout::new(self.keep_alive,
                                                     &self.reactor).ok();
                    if let Some(ref mut timeout) = *timeout {
                        try_ready!(timeout.poll());
                        // If we come here, the timeout triggered
                        // already. Let’s panic because this can only lead
                        // to trouble later ...
                        panic!("Timeout triggered right away.");
                    }
                    return Ok(Async::NotReady)
                }
            }
            State::Dead => panic!("poll on a dead service")
        }

        self.state = match mem::replace(&mut self.state, State::Dead) {
            State::Idle(receiver) => {
                let sock = try!(self.factory.create(&self.reactor));
                let service = S::create(sock, receiver, self.request_timeout);
                let timeout = reactor::Timeout::new(self.keep_alive,
                                                    &self.reactor).ok();
                State::Active{service: service, timeout: timeout}
            }
            State::Active{service, ..} => {
                match service.finalize() {
                    Some(receiver) => State::Idle(receiver),
                    None => return Ok(Async::Ready(()))
                }
            }
            State::Dead => panic!()
        };
        Ok(Async::NotReady)
    }
}

//------------ SequentialService ---------------------------------------------

/// A service in sequential request mode.
struct SequentialService<T: TransportFactory> {
    phantom: ::std::marker::PhantomData<T>
}

//--- ExpiringService

impl<T: TransportFactory> ExpiringService<T> for SequentialService<T> {
    fn create(sock: T::Future, recv: Peekable<Receiver<ServiceRequest>>,
              request_timeout: Duration) -> Self {
        unimplemented!()
    }

    fn finalize(self) -> Option<Peekable<Receiver<ServiceRequest>>> {
        unimplemented!()
    }
}

//--- Stream

impl<T: TransportFactory> Stream for SequentialService<T> {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<()>, io::Error> {
        unimplemented!()
    }
}

//------------ MultiplexService ----------------------------------------------

/// A service in multiplex mode.
struct MultiplexService<T: TransportFactory> {
    phantom: ::std::marker::PhantomData<T>
}

//--- ExpiringService

impl<T: TransportFactory> ExpiringService<T> for MultiplexService<T> {
    fn create(sock: T::Future, recv: Peekable<Receiver<ServiceRequest>>,
              request_timeout: Duration) -> Self {
        unimplemented!()
    }

    fn finalize(self) -> Option<Peekable<Receiver<ServiceRequest>>> {
        unimplemented!()
    }
}

//--- Stream

impl<T: TransportFactory> Stream for MultiplexService<T> {
    type Item = ();
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<()>, io::Error> {
        unimplemented!()
    }
}

<|endoftext|>


<commit_before><commit_msg>Remove unnecessary trait restriction<commit_after><|endoftext|>


<commit_before><commit_msg>Start aggregating metrics<commit_after><|endoftext|>