<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// Code to handle a single block device.

use std::fs::OpenOptions;
use std::path::PathBuf;

use devicemapper::Device;
use devicemapper::Segment;
use devicemapper::Sectors;
use time::Timespec;

use super::super::errors::EngineResult;
use super::super::types::{DevUuid, PoolUuid};

use super::metadata::BDA;
use super::range_alloc::RangeAllocator;

#[derive(Debug)]
pub struct BlockDev {
    dev: Device,
    pub devnode: PathBuf,
    bda: BDA,
    used: RangeAllocator,
}

impl BlockDev {
    pub fn new(dev: Device, devnode: PathBuf, bda: BDA, allocator: RangeAllocator) -> BlockDev {
        BlockDev {
            dev: dev,
            devnode: devnode,
            bda: bda,
            used: allocator,
        }
    }

    pub fn wipe_metadata(self) -> EngineResult<()> {
        let mut f = try!(OpenOptions::new().write(true).open(&self.devnode));
        BDA::wipe(&mut f)
    }

    pub fn save_state(&mut self, time: &Timespec, metadata: &[u8]) -> EngineResult<()> {
        let mut f = try!(OpenOptions::new().write(true).open(&self.devnode));
        self.bda.save_state(time, metadata, &mut f)
    }

    pub fn load_state(&self) -> EngineResult<Option<Vec<u8>>> {
        let mut f = try!(OpenOptions::new().read(true).open(&self.devnode));
        self.bda.load_state(&mut f)
    }

    /// List the available-for-upper-layer-use range in this blockdev.
    pub fn avail_range(&self) -> Segment {
        let start = self.bda.size();
        let size = self.size();
        // Blockdev size is at least MIN_DEV_SIZE, so this can fail only if
        // size of metadata area exceeds 1 GiB. Initial metadata area size
        // is 4 MiB.
        assert!(start <= size);
        Segment::new(self.dev, start, size - start)
    }

    /// The device's UUID.
    pub fn uuid(&self) -> &DevUuid {
        self.bda.dev_uuid()
    }

    /// The device's pool's UUID.
    pub fn pool_uuid(&self) -> &PoolUuid {
        self.bda.pool_uuid()
    }

    /// The device's size.
    pub fn size(&self) -> Sectors {
        self.bda.dev_size()
    }

    /// Last time metadata was written to this device.
    pub fn last_update_time(&self) -> Option<&Timespec> {
        self.bda.last_update_time()
    }

    pub fn available(&self) -> Sectors {
        self.used.available()
    }

    // Find some sector ranges that could be allocated. If more
    // sectors are needed than our capacity, return partial results.
    pub fn request_space(&mut self, size: Sectors) -> (Sectors, Vec<Segment>) {
        let (size, segs) = self.used.request(size);
        (size,
         segs.iter()
             .map(|&(start, len)| Segment::new(self.dev, start, len))
             .collect())
    }
}
<commit_msg>Omit unused method<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

// Code to handle a single block device.

use std::fs::OpenOptions;
use std::path::PathBuf;

use devicemapper::Device;
use devicemapper::Segment;
use devicemapper::Sectors;
use time::Timespec;

use super::super::errors::EngineResult;
use super::super::types::{DevUuid, PoolUuid};

use super::metadata::BDA;
use super::range_alloc::RangeAllocator;

#[derive(Debug)]
pub struct BlockDev {
    dev: Device,
    pub devnode: PathBuf,
    bda: BDA,
    used: RangeAllocator,
}

impl BlockDev {
    pub fn new(dev: Device, devnode: PathBuf, bda: BDA, allocator: RangeAllocator) -> BlockDev {
        BlockDev {
            dev: dev,
            devnode: devnode,
            bda: bda,
            used: allocator,
        }
    }

    pub fn wipe_metadata(self) -> EngineResult<()> {
        let mut f = try!(OpenOptions::new().write(true).open(&self.devnode));
        BDA::wipe(&mut f)
    }

    pub fn save_state(&mut self, time: &Timespec, metadata: &[u8]) -> EngineResult<()> {
        let mut f = try!(OpenOptions::new().write(true).open(&self.devnode));
        self.bda.save_state(time, metadata, &mut f)
    }

    /// List the available-for-upper-layer-use range in this blockdev.
    pub fn avail_range(&self) -> Segment {
        let start = self.bda.size();
        let size = self.size();
        // Blockdev size is at least MIN_DEV_SIZE, so this can fail only if
        // size of metadata area exceeds 1 GiB. Initial metadata area size
        // is 4 MiB.
        assert!(start <= size);
        Segment::new(self.dev, start, size - start)
    }

    /// The device's UUID.
    pub fn uuid(&self) -> &DevUuid {
        self.bda.dev_uuid()
    }

    /// The device's pool's UUID.
    pub fn pool_uuid(&self) -> &PoolUuid {
        self.bda.pool_uuid()
    }

    /// The device's size.
    pub fn size(&self) -> Sectors {
        self.bda.dev_size()
    }

    /// Last time metadata was written to this device.
    pub fn last_update_time(&self) -> Option<&Timespec> {
        self.bda.last_update_time()
    }

    pub fn available(&self) -> Sectors {
        self.used.available()
    }

    // Find some sector ranges that could be allocated. If more
    // sectors are needed than our capacity, return partial results.
    pub fn request_space(&mut self, size: Sectors) -> (Sectors, Vec<Segment>) {
        let (size, segs) = self.used.request(size);
        (size,
         segs.iter()
             .map(|&(start, len)| Segment::new(self.dev, start, len))
             .collect())
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix: Make everything cfg(test)<commit_after><|endoftext|>


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

enum Foo {
    Bar = 0xDEADBEE
}

const X: Foo = Bar;

fn main() {
    assert((X as uint) == 0xDEADBEE);
}
<|endoftext|>


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

#![feature(unboxed_closures)]
#![deny(unused_mut)]

// Test that mutating a mutable upvar in a capture-by-value unboxed
// closure does not ice (issue #18238) and marks the upvar as used
// mutably so we do not get a spurious warning about it not needing to
// be declared mutable (issue #18336).

fn main() {
    {
        let mut x = 0u;
        move |&mut:| x += 1;
    }
    {
        let mut x = 0u;
        move |:| x += 1;
    }
}
<|endoftext|>


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

#![feature(const_int_ops)]
#![feature(test)]

extern crate test;
use test::black_box as b;

const BE_U32: u32 = 55u32.to_be();
const LE_U32: u32 = 55u32.to_le();

fn main() {
    assert_eq!(BE_U32, b(55u32).to_be());
    assert_eq!(LE_U32, b(55u32).to_le());

    #[cfg(not(target_arch = "asmjs"))]
    {
        const BE_U128: u128 = 999999u128.to_be();
        const LE_I128: i128 = -999999i128.to_le();
        assert_eq!(BE_U128, b(999999u128).to_be());
        assert_eq!(LE_I128, b(-999999i128).to_le());
    }
}
<commit_msg>run-pass/const-endianness: negate before to_le()<commit_after>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(const_int_ops)]
#![feature(test)]

extern crate test;
use test::black_box as b;

const BE_U32: u32 = 55u32.to_be();
const LE_U32: u32 = 55u32.to_le();

fn main() {
    assert_eq!(BE_U32, b(55u32).to_be());
    assert_eq!(LE_U32, b(55u32).to_le());

    #[cfg(not(target_arch = "asmjs"))]
    {
        const BE_U128: u128 = 999999u128.to_be();
        const LE_I128: i128 = (-999999i128).to_le();
        assert_eq!(BE_U128, b(999999u128).to_be());
        assert_eq!(LE_I128, b(-999999i128).to_le());
    }
}
<|endoftext|>


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

// Detecting lib features (i.e. features that are not lang features).
//
// These are declared using stability attributes (e.g. `#[stable (..)]`
// and `#[unstable (..)]`), but are not declared in one single location
// (unlike lang features), which means we need to collect them instead.

use ty::TyCtxt;
use syntax::symbol::Symbol;
use syntax::ast::{Attribute, MetaItem, MetaItemKind};
use syntax_pos::{Span, DUMMY_SP};
use hir;
use hir::itemlikevisit::ItemLikeVisitor;
use rustc_data_structures::fx::{FxHashSet, FxHashMap};
use errors::DiagnosticId;

pub struct LibFeatures {
    // A map from feature to stabilisation version.
    pub stable: FxHashMap<Symbol, Symbol>,
    pub unstable: FxHashSet<Symbol>,
}

impl LibFeatures {
    fn new() -> LibFeatures {
        LibFeatures {
            stable: FxHashMap(),
            unstable: FxHashSet(),
        }
    }

    pub fn to_vec(&self) -> Vec<(Symbol, Option<Symbol>)> {
        let mut all_features: Vec<_> = self.stable.iter().map(|(f, s)| (*f, Some(*s)))
            .chain(self.unstable.iter().map(|f| (*f, None)))
            .collect();
        all_features.sort_unstable_by_key(|f| f.0.as_str());
        all_features
    }
}

pub struct LibFeatureCollector<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    lib_features: LibFeatures,
}

impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> {
    fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatureCollector<'a, 'tcx> {
        LibFeatureCollector {
            tcx,
            lib_features: LibFeatures::new(),
        }
    }

    fn extract(&self, attrs: &[Attribute]) -> Vec<(Symbol, Option<Symbol>, Span)> {
        let stab_attrs = vec!["stable", "unstable", "rustc_const_unstable"];
        let mut features = vec![];

        for attr in attrs {
            // Find a stability attribute (i.e. `#[stable (..)]`, `#[unstable (..)]`,
            // `#[rustc_const_unstable (..)]`).
            if let Some(stab_attr) = stab_attrs.iter().find(|stab_attr| {
                attr.check_name(stab_attr)
            }) {
                let meta_item = attr.meta();
                if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta_item {
                    let mut feature = None;
                    let mut since = None;
                    for meta in metas {
                        if let Some(mi) = meta.meta_item() {
                            // Find the `feature = ".."` meta-item.
                            match (&*mi.name().as_str(), mi.value_str()) {
                                ("feature", val) => feature = val,
                                ("since", val) => since = val,
                                _ => {}
                            }
                        }
                    }
                    if let Some(feature) = feature {
                        // This additional check for stability is to make sure we
                        // don't emit additional, irrelevant errors for malformed
                        // attributes.
                        if *stab_attr != "stable" || since.is_some() {
                            features.push((feature, since, attr.span));
                        }
                    }
                    // We need to iterate over the other attributes, because
                    // `rustc_const_unstable` is not mutually exclusive with
                    // the other stability attributes, so we can't just `break`
                    // here.
                }
            }
        }

        features
    }

    fn collect_feature(&mut self, feature: Symbol, since: Option<Symbol>, span: Span) {
        let already_in_stable = self.lib_features.stable.contains_key(&feature);
        let already_in_unstable = self.lib_features.unstable.contains(&feature);

        match (since, already_in_stable, already_in_unstable) {
            (Some(since), _, false) => {
                if let Some(prev_since) = self.lib_features.stable.get(&feature) {
                    if *prev_since != since {
                        let msg = format!(
                            "feature `{}` is declared stable since {}, \
                             but was previously declared stable since {}",
                            feature,
                            since,
                            prev_since,
                        );
                        self.tcx.sess.struct_span_err_with_code(span, &msg,
                            DiagnosticId::Error("E0711".into())).emit();
                        return;
                    }
                }

                self.lib_features.stable.insert(feature, since);
            }
            (None, false, _) => {
                self.lib_features.unstable.insert(feature);
            }
            (Some(_), _, true) | (None, true, _) => {
                let msg = format!(
                    "feature `{}` is declared {}, but was previously declared {}",
                    feature,
                    if since.is_some() { "stable"} else { "unstable" },
                    if since.is_none() { "stable"} else { "unstable" },
                );
                self.tcx.sess.struct_span_err_with_code(span, &msg,
                    DiagnosticId::Error("E0711".into())).emit();
            }
        }
    }

    fn collect_from_attrs(&mut self, attrs: &[Attribute]) {
        for (feature, stable, span) in self.extract(attrs) {
            self.collect_feature(feature, stable, span);
        }
    }
}

