<commit_before><commit_msg>Example to use unwrap and optional parameter<commit_after>fn checked_division(dividend: i32, divisor: i32) -> Option<i32> {
    if divisor == 0 {
        None
    } else {
        Some(dividend / divisor)
    }
}

fn try_division(dividend: i32, divisor: i32) {
    match checked_division(dividend, divisor) {
        None =>println!("{} / {} failed", dividend, divisor),
        Some(quotient) => {
            println!("{} / {} = {}", dividend, divisor, quotient)
        },
    }
}

fn main () {
    try_division(4,2);
    try_division(1,0);
    let none: Option<i32> = None;
    let _equivalent_none = None::<i32>;
    let optional_float = Some(0f32);

    println!("1- {:?} unwraps to {:?}", optional_float, optional_float.unwrap());
    //println!("2- {:?} unwraps to {:?}", _equivalent_none, _equivalent_none.unwrap());
    println!("3- {:?} unwraps to {:?}", none, none.unwrap());
}
<|endoftext|>


<commit_before><commit_msg>:fire: Remove unused stub<commit_after><|endoftext|>


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

// #[warn(deprecated_mode)];

use middle::ty;

use middle::typeck::isr_alist;
use util::common::indenter;
use util::ppaux::region_to_str;
use util::ppaux;

use extra::list::Cons;

// Helper functions related to manipulating region types.

pub fn replace_bound_regions_in_fn_sig(
    tcx: ty::ctxt,
    isr: isr_alist,
    opt_self_ty: Option<ty::t>,
    fn_sig: &ty::FnSig,
    mapf: &fn(ty::bound_region) -> ty::Region)
    -> (isr_alist, Option<ty::t>, ty::FnSig)
{
    let mut all_tys = ty::tys_in_fn_sig(fn_sig);

    for &self_ty in opt_self_ty.iter() {
        all_tys.push(self_ty);
    }

    for &t in opt_self_ty.iter() { all_tys.push(t) }

    debug2!("replace_bound_regions_in_fn_sig(self_ty={:?}, fn_sig={}, \
            all_tys={:?})",
           opt_self_ty.map(|t| ppaux::ty_to_str(tcx, *t)),
           ppaux::fn_sig_to_str(tcx, fn_sig),
           all_tys.map(|t| ppaux::ty_to_str(tcx, *t)));
    let _i = indenter();

    let isr = do create_bound_region_mapping(tcx, isr, all_tys) |br| {
        debug2!("br={:?}", br);
        mapf(br)
    };
    let new_fn_sig = ty::fold_sig(fn_sig, |t| {
        replace_bound_regions(tcx, isr, t)
    });
    let new_self_ty = opt_self_ty.map(|t| replace_bound_regions(tcx, isr, *t));

    debug2!("result of replace_bound_regions_in_fn_sig: \
            new_self_ty={:?}, \
            fn_sig={}",
           new_self_ty.map(|t| ppaux::ty_to_str(tcx, *t)),
           ppaux::fn_sig_to_str(tcx, &new_fn_sig));

    return (isr, new_self_ty, new_fn_sig);

    // Takes `isr`, a (possibly empty) mapping from in-scope region
    // names ("isr"s) to their corresponding regions; `tys`, a list of
    // types, and `to_r`, a closure that takes a bound_region and
    // returns a region.  Returns an updated version of `isr`,
    // extended with the in-scope region names from all of the bound
    // regions appearing in the types in the `tys` list (if they're
    // not in `isr` already), with each of those in-scope region names
    // mapped to a region that's the result of applying `to_r` to
    // itself.
    fn create_bound_region_mapping(
        tcx: ty::ctxt,
        isr: isr_alist,
        tys: ~[ty::t],
        to_r: &fn(ty::bound_region) -> ty::Region) -> isr_alist {

        // Takes `isr` (described above), `to_r` (described above),
        // and `r`, a region.  If `r` is anything other than a bound
        // region, or if it's a bound region that already appears in
        // `isr`, then we return `isr` unchanged.  If `r` is a bound
        // region that doesn't already appear in `isr`, we return an
        // updated isr_alist that now contains a mapping from `r` to
        // the result of calling `to_r` on it.
        fn append_isr(isr: isr_alist,
                      to_r: &fn(ty::bound_region) -> ty::Region,
                      r: ty::Region) -> isr_alist {
            match r {
              ty::re_empty | ty::re_free(*) | ty::re_static | ty::re_scope(_) |
              ty::re_infer(_) => {
                isr
              }
              ty::re_bound(br) => {
                match isr.find(br) {
                  Some(_) => isr,
                  None => @Cons((br, to_r(br)), isr)
                }
              }
            }
        }

        // For each type `ty` in `tys`...
        do tys.iter().fold(isr) |isr, ty| {
            let mut isr = isr;

            // Using fold_regions is inefficient, because it
            // constructs new types, but it avoids code duplication in
            // terms of locating all the regions within the various
            // kinds of types.  This had already caused me several
            // bugs so I decided to switch over.
            do ty::fold_regions(tcx, *ty) |r, in_fn| {
                if !in_fn { isr = append_isr(isr, |br| to_r(br), r); }
                r
            };

            isr
        }
    }

    // Takes `isr`, a mapping from in-scope region names ("isr"s) to
    // their corresponding regions; and `ty`, a type.  Returns an
    // updated version of `ty`, in which bound regions in `ty` have
    // been replaced with the corresponding bindings in `isr`.
    fn replace_bound_regions(
        tcx: ty::ctxt,
        isr: isr_alist,
        ty: ty::t) -> ty::t {

        do ty::fold_regions(tcx, ty) |r, in_fn| {
            let r1 = match r {
              // As long as we are not within a fn() type, `&T` is
              // mapped to the free region anon_r.  But within a fn
              // type, it remains bound.
              ty::re_bound(ty::br_anon(_)) if in_fn => r,

              ty::re_bound(br) => {
                match isr.find(br) {
                  // In most cases, all named, bound regions will be
                  // mapped to some free region.
                  Some(fr) => fr,

                  // But in the case of a fn() type, there may be
                  // named regions within that remain bound:
                  None if in_fn => r,
                  None => {
                    tcx.sess.bug(
                        format!("Bound region not found in \
                              in_scope_regions list: {}",
                             region_to_str(tcx, "", false, r)));
                  }
                }
              }

              // Free regions like these just stay the same:
              ty::re_empty |
              ty::re_static |
              ty::re_scope(_) |
              ty::re_free(*) |
              ty::re_infer(_) => r
            };
            r1
        }
    }
}

pub fn relate_nested_regions(
    tcx: ty::ctxt,
    opt_region: Option<ty::Region>,
    ty: ty::t,
    relate_op: &fn(ty::Region, ty::Region))
{
    /*!
     *
     * This rather specialized function walks each region `r` that appear
     * in `ty` and invokes `relate_op(r_encl, r)` for each one.  `r_encl`
     * here is the region of any enclosing `&'r T` pointer.  If there is
     * no enclosing pointer, and `opt_region` is Some, then `opt_region.get()`
     * is used instead.  Otherwise, no callback occurs at all).
     *
     * Here are some examples to give you an intution:
     *
     * - `relate_nested_regions(Some('r1), &'r2 uint)` invokes
     *   - `relate_op('r1, 'r2)`
     * - `relate_nested_regions(Some('r1), &'r2 &'r3 uint)` invokes
     *   - `relate_op('r1, 'r2)`
     *   - `relate_op('r2, 'r3)`
     * - `relate_nested_regions(None, &'r2 &'r3 uint)` invokes
     *   - `relate_op('r2, 'r3)`
     * - `relate_nested_regions(None, &'r2 &'r3 &'r4 uint)` invokes
     *   - `relate_op('r2, 'r3)`
     *   - `relate_op('r2, 'r4)`
     *   - `relate_op('r3, 'r4)`
     *
     * This function is used in various pieces of code because we enforce the
     * constraint that a region pointer cannot outlive the things it points at.
     * Hence, in the second example above, `'r2` must be a subregion of `'r3`.
     */

    let mut the_stack = ~[];
    for &r in opt_region.iter() { the_stack.push(r); }
    walk_ty(tcx, &mut the_stack, ty, relate_op);

    fn walk_ty(tcx: ty::ctxt,
               the_stack: &mut ~[ty::Region],
               ty: ty::t,
               relate_op: &fn(ty::Region, ty::Region))
    {
        match ty::get(ty).sty {
            ty::ty_rptr(r, ref mt) |
            ty::ty_evec(ref mt, ty::vstore_slice(r)) => {
                relate(*the_stack, r, |x,y| relate_op(x,y));
                the_stack.push(r);
                walk_ty(tcx, the_stack, mt.ty, |x,y| relate_op(x,y));
                the_stack.pop();
            }
            _ => {
                ty::fold_regions_and_ty(
                    tcx,
                    ty,
                    |r| { relate(     *the_stack, r, |x,y| relate_op(x,y)); r },
                    |t| { walk_ty(tcx, the_stack, t, |x,y| relate_op(x,y)); t },
                    |t| { walk_ty(tcx, the_stack, t, |x,y| relate_op(x,y)); t });
            }
        }
    }

    fn relate(the_stack: &[ty::Region],
              r_sub: ty::Region,
              relate_op: &fn(ty::Region, ty::Region))
    {
        for &r in the_stack.iter() {
            if !r.is_bound() && !r_sub.is_bound() {
                relate_op(r, r_sub);
            }
        }
    }
}

pub fn relate_free_regions(
    tcx: ty::ctxt,
    self_ty: Option<ty::t>,
    fn_sig: &ty::FnSig)
{
    /*!
     * This function populates the region map's `free_region_map`.
     * It walks over the transformed self type and argument types
     * for each function just before we check the body of that
     * function, looking for types where you have a borrowed
     * pointer to other borrowed data (e.g., `&'a &'b [uint]`.
     * We do not allow borrowed pointers to outlive the things they
     * point at, so we can assume that `'a <= 'b`.
     *
     * Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
     */

    debug2!("relate_free_regions >>");

    let mut all_tys = ~[];
    for arg in fn_sig.inputs.iter() {
        all_tys.push(*arg);
    }
    for &t in self_ty.iter() {
        all_tys.push(t);
    }

    for &t in all_tys.iter() {
        debug2!("relate_free_regions(t={})", ppaux::ty_to_str(tcx, t));
        relate_nested_regions(tcx, None, t, |a, b| {
            match (&a, &b) {
                (&ty::re_free(free_a), &ty::re_free(free_b)) => {
                    tcx.region_maps.relate_free_regions(free_a, free_b);
                }
                _ => {}
            }
        })
    }

    debug2!("<< relate_free_regions");
}
<commit_msg>remove duplicate statement<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.

// #[warn(deprecated_mode)];

use middle::ty;

use middle::typeck::isr_alist;
use util::common::indenter;
use util::ppaux::region_to_str;
use util::ppaux;

use extra::list::Cons;

// Helper functions related to manipulating region types.

