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

//! Code for type-checking closure expressions.

use super::{check_fn, Expectation, FnCtxt};

use astconv;
use middle::infer;
use middle::region::CodeExtent;
use middle::subst;
use middle::ty::{self, ToPolyTraitRef, Ty};
use rscope::RegionScope;
use syntax::abi;
use syntax::ast;
use syntax::ast::CaptureClause::*;
use syntax::ast_util;
use util::ppaux::Repr;

pub fn check_expr_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
                                   expr: &ast::Expr,
                                   capture: ast::CaptureClause,
                                   opt_kind: Option<ast::UnboxedClosureKind>,
                                   decl: &ast::FnDecl,
                                   body: &ast::Block,
                                   expected: Expectation<'tcx>) {
    debug!("check_expr_closure(expr={},expected={})",
           expr.repr(fcx.tcx()),
           expected.repr(fcx.tcx()));

    let expected_sig_and_kind = expected.map_to_option(fcx, |ty| {
        deduce_unboxed_closure_expectations_from_expected_type(fcx, ty)
    });

    match opt_kind {
        None => {
            // If users didn't specify what sort of closure they want,
            // examine the expected type. For now, if we see explicit
            // evidence than an unboxed closure is desired, we'll use
            // that, otherwise we'll fall back to boxed closures.
            match expected_sig_and_kind {
                None => { // doesn't look like an unboxed closure
                    let region = astconv::opt_ast_region_to_region(fcx,
                                                                   fcx,
                                                                   expr.span,
                                                                   &None);

                    check_boxed_closure(fcx,
                                        expr,
                                        ty::RegionTraitStore(region, ast::MutMutable),
                                        decl,
                                        body,
                                        expected);

                    match capture {
                        CaptureByValue => {
                            fcx.ccx.tcx.sess.span_err(
                                expr.span,
                                "boxed closures can't capture by value, \
                                if you want to use an unboxed closure, \
                                explicitly annotate its kind: e.g. `move |:|`");
                        },
                        CaptureByRef => {}
                    }
                }
                Some((sig, kind)) => {
                    check_unboxed_closure(fcx, expr, kind, decl, body, Some(sig));
                }
            }
        }

        Some(kind) => {
            let kind = match kind {
                ast::FnUnboxedClosureKind => ty::FnUnboxedClosureKind,
                ast::FnMutUnboxedClosureKind => ty::FnMutUnboxedClosureKind,
                ast::FnOnceUnboxedClosureKind => ty::FnOnceUnboxedClosureKind,
            };

            let expected_sig = expected_sig_and_kind.map(|t| t.0);
            check_unboxed_closure(fcx, expr, kind, decl, body, expected_sig);
        }
    }
}

fn check_unboxed_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
                                  expr: &ast::Expr,
                                  kind: ty::UnboxedClosureKind,
                                  decl: &ast::FnDecl,
                                  body: &ast::Block,
                                  expected_sig: Option<ty::FnSig<'tcx>>) {
    let expr_def_id = ast_util::local_def(expr.id);

    debug!("check_unboxed_closure kind={} expected_sig={}",
           kind,
           expected_sig.repr(fcx.tcx()));

    let mut fn_ty = astconv::ty_of_closure(
        fcx,
        ast::Unsafety::Normal,
        ast::Many,

        // The `RegionTraitStore` and region_existential_bounds
        // are lies, but we ignore them so it doesn't matter.
        //
        // FIXME(pcwalton): Refactor this API.
        ty::region_existential_bound(ty::ReStatic),
        ty::RegionTraitStore(ty::ReStatic, ast::MutImmutable),

        decl,
        abi::RustCall,
        expected_sig);

    let region = match fcx.anon_regions(expr.span, 1) {
        Err(_) => {
            fcx.ccx.tcx.sess.span_bug(expr.span,
                                      "can't make anon regions here?!")
        }
        Ok(regions) => regions[0],
    };

    let closure_type = ty::mk_unboxed_closure(fcx.ccx.tcx,
                                              expr_def_id,
                                              fcx.ccx.tcx.mk_region(region),
                                              fcx.ccx.tcx.mk_substs(
                                                  fcx.inh.param_env.free_substs.clone()));

    fcx.write_ty(expr.id, closure_type);

    let fn_sig =
        ty::liberate_late_bound_regions(fcx.tcx(), CodeExtent::from_node_id(body.id), &fn_ty.sig);

    check_fn(fcx.ccx,
             ast::Unsafety::Normal,
             expr.id,
             &fn_sig,
             decl,
             expr.id,
             &*body,
             fcx.inh);

    // Tuple up the arguments and insert the resulting function type into
    // the `unboxed_closures` table.
    fn_ty.sig.0.inputs = vec![ty::mk_tup(fcx.tcx(), fn_ty.sig.0.inputs)];

    debug!("unboxed_closure for {} --> sig={} kind={}",
           expr_def_id.repr(fcx.tcx()),
           fn_ty.sig.repr(fcx.tcx()),
           kind);

    let unboxed_closure = ty::UnboxedClosure {
        closure_type: fn_ty,
        kind: kind,
    };

    fcx.inh
        .unboxed_closures
        .borrow_mut()
        .insert(expr_def_id, unboxed_closure);
}