impl<'a, 'v, 'tcx> ItemLikeVisitor<'v> for LibFeatureCollector<'a, 'tcx> {
    fn visit_item(&mut self, item: &hir::Item) {
        self.collect_from_attrs(&item.attrs);
    }

    fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
        self.collect_from_attrs(&trait_item.attrs);
    }

    fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
        self.collect_from_attrs(&impl_item.attrs);
    }
}

pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatures {
    let mut collector = LibFeatureCollector::new(tcx);
    for &cnum in tcx.crates().iter() {
        for &(feature, since) in tcx.defined_lib_features(cnum).iter() {
            collector.collect_feature(feature, since, DUMMY_SP);
        }
    }
    collector.collect_from_attrs(&tcx.hir.krate().attrs);
    tcx.hir.krate().visit_all_item_likes(&mut collector);
    for exported_macro in &tcx.hir.krate().exported_macros {
        collector.collect_from_attrs(&exported_macro.attrs);
    }
    collector.lib_features
}
<commit_msg>Auto merge of #53397 - varkor:feature-collector-expand-visitor, r=nikomatsakis<commit_after>// Copyright 2018 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.

// Detecting lib features (i.e. features that are not lang features).
//
// These are declared using stability attributes (e.g. `#[stable (..)]`
// and `#[unstable (..)]`), but are not declared in one single location
// (unlike lang features), which means we need to collect them instead.

use ty::TyCtxt;
use syntax::symbol::Symbol;
use syntax::ast::{Attribute, MetaItem, MetaItemKind};
use syntax_pos::{Span, DUMMY_SP};
use hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_data_structures::fx::{FxHashSet, FxHashMap};
use errors::DiagnosticId;

pub struct LibFeatures {
    // A map from feature to stabilisation version.
    pub stable: FxHashMap<Symbol, Symbol>,
    pub unstable: FxHashSet<Symbol>,
}

impl LibFeatures {
    fn new() -> LibFeatures {
        LibFeatures {
            stable: FxHashMap(),
            unstable: FxHashSet(),
        }
    }

    pub fn to_vec(&self) -> Vec<(Symbol, Option<Symbol>)> {
        let mut all_features: Vec<_> = self.stable.iter().map(|(f, s)| (*f, Some(*s)))
            .chain(self.unstable.iter().map(|f| (*f, None)))
            .collect();
        all_features.sort_unstable_by_key(|f| f.0.as_str());
        all_features
    }
}

pub struct LibFeatureCollector<'a, 'tcx: 'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    lib_features: LibFeatures,
}

impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> {
    fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatureCollector<'a, 'tcx> {
        LibFeatureCollector {
            tcx,
            lib_features: LibFeatures::new(),
        }
    }

    fn extract(&self, attr: &Attribute) -> Option<(Symbol, Option<Symbol>, Span)> {
        let stab_attrs = vec!["stable", "unstable", "rustc_const_unstable"];

        // Find a stability attribute (i.e. `#[stable (..)]`, `#[unstable (..)]`,
        // `#[rustc_const_unstable (..)]`).
        if let Some(stab_attr) = stab_attrs.iter().find(|stab_attr| {
            attr.check_name(stab_attr)
        }) {
            let meta_item = attr.meta();
            if let Some(MetaItem { node: MetaItemKind::List(ref metas), .. }) = meta_item {
                let mut feature = None;
                let mut since = None;
                for meta in metas {
                    if let Some(mi) = meta.meta_item() {
                        // Find the `feature = ".."` meta-item.
                        match (&*mi.name().as_str(), mi.value_str()) {
                            ("feature", val) => feature = val,
                            ("since", val) => since = val,
                            _ => {}
                        }
                    }
                }
                if let Some(feature) = feature {
                    // This additional check for stability is to make sure we
                    // don't emit additional, irrelevant errors for malformed
                    // attributes.
                    if *stab_attr != "stable" || since.is_some() {
                        return Some((feature, since, attr.span));
                    }
                }
                // We need to iterate over the other attributes, because
                // `rustc_const_unstable` is not mutually exclusive with
                // the other stability attributes, so we can't just `break`
                // here.
            }
        }

        None
    }

    fn collect_feature(&mut self, feature: Symbol, since: Option<Symbol>, span: Span) {
        let already_in_stable = self.lib_features.stable.contains_key(&feature);
        let already_in_unstable = self.lib_features.unstable.contains(&feature);

        match (since, already_in_stable, already_in_unstable) {
            (Some(since), _, false) => {
                if let Some(prev_since) = self.lib_features.stable.get(&feature) {
                    if *prev_since != since {
                        let msg = format!(
                            "feature `{}` is declared stable since {}, \
                             but was previously declared stable since {}",
                            feature,
                            since,
                            prev_since,
                        );
                        self.tcx.sess.struct_span_err_with_code(span, &msg,
                            DiagnosticId::Error("E0711".into())).emit();
                        return;
                    }
                }

                self.lib_features.stable.insert(feature, since);
            }
            (None, false, _) => {
                self.lib_features.unstable.insert(feature);
            }
            (Some(_), _, true) | (None, true, _) => {
                let msg = format!(
                    "feature `{}` is declared {}, but was previously declared {}",
                    feature,
                    if since.is_some() { "stable"} else { "unstable" },
                    if since.is_none() { "stable"} else { "unstable" },
                );
                self.tcx.sess.struct_span_err_with_code(span, &msg,
                    DiagnosticId::Error("E0711".into())).emit();
            }
        }
    }
}

impl<'a, 'tcx> Visitor<'tcx> for LibFeatureCollector<'a, 'tcx> {
    fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
        NestedVisitorMap::All(&self.tcx.hir)
    }

    fn visit_attribute(&mut self, attr: &'tcx Attribute) {
        if let Some((feature, stable, span)) = self.extract(attr) {
            self.collect_feature(feature, stable, span);
        }
    }
}

pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> LibFeatures {
    let mut collector = LibFeatureCollector::new(tcx);
    for &cnum in tcx.crates().iter() {
        for &(feature, since) in tcx.defined_lib_features(cnum).iter() {
            collector.collect_feature(feature, since, DUMMY_SP);
        }
    }
    intravisit::walk_crate(&mut collector, tcx.hir.krate());
    collector.lib_features
}
<|endoftext|>


<commit_before>use std::ops::{Add, Sub, Mul, Div, Shl, Shr};

macro_rules! wrapping_impl {
    ($trait_name:ident, $method:ident, $t:ty) => {
        impl $trait_name for $t {
            #[inline]
            fn $method(&self, v: &Self) -> Self {
                <$t>::$method(*self, *v)
            }
        }
    };
    ($trait_name:ident, $method:ident, $t:ty, $rhs:ty) => {
        impl $trait_name<$rhs> for $t {
            #[inline]
            fn $method(&self, v: &$rhs) -> Self {
                <$t>::$method(*self, *v)
            }
        }
    }
}