pub fn replace_bound_regions_in_fn_sig(
    tcx: ty::ctxt,
    isr: isr_alist,
    opt_self_ty: Option<ty::t>,
    fn_sig: &ty::FnSig,
    mapf: &fn(ty::bound_region) -> ty::Region)
    -> (isr_alist, Option<ty::t>, ty::FnSig)
{
    let mut all_tys = ty::tys_in_fn_sig(fn_sig);

    for &t in opt_self_ty.iter() { all_tys.push(t) }

    debug2!("replace_bound_regions_in_fn_sig(self_ty={:?}, fn_sig={}, \
            all_tys={:?})",
           opt_self_ty.map(|t| ppaux::ty_to_str(tcx, *t)),
           ppaux::fn_sig_to_str(tcx, fn_sig),
           all_tys.map(|t| ppaux::ty_to_str(tcx, *t)));
    let _i = indenter();

    let isr = do create_bound_region_mapping(tcx, isr, all_tys) |br| {
        debug2!("br={:?}", br);
        mapf(br)
    };
    let new_fn_sig = ty::fold_sig(fn_sig, |t| {
        replace_bound_regions(tcx, isr, t)
    });
    let new_self_ty = opt_self_ty.map(|t| replace_bound_regions(tcx, isr, *t));

    debug2!("result of replace_bound_regions_in_fn_sig: \
            new_self_ty={:?}, \
            fn_sig={}",
           new_self_ty.map(|t| ppaux::ty_to_str(tcx, *t)),
           ppaux::fn_sig_to_str(tcx, &new_fn_sig));

    return (isr, new_self_ty, new_fn_sig);

    // Takes `isr`, a (possibly empty) mapping from in-scope region
    // names ("isr"s) to their corresponding regions; `tys`, a list of
    // types, and `to_r`, a closure that takes a bound_region and
    // returns a region.  Returns an updated version of `isr`,
    // extended with the in-scope region names from all of the bound
    // regions appearing in the types in the `tys` list (if they're
    // not in `isr` already), with each of those in-scope region names
    // mapped to a region that's the result of applying `to_r` to
    // itself.
    fn create_bound_region_mapping(
        tcx: ty::ctxt,
        isr: isr_alist,
        tys: ~[ty::t],
        to_r: &fn(ty::bound_region) -> ty::Region) -> isr_alist {

        // Takes `isr` (described above), `to_r` (described above),
        // and `r`, a region.  If `r` is anything other than a bound
        // region, or if it's a bound region that already appears in
        // `isr`, then we return `isr` unchanged.  If `r` is a bound
        // region that doesn't already appear in `isr`, we return an
        // updated isr_alist that now contains a mapping from `r` to
        // the result of calling `to_r` on it.
        fn append_isr(isr: isr_alist,
                      to_r: &fn(ty::bound_region) -> ty::Region,
                      r: ty::Region) -> isr_alist {
            match r {
              ty::re_empty | ty::re_free(*) | ty::re_static | ty::re_scope(_) |
              ty::re_infer(_) => {
                isr
              }
              ty::re_bound(br) => {
                match isr.find(br) {
                  Some(_) => isr,
                  None => @Cons((br, to_r(br)), isr)
                }
              }
            }
        }

        // For each type `ty` in `tys`...
        do tys.iter().fold(isr) |isr, ty| {
            let mut isr = isr;

            // Using fold_regions is inefficient, because it
            // constructs new types, but it avoids code duplication in
            // terms of locating all the regions within the various
            // kinds of types.  This had already caused me several
            // bugs so I decided to switch over.
            do ty::fold_regions(tcx, *ty) |r, in_fn| {
                if !in_fn { isr = append_isr(isr, |br| to_r(br), r); }
                r
            };

            isr
        }
    }

    // Takes `isr`, a mapping from in-scope region names ("isr"s) to
    // their corresponding regions; and `ty`, a type.  Returns an
    // updated version of `ty`, in which bound regions in `ty` have
    // been replaced with the corresponding bindings in `isr`.
    fn replace_bound_regions(
        tcx: ty::ctxt,
        isr: isr_alist,
        ty: ty::t) -> ty::t {

        do ty::fold_regions(tcx, ty) |r, in_fn| {
            let r1 = match r {
              // As long as we are not within a fn() type, `&T` is
              // mapped to the free region anon_r.  But within a fn
              // type, it remains bound.
              ty::re_bound(ty::br_anon(_)) if in_fn => r,

              ty::re_bound(br) => {
                match isr.find(br) {
                  // In most cases, all named, bound regions will be
                  // mapped to some free region.
                  Some(fr) => fr,

                  // But in the case of a fn() type, there may be
                  // named regions within that remain bound:
                  None if in_fn => r,
                  None => {
                    tcx.sess.bug(
                        format!("Bound region not found in \
                              in_scope_regions list: {}",
                             region_to_str(tcx, "", false, r)));
                  }
                }
              }

              // Free regions like these just stay the same:
              ty::re_empty |
              ty::re_static |
              ty::re_scope(_) |
              ty::re_free(*) |
              ty::re_infer(_) => r
            };
            r1
        }
    }
}

pub fn relate_nested_regions(
    tcx: ty::ctxt,
    opt_region: Option<ty::Region>,
    ty: ty::t,
    relate_op: &fn(ty::Region, ty::Region))
{
    /*!
     *
     * This rather specialized function walks each region `r` that appear
     * in `ty` and invokes `relate_op(r_encl, r)` for each one.  `r_encl`
     * here is the region of any enclosing `&'r T` pointer.  If there is
     * no enclosing pointer, and `opt_region` is Some, then `opt_region.get()`
     * is used instead.  Otherwise, no callback occurs at all).
     *
     * Here are some examples to give you an intution:
     *
     * - `relate_nested_regions(Some('r1), &'r2 uint)` invokes
     *   - `relate_op('r1, 'r2)`
     * - `relate_nested_regions(Some('r1), &'r2 &'r3 uint)` invokes
     *   - `relate_op('r1, 'r2)`
     *   - `relate_op('r2, 'r3)`
     * - `relate_nested_regions(None, &'r2 &'r3 uint)` invokes
     *   - `relate_op('r2, 'r3)`
     * - `relate_nested_regions(None, &'r2 &'r3 &'r4 uint)` invokes
     *   - `relate_op('r2, 'r3)`
     *   - `relate_op('r2, 'r4)`
     *   - `relate_op('r3, 'r4)`
     *
     * This function is used in various pieces of code because we enforce the
     * constraint that a region pointer cannot outlive the things it points at.
     * Hence, in the second example above, `'r2` must be a subregion of `'r3`.
     */

    let mut the_stack = ~[];
    for &r in opt_region.iter() { the_stack.push(r); }
    walk_ty(tcx, &mut the_stack, ty, relate_op);

    fn walk_ty(tcx: ty::ctxt,
               the_stack: &mut ~[ty::Region],
               ty: ty::t,
               relate_op: &fn(ty::Region, ty::Region))
    {
        match ty::get(ty).sty {
            ty::ty_rptr(r, ref mt) |
            ty::ty_evec(ref mt, ty::vstore_slice(r)) => {
                relate(*the_stack, r, |x,y| relate_op(x,y));
                the_stack.push(r);
                walk_ty(tcx, the_stack, mt.ty, |x,y| relate_op(x,y));
                the_stack.pop();
            }
            _ => {
                ty::fold_regions_and_ty(
                    tcx,
                    ty,
                    |r| { relate(     *the_stack, r, |x,y| relate_op(x,y)); r },
                    |t| { walk_ty(tcx, the_stack, t, |x,y| relate_op(x,y)); t },
                    |t| { walk_ty(tcx, the_stack, t, |x,y| relate_op(x,y)); t });
            }
        }
    }

    fn relate(the_stack: &[ty::Region],
              r_sub: ty::Region,
              relate_op: &fn(ty::Region, ty::Region))
    {
        for &r in the_stack.iter() {
            if !r.is_bound() && !r_sub.is_bound() {
                relate_op(r, r_sub);
            }
        }
    }
}

pub fn relate_free_regions(
    tcx: ty::ctxt,
    self_ty: Option<ty::t>,
    fn_sig: &ty::FnSig)
{
    /*!
     * This function populates the region map's `free_region_map`.
     * It walks over the transformed self type and argument types
     * for each function just before we check the body of that
     * function, looking for types where you have a borrowed
     * pointer to other borrowed data (e.g., `&'a &'b [uint]`.
     * We do not allow borrowed pointers to outlive the things they
     * point at, so we can assume that `'a <= 'b`.
     *
     * Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
     */

    debug2!("relate_free_regions >>");

    let mut all_tys = ~[];
    for arg in fn_sig.inputs.iter() {
        all_tys.push(*arg);
    }
    for &t in self_ty.iter() {
        all_tys.push(t);
    }

    for &t in all_tys.iter() {
        debug2!("relate_free_regions(t={})", ppaux::ty_to_str(tcx, t));
        relate_nested_regions(tcx, None, t, |a, b| {
            match (&a, &b) {
                (&ty::re_free(free_a), &ty::re_free(free_b)) => {
                    tcx.region_maps.relate_free_regions(free_a, free_b);
                }
                _ => {}
            }
        })
    }

    debug2!("<< relate_free_regions");
}
<|endoftext|>


<commit_before><commit_msg>Stop using deprecated RefCell<T>::get<commit_after><|endoftext|>


<commit_before><commit_msg>Complete problem 8<commit_after>use num::traits::ToPrimitive;

pub fn demo(n: String, num_digits: usize) {
    println!("{}", alg(n, num_digits));
}

fn alg(n: String, num_digits: usize) -> u64 {
    let digits = n.chars().collect::<Vec<char>>();
    let mut largest_product = 0;

    for i in 1..digits.len() - num_digits {
        use std::cmp;
        let current_product = digits[i..i+num_digits].iter()
            .fold(1, |acc, x| acc * x.to_digit(10).unwrap().to_u64().unwrap());
        largest_product = cmp::max(largest_product, current_product);
    }

    largest_product
}
<|endoftext|>


<commit_before><commit_msg>Fix deprecated methods<commit_after><|endoftext|>


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


<commit_before><commit_msg>Refactor: Split actual list implementation from argument processing<commit_after><|endoftext|>


<commit_before><commit_msg>vec: some cleanup<commit_after><|endoftext|>


<commit_before>use std::str::FromStr;

mod generated;
use self::generated::EFFECTIVENESS_CHART;

#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum Effectiveness {
    DoubleNotVery,
    NotVery,
    Normal,
    SuperEffective
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum PokeType {
    Normal = 0,
    Fighting = 1,
    Flying = 2,
    Poison = 3,
    Ground = 4,
    Rock = 5,
    Bug = 6,
    Ghost = 7,
    Steel = 8,
    Fire = 9,
    Water = 10,
    Grass = 11,
    Electric = 12,
    Psychic = 13,
    Ice = 14,
    Dragon = 15,
    Dark = 16,
    Fairy = 17
}

impl PokeType {
    pub fn efficacy_against(&self, other: PokeType) -> Effectiveness {
        EFFECTIVENESS_CHART[*self as usize][other as usize]
    }
}

impl FromStr for PokeType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let lowercase = s.to_lowercase();

        match lowercase.as_ref() {
            "normal" => Ok(PokeType::Normal),
            "fighting" => Ok(PokeType::Fighting),
            "flying" => Ok(PokeType::Flying),
            "poison" => Ok(PokeType::Poison),
            "ground" => Ok(PokeType::Ground),
            "rock" => Ok(PokeType::Rock),
            "bug" => Ok(PokeType::Bug),
            "ghost" => Ok(PokeType::Ghost),
            "steel" => Ok(PokeType::Steel),
            "fire" => Ok(PokeType::Fire),
            "water" => Ok(PokeType::Water),
            "grass" => Ok(PokeType::Grass),
            "electric" => Ok(PokeType::Electric),
            "psychic" => Ok(PokeType::Psychic),
            "ice" => Ok(PokeType::Ice),
            "dragon" => Ok(PokeType::Dragon),
            "dark" => Ok(PokeType::Dark),
            "fairy" => Ok(PokeType::Fairy),
            _ => Err(())
        }
    }
}

#[cfg(test)]
mod tests {
    use ::{PokeType, Effectiveness};

    #[test]
    fn efficacy_against() {
        let electric_v_ground = PokeType::Electric.efficacy_against(PokeType::Ground);
        assert_eq!(Effectiveness::DoubleNotVery, electric_v_ground);

        let grass_v_bug = PokeType::Grass.efficacy_against(PokeType::Bug);
        assert_eq!(Effectiveness::NotVery, grass_v_bug);

        let poison_v_flying = PokeType::Poison.efficacy_against(PokeType::Flying);
        assert_eq!(Effectiveness::Normal, poison_v_flying);

        let fighting_v_normal = PokeType::Fighting.efficacy_against(PokeType::Normal);
        assert_eq!(Effectiveness::SuperEffective, fighting_v_normal);
    }
}
<commit_msg>Add PokemonType parse tests<commit_after>use std::str::FromStr;