fn deduce_unboxed_closure_expectations_from_expected_type<'a,'tcx>(
    fcx: &FnCtxt<'a,'tcx>,
    expected_ty: Ty<'tcx>)
    -> Option<(ty::FnSig<'tcx>,ty::UnboxedClosureKind)>
{
    match expected_ty.sty {
        ty::ty_trait(ref object_type) => {
            let trait_ref =
                object_type.principal_trait_ref_with_self_ty(fcx.tcx(),
                                                             fcx.tcx().types.err);
            deduce_unboxed_closure_expectations_from_trait_ref(fcx, &trait_ref)
        }
        ty::ty_infer(ty::TyVar(vid)) => {
            deduce_unboxed_closure_expectations_from_obligations(fcx, vid)
        }
        _ => {
            None
        }
    }
}

fn deduce_unboxed_closure_expectations_from_trait_ref<'a,'tcx>(
    fcx: &FnCtxt<'a,'tcx>,
    trait_ref: &ty::PolyTraitRef<'tcx>)
    -> Option<(ty::FnSig<'tcx>, ty::UnboxedClosureKind)>
{
    let tcx = fcx.tcx();

    debug!("deduce_unboxed_closure_expectations_from_object_type({})",
           trait_ref.repr(tcx));

    let kind = match tcx.lang_items.fn_trait_kind(trait_ref.def_id()) {
        Some(k) => k,
        None => { return None; }
    };

    debug!("found object type {}", kind);

    let arg_param_ty = *trait_ref.substs().types.get(subst::TypeSpace, 0);
    let arg_param_ty = fcx.infcx().resolve_type_vars_if_possible(&arg_param_ty);
    debug!("arg_param_ty {}", arg_param_ty.repr(tcx));

    let input_tys = match arg_param_ty.sty {
        ty::ty_tup(ref tys) => { (*tys).clone() }
        _ => { return None; }
    };
    debug!("input_tys {}", input_tys.repr(tcx));

    let ret_param_ty = *trait_ref.substs().types.get(subst::TypeSpace, 1);
    let ret_param_ty = fcx.infcx().resolve_type_vars_if_possible(&ret_param_ty);
    debug!("ret_param_ty {}", ret_param_ty.repr(tcx));

    let fn_sig = ty::FnSig {
        inputs: input_tys,
        output: ty::FnConverging(ret_param_ty),
        variadic: false
    };
    debug!("fn_sig {}", fn_sig.repr(tcx));

    return Some((fn_sig, kind));
}

fn deduce_unboxed_closure_expectations_from_obligations<'a,'tcx>(
    fcx: &FnCtxt<'a,'tcx>,
    expected_vid: ty::TyVid)
    -> Option<(ty::FnSig<'tcx>, ty::UnboxedClosureKind)>
{
    // Here `expected_ty` is known to be a type inference variable.
    for obligation in fcx.inh.fulfillment_cx.borrow().pending_obligations().iter() {
        match obligation.predicate {
            ty::Predicate::Trait(ref trait_predicate) => {
                let trait_ref = trait_predicate.to_poly_trait_ref();
                let self_ty = fcx.infcx().shallow_resolve(trait_ref.self_ty());
                match self_ty.sty {
                    ty::ty_infer(ty::TyVar(v)) if expected_vid == v => { }
                    _ => { continue; }
                }

                match deduce_unboxed_closure_expectations_from_trait_ref(fcx, &trait_ref) {
                    Some(e) => { return Some(e); }
                    None => { }
                }
            }
            _ => { }
        }
    }

    None
}

fn check_boxed_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
                                expr: &ast::Expr,
                                store: ty::TraitStore,
                                decl: &ast::FnDecl,
                                body: &ast::Block,
                                expected: Expectation<'tcx>) {
    let tcx = fcx.ccx.tcx;

    // Find the expected input/output types (if any). Substitute
    // fresh bound regions for any bound regions we find in the
    // expected types so as to avoid capture.
    let expected_cenv = expected.map_to_option(fcx, |ty| match ty.sty {
        _ => None
    });
    let (expected_sig, expected_onceness, expected_bounds) = match expected_cenv {
        Some(cenv) => {
            let (sig, _) =
                ty::replace_late_bound_regions(
                    tcx,
                    &cenv.sig,
                    |_, debruijn| fcx.inh.infcx.fresh_bound_region(debruijn));
            let onceness = match (&store, &cenv.store) {
                // As the closure type and onceness go, only three
                // combinations are legit:
                //      once closure
                //      many closure
                //      once proc
                // If the actual and expected closure type disagree with
                // each other, set expected onceness to be always Once or
                // Many according to the actual type. Otherwise, it will
                // yield either an illegal "many proc" or a less known
                // "once closure" in the error message.
                (&ty::UniqTraitStore, &ty::UniqTraitStore) |
                (&ty::RegionTraitStore(..), &ty::RegionTraitStore(..)) =>
                    cenv.onceness,
                (&ty::UniqTraitStore, _) => ast::Once,
                (&ty::RegionTraitStore(..), _) => ast::Many,
            };
            (Some(sig), onceness, cenv.bounds.clone())
        }
        _ => {
            // Not an error! Means we're inferring the closure type
            let region = fcx.infcx().next_region_var(
                infer::AddrOfRegion(expr.span));
            let bounds = ty::region_existential_bound(region);
            let onceness = ast::Many;
            (None, onceness, bounds)
        }
    };

    // construct the function type
    let fn_ty = astconv::ty_of_closure(fcx,
                                       ast::Unsafety::Normal,
                                       expected_onceness,
                                       expected_bounds,
                                       store,
                                       decl,
                                       abi::Rust,
                                       expected_sig);
    let fn_sig = fn_ty.sig.clone();
    let fty = panic!("stub");
    debug!("check_expr_fn fty={}", fcx.infcx().ty_to_string(fty));

    fcx.write_ty(expr.id, fty);

    // If the closure is a stack closure and hasn't had some non-standard
    // style inferred for it, then check it under its parent's style.
    // Otherwise, use its own
    let (inherited_style, inherited_style_id) = match store {
        ty::RegionTraitStore(..) => (fcx.ps.borrow().unsafety,
                                     fcx.ps.borrow().def),
        ty::UniqTraitStore => (ast::Unsafety::Normal, expr.id)
    };

    let fn_sig =
        ty::liberate_late_bound_regions(tcx, CodeExtent::from_node_id(body.id), &fn_sig);

    check_fn(fcx.ccx,
             inherited_style,
             inherited_style_id,
             &fn_sig,
             &*decl,
             expr.id,
             &*body,
             fcx.inh);
}
<commit_msg>typeck: there are only unboxed closures now<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.

//! Code for type-checking closure expressions.

use super::{check_fn, Expectation, FnCtxt};

use astconv;
use middle::infer;
use middle::region::CodeExtent;
use middle::subst;
use middle::ty::{self, ToPolyTraitRef, Ty};
use rscope::RegionScope;
use syntax::abi;
use syntax::ast;
use syntax::ast::CaptureClause::*;
use syntax::ast_util;
use util::ppaux::Repr;

pub fn check_expr_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
                                   expr: &ast::Expr,
                                   capture: ast::CaptureClause,
                                   opt_kind: Option<ast::UnboxedClosureKind>,
                                   decl: &ast::FnDecl,
                                   body: &ast::Block,
                                   expected: Expectation<'tcx>) {
    debug!("check_expr_closure(expr={},expected={})",
           expr.repr(fcx.tcx()),
           expected.repr(fcx.tcx()));

    let expected_sig_and_kind = expected.map_to_option(fcx, |ty| {
        deduce_unboxed_closure_expectations_from_expected_type(fcx, ty)
    });

    match opt_kind {
        None => {
            // If users didn't specify what sort of closure they want,
            // examine the expected type. For now, if we see explicit
            // evidence than an unboxed closure is desired, we'll use
            // that, otherwise we'll fall back to boxed closures.
            match expected_sig_and_kind {
                None => { // don't have information about the kind, request explicit annotation
                    // HACK We still need to typeck the body, so assume `FnMut` kind just for that
                    let kind = ty::FnMutUnboxedClosureKind;

                    check_unboxed_closure(fcx, expr, kind, decl, body, None);

                    fcx.ccx.tcx.sess.span_err(
                        expr.span,
                        "Can't infer the \"kind\" of the closure, explicitly annotate it. e.g. \
                        `|&:| {}`");
                },
                Some((sig, kind)) => {
                    check_unboxed_closure(fcx, expr, kind, decl, body, Some(sig));
                }
            }
        }

        Some(kind) => {
            let kind = match kind {
                ast::FnUnboxedClosureKind => ty::FnUnboxedClosureKind,
                ast::FnMutUnboxedClosureKind => ty::FnMutUnboxedClosureKind,
                ast::FnOnceUnboxedClosureKind => ty::FnOnceUnboxedClosureKind,
            };

            let expected_sig = expected_sig_and_kind.map(|t| t.0);
            check_unboxed_closure(fcx, expr, kind, decl, body, expected_sig);
        }
    }
}

fn check_unboxed_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
                                  expr: &ast::Expr,
                                  kind: ty::UnboxedClosureKind,
                                  decl: &ast::FnDecl,
                                  body: &ast::Block,
                                  expected_sig: Option<ty::FnSig<'tcx>>) {
    let expr_def_id = ast_util::local_def(expr.id);

    debug!("check_unboxed_closure kind={} expected_sig={}",
           kind,
           expected_sig.repr(fcx.tcx()));

    let mut fn_ty = astconv::ty_of_closure(
        fcx,
        ast::Unsafety::Normal,
        ast::Many,

        // The `RegionTraitStore` and region_existential_bounds
        // are lies, but we ignore them so it doesn't matter.
        //
        // FIXME(pcwalton): Refactor this API.
        ty::region_existential_bound(ty::ReStatic),
        ty::RegionTraitStore(ty::ReStatic, ast::MutImmutable),

        decl,
        abi::RustCall,
        expected_sig);

    let region = match fcx.anon_regions(expr.span, 1) {
        Err(_) => {
            fcx.ccx.tcx.sess.span_bug(expr.span,
                                      "can't make anon regions here?!")
        }
        Ok(regions) => regions[0],
    };

    let closure_type = ty::mk_unboxed_closure(fcx.ccx.tcx,
                                              expr_def_id,
                                              fcx.ccx.tcx.mk_region(region),
                                              fcx.ccx.tcx.mk_substs(
                                                  fcx.inh.param_env.free_substs.clone()));

    fcx.write_ty(expr.id, closure_type);

    let fn_sig =
        ty::liberate_late_bound_regions(fcx.tcx(), CodeExtent::from_node_id(body.id), &fn_ty.sig);

    check_fn(fcx.ccx,
             ast::Unsafety::Normal,
             expr.id,
             &fn_sig,
             decl,
             expr.id,
             &*body,
             fcx.inh);

    // Tuple up the arguments and insert the resulting function type into
    // the `unboxed_closures` table.
    fn_ty.sig.0.inputs = vec![ty::mk_tup(fcx.tcx(), fn_ty.sig.0.inputs)];

    debug!("unboxed_closure for {} --> sig={} kind={}",
           expr_def_id.repr(fcx.tcx()),
           fn_ty.sig.repr(fcx.tcx()),
           kind);

    let unboxed_closure = ty::UnboxedClosure {
        closure_type: fn_ty,
        kind: kind,
    };

    fcx.inh
        .unboxed_closures
        .borrow_mut()
        .insert(expr_def_id, unboxed_closure);
}

fn deduce_unboxed_closure_expectations_from_expected_type<'a,'tcx>(
    fcx: &FnCtxt<'a,'tcx>,
    expected_ty: Ty<'tcx>)
    -> Option<(ty::FnSig<'tcx>,ty::UnboxedClosureKind)>
{
    match expected_ty.sty {
        ty::ty_trait(ref object_type) => {
            let trait_ref =
                object_type.principal_trait_ref_with_self_ty(fcx.tcx(),
                                                             fcx.tcx().types.err);
            deduce_unboxed_closure_expectations_from_trait_ref(fcx, &trait_ref)
        }
        ty::ty_infer(ty::TyVar(vid)) => {
            deduce_unboxed_closure_expectations_from_obligations(fcx, vid)
        }
        _ => {
            None
        }
    }
}

fn deduce_unboxed_closure_expectations_from_trait_ref<'a,'tcx>(
    fcx: &FnCtxt<'a,'tcx>,
    trait_ref: &ty::PolyTraitRef<'tcx>)
    -> Option<(ty::FnSig<'tcx>, ty::UnboxedClosureKind)>
{
    let tcx = fcx.tcx();

    debug!("deduce_unboxed_closure_expectations_from_object_type({})",
           trait_ref.repr(tcx));

    let kind = match tcx.lang_items.fn_trait_kind(trait_ref.def_id()) {
        Some(k) => k,
        None => { return None; }
    };

    debug!("found object type {}", kind);

    let arg_param_ty = *trait_ref.substs().types.get(subst::TypeSpace, 0);
    let arg_param_ty = fcx.infcx().resolve_type_vars_if_possible(&arg_param_ty);
    debug!("arg_param_ty {}", arg_param_ty.repr(tcx));

    let input_tys = match arg_param_ty.sty {
        ty::ty_tup(ref tys) => { (*tys).clone() }
        _ => { return None; }
    };
    debug!("input_tys {}", input_tys.repr(tcx));

    let ret_param_ty = *trait_ref.substs().types.get(subst::TypeSpace, 1);
    let ret_param_ty = fcx.infcx().resolve_type_vars_if_possible(&ret_param_ty);
    debug!("ret_param_ty {}", ret_param_ty.repr(tcx));

    let fn_sig = ty::FnSig {
        inputs: input_tys,
        output: ty::FnConverging(ret_param_ty),
        variadic: false
    };
    debug!("fn_sig {}", fn_sig.repr(tcx));

    return Some((fn_sig, kind));
}

fn deduce_unboxed_closure_expectations_from_obligations<'a,'tcx>(
    fcx: &FnCtxt<'a,'tcx>,
    expected_vid: ty::TyVid)
    -> Option<(ty::FnSig<'tcx>, ty::UnboxedClosureKind)>
{
    // Here `expected_ty` is known to be a type inference variable.
    for obligation in fcx.inh.fulfillment_cx.borrow().pending_obligations().iter() {
        match obligation.predicate {
            ty::Predicate::Trait(ref trait_predicate) => {
                let trait_ref = trait_predicate.to_poly_trait_ref();
                let self_ty = fcx.infcx().shallow_resolve(trait_ref.self_ty());
                match self_ty.sty {
                    ty::ty_infer(ty::TyVar(v)) if expected_vid == v => { }
                    _ => { continue; }
                }

                match deduce_unboxed_closure_expectations_from_trait_ref(fcx, &trait_ref) {
                    Some(e) => { return Some(e); }
                    None => { }
                }
            }
            _ => { }
        }
    }

    None
}
<|endoftext|>


<commit_before><commit_msg>Regression test for #15034<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.

pub struct Lexer<'a> {
    input: &'a str,
}

impl<'a> Lexer<'a> {
    pub fn new(input: &'a str) -> Lexer<'a> {
        Lexer { input: input }
    }
}

struct Parser<'a> {
    lexer: &'a mut Lexer<'a>,
}

impl<'a> Parser<'a> {
    pub fn new(lexer: &'a mut Lexer) -> Parser<'a> {
        Parser { lexer: lexer }
        //~^ ERROR cannot infer an appropriate lifetime for lifetime parameter
    }
}

fn main() {}
<|endoftext|>


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

// Test that regionck suggestions in a provided method of a trait
// don't ICE

trait Foo<'a> {
    fn foo(&'a self);
    fn bar(&self) {
        self.foo();
        //~^ ERROR mismatched types: expected `&'a Self`, found `&Self` (lifetime mismatch)
    }
}

fn main() {}
<|endoftext|>


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

fn main() {
    static foo: Fn() -> u32 = || -> u32 {
        //~^ ERROR: mismatched types:
        //~| expected `core::ops::Fn() -> u32`,
        //~| found closure
        //~| (expected trait core::ops::Fn,
        //~| found closure)
        0
    };
}
<|endoftext|>


<commit_before><commit_msg>[No-auto] bin/core/git: Fix Clippy warnings<commit_after><|endoftext|>


<commit_before><commit_msg>Fix error handling for new API<commit_after><|endoftext|>


<commit_before><commit_msg>Add functionality to include store path (defaults to no)<commit_after><|endoftext|>


<commit_before><commit_msg>libcore: Add missing unit.rs<commit_after>/**
 * Functions for the unit type.
 */

use cmp::{Eq, Ord};

impl () : Eq {
    pure fn eq(&&_other: ()) -> bool { true }
}

impl () : Ord {
    pure fn lt(&&_other: ()) -> bool { false }
    pure fn le(&&_other: ()) -> bool { true }
    pure fn ge(&&_other: ()) -> bool { true }
    pure fn gt(&&_other: ()) -> bool { false }
}

<|endoftext|>


<commit_before><commit_msg>Make `use` declarations consistent<commit_after><|endoftext|>


<commit_before><commit_msg>Add day 25 part 1 solution<commit_after>// advent25.rs
// copy protection code

#[macro_use] extern crate scan_fmt;

use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).ok().expect("Failed to read line");
    let (row, col) = scan_fmt!(
        &input,
        "To continue, please consult the code grid in the manual.  Enter the code at row {}, column {}.",
        u32, u32);

    println!("code = {}", get_code(col.unwrap(), row.unwrap()));
}

fn get_triangular(x: u32) -> u32 {
    x * (x + 1) / 2
}

fn get_ordinal(x: u32, y: u32) -> u32 {
    x + get_triangular(x + y - 2)
}

fn get_code(x: u32, y: u32) -> u64 {
    const START_VAL: u64 = 20151125;
    const MULT_VAL: u64 = 252533;
    const MOD_VAL: u64 = 33554393;

    let mut val = START_VAL;

    for _ in 1..get_ordinal(x, y) {
        val = val * MULT_VAL % MOD_VAL;
    }

    val
}

#[test]
fn test_get_ordinal() {
    assert_eq!(1, get_ordinal(1, 1));
    assert_eq!(2, get_ordinal(1, 2));
    assert_eq!(3, get_ordinal(2, 1));
    assert_eq!(4, get_ordinal(1, 3));
    assert_eq!(5, get_ordinal(2, 2));
    assert_eq!(18, get_ordinal(3, 4));
    assert_eq!(21, get_ordinal(6, 1));
}

#[test]
fn test_get_code() {
    assert_eq!(20151125, get_code(1, 1));
    assert_eq!(77061, get_code(1, 5));
    assert_eq!(1534922, get_code(5, 6));
}

<|endoftext|>


<commit_before><commit_msg>fail to build if neither tls feature is enabled<commit_after>fn main() {
    let found_tls = cfg!(feature = "with_rustls") || cfg!(feature = "with_native_tls");
    if !found_tls {
        panic!(
            "slack: at least one of 'with_native_tls' or 'with_rustls' features must be enabled"
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>Add pin argument to Atomic::swap_box<commit_after><|endoftext|>


<commit_before><commit_msg>Missing file<commit_after>use time::Timespec;

pub const DEFAULT_CREATE_TIME: Timespec = Timespec {
    sec: 1381237736,
    nsec: 0,
};

pub const DEFAULT_TTL: Timespec = Timespec { sec: 1, nsec: 0 };
<|endoftext|>


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

//! # The Rust core allocation and collections library
//!
//! This library provides smart pointers and collections for managing
//! heap-allocated values.
//!
//! This library, like libcore, is not intended for general usage, but rather as
//! a building block of other libraries. The types and interfaces in this
//! library are re-exported through the [standard library](../std/index.html),
//! and should not be used through this library.
//!
//! ## Boxed values
//!
//! The [`Box`](boxed/index.html) type is a smart pointer type. There can
//! only be one owner of a `Box`, and the owner can decide to mutate the
//! contents, which live on the heap.
//!
//! This type can be sent among threads efficiently as the size of a `Box` value
//! is the same as that of a pointer. Tree-like data structures are often built
//! with boxes because each node often has only one owner, the parent.
//!
//! ## Reference counted pointers
//!
//! The [`Rc`](rc/index.html) type is a non-threadsafe reference-counted pointer
//! type intended for sharing memory within a thread. An `Rc` pointer wraps a
//! type, `T`, and only allows access to `&T`, a shared reference.
//!
//! This type is useful when inherited mutability (such as using `Box`) is too
//! constraining for an application, and is often paired with the `Cell` or
//! `RefCell` types in order to allow mutation.
//!
//! ## Atomically reference counted pointers
//!
//! The [`Arc`](arc/index.html) type is the threadsafe equivalent of the `Rc`
//! type. It provides all the same functionality of `Rc`, except it requires
//! that the contained type `T` is shareable. Additionally, `Arc<T>` is itself
//! sendable while `Rc<T>` is not.
//!
//! This type allows for shared access to the contained data, and is often
//! paired with synchronization primitives such as mutexes to allow mutation of
//! shared resources.
//!
//! ## Collections
//!
//! Implementations of the most common general purpose data structures are
//! defined in this library. They are re-exported through the
//! [standard collections library](../std/collections/index.html).
//!
//! ## Heap interfaces
//!
//! The [`alloc`](alloc/index.html) module defines the low-level interface to the
//! default global allocator. It is not compatible with the libc allocator API.

#![allow(unused_attributes)]
#![unstable(feature = "alloc",
            reason = "this library is unlikely to be stabilized in its current \
                      form or name",
            issue = "27783")]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/",
       issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
       test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))]
#![no_std]
#![needs_allocator]
#![deny(missing_debug_implementations)]

#![cfg_attr(test, allow(deprecated))] // rand
#![cfg_attr(not(test), feature(exact_size_is_empty))]
#![cfg_attr(not(test), feature(generator_trait))]
#![cfg_attr(test, feature(rand, test))]
#![feature(allocator_api)]
#![feature(allow_internal_unstable)]
#![feature(arbitrary_self_types)]
#![feature(ascii_ctype)]
#![feature(box_into_raw_non_null)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(cfg_target_has_atomic)]
#![feature(coerce_unsized)]
#![feature(collections_range)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(dropck_eyepatch)]
#![feature(exact_size_is_empty)]
#![feature(fmt_internals)]
#![feature(from_ref)]
#![feature(fundamental)]
#![feature(futures_api)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(needs_allocator)]
#![feature(optin_builtin_traits)]
#![feature(pattern)]
#![feature(pin)]
#![feature(ptr_internals)]
#![feature(ptr_offset_from)]
#![cfg_attr(stage0, feature(repr_transparent))]
#![feature(rustc_attrs)]
#![feature(specialization)]
#![feature(split_ascii_whitespace)]
#![feature(staged_api)]
#![feature(str_internals)]
#![feature(trusted_len)]
#![feature(try_reserve)]
#![feature(unboxed_closures)]
#![feature(unicode_internals)]
#![feature(unsize)]
#![feature(allocator_internals)]
#![feature(on_unimplemented)]
#![feature(exact_chunks)]
#![feature(pointer_methods)]
#![feature(inclusive_range_methods)]
#![feature(rustc_const_unstable)]
#![feature(const_vec_new)]

#![cfg_attr(not(test), feature(fn_traits, i128))]
#![cfg_attr(test, feature(test))]

// Allow testing this library

#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(test)]
extern crate test;
#[cfg(test)]
extern crate rand;

// Module with internal macros used by other modules (needs to be included before other modules).
#[macro_use]
mod macros;

#[rustc_deprecated(since = "1.27.0", reason = "use the heap module in core, alloc, or std instead")]
#[unstable(feature = "allocator_api", issue = "32838")]
/// Use the `alloc` module instead.
pub mod allocator {
    pub use alloc::*;
}

// Heaps provided for low-level allocation strategies

pub mod alloc;

#[unstable(feature = "futures_api",
           reason = "futures in libcore are unstable",
           issue = "50547")]
pub mod task;
// Primitive types using the heaps above

// Need to conditionally define the mod from `boxed.rs` to avoid
// duplicating the lang-items when building in test cfg; but also need
// to allow code to have `use boxed::Box;` declarations.
#[cfg(not(test))]
pub mod boxed;
#[cfg(test)]
mod boxed {
    pub use std::boxed::Box;
}
#[cfg(test)]
mod boxed_test;
#[cfg(target_has_atomic = "ptr")]
pub mod arc;
pub mod rc;
pub mod raw_vec;

// collections modules
pub mod binary_heap;
mod btree;
pub mod borrow;
pub mod fmt;
pub mod linked_list;
pub mod slice;
pub mod str;
pub mod string;
pub mod vec;
pub mod vec_deque;

#[stable(feature = "rust1", since = "1.0.0")]
pub mod btree_map {
    //! A map based on a B-Tree.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub use btree::map::*;
}

#[stable(feature = "rust1", since = "1.0.0")]
pub mod btree_set {
    //! A set based on a B-Tree.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub use btree::set::*;
}

#[cfg(not(test))]
mod std {
    pub use core::ops;      // RangeFull
}

/// An intermediate trait for specialization of `Extend`.
#[doc(hidden)]
trait SpecExtend<I: IntoIterator> {
    /// Extends `self` with the contents of the given iterator.
    fn spec_extend(&mut self, iter: I);
}

#[doc(no_inline)]
pub use binary_heap::BinaryHeap;
#[doc(no_inline)]
pub use btree_map::BTreeMap;
#[doc(no_inline)]
pub use btree_set::BTreeSet;
#[doc(no_inline)]
pub use linked_list::LinkedList;
#[doc(no_inline)]
pub use vec_deque::VecDeque;
#[doc(no_inline)]
pub use string::String;
#[doc(no_inline)]
pub use vec::Vec;
<commit_msg>Remove the unstable alloc::allocator module reexport, deprecated since 1.27<commit_after>// Copyright 2014-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.

//! # The Rust core allocation and collections library
//!
//! This library provides smart pointers and collections for managing
//! heap-allocated values.
//!
//! This library, like libcore, is not intended for general usage, but rather as
//! a building block of other libraries. The types and interfaces in this
//! library are re-exported through the [standard library](../std/index.html),
//! and should not be used through this library.
//!
//! ## Boxed values
//!
//! The [`Box`](boxed/index.html) type is a smart pointer type. There can
//! only be one owner of a `Box`, and the owner can decide to mutate the
//! contents, which live on the heap.
//!
//! This type can be sent among threads efficiently as the size of a `Box` value
//! is the same as that of a pointer. Tree-like data structures are often built
//! with boxes because each node often has only one owner, the parent.
//!
//! ## Reference counted pointers
//!
//! The [`Rc`](rc/index.html) type is a non-threadsafe reference-counted pointer
//! type intended for sharing memory within a thread. An `Rc` pointer wraps a
//! type, `T`, and only allows access to `&T`, a shared reference.
//!
//! This type is useful when inherited mutability (such as using `Box`) is too
//! constraining for an application, and is often paired with the `Cell` or
//! `RefCell` types in order to allow mutation.
//!
//! ## Atomically reference counted pointers
//!
//! The [`Arc`](arc/index.html) type is the threadsafe equivalent of the `Rc`
//! type. It provides all the same functionality of `Rc`, except it requires
//! that the contained type `T` is shareable. Additionally, `Arc<T>` is itself
//! sendable while `Rc<T>` is not.
//!
//! This type allows for shared access to the contained data, and is often
//! paired with synchronization primitives such as mutexes to allow mutation of
//! shared resources.
//!
//! ## Collections
//!
//! Implementations of the most common general purpose data structures are
//! defined in this library. They are re-exported through the
//! [standard collections library](../std/collections/index.html).
//!
//! ## Heap interfaces
//!
//! The [`alloc`](alloc/index.html) module defines the low-level interface to the
//! default global allocator. It is not compatible with the libc allocator API.

#![allow(unused_attributes)]
#![unstable(feature = "alloc",
            reason = "this library is unlikely to be stabilized in its current \
                      form or name",
            issue = "27783")]
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
       html_root_url = "https://doc.rust-lang.org/nightly/",
       issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
       test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))]