/// Performs addition that wrapps around on overflow.
pub trait WrappingAdd: Sized + Add<Self, Output=Self> {
    /// Wrapping (modular) addition. Computes `self + other`, wrapping around at the boundary of
    /// the type.
    fn wrapping_add(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingAdd, wrapping_add, u8);
wrapping_impl!(WrappingAdd, wrapping_add, u16);
wrapping_impl!(WrappingAdd, wrapping_add, u32);
wrapping_impl!(WrappingAdd, wrapping_add, u64);
wrapping_impl!(WrappingAdd, wrapping_add, usize);

wrapping_impl!(WrappingAdd, wrapping_add, i8);
wrapping_impl!(WrappingAdd, wrapping_add, i16);
wrapping_impl!(WrappingAdd, wrapping_add, i32);
wrapping_impl!(WrappingAdd, wrapping_add, i64);
wrapping_impl!(WrappingAdd, wrapping_add, isize);

/// Performs subtraction that wrapps around on overflow.
pub trait WrappingSub: Sized + Sub<Self, Output=Self> {
    /// Wrapping (modular) subtraction. Computes `self - other`, wrapping around at the boundary
    /// of the type.
    fn wrapping_sub(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingSub, wrapping_sub, u8);
wrapping_impl!(WrappingSub, wrapping_sub, u16);
wrapping_impl!(WrappingSub, wrapping_sub, u32);
wrapping_impl!(WrappingSub, wrapping_sub, u64);
wrapping_impl!(WrappingSub, wrapping_sub, usize);

wrapping_impl!(WrappingSub, wrapping_sub, i8);
wrapping_impl!(WrappingSub, wrapping_sub, i16);
wrapping_impl!(WrappingSub, wrapping_sub, i32);
wrapping_impl!(WrappingSub, wrapping_sub, i64);
wrapping_impl!(WrappingSub, wrapping_sub, isize);

/// Performs multiplication that wrapps around on overflow.
pub trait WrappingMul: Sized + Mul<Self, Output=Self> {
    /// Wrapping (modular) multiplication. Computes `self * other`, wrapping around at the boundary
    /// of the type.
    fn wrapping_mul(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingMul, wrapping_mul, u8);
wrapping_impl!(WrappingMul, wrapping_mul, u16);
wrapping_impl!(WrappingMul, wrapping_mul, u32);
wrapping_impl!(WrappingMul, wrapping_mul, u64);
wrapping_impl!(WrappingMul, wrapping_mul, usize);

wrapping_impl!(WrappingMul, wrapping_mul, i8);
wrapping_impl!(WrappingMul, wrapping_mul, i16);
wrapping_impl!(WrappingMul, wrapping_mul, i32);
wrapping_impl!(WrappingMul, wrapping_mul, i64);
wrapping_impl!(WrappingMul, wrapping_mul, isize);

/// Performs division that wrapps around on overflow.
pub trait WrappingDiv: Sized + Div<Self, Output=Self> {
    /// Wrapping (modular) division. Computes `self / other`, wrapping around at the boundary of
    /// the type.
    ///
    /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type
    /// (where `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a
    /// positive value that is too large to represent in the type. In such a case, this function
    /// returns `MIN` itself.
    ///
    /// # Panics
    ///
    /// This function will panic if rhs is 0.
    fn wrapping_div(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingDiv, wrapping_div, u8);
wrapping_impl!(WrappingDiv, wrapping_div, u16);
wrapping_impl!(WrappingDiv, wrapping_div, u32);
wrapping_impl!(WrappingDiv, wrapping_div, u64);
wrapping_impl!(WrappingDiv, wrapping_div, usize);

wrapping_impl!(WrappingDiv, wrapping_div, i8);
wrapping_impl!(WrappingDiv, wrapping_div, i16);
wrapping_impl!(WrappingDiv, wrapping_div, i32);
wrapping_impl!(WrappingDiv, wrapping_div, i64);
wrapping_impl!(WrappingDiv, wrapping_div, isize);

/// Performs bitwise shift left that wrapps around on overflow.
pub trait WrappingShl<RHS>: Sized + Shl<RHS, Output=Self> {
    /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes any
    /// high-order bits of rhs that would cause the shift to exceed the bitwidth of the type.
    ///
    /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is
    /// restricted to the range of the type, rather than the bits shifted out of the LHS being
    /// returned to the other end. The primitive integer types all implement a `rotate_left`
    /// function, which may be what you want instead.
    fn wrapping_shl(&self, v: &RHS) -> Self;
}

wrapping_impl!(WrappingShl, wrapping_shl, u8, u32);
wrapping_impl!(WrappingShl, wrapping_shl, u16, u32);
wrapping_impl!(WrappingShl, wrapping_shl, u32, u32);
wrapping_impl!(WrappingShl, wrapping_shl, u64, u32);
wrapping_impl!(WrappingShl, wrapping_shl, usize, u32);

wrapping_impl!(WrappingShl, wrapping_shl, i8, u32);
wrapping_impl!(WrappingShl, wrapping_shl, i16, u32);
wrapping_impl!(WrappingShl, wrapping_shl, i32, u32);
wrapping_impl!(WrappingShl, wrapping_shl, i64, u32);
wrapping_impl!(WrappingShl, wrapping_shl, isize, u32);

/// Performs bitwise shift right that wrapps around on overflow.
pub trait WrappingShr<RHS>: Sized + Shr<RHS, Output=Self> {
    /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask` removes any
    /// high-order bits of rhs that would cause the shift to exceed the bitwidth of the type.
    ///
    /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is
    /// restricted to the range of the type, rather than the bits shifted out of the LHS being
    /// returned to the other end. The primitive integer types all implement a `rotate_right`
    /// function, which may be what you want instead.
    fn wrapping_shr(&self, v: &RHS) -> Self;
}

wrapping_impl!(WrappingShr, wrapping_shr, u8, u32);
wrapping_impl!(WrappingShr, wrapping_shr, u16, u32);
wrapping_impl!(WrappingShr, wrapping_shr, u32, u32);
wrapping_impl!(WrappingShr, wrapping_shr, u64, u32);
wrapping_impl!(WrappingShr, wrapping_shr, usize, u32);

wrapping_impl!(WrappingShr, wrapping_shr, i8, u32);
wrapping_impl!(WrappingShr, wrapping_shr, i16, u32);
wrapping_impl!(WrappingShr, wrapping_shr, i32, u32);
wrapping_impl!(WrappingShr, wrapping_shr, i64, u32);
wrapping_impl!(WrappingShr, wrapping_shr, isize, u32);
<commit_msg>Ensure compatibility with Rust 1.0.0.<commit_after>use std::ops::{Add, Sub, Mul};

macro_rules! wrapping_impl {
    ($trait_name:ident, $method:ident, $t:ty) => {
        impl $trait_name for $t {
            #[inline]
            fn $method(&self, v: &Self) -> Self {
                <$t>::$method(*self, *v)
            }
        }
    };
    ($trait_name:ident, $method:ident, $t:ty, $rhs:ty) => {
        impl $trait_name<$rhs> for $t {
            #[inline]
            fn $method(&self, v: &$rhs) -> Self {
                <$t>::$method(*self, *v)
            }
        }
    }
}

/// Performs addition that wrapps around on overflow.
pub trait WrappingAdd: Sized + Add<Self, Output=Self> {
    /// Wrapping (modular) addition. Computes `self + other`, wrapping around at the boundary of
    /// the type.
    fn wrapping_add(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingAdd, wrapping_add, u8);
wrapping_impl!(WrappingAdd, wrapping_add, u16);
wrapping_impl!(WrappingAdd, wrapping_add, u32);
wrapping_impl!(WrappingAdd, wrapping_add, u64);
wrapping_impl!(WrappingAdd, wrapping_add, usize);

wrapping_impl!(WrappingAdd, wrapping_add, i8);
wrapping_impl!(WrappingAdd, wrapping_add, i16);
wrapping_impl!(WrappingAdd, wrapping_add, i32);
wrapping_impl!(WrappingAdd, wrapping_add, i64);
wrapping_impl!(WrappingAdd, wrapping_add, isize);

/// Performs subtraction that wrapps around on overflow.
pub trait WrappingSub: Sized + Sub<Self, Output=Self> {
    /// Wrapping (modular) subtraction. Computes `self - other`, wrapping around at the boundary
    /// of the type.
    fn wrapping_sub(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingSub, wrapping_sub, u8);
wrapping_impl!(WrappingSub, wrapping_sub, u16);
wrapping_impl!(WrappingSub, wrapping_sub, u32);
wrapping_impl!(WrappingSub, wrapping_sub, u64);
wrapping_impl!(WrappingSub, wrapping_sub, usize);

wrapping_impl!(WrappingSub, wrapping_sub, i8);
wrapping_impl!(WrappingSub, wrapping_sub, i16);
wrapping_impl!(WrappingSub, wrapping_sub, i32);
wrapping_impl!(WrappingSub, wrapping_sub, i64);
wrapping_impl!(WrappingSub, wrapping_sub, isize);

/// Performs multiplication that wrapps around on overflow.
pub trait WrappingMul: Sized + Mul<Self, Output=Self> {
    /// Wrapping (modular) multiplication. Computes `self * other`, wrapping around at the boundary
    /// of the type.
    fn wrapping_mul(&self, v: &Self) -> Self;
}

wrapping_impl!(WrappingMul, wrapping_mul, u8);
wrapping_impl!(WrappingMul, wrapping_mul, u16);
wrapping_impl!(WrappingMul, wrapping_mul, u32);
wrapping_impl!(WrappingMul, wrapping_mul, u64);
wrapping_impl!(WrappingMul, wrapping_mul, usize);

wrapping_impl!(WrappingMul, wrapping_mul, i8);
wrapping_impl!(WrappingMul, wrapping_mul, i16);
wrapping_impl!(WrappingMul, wrapping_mul, i32);
wrapping_impl!(WrappingMul, wrapping_mul, i64);
wrapping_impl!(WrappingMul, wrapping_mul, isize);
<|endoftext|>


<commit_before><commit_msg>Initial version of the client<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

#![crate_name="thrift-client"]
#![crate_type="bin"]

#[allow(dead_code)]
struct ThriftBinaryProtocol {
    x: i32,
}

impl ThriftBinaryProtocol {

    fn new() -> ThriftBinaryProtocol {
        ThriftBinaryProtocol { x: 0 }
    }

    fn write_message_begin(&self, name: &str, message_type: i32, seq_id: i32) -> i32 {
        println!("Protocol: message begin");

        // TODO: strict write
        let mut wsize: i32 = 0;
        wsize += self.write_string(name);
        wsize += self.write_byte(message_type as i8);
        wsize += self.write_i32(seq_id);
        wsize
    }

    fn write_string(&self, s: &str) -> i32 {
        println!("Protocol: {}", s);
        s.len() as i32
    }

    fn write_byte(&self, b: i8) -> i32 {
        println!("Protocol: {}", b);
        1
    }

    fn write_i32(&self, i: i32) -> i32 {
        println!("Protocol: {}", i);
        4
    }

    fn write_message_end(&self) {
        println!("Protocol: end");
    }
}

#[allow(dead_code)]
struct CalculatorPingArgs {
    dummy: i32  // TODO
}

impl CalculatorPingArgs {

    fn new() -> CalculatorPingArgs {
        CalculatorPingArgs { dummy: 1 }
    }

    fn write(&self, oprot: &ThriftBinaryProtocol) {
        println!("CalculatorPingArgs::write");
    }
}

#[allow(dead_code)]
struct CalculatorClient {
    oprotocol: ThriftBinaryProtocol,
    iprotocol: ThriftBinaryProtocol,
}

impl CalculatorClient {

    fn new(protocol: ThriftBinaryProtocol) -> CalculatorClient {
        CalculatorClient { oprotocol: protocol, iprotocol: protocol }
    }

    fn ping(&self) {
        self.send_ping();
        self.receive_ping();
    }

    fn send_ping(&self) {
        let cseqid: i32 = 0;
        let T_CALL = 0; // TODO
        self.oprotocol.write_message_begin("ping", T_CALL, cseqid);

        let args = CalculatorPingArgs::new();
        args.write(&self.oprotocol);

        self.oprotocol.write_message_end();
        // TODO:
//        self.oprotocol.get_transport().write_end();
//        self.oprotocol.get_transport().flush();
    }

    fn receive_ping(&self) {
        // TODO
    }
}

pub fn main() {
    //let socket = ThriftSocket::new("localhost", 9090);
    //let transport = ThriftBufferedTransport::new(socket);

    let protocol = ThriftBinaryProtocol::new( /*transport*/);
    let client = CalculatorClient::new(protocol);

    //transport.open();

    client.ping();

    println!("PASS")
}
<|endoftext|>


<commit_before><commit_msg>added CXXFLAGS=-std=c++11 to make<commit_after><|endoftext|>


<commit_before><commit_msg>Add doc example for `url::Url::scheme`.<commit_after><|endoftext|>


<commit_before><commit_msg>mugen<commit_after><|endoftext|>


<commit_before><commit_msg>Added for future use, not in use at the moment<commit_after>/*
Do we need to represent emotes the same way
TwitchLib does?
It adds a lot of functionality, so perhaps
in a later verison it is something we can add.

For now we'll just use the string representation of the emote
*/<|endoftext|>


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

#![feature(rustc_attrs)]
#![feature(slice_patterns)]
#![allow(dead_code)]
#![deny(illegal_floating_point_constant_pattern)]

// Matching against NaN should result in a warning

use std::f64::NAN;

#[rustc_error]
fn main() {
    let x = NAN;
    match x {
        NAN => {}, //~ ERROR floating point constants cannot be used
                   //~| WARNING hard error
        _ => {},
    };

    match [x, 1.0] {
        [NAN, _] => {}, //~ ERROR floating point constants cannot be used
                        //~| WARNING hard error
        _ => {},
    };
}
<|endoftext|>


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

// tests the good error message, not "missing module Foo" or something else unexpected

struct Foo;

fn main() {
    Foo::bar(); //~ ERROR type `Foo` does not implement any method in scope named `bar`
}
<|endoftext|>


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

// @!has trait_self_link/trait.Foo.html //a/@href ../trait_self_link/trait.Foo.html
pub trait Foo {}

pub struct Bar;

impl Foo for Bar {}
<|endoftext|>


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

// Make sure that invalid ranges generate an error during HIR lowering, not an ICE

#![feature(inclusive_range_syntax)]

pub fn main() {
    ..;
    0..;
    ..1;
    0..1;

    ...; //~ERROR inclusive range with no end
    0...; //~ERROR unexpected token
    ...1;
    0...1;
}

<|endoftext|>


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

fn a(&self) { }
//~^ ERROR `self` argument in bare function

fn main() { }<|endoftext|>


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

use std::env;
use common::Config;

/// Conversion table from triple OS name to Rust SYSNAME
const OS_TABLE: &'static [(&'static str, &'static str)] = &[
    ("android", "android"),
    ("bitrig", "bitrig"),
    ("darwin", "macos"),
    ("dragonfly", "dragonfly"),
    ("freebsd", "freebsd"),
    ("haiku", "haiku"),
    ("ios", "ios"),
    ("linux", "linux"),
    ("mingw32", "windows"),
    ("netbsd", "netbsd"),
    ("openbsd", "openbsd"),
    ("win32", "windows"),
    ("windows", "windows"),
    ("solaris", "solaris"),
    ("emscripten", "emscripten"),
];

const ARCH_TABLE: &'static [(&'static str, &'static str)] = &[
    ("aarch64", "aarch64"),
    ("amd64", "x86_64"),
    ("arm", "arm"),
    ("arm64", "aarch64"),
    ("hexagon", "hexagon"),
    ("i386", "x86"),
    ("i586", "x86"),
    ("i686", "x86"),
    ("mips", "mips"),
    ("msp430", "msp430"),
    ("powerpc", "powerpc"),
    ("powerpc64", "powerpc64"),
    ("s390x", "s390x"),
    ("sparc", "sparc"),
    ("x86_64", "x86_64"),
    ("xcore", "xcore"),
    ("asmjs", "asmjs"),
    ("wasm32", "wasm32"),
];

pub fn matches_os(triple: &str, name: &str) -> bool {
    // For the wasm32 bare target we ignore anything also ignored on emscripten
    // and then we also recognize `wasm32-bare` as the os for the target
    if triple == "wasm32-unknown-unknown" {
        return name == "emscripten" || name == "wasm32-bare"
    }
    for &(triple_os, os) in OS_TABLE {
        if triple.contains(triple_os) {
            return os == name;
        }
    }
    panic!("Cannot determine OS from triple");
}
pub fn get_arch(triple: &str) -> &'static str {
    for &(triple_arch, arch) in ARCH_TABLE {
        if triple.contains(triple_arch) {
            return arch;
        }
    }
    panic!("Cannot determine Architecture from triple");
}

pub fn get_env(triple: &str) -> Option<&str> {
    triple.split('-').nth(3)
}

pub fn get_pointer_width(triple: &str) -> &'static str {
    if (triple.contains("64") && !triple.ends_with("gnux32")) || triple.starts_with("s390x") {
        "64bit"
    } else {
        "32bit"
    }
}

pub fn make_new_path(path: &str) -> String {
    assert!(cfg!(windows));
    // Windows just uses PATH as the library search path, so we have to
    // maintain the current value while adding our own
    match env::var(lib_path_env_var()) {
        Ok(curr) => format!("{}{}{}", path, path_div(), curr),
        Err(..) => path.to_owned(),
    }
}

pub fn lib_path_env_var() -> &'static str {
    "PATH"
}
fn path_div() -> &'static str {
    ";"
}

pub fn logv(config: &Config, s: String) {
    debug!("{}", s);
    if config.verbose {
        println!("{}", s);
    }
}
<commit_msg>Add CloudABI to the list of supported targets in compiletest.<commit_after>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::env;
use common::Config;

/// Conversion table from triple OS name to Rust SYSNAME
const OS_TABLE: &'static [(&'static str, &'static str)] = &[
    ("android", "android"),
    ("bitrig", "bitrig"),
    ("cloudabi", "cloudabi"),
    ("darwin", "macos"),
    ("dragonfly", "dragonfly"),
    ("freebsd", "freebsd"),
    ("haiku", "haiku"),
    ("ios", "ios"),
    ("linux", "linux"),
    ("mingw32", "windows"),
    ("netbsd", "netbsd"),
    ("openbsd", "openbsd"),
    ("win32", "windows"),
    ("windows", "windows"),
    ("solaris", "solaris"),
    ("emscripten", "emscripten"),
];

const ARCH_TABLE: &'static [(&'static str, &'static str)] = &[
    ("aarch64", "aarch64"),
    ("amd64", "x86_64"),
    ("arm", "arm"),
    ("arm64", "aarch64"),
    ("hexagon", "hexagon"),
    ("i386", "x86"),
    ("i586", "x86"),
    ("i686", "x86"),
    ("mips", "mips"),
    ("msp430", "msp430"),
    ("powerpc", "powerpc"),
    ("powerpc64", "powerpc64"),
    ("s390x", "s390x"),
    ("sparc", "sparc"),
    ("x86_64", "x86_64"),
    ("xcore", "xcore"),
    ("asmjs", "asmjs"),
    ("wasm32", "wasm32"),
];

pub fn matches_os(triple: &str, name: &str) -> bool {
    // For the wasm32 bare target we ignore anything also ignored on emscripten
    // and then we also recognize `wasm32-bare` as the os for the target
    if triple == "wasm32-unknown-unknown" {
        return name == "emscripten" || name == "wasm32-bare"
    }
    for &(triple_os, os) in OS_TABLE {
        if triple.contains(triple_os) {
            return os == name;
        }
    }
    panic!("Cannot determine OS from triple");
}
pub fn get_arch(triple: &str) -> &'static str {
    for &(triple_arch, arch) in ARCH_TABLE {
        if triple.contains(triple_arch) {
            return arch;
        }
    }
    panic!("Cannot determine Architecture from triple");
}

pub fn get_env(triple: &str) -> Option<&str> {
    triple.split('-').nth(3)
}

pub fn get_pointer_width(triple: &str) -> &'static str {
    if (triple.contains("64") && !triple.ends_with("gnux32")) || triple.starts_with("s390x") {
        "64bit"
    } else {
        "32bit"
    }
}

pub fn make_new_path(path: &str) -> String {
    assert!(cfg!(windows));
    // Windows just uses PATH as the library search path, so we have to
    // maintain the current value while adding our own
    match env::var(lib_path_env_var()) {
        Ok(curr) => format!("{}{}{}", path, path_div(), curr),
        Err(..) => path.to_owned(),
    }
}

pub fn lib_path_env_var() -> &'static str {
    "PATH"
}
fn path_div() -> &'static str {
    ";"
}

pub fn logv(config: &Config, s: String) {
    debug!("{}", s);
    if config.verbose {
        println!("{}", s);
    }
}
<|endoftext|>


<commit_before>extern crate num_cpus;

use std::fs::File;
use std::io::prelude::*;
use regex::RegexSet;
use gitignore::*;
use std::path::PathBuf;
use self::num_cpus::get;
use std::fs::Metadata;

#[cfg(target_os = "linux")]
use std::os::linux::fs::MetadataExt;

#[cfg(target_os = "darwin")]
use std::os::unix::fs::MetadataExt;

#[cfg(target_os = "linux")]
pub fn size(m: &Metadata, blocks: bool) -> u64 {
    if blocks {
        m.st_blocks() * 512
    } else {
        m.len()
    }
}

#[cfg(target_os = "windows")]
pub fn size(m: &Metadata, _: bool) -> u64 {
    m.len()
}

#[cfg(target_os = "darwin")]
pub fn size(m: &Metadata, blocks: bool) -> u64 {
    if blocks {
        m.blocks() * 512 // idk if this is correct on bsd/linux
    } else {
        m.len()
    }
}

/// Gather the information from `.gitignore`, `.ignore`, and darcs `boring` files in a given
/// directory, and assemble a `RegexSet` from it.
pub fn mk_ignores(in_paths: &PathBuf, maybe_ignore: &Option<RegexSet>) -> Option<RegexSet> {

    if let Some(ref ignore) = *maybe_ignore {
        Some(ignore.to_owned())
    } else if let (ignore_path, Ok(mut file)) =
        {
            let mut ignore_path = in_paths.clone();
            ignore_path.push(".ignore");
            (ignore_path.clone(), File::open(ignore_path.clone()))
        } {
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("File read failed."); // ok because we check that the file exists
        Some(file_contents_to_regex(&contents, &ignore_path))
    } else if let (gitignore_path, Ok(mut file)) =
        {
            let mut gitignore_path = in_paths.clone();
            gitignore_path.push(".gitignore");
            (gitignore_path.clone(), File::open(gitignore_path))
        } {
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("File read failed."); // ok because we check that the file exists
        Some(file_contents_to_regex(&contents, &gitignore_path))
    } else if let (darcs_path, Ok(mut file)) =
        {
            let mut darcs_path = in_paths.clone();
            darcs_path.push("_darcs/prefs/boring");
            (darcs_path.clone(), File::open(darcs_path))
        } {
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("File read failed."); // ok because we check that the file exists
        Some(darcs_contents_to_regex(&contents, &darcs_path))
    } else {
        None
    }
}

/// Helper function to get the number of CPUs. We subtract 1, because the main thread that's doing
/// the spawning counts as one OS thread.
pub fn get_processors() -> usize {
    let n = get();
    if n > 1 {
        n - 1
    } else {
        n
    }
}
<commit_msg>mac again<commit_after>extern crate num_cpus;

use std::fs::File;
use std::io::prelude::*;
use regex::RegexSet;
use gitignore::*;
use std::path::PathBuf;
use self::num_cpus::get;
use std::fs::Metadata;

#[cfg(target_os = "linux")]
use std::os::linux::fs::MetadataExt;

#[cfg(target_os = "mac_os")]
use std::os::unix::fs::MetadataExt;

#[cfg(target_os = "linux")]
pub fn size(m: &Metadata, blocks: bool) -> u64 {
    if blocks {
        m.st_blocks() * 512
    } else {
        m.len()
    }
}

#[cfg(target_os = "windows")]
pub fn size(m: &Metadata, _: bool) -> u64 {
    m.len()
}

#[cfg(target_os = "mac_os")]
pub fn size(m: &Metadata, blocks: bool) -> u64 {
    if blocks {
        m.blocks() * 512 // idk if this is correct on bsd/linux
    } else {
        m.len()
    }
}

/// Gather the information from `.gitignore`, `.ignore`, and darcs `boring` files in a given
/// directory, and assemble a `RegexSet` from it.
pub fn mk_ignores(in_paths: &PathBuf, maybe_ignore: &Option<RegexSet>) -> Option<RegexSet> {

    if let Some(ref ignore) = *maybe_ignore {
        Some(ignore.to_owned())
    } else if let (ignore_path, Ok(mut file)) =
        {
            let mut ignore_path = in_paths.clone();
            ignore_path.push(".ignore");
            (ignore_path.clone(), File::open(ignore_path.clone()))
        } {
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("File read failed."); // ok because we check that the file exists
        Some(file_contents_to_regex(&contents, &ignore_path))
    } else if let (gitignore_path, Ok(mut file)) =
        {
            let mut gitignore_path = in_paths.clone();
            gitignore_path.push(".gitignore");
            (gitignore_path.clone(), File::open(gitignore_path))
        } {
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("File read failed."); // ok because we check that the file exists
        Some(file_contents_to_regex(&contents, &gitignore_path))
    } else if let (darcs_path, Ok(mut file)) =
        {
            let mut darcs_path = in_paths.clone();
            darcs_path.push("_darcs/prefs/boring");
            (darcs_path.clone(), File::open(darcs_path))
        } {
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("File read failed."); // ok because we check that the file exists
        Some(darcs_contents_to_regex(&contents, &darcs_path))
    } else {
        None
    }
}

/// Helper function to get the number of CPUs. We subtract 1, because the main thread that's doing
/// the spawning counts as one OS thread.
pub fn get_processors() -> usize {
    let n = get();
    if n > 1 {
        n - 1
    } else {
        n
    }
}
<|endoftext|>


<commit_before><commit_msg>Make VgaConsole take chars instead of bytes<commit_after><|endoftext|>


<commit_before><commit_msg>add codegen test<commit_after>// compile-flags: -C no-prepopulate-passes

#![crate_type = "lib"]

// Hack to get the correct size for the length part in slices
// CHECK: @helper([[USIZE:i[0-9]+]] %_1)
#[no_mangle]
pub fn helper(_: usize) {
}

// Check that we correctly generate a GEP for a ZST that is not included in Scalar layout
// CHECK-LABEL: @scalar_layout
#[no_mangle]
pub fn scalar_layout(s: &(u64, ())) {
// CHECK: [[X0:%[0-9]+]] = bitcast i64* %s to i8*
// CHECK-NEXT: [[X1:%[0-9]+]] = getelementptr i8, i8* [[X0]], [[USIZE]] 8
    let x = &s.1;
    &x; // keep variable in an alloca
}

// Check that we correctly generate a GEP for a ZST that is not included in ScalarPair layout
// CHECK-LABEL: @scalarpair_layout
#[no_mangle]
pub fn scalarpair_layout(s: &(u64, u32, ())) {
// CHECK: [[X0:%[0-9]+]] = bitcast { i64, i32 }* %s to i8*
// CHECK-NEXT: [[X1:%[0-9]+]] = getelementptr i8, i8* [[X0]], [[USIZE]] 12
    let x = &s.2;
    &x; // keep variable in an alloca
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #336 - kbknapp:issue-333, r=kbknapp<commit_after><|endoftext|>


<commit_before><commit_msg>Start of asn1 type cereal<commit_after>use tag;
use err;

use std::io;

struct OctetString(Vec<u8>);

impl Asn1Serialize for OctetString {
  fn serialize<W: io::Write>(&self, writer: W) -> Result<(), err::EncodeError> {
    try!(writer.write(&self.0));
  }
}

impl Asn1Deserialize for OctetString {
  fn deserialize<I: Iterator<Item=io::Result<u8>>>(reader: I) -> Result<Self, err::DecodeError> {
    unimplemented!();
  }
}

impl Asn1Info for OctetString {
  fn asn1_type() -> tag::Type {
    "OCCTET STRING".into()
  }

  fn asn1_class() -> tag::Class {
    tag::Class::Universal
  }

  fn asn1_tagnum() -> tag::TagNum {
    4.into()
  }

  fn asn1_constructed() -> bool {
    false
  }
}
<|endoftext|>


<commit_before><commit_msg>added some lex tuples<commit_after><|endoftext|>


<commit_before><commit_msg>epoll_ctl ffi stuff<commit_after><|endoftext|>


<commit_before><commit_msg>Added `error.rs` module.<commit_after>use std;
use std::result;
use std::error::Error;
use std::fmt;

use time;

#[derive(Debug, Clone)]
pub enum DurationError {
    StdOutOfRange,
    SystemTimeError(std::time::SystemTimeError),
}

impl Error for DurationError {
    fn description(&self) -> &str {
        match *self {
            DurationError::StdOutOfRange => {
                "Conversion between FloatDuration and std::time::Duration \
                 out of range"
            }
            DurationError::SystemTimeError(ref e) => e.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            DurationError::StdOutOfRange => None,
            DurationError::SystemTimeError(ref e) => Some(e),
        }
    }
}

impl From<time::OutOfRangeError> for DurationError {
    fn from(_: time::OutOfRangeError) -> DurationError {
        DurationError::StdOutOfRange
    }
}
impl From<std::time::SystemTimeError> for DurationError {
    fn from(err: std::time::SystemTimeError) -> DurationError {
        DurationError::SystemTimeError(err)
    }
}

impl fmt::Display for DurationError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.description())
    }
}

pub type Result<T> = result::Result<T, DurationError>;
<|endoftext|>


<commit_before><commit_msg>Derive standard traits for HNil and HCons<commit_after><|endoftext|>


<commit_before><commit_msg>Added `remove` on `Index`<commit_after><|endoftext|>


<commit_before><commit_msg>load and draw image on screen<commit_after><|endoftext|>


<commit_before><commit_msg>Add additional methods to help creating PluginMeta structs<commit_after><|endoftext|>


<commit_before><commit_msg>Add comments on modules<commit_after><|endoftext|>


<commit_before><commit_msg>Change writer::pack_directory to return io::Result<commit_after><|endoftext|>


<commit_before>/// A module for permission units
pub mod permission_unit;
/// A module for checking string (wildcard) matches
pub mod str_match;
/// A module for permissions
pub mod permission;

#[test]
fn test() {
    use str_match::*;
    use permission_unit::*;
    use permission::*;
    // Test string matches (wildcard chars)
    assert!(str_match("hey*hey", "heyabchey"));
    assert!(str_match("hey\\*hey*", "hey*heycatsarefunny"));
    // Test permission units
    assert!(PermissionUnit::from_str("rw=hey").read());
    assert!(!PermissionUnit::from_str("r=hey").write());
    assert!(PermissionUnit::from_str("r=hey").read_foc());
    assert!(PermissionUnit::from_str("r=file:home/*").applies(&PermissionUnit::from_str("R=file:home/lal")));
    assert!(PermissionUnit::from_str("R=file:home/lal").read_foc);
    assert!(PermissionUnit::from_str("r=file:home/lal").read_foc());
    assert!(!PermissionUnit::from_str("RW=http:*").read());
    // Test permissions
    assert!(Permission::from_str("rw=file:home/*-rw=file:veryimportant").test(PermissionUnit::from_str("rw=file:home/lal")));
    assert!(Permission::from_str("rw=file:home/*-rw=file:veryimportant").test(PermissionUnit::from_str("rw=file:home/veryimportant")));
    assert!(Permission::from_str("rw=i\\+can\\+do\\+like\\+this").test(PermissionUnit::from_str("rw=file:i+can+do+like+this")));
    // assert!(!Permission::from_str("RW=http:*+").test(PermissionUnit::from_str("rw=http://google.com")));
    // TODO: Failes when using uppercase RW
}
<commit_msg>It works! TODO: Focus<commit_after>/// A module for permission units
pub mod permission_unit;
/// A module for checking string (wildcard) matches
pub mod str_match;
/// A module for permissions
pub mod permission;

#[test]
fn test() {
    use str_match::*;
    use permission_unit::*;
    use permission::*;
    // Test string matches (wildcard chars)
    assert!(str_match("hey*hey", "heyabchey"));
    assert!(str_match("hey\\*hey*", "hey*heycatsarefunny"));
    // Test permission units
    assert!(PermissionUnit::from_str("rw=hey").read());
    assert!(!PermissionUnit::from_str("r=hey").write());
    assert!(PermissionUnit::from_str("r=hey").read_foc());
    assert!(PermissionUnit::from_str("r=file:home/*").applies(&PermissionUnit::from_str("R=file:home/lal")));
    assert!(PermissionUnit::from_str("R=file:home/lal").read_foc);
    assert!(PermissionUnit::from_str("r=file:home/lal").read_foc());
    assert!(!PermissionUnit::from_str("RW=http:*").read());
    // Test permissions
    assert!(Permission::from_str("rw=file:home/*-rw=file:veryimportant").test(PermissionUnit::from_str("rw=file:home/lal")));
    assert!(Permission::from_str("rw=file:home/*-rw=file:veryimportant").test(PermissionUnit::from_str("rw=file:home/veryimportant")));
    assert!(Permission::from_str("rw=i\\+can\\+do\\+like\\+this").test(PermissionUnit::from_str("rw=file:i+can+do+like+this")));

    // assert!(!Permission::from_str("RW=http:*").test(PermissionUnit::from_str("rw=http://google.com")));
    // TODO: Failes when using uppercase RW
}
<|endoftext|>


<commit_before><commit_msg>Change InvalidInput to EndOfFile in several cases<commit_after><|endoftext|>


<commit_before><commit_msg>Add the processor.<commit_after>use std::collections::BTreeMap;
use yaml_rust::Yaml;
use project::parser::Command;
use tmux;

pub fn main(commands: &Vec<Command>) -> () {
    let sess = "test".to_string();

    let (first_window, exec_commands) = commands.split_at(1);
    tmux::new_session(sess.clone(), first_window[0].value.clone());

    for w in exec_commands {
        tmux::new_window(sess.clone(), w.value.clone());
    };

    tmux::open(sess.clone());
}
<|endoftext|>


<commit_before><commit_msg>added string example<commit_after>use std::borrow::Cow;

fn remove_spaces<'a>(input: &'a str) -> Cow<'a, str> {
    if input.contains(' ') {
        let mut buf = String::with_capacity(input.len());

        for c in input.chars() {
            if c != ' ' {
                buf.push(c);
            }
        }

        return Cow::Owned(buf);
    }

    return Cow::Borrowed(input);
}

fn main() {
    let s = remove_spaces("I love Rustlang");
    println!("{}", s);
}<|endoftext|>


<commit_before><commit_msg>Add solution to problem 56<commit_after>#[macro_use] extern crate libeuler;
extern crate num;

use num::bigint::{BigInt, ToBigInt};
use num::traits::{Zero, ToPrimitive};
/// A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost
/// unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the
/// digits in each number is only 1.
///
/// Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?
fn main() {
    solutions! {
        sol naive {
            let ten = 10.to_bigint().unwrap();
            let mut maxsum = 0;
            for a in 90..100 {
                let ab = a.to_bigint().unwrap();
                let mut ap = num::pow(ab.clone(), 89);
                for _ in 90..100 {
                    ap = &ap * &ab;

                    let mut d = ap.clone();
                    let mut sum = 0;

                    while d > BigInt::zero() {
                        sum += (&d % &ten).to_i64().unwrap();
                        d = &d / &ten;
                    }

                    if sum > maxsum {
                        maxsum = sum;
                        println!("{}", maxsum);
                    }
                }
            }

            maxsum
        }
    }
}
<|endoftext|>


<commit_before>use gl;
use gl::types::*;
use types::{Color, Viewport, Capability, GLError};
use buffer::{ArrayBufferBinder, ElementArrayBufferBinder};
use program::{ProgramBinder, ProgramAttrib};
use framebuffer::FramebufferBinder;
use renderbuffer::RenderbufferBinder;
use texture_units::TextureUnits;

pub struct Context {
    pub array_buffer: ArrayBufferBinder,
    pub element_array_buffer: ElementArrayBufferBinder,
    pub program: ProgramBinder,
    pub framebuffer: FramebufferBinder,
    pub renderbuffer: RenderbufferBinder,
    pub tex_units: TextureUnits
}

impl Context {
    pub unsafe fn current_context() -> Self {
        Context {
            array_buffer: ArrayBufferBinder,
            element_array_buffer: ElementArrayBufferBinder,
            program: ProgramBinder,
            framebuffer: FramebufferBinder,
            renderbuffer: RenderbufferBinder,
            tex_units: TextureUnits::current()
        }
    }

    pub fn clear_color(&mut self, color: Color) {
        unsafe {
            gl::ClearColor(color.r, color.g, color.b, color.a);
        }
    }

    pub fn enable(&mut self, cap: Capability) {
        unsafe {
            gl::Enable(cap.gl_enum());
            dbg_gl_sanity_check! {
                GLError::InvalidEnum => "`cap` is not a valid OpenGL capability",
                _ => "Unknown error"
            }
        }
    }

    pub fn disable(&mut self, cap: Capability) {
        unsafe {
            gl::Disable(cap.gl_enum());
            dbg_gl_sanity_check! {
                GLError::InvalidEnum => "`cap` is not a valid OpenGL capability",
                _ => "Unknown error"
            }
        }
    }

    pub fn enable_vertex_attrib_array(&self, attrib: ProgramAttrib) {
        unsafe {
            gl::EnableVertexAttribArray(attrib.gl_index);
            dbg_gl_error! {
                GLError::InvalidValue => "`index` is >= GL_MAX_VERTEX_ATTRIBS",
                _ => "Unknown error"
            }
        }
    }

    pub fn viewport(&self, viewport: Viewport) {
        unsafe {
            gl::Viewport(viewport.x as GLint,
                         viewport.y as GLint,
                         viewport.width as GLsizei,
                         viewport.height as GLsizei);
            dbg_gl_sanity_check! {
                GLError::InvalidValue => "`width` or `height` is negative",
                _ => "Unknown error"
            }
        }
    }

    pub fn get_error() -> Option<GLError> {
        unsafe {
            match gl::GetError() {
                gl::INVALID_ENUM =>
                    Some(GLError::InvalidEnum),
                gl::INVALID_VALUE =>
                    Some(GLError::InvalidValue),
                gl::INVALID_OPERATION =>
                    Some(GLError::InvalidOperation),
                gl::INVALID_FRAMEBUFFER_OPERATION =>
                    Some(GLError::InvalidFramebufferOperation),
                gl::OUT_OF_MEMORY =>
                    Some(GLError::OutOfMemory),
                _ =>
                    None
            }
        }
    }
}

#[macro_export]
macro_rules! bind_array_buffer {
    ($gl:expr, $buffer:expr) => {
        $gl.array_buffer.bind($buffer)
    }
}

#[macro_export]
macro_rules! bind_element_array_buffer {
    ($gl:expr, $buffer:expr) => {
        $gl.element_array_buffer.bind($buffer)
    }
}

#[macro_export]
macro_rules! use_program {
    ($gl:expr, $program:expr) => {
        $gl.program.bind($program)
    }
}

#[macro_export]
macro_rules! bind_framebuffer {
    ($gl:expr, $fbo:expr) => {
        $gl.framebuffer.bind($fbo)
    }
}

#[macro_export]
macro_rules! current_framebuffer_binding {
    ($gl:expr) => {
        $gl.framebuffer.current_binding()
    }
}

#[macro_export]
macro_rules! bind_renderbuffer {
    ($gl:expr, $renderbuffer:expr) => {
        $gl.renderbuffer.bind($renderbuffer)
    }
}

// HACK: Workaround for issue described here:
// https://www.reddit.com/r/rust/comments/339yj3/tuple_indexing_in_a_macro/cqiyv4n
#[macro_export]
macro_rules! _glitter_expr {
    ($x:expr) => ($x)
}

#[macro_export]
macro_rules! active_texture {
    ($gl:expr, $idx:tt) => {
        _glitter_expr!($gl.tex_units.$idx.active())
    }
}

#[macro_export]
macro_rules! active_texture_n {
    ($gl:expr, $idx:expr) => {
        $gl.tex_units.nth_unit($idx).active()
    }
}
<commit_msg>Add `ContextOf` type<commit_after>use gl;
use gl::types::*;
use types::{Color, Viewport, Capability, GLError};
use buffer::{ArrayBufferBinder, ElementArrayBufferBinder};
use program::{ProgramBinder, ProgramAttrib};
use framebuffer::FramebufferBinder;
use renderbuffer::RenderbufferBinder;
use texture_units::TextureUnits;

pub type Context = ContextOf<ArrayBufferBinder,
                             ElementArrayBufferBinder,
                             ProgramBinder,
                             FramebufferBinder,
                             RenderbufferBinder,
                             TextureUnits>;

pub struct ContextOf<AB, EAB, P, FB, RB, TU> {
    pub array_buffer: AB,
    pub element_array_buffer: EAB,
    pub program: P,
    pub framebuffer: FB,
    pub renderbuffer: RB,
    pub tex_units: TU
}

impl Context {
    pub unsafe fn current_context() -> Self {
        Context {
            array_buffer: ArrayBufferBinder,
            element_array_buffer: ElementArrayBufferBinder,
            program: ProgramBinder,
            framebuffer: FramebufferBinder,
            renderbuffer: RenderbufferBinder,
            tex_units: TextureUnits::current()
        }
    }

    pub fn clear_color(&mut self, color: Color) {
        unsafe {
            gl::ClearColor(color.r, color.g, color.b, color.a);
        }
    }

    pub fn enable(&mut self, cap: Capability) {
        unsafe {
            gl::Enable(cap.gl_enum());
            dbg_gl_sanity_check! {
                GLError::InvalidEnum => "`cap` is not a valid OpenGL capability",
                _ => "Unknown error"
            }
        }
    }

    pub fn disable(&mut self, cap: Capability) {
        unsafe {
            gl::Disable(cap.gl_enum());
            dbg_gl_sanity_check! {
                GLError::InvalidEnum => "`cap` is not a valid OpenGL capability",
                _ => "Unknown error"
            }
        }
    }

    pub fn enable_vertex_attrib_array(&self, attrib: ProgramAttrib) {
        unsafe {
            gl::EnableVertexAttribArray(attrib.gl_index);
            dbg_gl_error! {
                GLError::InvalidValue => "`index` is >= GL_MAX_VERTEX_ATTRIBS",
                _ => "Unknown error"
            }
        }
    }

    pub fn viewport(&self, viewport: Viewport) {
        unsafe {
            gl::Viewport(viewport.x as GLint,
                         viewport.y as GLint,
                         viewport.width as GLsizei,
                         viewport.height as GLsizei);
            dbg_gl_sanity_check! {
                GLError::InvalidValue => "`width` or `height` is negative",
                _ => "Unknown error"
            }
        }
    }

    pub fn get_error() -> Option<GLError> {
        unsafe {
            match gl::GetError() {
                gl::INVALID_ENUM =>
                    Some(GLError::InvalidEnum),
                gl::INVALID_VALUE =>
                    Some(GLError::InvalidValue),
                gl::INVALID_OPERATION =>
                    Some(GLError::InvalidOperation),
                gl::INVALID_FRAMEBUFFER_OPERATION =>
                    Some(GLError::InvalidFramebufferOperation),
                gl::OUT_OF_MEMORY =>
                    Some(GLError::OutOfMemory),
                _ =>
                    None
            }
        }
    }
}

#[macro_export]
macro_rules! bind_array_buffer {
    ($gl:expr, $buffer:expr) => {
        $gl.array_buffer.bind($buffer)
    }
}

#[macro_export]
macro_rules! bind_element_array_buffer {
    ($gl:expr, $buffer:expr) => {
        $gl.element_array_buffer.bind($buffer)
    }
}

#[macro_export]
macro_rules! use_program {
    ($gl:expr, $program:expr) => {
        $gl.program.bind($program)
    }
}

#[macro_export]
macro_rules! bind_framebuffer {
    ($gl:expr, $fbo:expr) => {
        $gl.framebuffer.bind($fbo)
    }
}

#[macro_export]
macro_rules! current_framebuffer_binding {
    ($gl:expr) => {
        $gl.framebuffer.current_binding()
    }
}

#[macro_export]
macro_rules! bind_renderbuffer {
    ($gl:expr, $renderbuffer:expr) => {
        $gl.renderbuffer.bind($renderbuffer)
    }
}

// HACK: Workaround for issue described here:
// https://www.reddit.com/r/rust/comments/339yj3/tuple_indexing_in_a_macro/cqiyv4n
#[macro_export]
macro_rules! _glitter_expr {
    ($x:expr) => ($x)
}

#[macro_export]
macro_rules! active_texture {
    ($gl:expr, $idx:tt) => {
        _glitter_expr!($gl.tex_units.$idx.active())
    }
}

#[macro_export]
macro_rules! active_texture_n {
    ($gl:expr, $idx:expr) => {
        $gl.tex_units.nth_unit($idx).active()
    }
}
<|endoftext|>


<commit_before>//! This module defines the `Bits`, `Dibits`, and `Tribits` iterators as well as the
//! wrapper types `Bit`, `Dibit`, and `Tribit`, for working with sub-byte values.
//!
//! The wrapped values of `Bit`, `Dibit`, and `Tribit, are guaranteed to have only one,
//! two, or three bits, respectively.

use std;

/// Iterate over individual bits of a byte source, MSB to LSB.
pub type Bits<T> = SubByteIter<BitParams, T>;
/// Iterate over the dibits of a byte source, MSB to LSB.
pub type Dibits<T> = SubByteIter<DibitParams, T>;

/// Defines parameters needed for (power of two) sub-byte iterators.
pub trait IterParams {
    /// Type to yield at each iteration.
    type IterType;