mod generated;
use self::generated::EFFECTIVENESS_CHART;

#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum Effectiveness {
    DoubleNotVery,
    NotVery,
    Normal,
    SuperEffective
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
pub enum PokeType {
    Normal = 0,
    Fighting = 1,
    Flying = 2,
    Poison = 3,
    Ground = 4,
    Rock = 5,
    Bug = 6,
    Ghost = 7,
    Steel = 8,
    Fire = 9,
    Water = 10,
    Grass = 11,
    Electric = 12,
    Psychic = 13,
    Ice = 14,
    Dragon = 15,
    Dark = 16,
    Fairy = 17
}

impl PokeType {
    pub fn efficacy_against(&self, other: PokeType) -> Effectiveness {
        EFFECTIVENESS_CHART[*self as usize][other as usize]
    }
}

impl FromStr for PokeType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let lowercase = s.to_lowercase();

        match lowercase.as_ref() {
            "normal" => Ok(PokeType::Normal),
            "fighting" => Ok(PokeType::Fighting),
            "flying" => Ok(PokeType::Flying),
            "poison" => Ok(PokeType::Poison),
            "ground" => Ok(PokeType::Ground),
            "rock" => Ok(PokeType::Rock),
            "bug" => Ok(PokeType::Bug),
            "ghost" => Ok(PokeType::Ghost),
            "steel" => Ok(PokeType::Steel),
            "fire" => Ok(PokeType::Fire),
            "water" => Ok(PokeType::Water),
            "grass" => Ok(PokeType::Grass),
            "electric" => Ok(PokeType::Electric),
            "psychic" => Ok(PokeType::Psychic),
            "ice" => Ok(PokeType::Ice),
            "dragon" => Ok(PokeType::Dragon),
            "dark" => Ok(PokeType::Dark),
            "fairy" => Ok(PokeType::Fairy),
            _ => Err(())
        }
    }
}

#[cfg(test)]
mod tests {
    use ::{PokeType, Effectiveness};

    #[test]
    fn efficacy_against() {
        let electric_v_ground = PokeType::Electric.efficacy_against(PokeType::Ground);
        assert_eq!(Effectiveness::DoubleNotVery, electric_v_ground);

        let grass_v_bug = PokeType::Grass.efficacy_against(PokeType::Bug);
        assert_eq!(Effectiveness::NotVery, grass_v_bug);

        let poison_v_flying = PokeType::Poison.efficacy_against(PokeType::Flying);
        assert_eq!(Effectiveness::Normal, poison_v_flying);

        let fighting_v_normal = PokeType::Fighting.efficacy_against(PokeType::Normal);
        assert_eq!(Effectiveness::SuperEffective, fighting_v_normal);
    }

    #[test]
    fn from_string() {
        assert_eq!(PokeType::Dragon, "dragon".parse().unwrap());
        assert_eq!(PokeType::Ice, "Ice".parse().unwrap());

        let error: Result<PokeType, ()> = "gibberish".parse();
        assert!(error.is_err());
    }
}
<|endoftext|>


<commit_before><commit_msg>nbt: Removes some stray `&mut *`.<commit_after><|endoftext|>


<commit_before><commit_msg>Add more documentation for Adapter pattern<commit_after><|endoftext|>


<commit_before><commit_msg>Add RNG test.<commit_after>use capsules::test::rng::TestRng;
use kernel::hil::rng::{RNG, Continue, Client};
use hotel::trng;

pub unsafe fn run_rng() {
    let r = static_init_test_rng();
    trng::TRNG0.set_client(r);
    r.run();
}

unsafe fn static_init_test_rng() -> &'static mut TestRng<'static> {
    static_init!(
        TestRng<'static>,
        TestRng::new(&trng::TRNG0)
    )
}
<|endoftext|>


<commit_before><commit_msg>enumeration over a range<commit_after><|endoftext|>


<commit_before>use std::path::{Path, PathBuf, Component};
use std::error::Error;
use std::fs::{self, metadata, File};

/// This is copied from the rust source code until Path_ Ext stabilizes.
/// You can use it, but be aware that it will be removed when those features go to rust stable
pub trait PathExt {
    fn exists(&self) -> bool;
    fn is_file(&self) -> bool;
    fn is_dir(&self) -> bool;
}

impl PathExt for Path {
    fn exists(&self) -> bool {
        metadata(self).is_ok()
    }

    fn is_file(&self) -> bool {
       metadata(self).map(|s| s.is_file()).unwrap_or(false)
    }

    fn is_dir(&self) -> bool {
       metadata(self).map(|s| s.is_dir()).unwrap_or(false)
    }
}

/// Takes a path and returns a path containing just enough `../` to point to the root of the given path.
///
/// This is mostly interesting for a relative path to point back to the directory from where the
/// path starts.
///
/// ```ignore
/// let mut path = Path::new("some/relative/path");
///
/// println!("{}", path_to_root(&path));
/// ```
///
/// **Outputs**
///
/// ```text
/// "../../"
/// ```
///
/// **note:** it's not very fool-proof, if you find a situation where it doesn't return the correct
/// path. Consider [submitting a new issue](https://github.com/azerupi/mdBook/issues) or a
/// [pull-request](https://github.com/azerupi/mdBook/pulls) to improve it.

pub fn path_to_root(path: &Path) -> String {
    debug!("[fn]: path_to_root");
    // Remove filename and add "../" for every directory

    path.to_path_buf().parent().expect("")
        .components().fold(String::new(), |mut s, c| {
            match c {
                Component::Normal(_) => s.push_str("../"),
                _ => {
                    debug!("[*]: Other path component... {:?}", c);
                }
            }
            s
        })
}

/// This function checks for every component in a path if the directory exists,
/// if it does not it is created.

pub fn create_path(path: &Path) -> Result<(), Box<Error>> {
    debug!("[fn]: create_path");

    // Create directories if they do not exist
    let mut constructed_path = PathBuf::new();

    for component in path.components() {

        let mut dir;
        match component {
            Component::Normal(_) => { dir = PathBuf::from(component.as_os_str()); },
            Component::RootDir => {
                debug!("[*]: Root directory");
                // This doesn't look very compatible with Windows...
                constructed_path.push("/");
                continue
            },
            _ => continue,
        }

        constructed_path.push(&dir);
        debug!("[*]: {:?}", constructed_path);

        if !constructed_path.exists() || !constructed_path.is_dir() {
            try!(fs::create_dir(&constructed_path));
            debug!("[*]: Directory created {:?}", constructed_path);
        } else {
            debug!("[*]: Directory exists {:?}", constructed_path);
            continue
        }

    }

    debug!("[*]: Constructed path: {:?}", constructed_path);

    Ok(())
}

/// This function creates a file and returns it. But before creating the file it checks every
/// directory in the path to see if it exists, and if it does not it will be created.

pub fn create_file(path: &Path) -> Result<File, Box<Error>> {
    debug!("[fn]: create_file");

    // Construct path
    if let Some(p) = path.parent() {
        try!(create_path(p));
    }

    debug!("[*]: Create file: {:?}", path);
    let f = try!(File::create(path));

    Ok(f)
}

/// Removes all the content of a directory but not the directory itself

pub fn remove_dir_content(dir: &Path) -> Result<(), Box<Error>> {
    for item in try!(fs::read_dir(dir)) {
        if let Ok(item) = item {
            let item = item.path();
            if item.is_dir() { try!(fs::remove_dir_all(item)); } else { try!(fs::remove_file(item)); }
        }
    }
    Ok(())
}
<commit_msg>Added utility function to copy all files recursively except files that have an extension present in the ext_blacklist parameter<commit_after>use std::path::{Path, PathBuf, Component};
use std::error::Error;
use std::fs::{self, metadata, File};

/// This is copied from the rust source code until Path_ Ext stabilizes.
/// You can use it, but be aware that it will be removed when those features go to rust stable
pub trait PathExt {
    fn exists(&self) -> bool;
    fn is_file(&self) -> bool;
    fn is_dir(&self) -> bool;
}

impl PathExt for Path {
    fn exists(&self) -> bool {
        metadata(self).is_ok()
    }

    fn is_file(&self) -> bool {
       metadata(self).map(|s| s.is_file()).unwrap_or(false)
    }

    fn is_dir(&self) -> bool {
       metadata(self).map(|s| s.is_dir()).unwrap_or(false)
    }
}

/// Takes a path and returns a path containing just enough `../` to point to the root of the given path.
///
/// This is mostly interesting for a relative path to point back to the directory from where the
/// path starts.
///
/// ```ignore
/// let mut path = Path::new("some/relative/path");
///
/// println!("{}", path_to_root(&path));
/// ```
///
/// **Outputs**
///
/// ```text
/// "../../"
/// ```
///
/// **note:** it's not very fool-proof, if you find a situation where it doesn't return the correct
/// path. Consider [submitting a new issue](https://github.com/azerupi/mdBook/issues) or a
/// [pull-request](https://github.com/azerupi/mdBook/pulls) to improve it.

pub fn path_to_root(path: &Path) -> String {
    debug!("[fn]: path_to_root");
    // Remove filename and add "../" for every directory

    path.to_path_buf().parent().expect("")
        .components().fold(String::new(), |mut s, c| {
            match c {
                Component::Normal(_) => s.push_str("../"),
                _ => {
                    debug!("[*]: Other path component... {:?}", c);
                }
            }
            s
        })
}

/// This function checks for every component in a path if the directory exists,
/// if it does not it is created.

pub fn create_path(path: &Path) -> Result<(), Box<Error>> {
    debug!("[fn]: create_path");

    // Create directories if they do not exist
    let mut constructed_path = PathBuf::new();

    for component in path.components() {

        let mut dir;
        match component {
            Component::Normal(_) => { dir = PathBuf::from(component.as_os_str()); },
            Component::RootDir => {
                debug!("[*]: Root directory");
                // This doesn't look very compatible with Windows...
                constructed_path.push("/");
                continue
            },
            _ => continue,
        }

        constructed_path.push(&dir);
        debug!("[*]: {:?}", constructed_path);

        if !constructed_path.exists() || !constructed_path.is_dir() {
            try!(fs::create_dir(&constructed_path));
            debug!("[*]: Directory created {:?}", constructed_path);
        } else {
            debug!("[*]: Directory exists {:?}", constructed_path);
            continue
        }

    }

    debug!("[*]: Constructed path: {:?}", constructed_path);

    Ok(())
}

/// This function creates a file and returns it. But before creating the file it checks every
/// directory in the path to see if it exists, and if it does not it will be created.

pub fn create_file(path: &Path) -> Result<File, Box<Error>> {
    debug!("[fn]: create_file");

    // Construct path
    if let Some(p) = path.parent() {
        try!(create_path(p));
    }

    debug!("[*]: Create file: {:?}", path);
    let f = try!(File::create(path));

    Ok(f)
}

/// Removes all the content of a directory but not the directory itself

pub fn remove_dir_content(dir: &Path) -> Result<(), Box<Error>> {
    for item in try!(fs::read_dir(dir)) {
        if let Ok(item) = item {
            let item = item.path();
            if item.is_dir() { try!(fs::remove_dir_all(item)); } else { try!(fs::remove_file(item)); }
        }
    }
    Ok(())
}

/// **Untested!**
///
/// Copies all files of a directory to another one except the files with the extensions given in the
/// `ext_blacklist` array