#![no_std]
#![needs_allocator]
#![deny(missing_debug_implementations)]

#![cfg_attr(test, allow(deprecated))] // rand
#![cfg_attr(not(test), feature(exact_size_is_empty))]
#![cfg_attr(not(test), feature(generator_trait))]
#![cfg_attr(test, feature(rand, test))]
#![feature(allocator_api)]
#![feature(allow_internal_unstable)]
#![feature(arbitrary_self_types)]
#![feature(ascii_ctype)]
#![feature(box_into_raw_non_null)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(cfg_target_has_atomic)]
#![feature(coerce_unsized)]
#![feature(collections_range)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(dropck_eyepatch)]
#![feature(exact_size_is_empty)]
#![feature(fmt_internals)]
#![feature(from_ref)]
#![feature(fundamental)]
#![feature(futures_api)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(needs_allocator)]
#![feature(optin_builtin_traits)]
#![feature(pattern)]
#![feature(pin)]
#![feature(ptr_internals)]
#![feature(ptr_offset_from)]
#![cfg_attr(stage0, feature(repr_transparent))]
#![feature(rustc_attrs)]
#![feature(specialization)]
#![feature(split_ascii_whitespace)]
#![feature(staged_api)]
#![feature(str_internals)]
#![feature(trusted_len)]
#![feature(try_reserve)]
#![feature(unboxed_closures)]
#![feature(unicode_internals)]
#![feature(unsize)]
#![feature(allocator_internals)]
#![feature(on_unimplemented)]
#![feature(exact_chunks)]
#![feature(pointer_methods)]
#![feature(inclusive_range_methods)]
#![feature(rustc_const_unstable)]
#![feature(const_vec_new)]