    /// Number of bits to consume at each iteration.
    fn bits() -> u8;
    /// Wrap the given bits in container type.
    fn wrap(bits: u8) -> Self::IterType;

    /// Number of iterations needed for each byte.
    fn iterations() -> u8 { 8 / Self::bits() }

    /// Verify the parameters are supported.
    fn validate() {
        // Only powers of two are valid because there can be no "leftovers."
        assert!(Self::bits().is_power_of_two());
    }
}

/// A single bit.
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
pub struct Bit(u8);

impl Bit {
    /// Construct a new `Bit` with the given bit in the LSB position.
    pub fn new(bits: u8) -> Bit {
        assert!(bits & 0b11111110 == 0);
        Bit(bits)
    }

    /// Get the wrapped bit value.
    pub fn bit(&self) -> u8 { self.0 }
}

/// Parameters for `Bits` iterator.
pub struct BitParams;

impl IterParams for BitParams {
    type IterType = Bit;
    fn bits() -> u8 { 1 }
    fn wrap(bits: u8) -> Bit { Bit::new(bits) }
}

/// Two bits.
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
pub struct Dibit(u8);

impl Dibit {
    /// Construct a new `Dibit` with the two given bits in the LSB position.
    pub fn new(bits: u8) -> Dibit {
        assert!(bits & 0b11111100 == 0);
        Dibit(bits)
    }