pub fn copy_files_except_ext(from: &Path, to: &Path, recursive: bool, ext_blacklist: &[String]) -> Result<(), Box<Error>> {

    // Check that from and to are different
    if from == to { return Ok(()) }

    for entry in try!(fs::read_dir(from)) {
        let entry = try!(entry);
        let metadata = try!(entry.metadata());

        // If the entry is a dir and the recursive option is enabled, call itself
        if metadata.is_dir() && recursive {
            try!(copy_files_except_ext(
                &from.join(entry.file_name()),
                &to.join(entry.file_name()),
                true,
                ext_blacklist
            ));
        } else if metadata.is_file() {

            // Check if it is in the blacklist
            if let Some(ext) = entry.path().extension() {
                if ext_blacklist.contains(&String::from(ext.to_str().unwrap())) { continue }

                try!(fs::copy(entry.path(), &to.join(entry.path().file_name().expect("a file should have a file name..."))));
            }
        }
    }
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>[Auto] bin/core/mv: Fix Clippy warnings<commit_after><|endoftext|>


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

// must-compile-successfully

#![feature(nll)]

use std::borrow::Cow;

#[derive(Clone, Debug)]
struct S<'a> {
    name: Cow<'a, str>
}

#[derive(Clone, Debug)]
struct T<'a> {
    s: Cow<'a, [S<'a>]>
}

fn main() {
    let s1 = [S { name: Cow::Borrowed("Test1") }, S { name: Cow::Borrowed("Test2") }];
    let b1 = T { s: Cow::Borrowed(&s1) };
    let s2 = [S { name: Cow::Borrowed("Test3") }, S { name: Cow::Borrowed("Test4") }];
    let b2 = T { s: Cow::Borrowed(&s2) };

    let mut v = Vec::new();
    v.push(b1);
    v.push(b2);

    println!("{:?}", v);
}
<|endoftext|>


<commit_before><commit_msg>test: Add tests for sw_vers parsing<commit_after>extern crate regex;
#[path="../src/sw_vers.rs"]
mod sw_vers;
#[path="../src/utils.rs"]
mod utils;

fn file() -> String {
"
ProductName:	Mac OS X
ProductVersion:	10.10.5
BuildVersion:	14F27
".to_string()
}

#[test]
pub fn parses_product_name() {
    let info = sw_vers::parse(file());
    assert_eq!(info.product_name, Some("Mac OS X".to_string()));
}

#[test]
pub fn parses_product_version() {
    let info = sw_vers::parse(file());
    assert_eq!(info.product_version, Some("10.10.5".to_string()));
}

#[test]
pub fn parses_build_version() {
    let info = sw_vers::parse(file());
    assert_eq!(info.build_version, Some("14F27".to_string()));
}
<|endoftext|>


<commit_before><commit_msg>Remove result print.<commit_after><|endoftext|>


<commit_before><commit_msg>Add content_offset for storing the device pixel offset in content<commit_after><|endoftext|>


<commit_before><commit_msg>cat scan<commit_after><|endoftext|>


<commit_before><commit_msg>Challenge 1 complete<commit_after>fn hex2nibble(hex : u8) -> Result<u8, ()> {
    match hex {
        0x30u8 ... 0x39u8 => Ok(hex - 0x30u8),
        0x41u8 ... 0x46u8 | 0x61u8 ... 0x66u8 => Ok((hex & !0x20u8) - 0x37),
        _ => Err(()),
    }
}

fn hex2octets(hex: Vec<u8>) -> Vec<u8> {
    let mut octets : Vec<u8> = Vec::with_capacity(&hex.len() / 2 + &hex.len() % 2);
    if hex.len() % 2 == 1 {
        octets.push(hex2nibble(hex[0]).unwrap())
    }
    for octet in hex[&hex.len() % 2 ..].chunks(2) {
        octets.push((hex2nibble(octet[0]).unwrap() << 4) + hex2nibble(octet[1]).unwrap())
    }
    octets
}

fn octets2base64(octets: Vec<u8>) -> Vec<u8> {
    let mut base64 : Vec<u8> = Vec::with_capacity(4 * (octets.len() / 3 + match octets.len() {
        0 => 0,
        _ => 1
    }));
    for chunk in octets.chunks(3) {
        let groups = match chunk.len() {
            1 => [(chunk[0] & 0xFCu8) >> 2, (chunk[0] & 0x03u8) << 4, 0xFFu8, 0xFFu8],
            2 => [(chunk[0] & 0xFCu8) >> 2, ((chunk[0] & 0x03u8) << 4) + ((chunk[1] & 0xF0u8) >> 4), (chunk[1] & 0x0Fu8) << 2, 0xFFu8],
            3 => [(chunk[0] & 0xFCu8) >> 2, ((chunk[0] & 0x03u8) << 4) + ((chunk[1] & 0xF0u8) >> 4), ((chunk[1] & 0x0Fu8) << 2) + ((chunk[2] & 0xC0u8) >> 6), chunk[2] & 0x3Fu8],
            _ => panic!(),
        };
        for group in &groups {
            base64.push(match *group {
                0x00u8 ... 0x19u8 => group + 0x41u8,
                0x1Au8 ... 0x33u8 => group + 0x47u8,
                0x34u8 ... 0x3Du8 => group - 0x04u8,
                0x3Eu8 => 0x2Bu8,
                0x3Fu8 => 0x2Fu8,
                0xFFu8 => 0x3Du8,
                _ => panic!(),
            })
        }
    }
    base64
}

fn hex2base64(hex: Vec<u8>) -> Vec<u8> {
    octets2base64(hex2octets(hex))
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_hex2nibble() {
        assert!(::hex2nibble('1' as u8) == Ok(1u8));
        assert!(::hex2nibble('2' as u8) == Ok(2u8));
        assert!(::hex2nibble('3' as u8) == Ok(3u8));
        assert!(::hex2nibble('4' as u8) == Ok(4u8));
        assert!(::hex2nibble('5' as u8) == Ok(5u8));
        assert!(::hex2nibble('6' as u8) == Ok(6u8));
        assert!(::hex2nibble('7' as u8) == Ok(7u8));
        assert!(::hex2nibble('8' as u8) == Ok(8u8));
        assert!(::hex2nibble('9' as u8) == Ok(9u8));
        assert!(::hex2nibble('a' as u8) == Ok(10u8));
        assert!(::hex2nibble('A' as u8) == Ok(10u8));
        assert!(::hex2nibble('b' as u8) == Ok(11u8));
        assert!(::hex2nibble('B' as u8) == Ok(11u8));
        assert!(::hex2nibble('c' as u8) == Ok(12u8));
        assert!(::hex2nibble('C' as u8) == Ok(12u8));
        assert!(::hex2nibble('d' as u8) == Ok(13u8));
        assert!(::hex2nibble('D' as u8) == Ok(13u8));
        assert!(::hex2nibble('e' as u8) == Ok(14u8));
        assert!(::hex2nibble('E' as u8) == Ok(14u8));
        assert!(::hex2nibble('f' as u8) == Ok(15u8));
        assert!(::hex2nibble('F' as u8) == Ok(15u8));
        assert!(::hex2nibble('z' as u8) == Err(()));
    }

    #[test]
    fn test_hex2octets() {
        assert!(::hex2octets(String::from("0").into_bytes()) == vec![0u8]);
        assert!(::hex2octets(String::from("a").into_bytes()) == vec![10u8]);
        assert!(::hex2octets(String::from("10").into_bytes()) == vec![16u8]);
        assert!(::hex2octets(String::from("1a").into_bytes()) == vec![26u8]);
        assert!(::hex2octets(String::from("100").into_bytes()) == vec![1u8, 0u8]);
        assert!(::hex2octets(String::from("1a00").into_bytes()) == vec![26u8, 0u8]);
        assert!(::hex2octets(String::from("12345").into_bytes()) == vec![1u8, 35u8, 69u8]);

    }

    #[test]
    fn test_octets2base64() {
        assert!(::octets2base64(vec![0u8]) == vec!['A' as u8, 'A' as u8, '=' as u8, '=' as u8]);
        assert!(::octets2base64(vec![128u8]).len() == 4);
        assert!(::octets2base64(vec![128u8]) == vec!['g' as u8, 'A' as u8, '=' as u8, '=' as u8]);
        assert!(::octets2base64(vec![0u8, 0u8]) == vec!['A' as u8, 'A' as u8, 'A' as u8, '=' as u8]);
        assert!(::octets2base64(vec![1u8, 35u8, 69u8]) == vec!['A' as u8, 'A' as u8, 'A' as u8, 'A' as u8]);

    }
}

fn main() -> () {
    let base64 = hex2base64(String::from("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d").into_bytes());
    println!("{}", String::from_utf8(base64).unwrap());
}<|endoftext|>


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

use hir::def_id::CrateNum;
use std::fmt::Debug;
use std::sync::Arc;