#![cfg_attr(not(test), feature(fn_traits, i128))]
#![cfg_attr(test, feature(test))]

// Allow testing this library

#[cfg(test)]
#[macro_use]
extern crate std;
#[cfg(test)]
extern crate test;
#[cfg(test)]
extern crate rand;

// Module with internal macros used by other modules (needs to be included before other modules).
#[macro_use]
mod macros;

// Heaps provided for low-level allocation strategies

pub mod alloc;

#[unstable(feature = "futures_api",
           reason = "futures in libcore are unstable",
           issue = "50547")]
pub mod task;
// Primitive types using the heaps above

// Need to conditionally define the mod from `boxed.rs` to avoid
// duplicating the lang-items when building in test cfg; but also need
// to allow code to have `use boxed::Box;` declarations.
#[cfg(not(test))]
pub mod boxed;
#[cfg(test)]
mod boxed {
    pub use std::boxed::Box;
}
#[cfg(test)]
mod boxed_test;
#[cfg(target_has_atomic = "ptr")]
pub mod arc;
pub mod rc;
pub mod raw_vec;

// collections modules
pub mod binary_heap;
mod btree;
pub mod borrow;
pub mod fmt;
pub mod linked_list;
pub mod slice;
pub mod str;
pub mod string;
pub mod vec;
pub mod vec_deque;

#[stable(feature = "rust1", since = "1.0.0")]
pub mod btree_map {
    //! A map based on a B-Tree.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub use btree::map::*;
}

#[stable(feature = "rust1", since = "1.0.0")]
pub mod btree_set {
    //! A set based on a B-Tree.
    #[stable(feature = "rust1", since = "1.0.0")]
    pub use btree::set::*;
}

#[cfg(not(test))]
mod std {
    pub use core::ops;      // RangeFull
}

/// An intermediate trait for specialization of `Extend`.
#[doc(hidden)]
trait SpecExtend<I: IntoIterator> {
    /// Extends `self` with the contents of the given iterator.
    fn spec_extend(&mut self, iter: I);
}

#[doc(no_inline)]
pub use binary_heap::BinaryHeap;
#[doc(no_inline)]
pub use btree_map::BTreeMap;
#[doc(no_inline)]
pub use btree_set::BTreeSet;
#[doc(no_inline)]
pub use linked_list::LinkedList;
#[doc(no_inline)]
pub use vec_deque::VecDeque;
#[doc(no_inline)]
pub use string::String;
#[doc(no_inline)]
pub use vec::Vec;
<|endoftext|>


<commit_before><commit_msg>Initial commit<commit_after>//! This module implements middleware to serve crates and readmes
//! from the `local_uploads/` directory. This is only used in
//! development environments.
use std::error::Error;

use conduit::{Request, Response, Handler};
use conduit_static::Static;
use conduit_middleware::AroundMiddleware;

// Can't derive debug because of Handler and Static.
#[allow(missing_debug_implementations)]
pub struct Middleware {
    handler: Option<Box<Handler>>,
    local_uploads: Static,
}

impl Default for Middleware {
    fn default() -> Middleware {
        Middleware {
            handler: None,
            local_uploads: Static::new("local_uploads"),
        }
    }
}

impl AroundMiddleware for Middleware {
    fn with_handler(&mut self, handler: Box<Handler>) {
        self.handler = Some(handler);
    }
}

impl Handler for Middleware {
    fn call(&self, req: &mut Request) -> Result<Response, Box<Error + Send>> {
        match self.local_uploads.call(req) {
            Ok(ref resp) if resp.status.0 == 404 => {}
            ret => return ret,
        }

        self.handler.as_ref().unwrap().call(req)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add the glorious `__diesel_parse_struct_body` macro<commit_after>// from <https://github.com/diesel-rs/diesel/blob/8bebe479cb05388220719b8b385fffb727d40588/diesel/src/macros/parse.rs>
// Copyright (C) 2016 Sean Griffin, licensed under MIT/Apache-2.0

/// Parses the body of a struct field, extracting the relevant information the
/// relevant information that we care about. This macro can handle either named
/// structs or tuple structs. It does not handle unit structs.
///
/// When calling this macro from the outside, it takes three arguments. The
/// first is a single token tree of passthrough information, which will be given
/// to the callback unchanged. The second is the name of the macro to call with
/// the parsed field. The third is the *entire* body of the struct, including
/// either the curly braces or parens.
///
/// If a tuple struct is given, all fields *must* be annotated with
/// `#[column_name(name)]`. Due to the nature of non-procedural macros, we
/// cannot give a helpful error message in this case.
///
/// The callback will be called with the given headers, and a list of fields
/// in record form with the following properties:
///
/// - `field_name` is the name of the field on the struct. This will not be
///   present if the struct is a tuple struct.
/// - `column_name` is the column the field corresponds to. This will either be
///   the value of a `#[column_name]` attribute on the field, or the field name
///   if not present.
/// - `field_type` is the type of the field on the struct.
/// - `field_kind` Will be either `regular` or `option` depending on whether
///   the type of the field was an option or not.
///
/// # Example
///
/// If this macro is called with:
///
/// ```ignore
/// __diesel_parse_struct_body {
///     (my original arguments),
///     callback = my_macro,
///     body = {
///         pub foo: i32,
///         bar: Option<i32>,
///         #[column_name(other)]
///         baz: String,
///     }
/// }
/// ```
///
/// Then the resulting expansion will be:
///
/// ```ignore
/// my_macro! {
///     (my original arguments),
///     fields = [{
///         field_name: foo,
///         column_name: foo,
///         field_ty: i32,
///         field_kind: regular,
///     }, {
///         field_name: bar,
///         column_name: bar,
///         field_ty: Option<i32>,
///         field_kind: option,
///     }, {
///         field_name: baz,
///         column_name: other,
///         field_ty: String,
///         field_kind: regular,
///     }],
/// }
#[macro_export]
#[doc(hidden)]
macro_rules! __diesel_parse_struct_body {
    // Entry point for named structs
    (
        $headers:tt,
        callback = $callback:ident,
        body = {$($body:tt)*},
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = [],
            body = ($($body)*,),
        }
    };

    // Entry point for tuple structs
    (
        $headers:tt,
        callback = $callback:ident,
        body = ($($body:tt)*),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = [],
            body = ($($body)*,),
        }
    };