    /// Get the wrapped dibit.
    pub fn bits(&self) -> u8 { self.0 }
}

/// Parameters for `Dibits` iterator.
pub struct DibitParams;

impl IterParams for DibitParams {
    type IterType = Dibit;
    fn bits() -> u8 { 2 }
    fn wrap(bits: u8) -> Dibit { Dibit::new(bits) }
}

/// Three bits.
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
pub struct Tribit(u8);

impl Tribit {
    /// Construct a new `Tribit` with the three given bits in the LSB position.
    pub fn new(bits: u8) -> Tribit {
        assert!(bits & 0b11111000 == 0);
        Tribit(bits)
    }

    /// Get the wrapped tribit.
    pub fn bits(&self) -> u8 { self.0 }
}

/// An iterator for sub-byte (bit-level) values.
pub struct SubByteIter<P, T> where
    P: IterParams, T: Iterator<Item = u8>
{
    params: std::marker::PhantomData<P>,
    /// Source of bytes.
    src: T,
    /// Current bit-level index into the current byte.
    idx: u8,
    /// Current byte in the source.
    byte: u8,
}

impl<P, T> SubByteIter<P, T> where
    P: IterParams, T: Iterator<Item = u8>
{
    /// Construct a new `SubByteIter` over the given byte source. All bits are iterated
    /// over, so the number of bits must be a byte multiple.
    pub fn new(src: T) -> SubByteIter<P, T> {
        SubByteIter {
            params: std::marker::PhantomData,
            src: src,
            byte: 0,
            idx: 0,
        }
    }
}

impl<P, T> Iterator for SubByteIter<P, T> where
    P: IterParams, T: Iterator<Item = u8>
{
    type Item = P::IterType;

    fn next(&mut self) -> Option<Self::Item> {
        if self.idx == 0 {
            self.byte = match self.src.next() {
                Some(b) => b,
                None => return None,
            };
        }

        // Extract MSBs.
        let bits = self.byte >> (8 - P::bits());

        // Strip off the MSBs for the next iteration.
        self.byte <<= P::bits();

        // Move to the next item and reset after all have been visited.
        self.idx += 1;
        self.idx %= P::iterations();

        Some(P::wrap(bits))
    }
}

/// Iterates over the tribits in a byte source.
pub struct Tribits<T: Iterator<Item = u8>> {
    /// The source of bytes.
    src: T,
    /// Current bit buffer, containing either 6 or 3 bits (in MSB position) or 0.
    bits: u8,
    /// Tribit index into `bits` (0 or 1).
    idx: usize,
    /// Buffered bits from current source byte, to be added to `bits`.
    buf: u8,
    /// Number of bits in `buf`, either 2, 4, 6, or 0.
    buf_bits: usize,
}

impl<T: Iterator<Item = u8>> Tribits<T> {
    /// Construct a new `Tribits` from the given source of bytes. The number of bytes must
    /// be a multiple of 3 (a multiple of 24 bits).
    pub fn new(src: T) -> Tribits<T> {
        Tribits {
            src: src,
            bits: 0,
            idx: 0,
            buf: 0,
            buf_bits: 0,
        }
    }
}

impl<T: Iterator<Item = u8>> Iterator for Tribits<T> {
    type Item = Tribit;