macro_rules! try_opt {
    ($e:expr) => (
        match $e {
            Some(r) => r,
            None => return None,
        }
    )
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
pub enum DepNode<D: Clone + Debug> {
    // The `D` type is "how definitions are identified".
    // During compilation, it is always `DefId`, but when serializing
    // it is mapped to `DefPath`.

    // Represents the `Krate` as a whole (the `hir::Krate` value) (as
    // distinct from the krate module). This is basically a hash of
    // the entire krate, so if you read from `Krate` (e.g., by calling
    // `tcx.hir.krate()`), we will have to assume that any change
    // means that you need to be recompiled. This is because the
    // `Krate` value gives you access to all other items. To avoid
    // this fate, do not call `tcx.hir.krate()`; instead, prefer
    // wrappers like `tcx.visit_all_items_in_krate()`.  If there is no
    // suitable wrapper, you can use `tcx.dep_graph.ignore()` to gain
    // access to the krate, but you must remember to add suitable
    // edges yourself for the individual items that you read.
    Krate,

    // Represents the HIR node with the given node-id
    Hir(D),

    // Represents the body of a function or method. The def-id is that of the
    // function/method.
    HirBody(D),

    // Represents the metadata for a given HIR node, typically found
    // in an extern crate.
    MetaData(D),

    // Represents some piece of metadata global to its crate.
    GlobalMetaData(D, GlobalMetaDataKind),

    // Represents some artifact that we save to disk. Note that these
    // do not have a def-id as part of their identifier.
    WorkProduct(Arc<WorkProductId>),

    // Represents different phases in the compiler.
    RegionMaps(D),
    Coherence,
    Resolve,
    CoherenceCheckTrait(D),
    CoherenceCheckImpl(D),
    CoherenceOverlapCheck(D),
    CoherenceOverlapCheckSpecial(D),
    Variance,
    PrivacyAccessLevels(CrateNum),

    // Represents the MIR for a fn; also used as the task node for
    // things read/modify that MIR.
    MirKrate,
    Mir(D),
    MirShim(Vec<D>),

    BorrowCheckKrate,
    BorrowCheck(D),
    RvalueCheck(D),
    Reachability,
    MirKeys,
    LateLintCheck,
    TransCrateItem(D),
    TransWriteMetadata,
    CrateVariances,

    // Nodes representing bits of computed IR in the tcx. Each shared
    // table in the tcx (or elsewhere) maps to one of these
    // nodes. Often we map multiple tables to the same node if there
    // is no point in distinguishing them (e.g., both the type and
    // predicates for an item wind up in `ItemSignature`).
    AssociatedItems(D),
    ItemSignature(D),
    ItemVarianceConstraints(D),
    ItemVariances(D),
    IsForeignItem(D),
    TypeParamPredicates((D, D)),
    SizedConstraint(D),
    DtorckConstraint(D),
    AdtDestructor(D),
    AssociatedItemDefIds(D),
    InherentImpls(D),
    TypeckBodiesKrate,
    TypeckTables(D),
    UsedTraitImports(D),
    ConstEval(D),
    SymbolName(D),
    SpecializationGraph(D),
    ObjectSafety(D),
    IsCopy(D),
    IsSized(D),
    IsFreeze(D),
    NeedsDrop(D),
    Layout(D),

    // The set of impls for a given trait. Ultimately, it would be
    // nice to get more fine-grained here (e.g., to include a
    // simplified type), but we can't do that until we restructure the
    // HIR to distinguish the *header* of an impl from its body.  This
    // is because changes to the header may change the self-type of
    // the impl and hence would require us to be more conservative
    // than changes in the impl body.
    TraitImpls(D),

    AllLocalTraitImpls,

    // Nodes representing caches. To properly handle a true cache, we
    // don't use a DepTrackingMap, but rather we push a task node.
    // Otherwise the write into the map would be incorrectly
    // attributed to the first task that happened to fill the cache,
    // which would yield an overly conservative dep-graph.
    TraitItems(D),
    ReprHints(D),

    // Trait selection cache is a little funny. Given a trait
    // reference like `Foo: SomeTrait<Bar>`, there could be
    // arbitrarily many def-ids to map on in there (e.g., `Foo`,
    // `SomeTrait`, `Bar`). We could have a vector of them, but it
    // requires heap-allocation, and trait sel in general can be a
    // surprisingly hot path. So instead we pick two def-ids: the
    // trait def-id, and the first def-id in the input types. If there
    // is no def-id in the input types, then we use the trait def-id
    // again. So for example:
    //
    // - `i32: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Clone }`
    // - `u32: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Clone }`
    // - `Clone: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Clone }`
    // - `Vec<i32>: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Vec }`
    // - `String: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: String }`
    // - `Foo: Trait<Bar>` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
    // - `Foo: Trait<i32>` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
    // - `(Foo, Bar): Trait` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
    // - `i32: Trait<Foo>` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
    //
    // You can see that we map many trait refs to the same
    // trait-select node.  This is not a problem, it just means
    // imprecision in our dep-graph tracking.  The important thing is
    // that for any given trait-ref, we always map to the **same**
    // trait-select node.
    TraitSelect { trait_def_id: D, input_def_id: D },

    // For proj. cache, we just keep a list of all def-ids, since it is
    // not a hotspot.
    ProjectionCache { def_ids: Vec<D> },

    ParamEnv(D),
    DescribeDef(D),
    DefSpan(D),
    Stability(D),
    Deprecation(D),
    ItemBodyNestedBodies(D),
    ConstIsRvaluePromotableToStatic(D),
    ImplParent(D),
    TraitOfItem(D),
    IsExportedSymbol(D),
    IsMirAvailable(D),
    ItemAttrs(D),
    FnArgNames(D),
}

impl<D: Clone + Debug> DepNode<D> {
    /// Used in testing
    pub fn from_label_string(label: &str, data: D) -> Result<DepNode<D>, ()> {
        macro_rules! check {
            ($($name:ident,)*) => {
                match label {
                    $(stringify!($name) => Ok(DepNode::$name(data)),)*
                    _ => Err(())
                }
            }
        }

        if label == "Krate" {
            // special case
            return Ok(DepNode::Krate);
        }

        check! {
            BorrowCheck,
            Hir,
            HirBody,
            TransCrateItem,
            AssociatedItems,
            ItemSignature,
            ItemVariances,
            IsForeignItem,
            AssociatedItemDefIds,
            InherentImpls,
            TypeckTables,
            UsedTraitImports,
            TraitImpls,
            ReprHints,
        }
    }

    pub fn map_def<E, OP>(&self, mut op: OP) -> Option<DepNode<E>>
        where OP: FnMut(&D) -> Option<E>, E: Clone + Debug
    {
        use self::DepNode::*;

        match *self {
            Krate => Some(Krate),
            BorrowCheckKrate => Some(BorrowCheckKrate),
            MirKrate => Some(MirKrate),
            TypeckBodiesKrate => Some(TypeckBodiesKrate),
            Coherence => Some(Coherence),
            CrateVariances => Some(CrateVariances),
            Resolve => Some(Resolve),
            Variance => Some(Variance),
            PrivacyAccessLevels(k) => Some(PrivacyAccessLevels(k)),
            Reachability => Some(Reachability),
            MirKeys => Some(MirKeys),
            LateLintCheck => Some(LateLintCheck),
            TransWriteMetadata => Some(TransWriteMetadata),

            // work product names do not need to be mapped, because
            // they are always absolute.
            WorkProduct(ref id) => Some(WorkProduct(id.clone())),

            IsCopy(ref d) => op(d).map(IsCopy),
            IsSized(ref d) => op(d).map(IsSized),
            IsFreeze(ref d) => op(d).map(IsFreeze),
            NeedsDrop(ref d) => op(d).map(NeedsDrop),
            Layout(ref d) => op(d).map(Layout),
            Hir(ref d) => op(d).map(Hir),
            HirBody(ref d) => op(d).map(HirBody),
            MetaData(ref d) => op(d).map(MetaData),
            CoherenceCheckTrait(ref d) => op(d).map(CoherenceCheckTrait),
            CoherenceCheckImpl(ref d) => op(d).map(CoherenceCheckImpl),
            CoherenceOverlapCheck(ref d) => op(d).map(CoherenceOverlapCheck),
            CoherenceOverlapCheckSpecial(ref d) => op(d).map(CoherenceOverlapCheckSpecial),
            Mir(ref d) => op(d).map(Mir),
            MirShim(ref def_ids) => {
                let def_ids: Option<Vec<E>> = def_ids.iter().map(op).collect();
                def_ids.map(MirShim)
            }
            BorrowCheck(ref d) => op(d).map(BorrowCheck),
            RegionMaps(ref d) => op(d).map(RegionMaps),
            RvalueCheck(ref d) => op(d).map(RvalueCheck),
            TransCrateItem(ref d) => op(d).map(TransCrateItem),
            AssociatedItems(ref d) => op(d).map(AssociatedItems),
            ItemSignature(ref d) => op(d).map(ItemSignature),
            ItemVariances(ref d) => op(d).map(ItemVariances),
            ItemVarianceConstraints(ref d) => op(d).map(ItemVarianceConstraints),
            IsForeignItem(ref d) => op(d).map(IsForeignItem),
            TypeParamPredicates((ref item, ref param)) => {
                Some(TypeParamPredicates((try_opt!(op(item)), try_opt!(op(param)))))
            }
            SizedConstraint(ref d) => op(d).map(SizedConstraint),
            DtorckConstraint(ref d) => op(d).map(DtorckConstraint),
            AdtDestructor(ref d) => op(d).map(AdtDestructor),
            AssociatedItemDefIds(ref d) => op(d).map(AssociatedItemDefIds),
            InherentImpls(ref d) => op(d).map(InherentImpls),
            TypeckTables(ref d) => op(d).map(TypeckTables),
            UsedTraitImports(ref d) => op(d).map(UsedTraitImports),
            ConstEval(ref d) => op(d).map(ConstEval),
            SymbolName(ref d) => op(d).map(SymbolName),
            SpecializationGraph(ref d) => op(d).map(SpecializationGraph),
            ObjectSafety(ref d) => op(d).map(ObjectSafety),
            TraitImpls(ref d) => op(d).map(TraitImpls),
            AllLocalTraitImpls => Some(AllLocalTraitImpls),
            TraitItems(ref d) => op(d).map(TraitItems),
            ReprHints(ref d) => op(d).map(ReprHints),
            TraitSelect { ref trait_def_id, ref input_def_id } => {
                op(trait_def_id).and_then(|trait_def_id| {
                    op(input_def_id).and_then(|input_def_id| {
                        Some(TraitSelect { trait_def_id: trait_def_id,
                                           input_def_id: input_def_id })
                    })
                })
            }
            ProjectionCache { ref def_ids } => {
                let def_ids: Option<Vec<E>> = def_ids.iter().map(op).collect();
                def_ids.map(|d| ProjectionCache { def_ids: d })
            }
            ParamEnv(ref d) => op(d).map(ParamEnv),
            DescribeDef(ref d) => op(d).map(DescribeDef),
            DefSpan(ref d) => op(d).map(DefSpan),
            Stability(ref d) => op(d).map(Stability),
            Deprecation(ref d) => op(d).map(Deprecation),
            ItemAttrs(ref d) => op(d).map(ItemAttrs),
            FnArgNames(ref d) => op(d).map(FnArgNames),
            ImplParent(ref d) => op(d).map(ImplParent),
            TraitOfItem(ref d) => op(d).map(TraitOfItem),
            IsExportedSymbol(ref d) => op(d).map(IsExportedSymbol),
            ItemBodyNestedBodies(ref d) => op(d).map(ItemBodyNestedBodies),
            ConstIsRvaluePromotableToStatic(ref d) => op(d).map(ConstIsRvaluePromotableToStatic),
            IsMirAvailable(ref d) => op(d).map(IsMirAvailable),
            GlobalMetaData(ref d, kind) => op(d).map(|d| GlobalMetaData(d, kind)),
        }
    }
}

/// A "work product" corresponds to a `.o` (or other) file that we
/// save in between runs. These ids do not have a DefId but rather
/// some independent path or string that persists between runs without
/// the need to be mapped or unmapped. (This ensures we can serialize
/// them even in the absence of a tcx.)
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
pub struct WorkProductId(pub String);

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
pub enum GlobalMetaDataKind {
    Krate,
    CrateDeps,
    DylibDependencyFormats,
    LangItems,
    LangItemsMissing,
    NativeLibraries,
    CodeMap,
    Impls,
    ExportedSymbols,
}
<commit_msg>Make some comments docs in librustc/dep_graph/dep_node.rs<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use hir::def_id::CrateNum;
use std::fmt::Debug;
use std::sync::Arc;

macro_rules! try_opt {
    ($e:expr) => (
        match $e {
            Some(r) => r,
            None => return None,
        }
    )
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
pub enum DepNode<D: Clone + Debug> {
    // The `D` type is "how definitions are identified".
    // During compilation, it is always `DefId`, but when serializing
    // it is mapped to `DefPath`.

    /// Represents the `Krate` as a whole (the `hir::Krate` value) (as
    /// distinct from the krate module). This is basically a hash of
    /// the entire krate, so if you read from `Krate` (e.g., by calling
    /// `tcx.hir.krate()`), we will have to assume that any change
    /// means that you need to be recompiled. This is because the
    /// `Krate` value gives you access to all other items. To avoid
    /// this fate, do not call `tcx.hir.krate()`; instead, prefer
    /// wrappers like `tcx.visit_all_items_in_krate()`.  If there is no
    /// suitable wrapper, you can use `tcx.dep_graph.ignore()` to gain
    /// access to the krate, but you must remember to add suitable
    /// edges yourself for the individual items that you read.
    Krate,

    /// Represents the HIR node with the given node-id
    Hir(D),

    /// Represents the body of a function or method. The def-id is that of the
    /// function/method.
    HirBody(D),

    /// Represents the metadata for a given HIR node, typically found
    /// in an extern crate.
    MetaData(D),

    /// Represents some piece of metadata global to its crate.
    GlobalMetaData(D, GlobalMetaDataKind),

    /// Represents some artifact that we save to disk. Note that these
    /// do not have a def-id as part of their identifier.
    WorkProduct(Arc<WorkProductId>),

    // Represents different phases in the compiler.
    RegionMaps(D),
    Coherence,
    Resolve,
    CoherenceCheckTrait(D),
    CoherenceCheckImpl(D),
    CoherenceOverlapCheck(D),
    CoherenceOverlapCheckSpecial(D),
    Variance,
    PrivacyAccessLevels(CrateNum),

    // Represents the MIR for a fn; also used as the task node for
    // things read/modify that MIR.
    MirKrate,
    Mir(D),
    MirShim(Vec<D>),

    BorrowCheckKrate,
    BorrowCheck(D),
    RvalueCheck(D),
    Reachability,
    MirKeys,
    LateLintCheck,
    TransCrateItem(D),
    TransWriteMetadata,
    CrateVariances,

    // Nodes representing bits of computed IR in the tcx. Each shared
    // table in the tcx (or elsewhere) maps to one of these
    // nodes. Often we map multiple tables to the same node if there
    // is no point in distinguishing them (e.g., both the type and
    // predicates for an item wind up in `ItemSignature`).
    AssociatedItems(D),
    ItemSignature(D),
    ItemVarianceConstraints(D),
    ItemVariances(D),
    IsForeignItem(D),
    TypeParamPredicates((D, D)),
    SizedConstraint(D),
    DtorckConstraint(D),
    AdtDestructor(D),
    AssociatedItemDefIds(D),
    InherentImpls(D),
    TypeckBodiesKrate,
    TypeckTables(D),
    UsedTraitImports(D),
    ConstEval(D),
    SymbolName(D),
    SpecializationGraph(D),
    ObjectSafety(D),
    IsCopy(D),
    IsSized(D),
    IsFreeze(D),
    NeedsDrop(D),
    Layout(D),

    /// The set of impls for a given trait. Ultimately, it would be
    /// nice to get more fine-grained here (e.g., to include a
    /// simplified type), but we can't do that until we restructure the
    /// HIR to distinguish the *header* of an impl from its body.  This
    /// is because changes to the header may change the self-type of
    /// the impl and hence would require us to be more conservative
    /// than changes in the impl body.
    TraitImpls(D),

    AllLocalTraitImpls,

    // Nodes representing caches. To properly handle a true cache, we
    // don't use a DepTrackingMap, but rather we push a task node.
    // Otherwise the write into the map would be incorrectly
    // attributed to the first task that happened to fill the cache,
    // which would yield an overly conservative dep-graph.
    TraitItems(D),
    ReprHints(D),

    /// Trait selection cache is a little funny. Given a trait
    /// reference like `Foo: SomeTrait<Bar>`, there could be
    /// arbitrarily many def-ids to map on in there (e.g., `Foo`,
    /// `SomeTrait`, `Bar`). We could have a vector of them, but it
    /// requires heap-allocation, and trait sel in general can be a
    /// surprisingly hot path. So instead we pick two def-ids: the
    /// trait def-id, and the first def-id in the input types. If there
    /// is no def-id in the input types, then we use the trait def-id
    /// again. So for example:
    ///
    /// - `i32: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Clone }`
    /// - `u32: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Clone }`
    /// - `Clone: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Clone }`
    /// - `Vec<i32>: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: Vec }`
    /// - `String: Clone` -> `TraitSelect { trait_def_id: Clone, self_def_id: String }`
    /// - `Foo: Trait<Bar>` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
    /// - `Foo: Trait<i32>` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
    /// - `(Foo, Bar): Trait` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
    /// - `i32: Trait<Foo>` -> `TraitSelect { trait_def_id: Trait, self_def_id: Foo }`
    ///
    /// You can see that we map many trait refs to the same
    /// trait-select node.  This is not a problem, it just means
    /// imprecision in our dep-graph tracking.  The important thing is
    /// that for any given trait-ref, we always map to the **same**
    /// trait-select node.
    TraitSelect { trait_def_id: D, input_def_id: D },

    /// For proj. cache, we just keep a list of all def-ids, since it is
    /// not a hotspot.
    ProjectionCache { def_ids: Vec<D> },

    ParamEnv(D),
    DescribeDef(D),
    DefSpan(D),
    Stability(D),
    Deprecation(D),
    ItemBodyNestedBodies(D),
    ConstIsRvaluePromotableToStatic(D),
    ImplParent(D),
    TraitOfItem(D),
    IsExportedSymbol(D),
    IsMirAvailable(D),
    ItemAttrs(D),
    FnArgNames(D),
}

impl<D: Clone + Debug> DepNode<D> {
    /// Used in testing
    pub fn from_label_string(label: &str, data: D) -> Result<DepNode<D>, ()> {
        macro_rules! check {
            ($($name:ident,)*) => {
                match label {
                    $(stringify!($name) => Ok(DepNode::$name(data)),)*
                    _ => Err(())
                }
            }
        }

        if label == "Krate" {
            // special case
            return Ok(DepNode::Krate);
        }

        check! {
            BorrowCheck,
            Hir,
            HirBody,
            TransCrateItem,
            AssociatedItems,
            ItemSignature,
            ItemVariances,
            IsForeignItem,
            AssociatedItemDefIds,
            InherentImpls,
            TypeckTables,
            UsedTraitImports,
            TraitImpls,
            ReprHints,
        }
    }

    pub fn map_def<E, OP>(&self, mut op: OP) -> Option<DepNode<E>>
        where OP: FnMut(&D) -> Option<E>, E: Clone + Debug
    {
        use self::DepNode::*;

        match *self {
            Krate => Some(Krate),
            BorrowCheckKrate => Some(BorrowCheckKrate),
            MirKrate => Some(MirKrate),
            TypeckBodiesKrate => Some(TypeckBodiesKrate),
            Coherence => Some(Coherence),
            CrateVariances => Some(CrateVariances),
            Resolve => Some(Resolve),
            Variance => Some(Variance),
            PrivacyAccessLevels(k) => Some(PrivacyAccessLevels(k)),
            Reachability => Some(Reachability),
            MirKeys => Some(MirKeys),
            LateLintCheck => Some(LateLintCheck),
            TransWriteMetadata => Some(TransWriteMetadata),

            // work product names do not need to be mapped, because
            // they are always absolute.
            WorkProduct(ref id) => Some(WorkProduct(id.clone())),

            IsCopy(ref d) => op(d).map(IsCopy),
            IsSized(ref d) => op(d).map(IsSized),
            IsFreeze(ref d) => op(d).map(IsFreeze),
            NeedsDrop(ref d) => op(d).map(NeedsDrop),
            Layout(ref d) => op(d).map(Layout),
            Hir(ref d) => op(d).map(Hir),
            HirBody(ref d) => op(d).map(HirBody),
            MetaData(ref d) => op(d).map(MetaData),
            CoherenceCheckTrait(ref d) => op(d).map(CoherenceCheckTrait),
            CoherenceCheckImpl(ref d) => op(d).map(CoherenceCheckImpl),
            CoherenceOverlapCheck(ref d) => op(d).map(CoherenceOverlapCheck),
            CoherenceOverlapCheckSpecial(ref d) => op(d).map(CoherenceOverlapCheckSpecial),
            Mir(ref d) => op(d).map(Mir),
            MirShim(ref def_ids) => {
                let def_ids: Option<Vec<E>> = def_ids.iter().map(op).collect();
                def_ids.map(MirShim)
            }
            BorrowCheck(ref d) => op(d).map(BorrowCheck),
            RegionMaps(ref d) => op(d).map(RegionMaps),
            RvalueCheck(ref d) => op(d).map(RvalueCheck),
            TransCrateItem(ref d) => op(d).map(TransCrateItem),
            AssociatedItems(ref d) => op(d).map(AssociatedItems),
            ItemSignature(ref d) => op(d).map(ItemSignature),
            ItemVariances(ref d) => op(d).map(ItemVariances),
            ItemVarianceConstraints(ref d) => op(d).map(ItemVarianceConstraints),
            IsForeignItem(ref d) => op(d).map(IsForeignItem),
            TypeParamPredicates((ref item, ref param)) => {
                Some(TypeParamPredicates((try_opt!(op(item)), try_opt!(op(param)))))
            }
            SizedConstraint(ref d) => op(d).map(SizedConstraint),
            DtorckConstraint(ref d) => op(d).map(DtorckConstraint),
            AdtDestructor(ref d) => op(d).map(AdtDestructor),
            AssociatedItemDefIds(ref d) => op(d).map(AssociatedItemDefIds),
            InherentImpls(ref d) => op(d).map(InherentImpls),
            TypeckTables(ref d) => op(d).map(TypeckTables),
            UsedTraitImports(ref d) => op(d).map(UsedTraitImports),
            ConstEval(ref d) => op(d).map(ConstEval),
            SymbolName(ref d) => op(d).map(SymbolName),
            SpecializationGraph(ref d) => op(d).map(SpecializationGraph),
            ObjectSafety(ref d) => op(d).map(ObjectSafety),
            TraitImpls(ref d) => op(d).map(TraitImpls),
            AllLocalTraitImpls => Some(AllLocalTraitImpls),
            TraitItems(ref d) => op(d).map(TraitItems),
            ReprHints(ref d) => op(d).map(ReprHints),
            TraitSelect { ref trait_def_id, ref input_def_id } => {
                op(trait_def_id).and_then(|trait_def_id| {
                    op(input_def_id).and_then(|input_def_id| {
                        Some(TraitSelect { trait_def_id: trait_def_id,
                                           input_def_id: input_def_id })
                    })
                })
            }
            ProjectionCache { ref def_ids } => {
                let def_ids: Option<Vec<E>> = def_ids.iter().map(op).collect();
                def_ids.map(|d| ProjectionCache { def_ids: d })
            }
            ParamEnv(ref d) => op(d).map(ParamEnv),
            DescribeDef(ref d) => op(d).map(DescribeDef),
            DefSpan(ref d) => op(d).map(DefSpan),
            Stability(ref d) => op(d).map(Stability),
            Deprecation(ref d) => op(d).map(Deprecation),
            ItemAttrs(ref d) => op(d).map(ItemAttrs),
            FnArgNames(ref d) => op(d).map(FnArgNames),
            ImplParent(ref d) => op(d).map(ImplParent),
            TraitOfItem(ref d) => op(d).map(TraitOfItem),
            IsExportedSymbol(ref d) => op(d).map(IsExportedSymbol),
            ItemBodyNestedBodies(ref d) => op(d).map(ItemBodyNestedBodies),
            ConstIsRvaluePromotableToStatic(ref d) => op(d).map(ConstIsRvaluePromotableToStatic),
            IsMirAvailable(ref d) => op(d).map(IsMirAvailable),
            GlobalMetaData(ref d, kind) => op(d).map(|d| GlobalMetaData(d, kind)),
        }
    }
}

/// A "work product" corresponds to a `.o` (or other) file that we
/// save in between runs. These ids do not have a DefId but rather
/// some independent path or string that persists between runs without
/// the need to be mapped or unmapped. (This ensures we can serialize
/// them even in the absence of a tcx.)
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
pub struct WorkProductId(pub String);

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)]
pub enum GlobalMetaDataKind {
    Krate,
    CrateDeps,
    DylibDependencyFormats,
    LangItems,
    LangItemsMissing,
    NativeLibraries,
    CodeMap,
    Impls,
    ExportedSymbols,
}
<|endoftext|>