    // FIXME: Replace with `vis` specifier if relevant RFC lands
    // First, strip `pub` if it exists
    (
        $headers:tt,
        callback = $callback:ident,
        fields = $fields:tt,
        body = (
            $(#$meta:tt)*
            pub $($tail:tt)*),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = $fields,
            body = ($(#$meta)* $($tail)*),
        }
    };

    // Since we blindly add a comma to the end of the body, we might have a
    // double trailing comma.  If it's the only token left, that's what
    // happened. Strip it.
    (
        $headers:tt,
        callback = $callback:ident,
        fields = $fields:tt,
        body = (,),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = $fields,
            body = (),
        }
    };

    // When we find #[column_name] followed by an option type, handle the
    // tuple struct field
    (
        $headers:tt,
        callback = $callback:ident,
        fields = [$($fields:tt)*],
        body = (
            #[column_name($column_name:ident)]
            Option<$field_ty:ty> , $($tail:tt)*),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = [$($fields)* {
                column_name: $column_name,
                field_ty: Option<$field_ty>,
                field_kind: option,
            }],
            body = ($($tail)*),
        }
    };

    // When we find #[column_name] followed by a type, handle the tuple struct
    // field
    (
        $headers:tt,
        callback = $callback:ident,
        fields = [$($fields:tt)*],
        body = (
            #[column_name($column_name:ident)]
            $field_ty:ty , $($tail:tt)*),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = [$($fields)* {
                column_name: $column_name,
                field_ty: $field_ty,
                field_kind: regular,
            }],
            body = ($($tail)*),
        }
    };

    // When we find #[column_name] followed by a named field, handle it
    (
        $headers:tt,
        callback = $callback:ident,
        fields = $fields:tt,
        body = (
            #[column_name($column_name:ident)]
            $field_name:ident : $($tail:tt)*),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = $fields,
            body = ($field_name as $column_name : $($tail)*),
        }
    };

    // If we got here and didn't have a #[column_name] attr,
    // then the column name is the same as the field name
    (
        $headers:tt,
        callback = $callback:ident,
        fields = $fields:tt,
        body = ($field_name:ident : $($tail:tt)*),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = $fields,
            body = ($field_name as $field_name : $($tail)*),
        }
    };

    // At this point we know the column and field name, handle when the type is option
    (
        $headers:tt,
        callback = $callback:ident,
        fields = [$($fields:tt)*],
        body = ($field_name:ident as $column_name:ident : Option<$field_ty:ty>, $($tail:tt)*),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = [$($fields)* {
                field_name: $field_name,
                column_name: $column_name,
                field_ty: Option<$field_ty>,
                field_kind: option,
            }],
            body = ($($tail)*),
        }
    };

    // Handle any type other than option
    (
        $headers:tt,
        callback = $callback:ident,
        fields = [$($fields:tt)*],
        body = ($field_name:ident as $column_name:ident : $field_ty:ty, $($tail:tt)*),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = [$($fields)* {
                field_name: $field_name,
                column_name: $column_name,
                field_ty: $field_ty,
                field_kind: regular,
            }],
            body = ($($tail)*),
        }
    };

    // When we reach a type with no column name annotation, handle the unnamed
    // tuple struct field. Since we require that either all fields are annotated
    // or none are, we could actually handle the whole body in one pass for this
    // case. However, anything using tuple structs without the column name
    // likely needs some ident per field to be useable and by handling each
    // field separately this way, the `field_kind` acts as a fresh ident each
    // time.
    (
        $headers:tt,
        callback = $callback:ident,
        fields = [$($fields:tt)*],
        body = ($field_ty:ty , $($tail:tt)*),
    ) => {
        __diesel_parse_struct_body! {
            $headers,
            callback = $callback,
            fields = [$($fields)* {
                field_ty: $field_ty,
                field_kind: bare,
            }],
            body = ($($tail)*),
        }
    };

    // At this point we've parsed the entire body. We create the pattern
    // for destructuring, and pass all the information back to the main macro
    // to generate the final impl
    (
        $headers:tt,
        callback = $callback:ident,
        fields = $fields:tt,
        body = (),
    ) => {
        $callback! {
            $headers,
            fields = $fields,
        }
    };
}

/// Hack to tell the compiler that something is in fact an item. This is needed
/// when `tt` fragments are used in specific positions.
#[doc(hidden)]
#[macro_export]
macro_rules!  __diesel_parse_as_item {
    ($i:item) => { $i }
}<|endoftext|>


<commit_before><commit_msg>refactor(tmux/session.rs): Remove unused import<commit_after><|endoftext|>


<commit_before><commit_msg>Saved list implementation<commit_after>use List::{Cons, Nil};
use std::rc::Rc;

enum List {
    Cons(i32, Rc<List>),
    Nil,
}

fn main () {
    let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
    let b = Cons(3, Rc::clone(&a));
    let c = Cons(4, Rc::clone(&a));

}

<|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

error_chain! {
    types {
        ContactError, ContactErrorKind, ResultExt, Result;
    }

    links {
        StoreError(::libimagstore::error::StoreError, ::libimagstore::error::StoreErrorKind);
    }

    foreign_links {
        Io(::std::io::Error);
        TomlQueryError(::toml_query::error::Error);
    }

    errors {

    }
}

<commit_msg>Add more error links<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

error_chain! {
    types {
        ContactError, ContactErrorKind, ResultExt, Result;
    }

    links {
        StoreError(::libimagstore::error::StoreError, ::libimagstore::error::StoreErrorKind);
        RefError(::libimagentryref::error::RefError, ::libimagentryref::error::RefErrorKind);
    }

    foreign_links {
        Io(::std::io::Error);
        TomlQueryError(::toml_query::error::Error);
        VObjectError(::vobject::ParseError);
    }

    errors {

    }
}

<|endoftext|>


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

// This test case tests the incremental compilation hash (ICH) implementation
// for struct constructor expressions.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

struct RegularStruct {
    x: i32,
    y: i64,
    z: i16,
}