    fn next(&mut self) -> Option<Self::Item> {
        // If on the first tribit, it's time to flush the buffer and (maybe) load another
        // byte.
        if self.idx == 0 {
            // Flush and reset the buffer.
            self.bits = self.buf;
            self.buf = 0;

            // Calculate the number of bits to buffer for the next iteration.
            self.buf_bits += 2;
            self.buf_bits %= 8;

            // Only load a new byte if bits need to be buffered.
            if self.buf_bits != 0 {
                let next = match self.src.next() {
                    Some(b) => b,
                    None => if self.buf_bits == 2 {
                        // In this case we've covered 8 tribits = 24 bits = 3 bytes
                        // exactly, so it's fine if there are no more bytes.
                        return None;
                    } else {
                        panic!("incomplete tribit");
                    }
                };

                // Add in some source bits after the MSBs.
                self.bits |= next >> self.buf_bits << 2;
                // Buffer the rest of the bits.
                self.buf = next << (8 - self.buf_bits);
            }
        }

        // Extract the 3 MSBs and strip them off for next time.
        let bits = self.bits >> 5;
        self.bits <<= 3;

        self.idx += 1;
        self.idx %= 2;

        Some(Tribit::new(bits))
    }
}

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

    #[test]
    fn validate_params() {
        BitParams::validate();
        DibitParams::validate();
    }