<commit_before>//! This module contains the `EvalContext` methods for executing a single step of the interpreter.
//!
//! The main entry point is the `step` method.

use rustc::mir;

use rustc::mir::interpret::EvalResult;
use super::{EvalContext, Machine};

impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
    pub fn inc_step_counter_and_check_limit(&mut self, n: usize) {
        self.terminators_remaining = self.terminators_remaining.saturating_sub(n);
        if self.terminators_remaining == 0 {
            self.tcx.sess.span_warn(self.frame().span, "Constant evaluating a complex constant, this might take some time");
            self.terminators_remaining = 1_000_000;
        }
    }

    /// Returns true as long as there are more things to do.
    pub fn step(&mut self) -> EvalResult<'tcx, bool> {
        if self.stack.is_empty() {
            return Ok(false);
        }

        let block = self.frame().block;
        let stmt_id = self.frame().stmt;
        let mir = self.mir();
        let basic_block = &mir.basic_blocks()[block];

        let old_frames = self.cur_frame();

        if let Some(stmt) = basic_block.statements.get(stmt_id) {
            assert_eq!(old_frames, self.cur_frame());
            self.statement(stmt)?;
            return Ok(true);
        }

        self.inc_step_counter_and_check_limit(1);

        let terminator = basic_block.terminator();
        assert_eq!(old_frames, self.cur_frame());
        self.terminator(terminator)?;
        Ok(true)
    }

    fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> EvalResult<'tcx> {
        trace!("{:?}", stmt);

        use rustc::mir::StatementKind::*;

        // Some statements (e.g. box) push new stack frames.  We have to record the stack frame number
        // *before* executing the statement.
        let frame_idx = self.cur_frame();
        self.tcx.span = stmt.source_info.span;
        self.memory.tcx.span = stmt.source_info.span;

        match stmt.kind {
            Assign(ref place, ref rvalue) => self.eval_rvalue_into_place(rvalue, place)?,

            SetDiscriminant {
                ref place,
                variant_index,
            } => {
                let dest = self.eval_place(place)?;
                let dest_ty = self.place_ty(place);
                self.write_discriminant_value(dest_ty, dest, variant_index)?;
            }

            // Mark locals as alive
            StorageLive(local) => {
                let old_val = self.frame_mut().storage_live(local);
                self.deallocate_local(old_val)?;
            }

            // Mark locals as dead
            StorageDead(local) => {
                let old_val = self.frame_mut().storage_dead(local);
                self.deallocate_local(old_val)?;
            }

            // Validity checks.
            Validate(op, ref places) => {
                for operand in places {
                    M::validation_op(self, op, operand)?;
                }
            }
            EndRegion(ce) => {
                M::end_region(self, Some(ce))?;
            }

            UserAssertTy(..) => {}

            // Defined to do nothing. These are added by optimization passes, to avoid changing the
            // size of MIR constantly.
            Nop => {}

            InlineAsm { .. } => return err!(InlineAsm),
        }

        self.stack[frame_idx].stmt += 1;
        Ok(())
    }

    fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> EvalResult<'tcx> {
        trace!("{:?}", terminator.kind);
        self.tcx.span = terminator.source_info.span;
        self.memory.tcx.span = terminator.source_info.span;
        self.eval_terminator(terminator)?;
        if !self.stack.is_empty() {
            trace!("// {:?}", self.frame().block);
        }
        Ok(())
    }
}
<commit_msg>Add a tracking issue for making the warning a lint<commit_after>//! This module contains the `EvalContext` methods for executing a single step of the interpreter.
//!
//! The main entry point is the `step` method.