// Change field value (regular struct) -----------------------------------------
#[cfg(cfail1)]
fn change_field_value_regular_struct() -> RegularStruct {
    RegularStruct {
        x: 0,
        y: 1,
        z: 2,
    }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn change_field_value_regular_struct() -> RegularStruct {
    RegularStruct {
        x: 0,
        y: 2,
        z: 2,
    }
}

// Change field order (regular struct) -----------------------------------------
#[cfg(cfail1)]
fn change_field_order_regular_struct() -> RegularStruct {
    RegularStruct {
        x: 3,
        y: 4,
        z: 5,
    }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn change_field_order_regular_struct() -> RegularStruct {
    RegularStruct {
        y: 4,
        x: 3,
        z: 5,
    }
}

// Add field (regular struct) --------------------------------------------------
#[cfg(cfail1)]
fn add_field_regular_struct() -> RegularStruct {
    let struct1 = RegularStruct {
        x: 3,
        y: 4,
        z: 5,
    };

    RegularStruct {
        x: 7,
        .. struct1
    }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn add_field_regular_struct() -> RegularStruct {
    let struct1 = RegularStruct {
        x: 3,
        y: 4,
        z: 5,
    };

    RegularStruct {
        x: 7,
        y: 8,
        .. struct1
    }
}

// Change field label (regular struct) -----------------------------------------
#[cfg(cfail1)]
fn change_field_label_regular_struct() -> RegularStruct {
    let struct1 = RegularStruct {
        x: 3,
        y: 4,
        z: 5,
    };

    RegularStruct {
        x: 7,
        y: 9,
        .. struct1
    }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn change_field_label_regular_struct() -> RegularStruct {
    let struct1 = RegularStruct {
        x: 3,
        y: 4,
        z: 5,
    };

    RegularStruct {
        x: 7,
        z: 9,
        .. struct1
    }
}

struct RegularStruct2 {
    x: i8,
    y: i8,
    z: i8,
}

// Change constructor path (regular struct) ------------------------------------
#[cfg(cfail1)]
fn change_constructor_path_regular_struct() {
    let _ = RegularStruct {
        x: 0,
        y: 1,
        z: 2,
    };
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn change_constructor_path_regular_struct() {
    let _ = RegularStruct2 {
        x: 0,
        y: 1,
        z: 2,
    };
}

// Change constructor path indirectly (regular struct) -------------------------
mod change_constructor_path_indirectly_regular_struct {
    #[cfg(cfail1)]
    use super::RegularStruct as Struct;
    #[cfg(not(cfail1))]
    use super::RegularStruct2 as Struct;

    fn function() -> Struct {
        Struct {
            x: 0,
            y: 1,
            z: 2,
        }
    }
}

struct TupleStruct(i32, i64, i16);

// Change field value (tuple struct) -------------------------------------------
#[cfg(cfail1)]
fn change_field_value_tuple_struct() -> TupleStruct {
    TupleStruct(0, 1, 2)
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn change_field_value_tuple_struct() -> TupleStruct {
    TupleStruct(0, 1, 3)
}

struct TupleStruct2(u16, u16, u16);

// Change constructor path (tuple struct) --------------------------------------
#[cfg(cfail1)]
fn change_constructor_path_tuple_struct() {
    let _ = TupleStruct(0, 1, 2);
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn change_constructor_path_tuple_struct() {
    let _ = TupleStruct2(0, 1, 2);
}

// Change constructor path indirectly (tuple struct) ---------------------------
mod change_constructor_path_indirectly_tuple_struct {
    #[cfg(cfail1)]
    use super::TupleStruct as Struct;
    #[cfg(not(cfail1))]
    use super::TupleStruct2 as Struct;

    fn function() -> Struct {
        Struct(0, 1, 2)
    }
}
<|endoftext|>


<commit_before><commit_msg>Write test crate.<commit_after><|endoftext|>


<commit_before><commit_msg>List plugins example<commit_after><|endoftext|>


<commit_before><commit_msg>interpreter example<commit_after>extern crate parity_wasm;

use std::env::args;

use parity_wasm::ModuleInstanceInterface;

fn main() {
    let args: Vec<_> = args().collect();
    if args.len() != 2 {
        println!("Usage: {} <wasm file> <arg>", args[0]);
        println!("    wasm file should contain exported `_call` function with single I32 argument");
        return;
    }

    let program = parity_wasm::ProgramInstance::new().expect("Failed to load program");
    let module = parity_wasm::deserialize_file(&args[1]).expect("Failed to load module");
    let module = program.add_module("main", module).expect("Failed to initialize module");
    let argument: i32 = args[1].parse().expect("Integer argument required");
    println!("Result: {:?}", module.execute_export("_call", vec![parity_wasm::RuntimeValue::I32(argument)]));
}
<|endoftext|>


<commit_before><commit_msg>Add example for accessing disk partition<commit_after>extern crate fatfs;

use std::{cmp, fs, io};
use std::io::{prelude::*, SeekFrom, ErrorKind};
use fatfs::{FileSystem, FsOptions, BufStream};

trait ReadWriteSeek: Read + Write + Seek {}
impl<T> ReadWriteSeek for T where T: Read + Write + Seek {}

// File wrapper for accessing part of file
#[derive(Clone)]
pub(crate) struct Partition<T: ReadWriteSeek> {
    inner: T,
    start_offset: u64,
    current_offset: u64,
    size: u64,
}

impl <T: ReadWriteSeek> Partition<T> {
    pub(crate) fn new(mut inner: T, start_offset: u64, size: u64) -> io::Result<Self> {
        inner.seek(SeekFrom::Start(start_offset))?;
        Ok(Self {
            start_offset, size, inner,
            current_offset: 0,
        })
    }
}

impl <T: ReadWriteSeek> Read for Partition<T> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let max_read_size = cmp::min((self.size - self.current_offset) as usize, buf.len());
        let bytes_read = self.inner.read(&mut buf[..max_read_size])?;
        self.current_offset += bytes_read as u64;
        Ok(bytes_read)
    }
}

impl <T: ReadWriteSeek> Write for Partition<T> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let max_write_size = cmp::min((self.size - self.current_offset) as usize, buf.len());
        let bytes_written = self.inner.write(&buf[..max_write_size])?;
        self.current_offset += bytes_written as u64;
        Ok(bytes_written)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

impl <T: ReadWriteSeek> Seek for Partition<T> {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        let new_offset = match pos {
            SeekFrom::Current(x) => self.current_offset as i64 + x,
            SeekFrom::Start(x) => x as i64,
            SeekFrom::End(x) => self.size as i64 + x,
        };
        if new_offset < 0 || new_offset as u64 > self.size {
            Err(io::Error::new(ErrorKind::InvalidInput, "invalid seek"))
        } else {
            self.inner.seek(SeekFrom::Start(self.start_offset + new_offset as u64))?;
            self.current_offset = new_offset as u64;
            Ok(self.current_offset)
        }
    }
}

fn main() {
    // Open disk image
    let file = fs::File::open("resources/fat32.img").unwrap();
    // Provide sample partition localization. In real application it should be read from MBR/GPT.
    let first_lba = 0;
    let last_lba = 10000;
    // Create partition using provided start address and size in bytes
    let partition = Partition::<fs::File>::new(file, first_lba, last_lba - first_lba + 1).unwrap();
    // Create buffered stream to optimize file access
    let mut buf_rdr = BufStream::new(partition);
    // Finally initialize filesystem struct using provided partition
    let fs = FileSystem::new(&mut buf_rdr, FsOptions::new()).unwrap();
    // Read and display volume label
    println!("Volume Label: {}", fs.volume_label());
    // other operations
}
<|endoftext|>


<commit_before><commit_msg>Make helper type derive Debug<commit_after><|endoftext|>


<commit_before><commit_msg>context: Display<commit_after><|endoftext|>


<commit_before><commit_msg>Format block_data_transfer() to pass rustfmt<commit_after><|endoftext|>


<commit_before><commit_msg>implement fmt::Display<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests for secure/insecure cookies.<commit_after><|endoftext|>


<commit_before><commit_msg>vga: Print out kernel section flags in binary rather than hex.<commit_after><|endoftext|>


<commit_before><commit_msg>Minor clippy warning fix.<commit_after><|endoftext|>


<commit_before><commit_msg>(cleanup) Re-export Error.<commit_after><|endoftext|>


<commit_before><commit_msg>feat: add logger initialization<commit_after><|endoftext|>


<commit_before><commit_msg>Use partial insertion sort<commit_after><|endoftext|>


<commit_before><commit_msg>Minor style tweaks.<commit_after><|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1524<commit_after>// https://leetcode.com/problems/number-of-sub-arrays-with-odd-sum/
pub fn num_of_subarrays(arr: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!("{}", num_of_subarrays(vec![1, 3, 5])); // 4
    println!("{}", num_of_subarrays(vec![2, 4, 6])); // 0
    println!("{}", num_of_subarrays(vec![1, 2, 3, 4, 5, 6, 7])); // 16
}
<|endoftext|>


<commit_before><commit_msg>solved dyack path problem using catalan numbers<commit_after><|endoftext|>


<commit_before>// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Various helper macros.

mod pso;
mod structure;

#[macro_export]
macro_rules! gfx_format {
    ($name:ident : $surface:ident = $container:ident<$channel:ident>) => {
        impl $crate::format::Formatted for $name {
            type Surface = $crate::format::$surface;
            type Channel = $crate::format::$channel;
            type View = $crate::format::$container<
                <$crate::format::$channel as $crate::format::ChannelTyped>::ShaderType
                >;
        }
    }
}

/// Defines vertex, constant and pipeline formats in one block
#[macro_export]
macro_rules! gfx_defines {
    ($(#[$attr:meta])* vertex $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    }) => {
        gfx_vertex_struct_meta!($(#[$attr])* vertex_struct_meta $name {$($field:$ty = $e,)+});
    };

    ($(#[$attr:meta])* constant $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    }) => {
        gfx_constant_struct_meta!($(#[$attr])* constant_struct_meta $name {$($field:$ty = $e,)+});
    };

    (pipeline $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    }) => {
        gfx_pipeline!($name {$($field:$ty = $e,)+});
    };

    // The recursive case for vertex structs
    ($(#[$attr:meta])* vertex $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    } $($tail:tt)+) => {
        gfx_defines! {
            $(#[$attr])*
            vertex $name { $($field : $ty = $e,)+ }
        }
        gfx_defines!($($tail)+);
    };

    // The recursive case for constant structs
    ($(#[$attr:meta])* constant $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    } $($tail:tt)+) => {
        gfx_defines! {
            $(#[$attr])*
            constant $name { $($field : $ty = $e,)+ }
        }
        gfx_defines!($($tail)+);
    };

    // The recursive case for the other keywords
    ($keyword:ident $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    } $($tail:tt)+) => {
        gfx_defines! {
            $keyword $name { $($field : $ty = $e,)+ }
        }
        gfx_defines!($($tail)+);
    };
}
<commit_msg>Improved gfx_defines documentation<commit_after>// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Various helper macros.

mod pso;
mod structure;

#[macro_export]
macro_rules! gfx_format {
    ($name:ident : $surface:ident = $container:ident<$channel:ident>) => {
        impl $crate::format::Formatted for $name {
            type Surface = $crate::format::$surface;
            type Channel = $crate::format::$channel;
            type View = $crate::format::$container<
                <$crate::format::$channel as $crate::format::ChannelTyped>::ShaderType
                >;
        }
    }
}

/// Defines vertex, constant and pipeline formats in one block.
///
/// # Example
///
/// ```{.rust}
/// #[macro_use]
/// extern crate gfx;
///
/// gfx_defines! {
///     vertex Vertex {
///         pos: [f32; 4] = "a_Pos",
///         tex_coord: [f32; 2] = "a_TexCoord",
///     }
///
///     constant Locals {
///         transform: [[f32; 4]; 4] = "u_Transform",
///     }
///
///     pipeline pipe {
///         vbuf: gfx::VertexBuffer<Vertex> = (),
///         transform: gfx::Global<[[f32; 4]; 4]> = "u_Transform",
///         locals: gfx::ConstantBuffer<Locals> = "Locals",
///         color: gfx::TextureSampler<[f32; 4]> = "t_Color",
///         out_color: gfx::RenderTarget<gfx::format::Rgba8> = "Target0",
///         out_depth: gfx::DepthTarget<gfx::format::DepthStencil> =
///             gfx::preset::depth::LESS_EQUAL_WRITE,
///     }
/// }
///
/// impl Vertex {
///     fn new(p: [i8; 3], tex: [i8; 2]) -> Vertex {
///         Vertex {
///             pos: [p[0] as f32, p[1] as f32, p[2] as f32, 1.0f32],
///             tex_coord: [tex[0] as f32, tex[1] as f32],
///         }
///     }
/// }
///
/// fn main() {
///     let vertex_data = [
///         Vertex::new([-1, -1, 1], [0, 0]),
///         Vertex::new([ 1, -1, 1], [1, 0]),
///         // Add more vertices..
///     ];
/// }
/// ```
/// `vertex` and `constant` structures defined with `gfx_defines!`
/// can be extended with attributes:
///
/// ```{.rust}
/// #[macro_use]
/// extern crate gfx;
///
/// gfx_defines! {
///     #[derive(Default)]
///     vertex Vertex {
///         pos: [f32; 4] = "a_Pos",
///         tex_coord: [f32; 2] = "a_TexCoord",
///     }
/// }
///
/// fn main() {
///     let vertex = Vertex::default();
///     assert_eq!(vertex.pos[0], 0f32);
///     assert_eq!(vertex.tex_coord[0], 0f32);
/// }
/// ```
///
/// # `pipe`
///
/// The `pipeline state object` can consist of:
///
/// - A single vertex buffer object to hold the vertices.
/// - Single or multiple constant buffer objects.
/// - Single or multiple global buffer objects.
/// - Single or multiple samplers such as texture samplers.
/// - [Render](pso/target/struct.RenderTarget.html), [blend](pso/target/struct.BlendTarget.html),
///   [depth](pso/target/struct.DepthTarget.html) and [stencil](pso/target/struct.StencilTarget.html) targets
/// - A shader resource view (SRV, DX11)
/// - A unordered access view (UAV, DX11, not yet implemented in OpenGL backend)
/// - Scissors rectangle value (DX11)
///
/// Structure of a `pipeline state object` can be defined
/// freely but should at the very least consist of one vertex buffer object.
///
/// # `vertex`
///
/// Defines the vertex format
///
/// # `constant`
///
/// Defines constants values
///
#[macro_export]
macro_rules! gfx_defines {
    ($(#[$attr:meta])* vertex $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    }) => {
        gfx_vertex_struct_meta!($(#[$attr])* vertex_struct_meta $name {$($field:$ty = $e,)+});
    };

    ($(#[$attr:meta])* constant $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    }) => {
        gfx_constant_struct_meta!($(#[$attr])* constant_struct_meta $name {$($field:$ty = $e,)+});
    };

    (pipeline $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    }) => {
        gfx_pipeline!($name {$($field:$ty = $e,)+});
    };

    // The recursive case for vertex structs
    ($(#[$attr:meta])* vertex $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    } $($tail:tt)+) => {
        gfx_defines! {
            $(#[$attr])*
            vertex $name { $($field : $ty = $e,)+ }
        }
        gfx_defines!($($tail)+);
    };

    // The recursive case for constant structs
    ($(#[$attr:meta])* constant $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    } $($tail:tt)+) => {
        gfx_defines! {
            $(#[$attr])*
            constant $name { $($field : $ty = $e,)+ }
        }
        gfx_defines!($($tail)+);
    };

    // The recursive case for the other keywords
    ($keyword:ident $name:ident {
            $( $field:ident : $ty:ty = $e:expr, )+
    } $($tail:tt)+) => {
        gfx_defines! {
            $keyword $name { $($field : $ty = $e,)+ }
        }
        gfx_defines!($($tail)+);
    };
}
<|endoftext|>


<commit_before><commit_msg>Problem 01<commit_after>enum List<T> {
    Cons(T, ~List<T>),
    Nil
}

fn last<'a, T>(list: &'a List<T>) -> Option<&'a T> {
    match *list {
        Nil => None,
        Cons(ref elem, ~Nil) => Some(elem),
        Cons(_, ~ref rest) => last(rest)
    }
}

fn main() {
    let list: List<char> = Cons('a', ~Cons('b', ~Cons('c', ~Nil)));
    println!("{:?}", last(&list));

    let list: List<uint> = Cons(6, ~Cons(7, ~Cons(42, ~Nil)));
    println!("{:?}", last(&list));

    let list: List<~str> = Cons(~"six", ~Cons(~"seven", ~Cons(~"forty-two", ~Nil)));
    println!("{:?}", last(&list));
}
<|endoftext|>


<commit_before><commit_msg>add super simple firebase api<commit_after>use std::str::FromStr;

use hyper::Uri;

use client::{self, ApiClient};

pub struct FirebaseService {}
pub type Hub<'a> = client::Hub<'a, FirebaseService>;

lazy_static! {
    static ref DATABASE_SCOPES: Vec<String> = vec!["https://www.googleapis.com/auth/firebase.database".into(),
                       "https://www.googleapis.com/auth/userinfo.email".into()];
}

impl<'a> Hub<'a> {
    pub fn get_data(&self, path: &str) -> client::Result<String> {
        let uri =
            Uri::from_str(&format!("https://{}.firebaseio.com/{}.json", self.project_id(), path))
                .expect("uri is valid");
        self.get(&uri, &*DATABASE_SCOPES)
    }
}
<|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.

/*!

The `ToBytes` and `IterBytes` traits

*/

use io;
use io::Writer;
use option::{None, Option, Some};
use str;

pub type Cb<'self> = &'self fn(buf: &const [u8]) -> bool;

/**
 * A trait to implement in order to make a type hashable;
 * This works in combination with the trait `Hash::Hash`, and
 * may in the future be merged with that trait or otherwise
 * modified when default methods and trait inheritence are
 * completed.
 */
pub trait IterBytes {
    /**
     * Call the provided callback `f` one or more times with
     * byte-slices that should be used when computing a hash
     * value or otherwise "flattening" the structure into
     * a sequence of bytes. The `lsb0` parameter conveys
     * whether the caller is asking for little-endian bytes
     * (`true`) or big-endian (`false`); this should only be
     * relevant in implementations that represent a single
     * multi-byte datum such as a 32 bit integer or 64 bit
     * floating-point value. It can be safely ignored for
     * larger structured types as they are usually processed
     * left-to-right in declaration order, regardless of
     * underlying memory endianness.
     */
    fn iter_bytes(&self, lsb0: bool, f: Cb);
}

impl IterBytes for bool {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        f([
            *self as u8
        ]);
    }
}

impl IterBytes for u8 {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        f([
            *self
        ]);
    }
}

impl IterBytes for u16 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        if lsb0 {
            f([
                *self as u8,
                (*self >> 8) as u8
            ]);
        } else {
            f([
                (*self >> 8) as u8,
                *self as u8
            ]);
        }
    }
}

impl IterBytes for u32 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        if lsb0 {
            f([
                *self as u8,
                (*self >> 8) as u8,
                (*self >> 16) as u8,
                (*self >> 24) as u8,
            ]);
        } else {
            f([
                (*self >> 24) as u8,
                (*self >> 16) as u8,
                (*self >> 8) as u8,
                *self as u8
            ]);
        }
    }
}

impl IterBytes for u64 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        if lsb0 {
            f([
                *self as u8,
                (*self >> 8) as u8,
                (*self >> 16) as u8,
                (*self >> 24) as u8,
                (*self >> 32) as u8,
                (*self >> 40) as u8,
                (*self >> 48) as u8,
                (*self >> 56) as u8
            ]);
        } else {
            f([
                (*self >> 56) as u8,
                (*self >> 48) as u8,
                (*self >> 40) as u8,
                (*self >> 32) as u8,
                (*self >> 24) as u8,
                (*self >> 16) as u8,
                (*self >> 8) as u8,
                *self as u8
            ]);
        }
    }
}

impl IterBytes for i8 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u8).iter_bytes(lsb0, f)
    }
}

impl IterBytes for i16 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u16).iter_bytes(lsb0, f)
    }
}

impl IterBytes for i32 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u32).iter_bytes(lsb0, f)
    }
}

impl IterBytes for i64 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u64).iter_bytes(lsb0, f)
    }
}