    #[test]
    fn test_bits() {
        const BITS: &'static [u8] = &[
            0b00011011,
            0b11001100,
        ];

        {
            let mut d = Dibits::new(BITS.iter().cloned());

            assert!(d.next().unwrap().0 == 0b00);
            assert!(d.next().unwrap().0 == 0b01);
            assert!(d.next().unwrap().0 == 0b10);
            assert!(d.next().unwrap().0 == 0b11);
            assert!(d.next().unwrap().0 == 0b11);
            assert!(d.next().unwrap().0 == 0b00);
            assert!(d.next().unwrap().0 == 0b11);
            assert!(d.next().unwrap().0 == 0b00);
            assert!(d.next().is_none());
        }

        {
            let mut b = Bits::new(BITS.iter().cloned());

            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 0);
        }
    }

    #[test]
    fn test_tribits() {
        let bytes = [
            0b00101001,
            0b11001011,
            0b10111000,
            0b00101001,
            0b11001011,
            0b10111000,
        ];
        let mut t = Tribits::new(bytes.iter().cloned());

        assert_eq!(t.next().unwrap().bits(), 0b001);
        assert_eq!(t.next().unwrap().bits(), 0b010);
        assert_eq!(t.next().unwrap().bits(), 0b011);
        assert_eq!(t.next().unwrap().bits(), 0b100);
        assert_eq!(t.next().unwrap().bits(), 0b101);
        assert_eq!(t.next().unwrap().bits(), 0b110);
        assert_eq!(t.next().unwrap().bits(), 0b111);
        assert_eq!(t.next().unwrap().bits(), 0b000);
        assert_eq!(t.next().unwrap().bits(), 0b001);
        assert_eq!(t.next().unwrap().bits(), 0b010);
        assert_eq!(t.next().unwrap().bits(), 0b011);
        assert_eq!(t.next().unwrap().bits(), 0b100);
        assert_eq!(t.next().unwrap().bits(), 0b101);
        assert_eq!(t.next().unwrap().bits(), 0b110);
        assert_eq!(t.next().unwrap().bits(), 0b111);
        assert_eq!(t.next().unwrap().bits(), 0b000);
        assert!(t.next().is_none());
    }

    #[test]
    #[should_panic]
    fn test_tribits_panic() {
        let bytes = [1, 2, 3, 4];
        let t = Tribits::new(bytes.iter().cloned());

        for _ in t {}
    }
}
<commit_msg>SubByteIter doesn't need to be public<commit_after>//! This module defines the `Bits`, `Dibits`, and `Tribits` iterators as well as the
//! wrapper types `Bit`, `Dibit`, and `Tribit`, for working with sub-byte values.
//!
//! The wrapped values of `Bit`, `Dibit`, and `Tribit, are guaranteed to have only one,
//! two, or three bits, respectively.

use std;

/// Iterate over individual bits of a byte source, MSB to LSB.
pub type Bits<T> = SubByteIter<BitParams, T>;
/// Iterate over the dibits of a byte source, MSB to LSB.
pub type Dibits<T> = SubByteIter<DibitParams, T>;

/// Defines parameters needed for (power of two) sub-byte iterators.
pub trait IterParams {
    /// Type to yield at each iteration.
    type IterType;

    /// Number of bits to consume at each iteration.
    fn bits() -> u8;
    /// Wrap the given bits in container type.
    fn wrap(bits: u8) -> Self::IterType;

    /// Number of iterations needed for each byte.
    fn iterations() -> u8 { 8 / Self::bits() }

    /// Verify the parameters are supported.
    fn validate() {
        // Only powers of two are valid because there can be no "leftovers."
        assert!(Self::bits().is_power_of_two());
    }
}

/// A single bit.
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
pub struct Bit(u8);

impl Bit {
    /// Construct a new `Bit` with the given bit in the LSB position.
    pub fn new(bits: u8) -> Bit {
        assert!(bits & 0b11111110 == 0);
        Bit(bits)
    }

    /// Get the wrapped bit value.
    pub fn bit(&self) -> u8 { self.0 }
}

/// Parameters for `Bits` iterator.
pub struct BitParams;

impl IterParams for BitParams {
    type IterType = Bit;
    fn bits() -> u8 { 1 }
    fn wrap(bits: u8) -> Bit { Bit::new(bits) }
}

/// Two bits.
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
pub struct Dibit(u8);

impl Dibit {
    /// Construct a new `Dibit` with the two given bits in the LSB position.
    pub fn new(bits: u8) -> Dibit {
        assert!(bits & 0b11111100 == 0);
        Dibit(bits)
    }

    /// Get the wrapped dibit.
    pub fn bits(&self) -> u8 { self.0 }
}

/// Parameters for `Dibits` iterator.
pub struct DibitParams;

impl IterParams for DibitParams {
    type IterType = Dibit;
    fn bits() -> u8 { 2 }
    fn wrap(bits: u8) -> Dibit { Dibit::new(bits) }
}

/// Three bits.
#[derive(Copy, Clone, Default, Debug, PartialEq, Eq)]
pub struct Tribit(u8);

impl Tribit {
    /// Construct a new `Tribit` with the three given bits in the LSB position.
    pub fn new(bits: u8) -> Tribit {
        assert!(bits & 0b11111000 == 0);
        Tribit(bits)
    }

    /// Get the wrapped tribit.
    pub fn bits(&self) -> u8 { self.0 }
}

/// An iterator for sub-byte (bit-level) values.
struct SubByteIter<P, T> where
    P: IterParams, T: Iterator<Item = u8>
{
    params: std::marker::PhantomData<P>,
    /// Source of bytes.
    src: T,
    /// Current bit-level index into the current byte.
    idx: u8,
    /// Current byte in the source.
    byte: u8,
}

impl<P, T> SubByteIter<P, T> where
    P: IterParams, T: Iterator<Item = u8>
{
    /// Construct a new `SubByteIter` over the given byte source. All bits are iterated
    /// over, so the number of bits must be a byte multiple.
    pub fn new(src: T) -> SubByteIter<P, T> {
        SubByteIter {
            params: std::marker::PhantomData,
            src: src,
            byte: 0,
            idx: 0,
        }
    }
}

impl<P, T> Iterator for SubByteIter<P, T> where
    P: IterParams, T: Iterator<Item = u8>
{
    type Item = P::IterType;

    fn next(&mut self) -> Option<Self::Item> {
        if self.idx == 0 {
            self.byte = match self.src.next() {
                Some(b) => b,
                None => return None,
            };
        }

        // Extract MSBs.
        let bits = self.byte >> (8 - P::bits());

        // Strip off the MSBs for the next iteration.
        self.byte <<= P::bits();

        // Move to the next item and reset after all have been visited.
        self.idx += 1;
        self.idx %= P::iterations();

        Some(P::wrap(bits))
    }
}

/// Iterates over the tribits in a byte source.
pub struct Tribits<T: Iterator<Item = u8>> {
    /// The source of bytes.
    src: T,
    /// Current bit buffer, containing either 6 or 3 bits (in MSB position) or 0.
    bits: u8,
    /// Tribit index into `bits` (0 or 1).
    idx: usize,
    /// Buffered bits from current source byte, to be added to `bits`.
    buf: u8,
    /// Number of bits in `buf`, either 2, 4, 6, or 0.
    buf_bits: usize,
}

impl<T: Iterator<Item = u8>> Tribits<T> {
    /// Construct a new `Tribits` from the given source of bytes. The number of bytes must
    /// be a multiple of 3 (a multiple of 24 bits).
    pub fn new(src: T) -> Tribits<T> {
        Tribits {
            src: src,
            bits: 0,
            idx: 0,
            buf: 0,
            buf_bits: 0,
        }
    }
}

impl<T: Iterator<Item = u8>> Iterator for Tribits<T> {
    type Item = Tribit;