use rustc::mir;

use rustc::mir::interpret::EvalResult;
use super::{EvalContext, Machine};

impl<'a, 'mir, 'tcx, M: Machine<'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
    pub fn inc_step_counter_and_check_limit(&mut self, n: usize) {
        self.terminators_remaining = self.terminators_remaining.saturating_sub(n);
        if self.terminators_remaining == 0 {
            // FIXME(#49980): make this warning a lint
            self.tcx.sess.span_warn(self.frame().span, "Constant evaluating a complex constant, this might take some time");
            self.terminators_remaining = 1_000_000;
        }
    }

    /// Returns true as long as there are more things to do.
    pub fn step(&mut self) -> EvalResult<'tcx, bool> {
        if self.stack.is_empty() {
            return Ok(false);
        }

        let block = self.frame().block;
        let stmt_id = self.frame().stmt;
        let mir = self.mir();
        let basic_block = &mir.basic_blocks()[block];

        let old_frames = self.cur_frame();

        if let Some(stmt) = basic_block.statements.get(stmt_id) {
            assert_eq!(old_frames, self.cur_frame());
            self.statement(stmt)?;
            return Ok(true);
        }

        self.inc_step_counter_and_check_limit(1);

        let terminator = basic_block.terminator();
        assert_eq!(old_frames, self.cur_frame());
        self.terminator(terminator)?;
        Ok(true)
    }

    fn statement(&mut self, stmt: &mir::Statement<'tcx>) -> EvalResult<'tcx> {
        trace!("{:?}", stmt);

        use rustc::mir::StatementKind::*;

        // Some statements (e.g. box) push new stack frames.  We have to record the stack frame number
        // *before* executing the statement.
        let frame_idx = self.cur_frame();
        self.tcx.span = stmt.source_info.span;
        self.memory.tcx.span = stmt.source_info.span;

        match stmt.kind {
            Assign(ref place, ref rvalue) => self.eval_rvalue_into_place(rvalue, place)?,

            SetDiscriminant {
                ref place,
                variant_index,
            } => {
                let dest = self.eval_place(place)?;
                let dest_ty = self.place_ty(place);
                self.write_discriminant_value(dest_ty, dest, variant_index)?;
            }

            // Mark locals as alive
            StorageLive(local) => {
                let old_val = self.frame_mut().storage_live(local);
                self.deallocate_local(old_val)?;
            }

            // Mark locals as dead
            StorageDead(local) => {
                let old_val = self.frame_mut().storage_dead(local);
                self.deallocate_local(old_val)?;
            }

            // Validity checks.
            Validate(op, ref places) => {
                for operand in places {
                    M::validation_op(self, op, operand)?;
                }
            }
            EndRegion(ce) => {
                M::end_region(self, Some(ce))?;
            }

            UserAssertTy(..) => {}

            // Defined to do nothing. These are added by optimization passes, to avoid changing the
            // size of MIR constantly.
            Nop => {}

            InlineAsm { .. } => return err!(InlineAsm),
        }

        self.stack[frame_idx].stmt += 1;
        Ok(())
    }

    fn terminator(&mut self, terminator: &mir::Terminator<'tcx>) -> EvalResult<'tcx> {
        trace!("{:?}", terminator.kind);
        self.tcx.span = terminator.source_info.span;
        self.memory.tcx.span = terminator.source_info.span;
        self.eval_terminator(terminator)?;
        if !self.stack.is_empty() {
            trace!("// {:?}", self.frame().block);
        }
        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>Add LU decomposition<commit_after>const IM: i64 = 139968;
const IA: i64 = 3877;
const IC: i64 = 29573;
static mut last: i64 = 42;

const MAT_SIZE: usize = 1500;

fn main() {
	let mut a: Vec<Vec<f32>> = Vec::with_capacity(MAT_SIZE);
	let mut l: Vec<Vec<f32>> = Vec::with_capacity(MAT_SIZE);
	let mut u: Vec<Vec<f32>> = Vec::with_capacity(MAT_SIZE);

	a.extend(std::iter::repeat(Vec::with_capacity(MAT_SIZE)).take(MAT_SIZE));
	l.extend(std::iter::repeat(Vec::with_capacity(MAT_SIZE)).take(MAT_SIZE));
	u.extend(std::iter::repeat(Vec::with_capacity(MAT_SIZE)).take(MAT_SIZE));

	unsafe {
		for i in 0..MAT_SIZE {
			for _ in 0..MAT_SIZE {
				a[i].push(gen_random(1.0));
			}
		}
	}
	lu(&a, &mut l, &mut u);
	println!("{}, {}", l[25][25], u[25][25]);
}

fn lu(a: & Vec<Vec<f32>>, l: &mut Vec<Vec<f32>>, u: &mut Vec<Vec<f32>>) {
	for i in 0..MAT_SIZE {
		for j in 0..MAT_SIZE {
			if j < i {
				l[j].push(0.0);
			} else {
				l[j].push(a[j][i]);
				for k in 0..i {
					l[j][i] = l[j][i] - l[j][k] * u[k][i];
				}
			}
		}
		for j in 0..MAT_SIZE {
			if j < i {
				u[i].push(0.0);
			} else if j == i {
				u[i].push(1.0);
			} else {
				u[i].push(a[i][j] / l[i][i]);
				for k in 0..i {
					u[i][j] = u[i][j] - ((l[i][k] * u[k][j]) / l[i][i]);
				}
			}
		}
	}
}

unsafe fn gen_random(max: f32) -> f32 {
	last = (last * IA + IC) % IM;
	max * (last as f32) / (IM as f32)
}<|endoftext|>


<commit_before><commit_msg>Added Rust implementation<commit_after>use std::time::duration::Duration;

fn main() {
    let duration = Duration::span(|| {
        let n: i32 = 10000000;
        let mut h: Vec<i32> = (0..n).collect();

        make_heap(&mut *h);

        for i in (1..n as usize).rev() {
            h.swap(0, i);
            push_down(0, i, &mut *h);
        }

        for (elt, i) in h.iter().zip(0..n) {
            assert!(*elt == i);
        }
    });
    println!("Done in {}", duration.num_milliseconds());
}

fn make_heap(h: &mut [i32]) {
    for i in (0..h.len() / 2).rev() {
        push_down(i, h.len(), h);
    }
}

fn push_down(mut pos: usize, size: usize, h: &mut [i32]) {
    while 2 * pos + 1 < size {
        let mut vic = 2 * pos + 1;
        if vic + 1 < size && h[vic + 1] > h[vic] {
            vic += 1;
        }

        if h[pos] > h[vic] {
            break;
        }

        h.swap(pos, vic);
        pos = vic;
    }
}
<|endoftext|>


<commit_before><commit_msg>get informations<commit_after>extern mod std;
use std::getopts::*;
use std::time::*;

fn print_usage(program: &str, _opts: &[std::getopts::Opt]) {
    io::println(fmt!("Usage: %s [options]", program));
    io::println("-o\t\tOutput");
    io::println("-h --help\tUsage");
}

// fn make_absolute(p: &Path) -> Path

fn get_license(args: Option<~str>) -> ~str {
    match args {
        Some(move x) => x.to_lower(),
        None => ~"bsd3"
    }
}

fn get_proj(args: Option<~str>) -> ~str {
    match args {
        Some(move x) => x,
        None => {
            match os::getcwd().filename() {
                Some(dir) => dir,
                None => ~"project"
            }
        }
    }
}

fn get_org(args: Option<~str>) -> ~str {
    match args {
        Some(move x) => x,
            None => {
                match os::getenv("USER") {
                    Some(dir) => dir,
                    None => ~"organization"
                }
            }
        }
}

fn get_year(args: Option<~str>) -> ~str {
    match args {
        Some(move x) => x,
        None => {
            let time = now();
            time.strftime("%Y")
        }
    }
}

fn main() {
    let args = os::args();

    let program = copy args[0];

    let opts = ~[
        optflag("h"),
        optflag("help"),
        optopt("year"),
        optopt("proj"),
        optopt("org"),
        optopt("license")
    ];
    let matches = match getopts(vec::tail(args), opts) {
        result::Ok(m) => { m }
        result::Err(f) => { fail fail_str(f) }
    };
    if opt_present(&matches, "h") || opt_present(&matches, "help") {
        print_usage(program, opts);
        return;
    }
    let year = opt_maybe_str(&matches, "year");
    let proj = opt_maybe_str(&matches, "proj");
    let org = opt_maybe_str(&matches, "org");
    let license = opt_maybe_str(&matches, "license");
    io::println(get_year(year));
    io::println(get_proj(proj));
    io::println(get_org(org));
    io::println(get_license(license));
}<|endoftext|>


<commit_before><commit_msg>rust 3<commit_after>fn smallest_prime_factor(n: u64) -> u64 {
  let mut prime_factor = 2;
  while n % prime_factor != 0 {
    prime_factor += 1;
  }
  prime_factor
}

fn largest_prime_factor(n: u64) -> u64 {
  let m = smallest_prime_factor(n);
  if m == n {
    m
  } else {
    largest_prime_factor(n / m)
  }
}

fn main () {
  println!("{}", largest_prime_factor(600851475143));
}
<|endoftext|>


<commit_before><commit_msg>type annotations<commit_after>fn main() {
    let x: i32 = 5;
    println!("{}", x);
}
<|endoftext|>


<commit_before>extern crate rgtk;

use rgtk::*;
use std::cmp::Ordering;
use std::collections::HashSet;
use std::io::fs;
use std::io::fs::PathExtensions;

fn path_sorter(a: &Path, b: &Path) -> Ordering {
    let leaf_a = a.filename_str();
    let leaf_b = b.filename_str();
    leaf_a.cmp(&leaf_b)
}

fn sort_paths(paths: &Vec<Path>) -> Vec<Path> {
    let mut paths_vec = paths.clone();
    paths_vec.sort_by(path_sorter);
    paths_vec
}

fn sort_string_paths(paths: &HashSet<String>) -> Vec<Path> {
    let mut paths_vec = Vec::new();
    for path in paths.iter() {
        paths_vec.push(Path::new(path));
    }
    paths_vec.sort_by(path_sorter);
    paths_vec
}

fn get_first_path(state: &::utils::State) -> Option<gtk::TreePath> {
    let mut iter = gtk::TreeIter::new().unwrap();
    let model = state.tree_store.get_model().unwrap();

    let path = if model.get_iter_first(&mut iter) {
        model.get_path(&iter)
    } else {
        None
    };

    iter.drop();
    path
}

pub fn update_project_buttons(state: &::utils::State) {
    let path = ::utils::get_selected_path(state);
    state.rename_button.set_sensitive(match path {
        Some(ref path_str) => !Path::new(path_str).is_dir(),
        None => false
    });
    state.remove_button.set_sensitive(path.is_some());
}

fn add_node(
    state: &::utils::State,
    node: &Path,
    parent: Option<&gtk::TreeIter>)
{
    let mut iter = gtk::TreeIter::new().unwrap();

    if let Some(leaf_str) = node.filename_str() {
        if !leaf_str.starts_with(".") {
            state.tree_store.append(&iter, parent);
            state.tree_store.set_string(&iter, 0, leaf_str);
            state.tree_store.set_string(&iter, 1, node.as_str().unwrap());

            if node.is_dir() {
                match fs::readdir(node) {
                    Ok(children) => {
                        for child in sort_paths(&children).iter() {
                            add_node(state, child, Some(&iter));
                        }
                    },
                    Err(e) => println!("Error updating tree: {}", e)
                }
            }
        }
    }

    iter.drop();
}

fn expand_nodes(
    state: &mut ::utils::State,
    tree: &mut gtk::TreeView,
    parent: Option<&gtk::TreeIter>)
{
    let mut iter = gtk::TreeIter::new().unwrap();

    if state.tree_model.iter_children(&mut iter, parent) {
        loop {
            if let Some(path_str) =
                state.tree_model.get_value(&iter, 1).get_string()
            {
                if let Some(selection_str) = state.selection.clone() {
                    if path_str == selection_str {
                        if let Some(path) = state.tree_model.get_path(&iter) {
                            tree.set_cursor(&path, None, false);
                        }
                    }
                }

                if state.expansions.contains(&path_str) {
                    if let Some(path) = state.tree_model.get_path(&iter) {
                        tree.expand_row(&path, false);
                    }
                    expand_nodes(state, tree, Some(&iter));
                }
            }

            if !state.tree_model.iter_next(&mut iter) {
                break;
            }
        }
    }

    iter.drop();
}

pub fn update_project_tree(
    state: &mut ::utils::State,
    tree: &mut gtk::TreeView)
{
    state.tree_store.clear();

    for path in sort_string_paths(&state.projects).iter() {
        add_node(state, path, None);
    }

    expand_nodes(state, tree, None);

    let mut iter = gtk::TreeIter::new().unwrap();
    if !state.tree_selection.get_selected(state.tree_model, &mut iter) {
        if let Some(path) = get_first_path(state) {
            tree.set_cursor(&path, None, false)
        }
    }
    iter.drop();

    update_project_buttons(state);
}
<commit_msg>Improve rename/remove disabling<commit_after>extern crate rgtk;

use rgtk::*;
use std::cmp::Ordering;
use std::collections::HashSet;
use std::io::fs;
use std::io::fs::PathExtensions;

fn path_sorter(a: &Path, b: &Path) -> Ordering {
    let leaf_a = a.filename_str();
    let leaf_b = b.filename_str();
    leaf_a.cmp(&leaf_b)
}

fn sort_paths(paths: &Vec<Path>) -> Vec<Path> {
    let mut paths_vec = paths.clone();
    paths_vec.sort_by(path_sorter);
    paths_vec
}

fn sort_string_paths(paths: &HashSet<String>) -> Vec<Path> {
    let mut paths_vec = Vec::new();
    for path in paths.iter() {
        paths_vec.push(Path::new(path));
    }
    paths_vec.sort_by(path_sorter);
    paths_vec
}

fn get_first_path(state: &::utils::State) -> Option<gtk::TreePath> {
    let mut iter = gtk::TreeIter::new().unwrap();
    let model = state.tree_store.get_model().unwrap();

    let path = if model.get_iter_first(&mut iter) {
        model.get_path(&iter)
    } else {
        None
    };

    iter.drop();
    path
}

pub fn update_project_buttons(state: &::utils::State) {
    if let Some(path_str) = ::utils::get_selected_path(state) {
        let is_project = state.projects.contains(&path_str);
        let path = Path::new(path_str);
        state.rename_button.set_sensitive(!path.is_dir());
        state.remove_button.set_sensitive(!path.is_dir() || is_project);
    } else {
        state.rename_button.set_sensitive(false);
        state.remove_button.set_sensitive(false);
    }
}

fn add_node(
    state: &::utils::State,
    node: &Path,
    parent: Option<&gtk::TreeIter>)
{
    let mut iter = gtk::TreeIter::new().unwrap();

    if let Some(leaf_str) = node.filename_str() {
        if !leaf_str.starts_with(".") {
            state.tree_store.append(&iter, parent);
            state.tree_store.set_string(&iter, 0, leaf_str);
            state.tree_store.set_string(&iter, 1, node.as_str().unwrap());

            if node.is_dir() {
                match fs::readdir(node) {
                    Ok(children) => {
                        for child in sort_paths(&children).iter() {
                            add_node(state, child, Some(&iter));
                        }
                    },
                    Err(e) => println!("Error updating tree: {}", e)
                }
            }
        }
    }

    iter.drop();
}

fn expand_nodes(
    state: &mut ::utils::State,
    tree: &mut gtk::TreeView,
    parent: Option<&gtk::TreeIter>)
{
    let mut iter = gtk::TreeIter::new().unwrap();

    if state.tree_model.iter_children(&mut iter, parent) {
        loop {
            if let Some(path_str) =
                state.tree_model.get_value(&iter, 1).get_string()
            {
                if let Some(selection_str) = state.selection.clone() {
                    if path_str == selection_str {
                        if let Some(path) = state.tree_model.get_path(&iter) {
                            tree.set_cursor(&path, None, false);
                        }
                    }
                }

                if state.expansions.contains(&path_str) {
                    if let Some(path) = state.tree_model.get_path(&iter) {
                        tree.expand_row(&path, false);
                    }
                    expand_nodes(state, tree, Some(&iter));
                }
            }

            if !state.tree_model.iter_next(&mut iter) {
                break;
            }
        }
    }

    iter.drop();
}

pub fn update_project_tree(
    state: &mut ::utils::State,
    tree: &mut gtk::TreeView)
{
    state.tree_store.clear();

    for path in sort_string_paths(&state.projects).iter() {
        add_node(state, path, None);
    }

    expand_nodes(state, tree, None);

    let mut iter = gtk::TreeIter::new().unwrap();
    if !state.tree_selection.get_selected(state.tree_model, &mut iter) {
        if let Some(path) = get_first_path(state) {
            tree.set_cursor(&path, None, false)
        }
    }
    iter.drop();

    update_project_buttons(state);
}
<|endoftext|>


<commit_before><commit_msg>Use vec.last instead of being lame<commit_after><|endoftext|>


<commit_before><commit_msg>Added solution for problem 6.<commit_after>// The sum of the squares of the first ten natural numbers is,
// 12 + 22 + ... + 102 = 385
//
// The square of the sum of the first ten natural numbers is,
// (1 + 2 + ... + 10)2 = 552 = 3025
//
// Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
//
// Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

fn main() {
    let limit = 100;
    let sum: i64 = (0..limit + 1).fold(0, |sum, i| sum + i);
    let squared_sum = sum * sum;
    let sum_squares: i64 = (0..limit + 1).map(|i| i * i).fold(0, |sum, i| sum + i);
    let solution = squared_sum - sum_squares;
    println!("Solution: {}", solution);
}
<|endoftext|>


<commit_before><commit_msg>User stats: direct message = unicode only; public channel = includes custom emoji on the same server<commit_after><|endoftext|>


<commit_before><commit_msg>Trigger needs to be a bitflags because oneshotness is independent from edge/level-triggering apparently<commit_after><|endoftext|>


<commit_before><commit_msg>Fix ordering for pages in 'stats' command<commit_after><|endoftext|>


<commit_before>// A port of task-killjoin to use a class with a dtor to manage
// the join.

use std;
import task;

class notify {
    let ch: comm::chan<bool>; let v: @mut bool;
    new(ch: comm::chan<bool>, v: @mut bool) { self.ch = ch; self.v = v; }
    drop {
        #error["notify: task=%? v=%x unwinding=%b b=%b",
               task::get_task(),
               ptr::addr_of(*(self.v)) as uint,
               task::failing(),
               *(self.v)];
        let b = *(self.v);
        comm::send(self.ch, b);
    }
}

fn joinable(+f: fn~()) -> comm::port<bool> {
    fn wrapper(+c: comm::chan<bool>, +f: fn()) {
        let b = @mut false;
        #error["wrapper: task=%? allocated v=%x",
               task::get_task(),
               ptr::addr_of(*b) as uint];
        let _r = notify(c, b);
        f();
        *b = true;
    }
    let p = comm::port();
    let c = comm::chan(p);
    do task::spawn_unlinked { wrapper(c, copy f) };
    p
}

fn join(port: comm::port<bool>) -> bool {
    comm::recv(port)
}

fn supervised() {
    // Yield to make sure the supervisor joins before we
    // fail. This is currently not needed because the supervisor
    // runs first, but I can imagine that changing.
    #error["supervised task=%?", task::get_task];
    task::yield();
    fail;
}

fn supervisor() {
    #error["supervisor task=%?", task::get_task()];
    let t = joinable(supervised);
    join(t);
}

fn main() {
    join(joinable(supervisor));
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>Oops, xfail-win32 task-killjoin-rsrc<commit_after>// xfail-win32

// A port of task-killjoin to use a class with a dtor to manage
// the join.

use std;
import task;

class notify {
    let ch: comm::chan<bool>; let v: @mut bool;
    new(ch: comm::chan<bool>, v: @mut bool) { self.ch = ch; self.v = v; }
    drop {
        #error["notify: task=%? v=%x unwinding=%b b=%b",
               task::get_task(),
               ptr::addr_of(*(self.v)) as uint,
               task::failing(),
               *(self.v)];
        let b = *(self.v);
        comm::send(self.ch, b);
    }
}

fn joinable(+f: fn~()) -> comm::port<bool> {
    fn wrapper(+c: comm::chan<bool>, +f: fn()) {
        let b = @mut false;
        #error["wrapper: task=%? allocated v=%x",
               task::get_task(),
               ptr::addr_of(*b) as uint];
        let _r = notify(c, b);
        f();
        *b = true;
    }
    let p = comm::port();
    let c = comm::chan(p);
    do task::spawn_unlinked { wrapper(c, copy f) };
    p
}

fn join(port: comm::port<bool>) -> bool {
    comm::recv(port)
}

fn supervised() {
    // Yield to make sure the supervisor joins before we
    // fail. This is currently not needed because the supervisor
    // runs first, but I can imagine that changing.
    #error["supervised task=%?", task::get_task];
    task::yield();
    fail;
}

fn supervisor() {
    #error["supervisor task=%?", task::get_task()];
    let t = joinable(supervised);
    join(t);
}

fn main() {
    join(joinable(supervisor));
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>


<commit_before><commit_msg>Use an empty enum for Void<commit_after><|endoftext|>


<commit_before><commit_msg>Optimize backend impl to not hold open files<commit_after><|endoftext|>


<commit_before><commit_msg>Clarify the idea behind the completeness method<commit_after><|endoftext|>


<commit_before><commit_msg>Implement approximate logarithm of base 2<commit_after><|endoftext|>


<commit_before><commit_msg>Measure throughput of bench_decode_spec_example_full()<commit_after><|endoftext|>