impl IterBytes for char {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u32).iter_bytes(lsb0, f)
    }
}

#[cfg(target_word_size = "32")]
pub mod x32 {
    use to_bytes::{Cb, IterBytes};

    impl IterBytes for uint {
        #[inline(always)]
        fn iter_bytes(&self, lsb0: bool, f: Cb) {
            (*self as u32).iter_bytes(lsb0, f)
        }
    }
}

#[cfg(target_word_size = "64")]
pub mod x64 {
    use to_bytes::{Cb, IterBytes};

    impl IterBytes for uint {
        #[inline(always)]
        fn iter_bytes(&self, lsb0: bool, f: Cb) {
            (*self as u64).iter_bytes(lsb0, f)
        }
    }
}

impl IterBytes for int {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as uint).iter_bytes(lsb0, f)
    }
}

impl<'self,A:IterBytes> IterBytes for &'self [A] {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        for (*self).each |elt| {
            do elt.iter_bytes(lsb0) |bytes| {
                f(bytes)
            }
        }
    }
}

impl<A:IterBytes,B:IterBytes> IterBytes for (A,B) {
  #[inline(always)]
  fn iter_bytes(&self, lsb0: bool, f: Cb) {
    match *self {
      (ref a, ref b) => {
        iter_bytes_2(a, b, lsb0, f);
      }
    }
  }
}

impl<A:IterBytes,B:IterBytes,C:IterBytes> IterBytes for (A,B,C) {
  #[inline(always)]
  fn iter_bytes(&self, lsb0: bool, f: Cb) {
    match *self {
      (ref a, ref b, ref c) => {
        iter_bytes_3(a, b, c, lsb0, f);
      }
    }
  }
}

// Move this to vec, probably.
fn borrow<'x,A>(a: &'x [A]) -> &'x [A] {
    a
}

impl<A:IterBytes> IterBytes for ~[A] {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        borrow(*self).iter_bytes(lsb0, f)
    }
}

impl<A:IterBytes> IterBytes for @[A] {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        borrow(*self).iter_bytes(lsb0, f)
    }
}

pub fn iter_bytes_2<A:IterBytes,B:IterBytes>(a: &A, b: &B,
                                            lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_3<A: IterBytes,
                B: IterBytes,
                C: IterBytes>(a: &A, b: &B, c: &C,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_4<A: IterBytes,
                B: IterBytes,
                C: IterBytes,
                D: IterBytes>(a: &A, b: &B, c: &C,
                              d: &D,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_5<A: IterBytes,
                B: IterBytes,
                C: IterBytes,
                D: IterBytes,
                E: IterBytes>(a: &A, b: &B, c: &C,
                              d: &D, e: &E,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    e.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_6<A: IterBytes,
                B: IterBytes,
                C: IterBytes,
                D: IterBytes,
                E: IterBytes,
                F: IterBytes>(a: &A, b: &B, c: &C,
                              d: &D, e: &E, f: &F,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    e.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    f.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_7<A: IterBytes,
                B: IterBytes,
                C: IterBytes,
                D: IterBytes,
                E: IterBytes,
                F: IterBytes,
                G: IterBytes>(a: &A, b: &B, c: &C,
                              d: &D, e: &E, f: &F,
                              g: &G,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    e.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    f.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    g.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

impl<'self> IterBytes for &'self str {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        do str::byte_slice(*self) |bytes| {
            f(bytes);
        }
    }
}

impl IterBytes for ~str {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        do str::byte_slice(*self) |bytes| {
            f(bytes);
        }
    }
}

impl IterBytes for @str {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        do str::byte_slice(*self) |bytes| {
            f(bytes);
        }
    }
}

impl<A:IterBytes> IterBytes for Option<A> {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        match *self {
          Some(ref a) => iter_bytes_2(&0u8, a, lsb0, f),
          None => 1u8.iter_bytes(lsb0, f)
        }
    }
}

impl<'self,A:IterBytes> IterBytes for &'self A {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (**self).iter_bytes(lsb0, f);
    }
}

impl<A:IterBytes> IterBytes for @A {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (**self).iter_bytes(lsb0, f);
    }
}