    fn next(&mut self) -> Option<Self::Item> {
        // If on the first tribit, it's time to flush the buffer and (maybe) load another
        // byte.
        if self.idx == 0 {
            // Flush and reset the buffer.
            self.bits = self.buf;
            self.buf = 0;

            // Calculate the number of bits to buffer for the next iteration.
            self.buf_bits += 2;
            self.buf_bits %= 8;

            // Only load a new byte if bits need to be buffered.
            if self.buf_bits != 0 {
                let next = match self.src.next() {
                    Some(b) => b,
                    None => if self.buf_bits == 2 {
                        // In this case we've covered 8 tribits = 24 bits = 3 bytes
                        // exactly, so it's fine if there are no more bytes.
                        return None;
                    } else {
                        panic!("incomplete tribit");
                    }
                };

                // Add in some source bits after the MSBs.
                self.bits |= next >> self.buf_bits << 2;
                // Buffer the rest of the bits.
                self.buf = next << (8 - self.buf_bits);
            }
        }

        // Extract the 3 MSBs and strip them off for next time.
        let bits = self.bits >> 5;
        self.bits <<= 3;

        self.idx += 1;
        self.idx %= 2;

        Some(Tribit::new(bits))
    }
}

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

    #[test]
    fn validate_params() {
        BitParams::validate();
        DibitParams::validate();
    }

    #[test]
    fn test_bits() {
        const BITS: &'static [u8] = &[
            0b00011011,
            0b11001100,
        ];

        {
            let mut d = Dibits::new(BITS.iter().cloned());

            assert!(d.next().unwrap().0 == 0b00);
            assert!(d.next().unwrap().0 == 0b01);
            assert!(d.next().unwrap().0 == 0b10);
            assert!(d.next().unwrap().0 == 0b11);
            assert!(d.next().unwrap().0 == 0b11);
            assert!(d.next().unwrap().0 == 0b00);
            assert!(d.next().unwrap().0 == 0b11);
            assert!(d.next().unwrap().0 == 0b00);
            assert!(d.next().is_none());
        }

        {
            let mut b = Bits::new(BITS.iter().cloned());

            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 1);
            assert!(b.next().unwrap().0 == 0);
            assert!(b.next().unwrap().0 == 0);
        }
    }

    #[test]
    fn test_tribits() {
        let bytes = [
            0b00101001,
            0b11001011,
            0b10111000,
            0b00101001,
            0b11001011,
            0b10111000,
        ];
        let mut t = Tribits::new(bytes.iter().cloned());

        assert_eq!(t.next().unwrap().bits(), 0b001);
        assert_eq!(t.next().unwrap().bits(), 0b010);
        assert_eq!(t.next().unwrap().bits(), 0b011);
        assert_eq!(t.next().unwrap().bits(), 0b100);
        assert_eq!(t.next().unwrap().bits(), 0b101);
        assert_eq!(t.next().unwrap().bits(), 0b110);
        assert_eq!(t.next().unwrap().bits(), 0b111);
        assert_eq!(t.next().unwrap().bits(), 0b000);
        assert_eq!(t.next().unwrap().bits(), 0b001);
        assert_eq!(t.next().unwrap().bits(), 0b010);
        assert_eq!(t.next().unwrap().bits(), 0b011);
        assert_eq!(t.next().unwrap().bits(), 0b100);
        assert_eq!(t.next().unwrap().bits(), 0b101);
        assert_eq!(t.next().unwrap().bits(), 0b110);
        assert_eq!(t.next().unwrap().bits(), 0b111);
        assert_eq!(t.next().unwrap().bits(), 0b000);
        assert!(t.next().is_none());
    }

    #[test]
    #[should_panic]
    fn test_tribits_panic() {
        let bytes = [1, 2, 3, 4];
        let t = Tribits::new(bytes.iter().cloned());

        for _ in t {}
    }
}
<|endoftext|>


<commit_before>#![feature(test)]

extern crate clap;
extern crate test;

use clap::{App, Arg, SubCommand};

use test::Bencher;

static M_VAL_NAMES: [&'static str; 2] = ["one", "two"];
static ARGS: &'static str = "-o --option=[opt]... 'tests options'
                             [positional] 'tests positionals'";
static OPT3_VALS: [&'static str; 2] = ["fast", "slow"];
static POS3_VALS: [&'static str; 2] = ["vi", "emacs"];

macro_rules! create_app {
    () => ({
        App::new("claptests")
                .version("0.1")
                .about("tests clap library")
                .author("Kevin K. <kbknapp@gmail.com>")
                .args_from_usage(ARGS)
                .arg(Arg::from_usage("-f --flag... 'tests flags'")
                             .global(true))
                .args(vec![
                          Arg::from_usage("[flag2] -F 'tests flags with exclusions'").conflicts_with("flag").requires("option2"),
                          Arg::from_usage("--long-option-2 [option2] 'tests long options with exclusions'").conflicts_with("option").requires("positional2"),
                          Arg::from_usage("[positional2] 'tests positionals with exclusions'"),
                          Arg::from_usage("-O --Option [option3] 'tests options with specific value sets'").possible_values(&OPT3_VALS),
                          Arg::from_usage("[positional3]... 'tests positionals with specific values'").possible_values(&POS3_VALS),
                          Arg::from_usage("--multvals [multvals] 'Tests mutliple values, not mult occs'").value_names(&M_VAL_NAMES),
                          Arg::from_usage("--multvalsmo [multvalsmo]... 'Tests mutliple values, not mult occs'").value_names(&M_VAL_NAMES),
                          Arg::from_usage("--minvals2 [minvals]... 'Tests 2 min vals'").min_values(2),
                          Arg::from_usage("--maxvals3 [maxvals]... 'Tests 3 max vals'").max_values(3)
                    ])
                .subcommand(SubCommand::with_name("subcmd")
                                        .about("tests subcommands")
                                        .version("0.1")
                                        .author("Kevin K. <kbknapp@gmail.com>")
                                        .arg_from_usage("-o --option [scoption]... 'tests options'")
                                        .arg_from_usage("[scpositional] 'tests positionals'"))
    })
}

#[bench]
fn build_app(b: &mut Bencher) {

    b.iter(|| create_app!());
}

#[bench]
fn parse_clean(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec![""]));
}

<commit_msg>tests(benchmark): Add benchmarks<commit_after>#![feature(test)]

extern crate clap;
extern crate test;

use clap::{App, Arg, SubCommand};

use test::Bencher;

static M_VAL_NAMES: [&'static str; 2] = ["one", "two"];
static ARGS: &'static str = "-o --option=[opt]... 'tests options'
                             [positional] 'tests positionals'";
static OPT3_VALS: [&'static str; 2] = ["fast", "slow"];
static POS3_VALS: [&'static str; 2] = ["vi", "emacs"];

macro_rules! create_app {
    () => ({
        App::new("claptests")
                .version("0.1")
                .about("tests clap library")
                .author("Kevin K. <kbknapp@gmail.com>")
                .args_from_usage(ARGS)
                .arg(Arg::from_usage("-f --flag... 'tests flags'")
                             .global(true))
                .args(vec![
                          Arg::from_usage("[flag2] -F 'tests flags with exclusions'").conflicts_with("flag").requires("option2"),
                          Arg::from_usage("--long-option-2 [option2] 'tests long options with exclusions'").conflicts_with("option").requires("positional2"),
                          Arg::from_usage("[positional2] 'tests positionals with exclusions'"),
                          Arg::from_usage("-O --Option [option3] 'tests options with specific value sets'").possible_values(&OPT3_VALS),
                          Arg::from_usage("[positional3]... 'tests positionals with specific values'").possible_values(&POS3_VALS),
                          Arg::from_usage("--multvals [multvals] 'Tests mutliple values, not mult occs'").value_names(&M_VAL_NAMES),
                          Arg::from_usage("--multvalsmo [multvalsmo]... 'Tests mutliple values, not mult occs'").value_names(&M_VAL_NAMES),
                          Arg::from_usage("--minvals2 [minvals]... 'Tests 2 min vals'").min_values(2),
                          Arg::from_usage("--maxvals3 [maxvals]... 'Tests 3 max vals'").max_values(3)
                    ])
                .subcommand(SubCommand::with_name("subcmd")
                                        .about("tests subcommands")
                                        .version("0.1")
                                        .author("Kevin K. <kbknapp@gmail.com>")
                                        .arg_from_usage("-o --option [scoption]... 'tests options'")
                                        .arg_from_usage("[scpositional] 'tests positionals'"))
    })
}

#[bench]
fn build_app(b: &mut Bencher) {

    b.iter(|| create_app!());
}

#[bench]
fn parse_clean(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec![""]));
}

#[bench]
fn parse_flag(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "-f"]));
}

#[bench]
fn parse_option(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "-o", "option1"]));
}

#[bench]
fn parse_positional(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "arg1"]));
}

#[bench]
fn parse_sc_clean(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "subcmd"]));
}

#[bench]
fn parse_sc_flag(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "subcmd", "-f"]));
}

#[bench]
fn parse_sc_option(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "subcmd", "-o", "option1"]));
}

#[bench]
fn parse_sc_positional(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "subcmd", "arg1"]));
}

#[bench]
fn parse_complex1(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "-ff", "-o", "option1", "arg1", "-O", "fast", "arg2", "--multvals", "one", "two", "three"]));
}

#[bench]
fn parse_complex2(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "arg1", "-f", "arg2", "--long-option-2", "some", "-O", "slow", "--multvalsmo", "one", "two", "--minvals2", "3", "2", "1"]));
}

#[bench]
fn parse_sc_complex(b: &mut Bencher) {
    b.iter(|| create_app!().get_matches_from(vec!["", "subcmd", "-f", "-o", "option1", "arg1"]));
}
<|endoftext|>


<commit_before><commit_msg>Remove get_description function<commit_after><|endoftext|>


<commit_before><commit_msg>Remove bounds checks in wram<commit_after><|endoftext|>