impl<A:IterBytes> IterBytes for ~A {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (**self).iter_bytes(lsb0, f);
    }
}

// NB: raw-pointer IterBytes does _not_ dereference
// to the target; it just gives you the pointer-bytes.
impl<A> IterBytes for *const A {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as uint).iter_bytes(lsb0, f);
    }
}

trait ToBytes {
    fn to_bytes(&self, lsb0: bool) -> ~[u8];
}

impl<A:IterBytes> ToBytes for A {
    fn to_bytes(&self, lsb0: bool) -> ~[u8] {
        do io::with_bytes_writer |wr| {
            for self.iter_bytes(lsb0) |bytes| {
                wr.write(bytes)
            }
        }
    }
}
<commit_msg>auto merge of #6217 : Sodel-the-Vociferous/rust/export-ToBytes, r=graydon<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.

/*!

The `ToBytes` and `IterBytes` traits

*/

use io;
use io::Writer;
use option::{None, Option, Some};
use str;

pub type Cb<'self> = &'self fn(buf: &const [u8]) -> bool;

/**
 * A trait to implement in order to make a type hashable;
 * This works in combination with the trait `Hash::Hash`, and
 * may in the future be merged with that trait or otherwise
 * modified when default methods and trait inheritence are
 * completed.
 */
pub trait IterBytes {
    /**
     * Call the provided callback `f` one or more times with
     * byte-slices that should be used when computing a hash
     * value or otherwise "flattening" the structure into
     * a sequence of bytes. The `lsb0` parameter conveys
     * whether the caller is asking for little-endian bytes
     * (`true`) or big-endian (`false`); this should only be
     * relevant in implementations that represent a single
     * multi-byte datum such as a 32 bit integer or 64 bit
     * floating-point value. It can be safely ignored for
     * larger structured types as they are usually processed
     * left-to-right in declaration order, regardless of
     * underlying memory endianness.
     */
    fn iter_bytes(&self, lsb0: bool, f: Cb);
}

impl IterBytes for bool {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        f([
            *self as u8
        ]);
    }
}

impl IterBytes for u8 {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        f([
            *self
        ]);
    }
}

impl IterBytes for u16 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        if lsb0 {
            f([
                *self as u8,
                (*self >> 8) as u8
            ]);
        } else {
            f([
                (*self >> 8) as u8,
                *self as u8
            ]);
        }
    }
}

impl IterBytes for u32 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        if lsb0 {
            f([
                *self as u8,
                (*self >> 8) as u8,
                (*self >> 16) as u8,
                (*self >> 24) as u8,
            ]);
        } else {
            f([
                (*self >> 24) as u8,
                (*self >> 16) as u8,
                (*self >> 8) as u8,
                *self as u8
            ]);
        }
    }
}

impl IterBytes for u64 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        if lsb0 {
            f([
                *self as u8,
                (*self >> 8) as u8,
                (*self >> 16) as u8,
                (*self >> 24) as u8,
                (*self >> 32) as u8,
                (*self >> 40) as u8,
                (*self >> 48) as u8,
                (*self >> 56) as u8
            ]);
        } else {
            f([
                (*self >> 56) as u8,
                (*self >> 48) as u8,
                (*self >> 40) as u8,
                (*self >> 32) as u8,
                (*self >> 24) as u8,
                (*self >> 16) as u8,
                (*self >> 8) as u8,
                *self as u8
            ]);
        }
    }
}

impl IterBytes for i8 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u8).iter_bytes(lsb0, f)
    }
}

impl IterBytes for i16 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u16).iter_bytes(lsb0, f)
    }
}

impl IterBytes for i32 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u32).iter_bytes(lsb0, f)
    }
}

impl IterBytes for i64 {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u64).iter_bytes(lsb0, f)
    }
}

impl IterBytes for char {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as u32).iter_bytes(lsb0, f)
    }
}

#[cfg(target_word_size = "32")]
pub mod x32 {
    use to_bytes::{Cb, IterBytes};

    impl IterBytes for uint {
        #[inline(always)]
        fn iter_bytes(&self, lsb0: bool, f: Cb) {
            (*self as u32).iter_bytes(lsb0, f)
        }
    }
}

#[cfg(target_word_size = "64")]
pub mod x64 {
    use to_bytes::{Cb, IterBytes};

    impl IterBytes for uint {
        #[inline(always)]
        fn iter_bytes(&self, lsb0: bool, f: Cb) {
            (*self as u64).iter_bytes(lsb0, f)
        }
    }
}

impl IterBytes for int {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as uint).iter_bytes(lsb0, f)
    }
}

impl<'self,A:IterBytes> IterBytes for &'self [A] {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        for (*self).each |elt| {
            do elt.iter_bytes(lsb0) |bytes| {
                f(bytes)
            }
        }
    }
}

impl<A:IterBytes,B:IterBytes> IterBytes for (A,B) {
  #[inline(always)]
  fn iter_bytes(&self, lsb0: bool, f: Cb) {
    match *self {
      (ref a, ref b) => {
        iter_bytes_2(a, b, lsb0, f);
      }
    }
  }
}

impl<A:IterBytes,B:IterBytes,C:IterBytes> IterBytes for (A,B,C) {
  #[inline(always)]
  fn iter_bytes(&self, lsb0: bool, f: Cb) {
    match *self {
      (ref a, ref b, ref c) => {
        iter_bytes_3(a, b, c, lsb0, f);
      }
    }
  }
}

// Move this to vec, probably.
fn borrow<'x,A>(a: &'x [A]) -> &'x [A] {
    a
}

impl<A:IterBytes> IterBytes for ~[A] {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        borrow(*self).iter_bytes(lsb0, f)
    }
}

impl<A:IterBytes> IterBytes for @[A] {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        borrow(*self).iter_bytes(lsb0, f)
    }
}

pub fn iter_bytes_2<A:IterBytes,B:IterBytes>(a: &A, b: &B,
                                            lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_3<A: IterBytes,
                B: IterBytes,
                C: IterBytes>(a: &A, b: &B, c: &C,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_4<A: IterBytes,
                B: IterBytes,
                C: IterBytes,
                D: IterBytes>(a: &A, b: &B, c: &C,
                              d: &D,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_5<A: IterBytes,
                B: IterBytes,
                C: IterBytes,
                D: IterBytes,
                E: IterBytes>(a: &A, b: &B, c: &C,
                              d: &D, e: &E,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    e.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_6<A: IterBytes,
                B: IterBytes,
                C: IterBytes,
                D: IterBytes,
                E: IterBytes,
                F: IterBytes>(a: &A, b: &B, c: &C,
                              d: &D, e: &E, f: &F,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    e.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    f.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

pub fn iter_bytes_7<A: IterBytes,
                B: IterBytes,
                C: IterBytes,
                D: IterBytes,
                E: IterBytes,
                F: IterBytes,
                G: IterBytes>(a: &A, b: &B, c: &C,
                              d: &D, e: &E, f: &F,
                              g: &G,
                              lsb0: bool, z: Cb) {
    let mut flag = true;
    a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    e.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    f.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
    if !flag { return; }
    g.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag});
}

impl<'self> IterBytes for &'self str {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        do str::byte_slice(*self) |bytes| {
            f(bytes);
        }
    }
}

impl IterBytes for ~str {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        do str::byte_slice(*self) |bytes| {
            f(bytes);
        }
    }
}

impl IterBytes for @str {
    #[inline(always)]
    fn iter_bytes(&self, _lsb0: bool, f: Cb) {
        do str::byte_slice(*self) |bytes| {
            f(bytes);
        }
    }
}

impl<A:IterBytes> IterBytes for Option<A> {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        match *self {
          Some(ref a) => iter_bytes_2(&0u8, a, lsb0, f),
          None => 1u8.iter_bytes(lsb0, f)
        }
    }
}

impl<'self,A:IterBytes> IterBytes for &'self A {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (**self).iter_bytes(lsb0, f);
    }
}

impl<A:IterBytes> IterBytes for @A {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (**self).iter_bytes(lsb0, f);
    }
}

impl<A:IterBytes> IterBytes for ~A {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (**self).iter_bytes(lsb0, f);
    }
}

// NB: raw-pointer IterBytes does _not_ dereference
// to the target; it just gives you the pointer-bytes.
impl<A> IterBytes for *const A {
    #[inline(always)]
    fn iter_bytes(&self, lsb0: bool, f: Cb) {
        (*self as uint).iter_bytes(lsb0, f);
    }
}

pub trait ToBytes {
    fn to_bytes(&self, lsb0: bool) -> ~[u8];
}

impl<A:IterBytes> ToBytes for A {
    fn to_bytes(&self, lsb0: bool) -> ~[u8] {
        do io::with_bytes_writer |wr| {
            for self.iter_bytes(lsb0) |bytes| {
                wr.write(bytes)
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>indexing on chars by walking from start<commit_after><|endoftext|>


<commit_before><commit_msg>Trait fun<commit_after><|endoftext|>


<commit_before><commit_msg>Moved box tests to `tests/test_boxes.rs`<commit_after>extern crate algorst;

use algorst::MyBox;

#[test]
fn i32_works() {
    let b: MyBox<i32> = MyBox::new(4i32);
    assert_eq!(4, b.get());
}

#[test]
fn str_works() {
    let b: MyBox<&str> = MyBox::new("foo");
    assert_eq!("foo", b.get());
}
<|endoftext|>