<commit_before>// NB: this file is #include_str'ed into the compiler, re-parsed
// and injected into each crate the compiler builds. Keep it small.

mod intrinsic {

    import rusti::visit_tydesc;
    export ty_visitor, get_tydesc, visit_tydesc, tydesc;

    // FIXME (#2712): remove this when the interface has settled and the
    // version in sys is no longer present.
    fn get_tydesc<T>() -> *tydesc {
        rusti::get_tydesc::<T>() as *tydesc
    }

    enum tydesc = {
        first_param: **u8,
        size: uint,
        align: uint
        // Remaining fields not listed
    };

    trait ty_visitor {
        fn visit_bot() -> bool;
        fn visit_nil() -> bool;
        fn visit_bool() -> bool;

        fn visit_int() -> bool;
        fn visit_i8() -> bool;
        fn visit_i16() -> bool;
        fn visit_i32() -> bool;
        fn visit_i64() -> bool;

        fn visit_uint() -> bool;
        fn visit_u8() -> bool;
        fn visit_u16() -> bool;
        fn visit_u32() -> bool;
        fn visit_u64() -> bool;

        fn visit_float() -> bool;
        fn visit_f32() -> bool;
        fn visit_f64() -> bool;

        fn visit_char() -> bool;
        fn visit_str() -> bool;

        fn visit_estr_box() -> bool;
        fn visit_estr_uniq() -> bool;
        fn visit_estr_slice() -> bool;
        fn visit_estr_fixed(n: uint, sz: uint, align: uint) -> bool;

        fn visit_box(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_uniq(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_ptr(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_rptr(mtbl: uint, inner: *tydesc) -> bool;

        fn visit_vec(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_unboxed_vec(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_evec_box(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_evec_uniq(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_evec_slice(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_evec_fixed(n: uint, sz: uint, align: uint,
                            mtbl: uint, inner: *tydesc) -> bool;

        fn visit_enter_rec(n_fields: uint,
                           sz: uint, align: uint) -> bool;
        fn visit_rec_field(i: uint, name: &str,
                           mtbl: uint, inner: *tydesc) -> bool;
        fn visit_leave_rec(n_fields: uint,
                           sz: uint, align: uint) -> bool;

        fn visit_enter_class(n_fields: uint,
                             sz: uint, align: uint) -> bool;
        fn visit_class_field(i: uint, name: &str,
                             mtbl: uint, inner: *tydesc) -> bool;
        fn visit_leave_class(n_fields: uint,
                             sz: uint, align: uint) -> bool;

        fn visit_enter_tup(n_fields: uint,
                           sz: uint, align: uint) -> bool;
        fn visit_tup_field(i: uint, inner: *tydesc) -> bool;
        fn visit_leave_tup(n_fields: uint,
                           sz: uint, align: uint) -> bool;

        fn visit_enter_enum(n_variants: uint,
                            sz: uint, align: uint) -> bool;
        fn visit_enter_enum_variant(variant: uint,
                                    disr_val: int,
                                    n_fields: uint,
                                    name: &str) -> bool;
        fn visit_enum_variant_field(i: uint, inner: *tydesc) -> bool;
        fn visit_leave_enum_variant(variant: uint,
                                    disr_val: int,
                                    n_fields: uint,
                                    name: &str) -> bool;
        fn visit_leave_enum(n_variants: uint,
                            sz: uint, align: uint) -> bool;

        fn visit_enter_fn(purity: uint, proto: uint,
                          n_inputs: uint, retstyle: uint) -> bool;
        fn visit_fn_input(i: uint, mode: uint, inner: *tydesc) -> bool;
        fn visit_fn_output(retstyle: uint, inner: *tydesc) -> bool;
        fn visit_leave_fn(purity: uint, proto: uint,
                          n_inputs: uint, retstyle: uint) -> bool;

        fn visit_trait() -> bool;
        fn visit_var() -> bool;
        fn visit_var_integral() -> bool;
        fn visit_param(i: uint) -> bool;
        fn visit_self() -> bool;
        fn visit_type() -> bool;
        fn visit_opaque_box() -> bool;
        fn visit_constr(inner: *tydesc) -> bool;
        fn visit_closure_ptr(ck: uint) -> bool;
    }

    #[abi = "rust-intrinsic"]
    extern mod rusti {
        fn get_tydesc<T>() -> *();
        fn visit_tydesc(td: *tydesc, &&tv: ty_visitor);
    }
}
<commit_msg>Mark intrinsic::tydesc with #[allow(non_camel_case_types)]<commit_after>// NB: this file is #include_str'ed into the compiler, re-parsed
// and injected into each crate the compiler builds. Keep it small.

mod intrinsic {

    import rusti::visit_tydesc;
    export ty_visitor, get_tydesc, visit_tydesc, tydesc;

    // FIXME (#2712): remove this when the interface has settled and the
    // version in sys is no longer present.
    fn get_tydesc<T>() -> *tydesc {
        rusti::get_tydesc::<T>() as *tydesc
    }

    #[allow(non_camel_case_types)]
    enum tydesc = {
        first_param: **u8,
        size: uint,
        align: uint
        // Remaining fields not listed
    };

    trait ty_visitor {
        fn visit_bot() -> bool;
        fn visit_nil() -> bool;
        fn visit_bool() -> bool;

        fn visit_int() -> bool;
        fn visit_i8() -> bool;
        fn visit_i16() -> bool;
        fn visit_i32() -> bool;
        fn visit_i64() -> bool;

        fn visit_uint() -> bool;
        fn visit_u8() -> bool;
        fn visit_u16() -> bool;
        fn visit_u32() -> bool;
        fn visit_u64() -> bool;

        fn visit_float() -> bool;
        fn visit_f32() -> bool;
        fn visit_f64() -> bool;

        fn visit_char() -> bool;
        fn visit_str() -> bool;

        fn visit_estr_box() -> bool;
        fn visit_estr_uniq() -> bool;
        fn visit_estr_slice() -> bool;
        fn visit_estr_fixed(n: uint, sz: uint, align: uint) -> bool;

        fn visit_box(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_uniq(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_ptr(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_rptr(mtbl: uint, inner: *tydesc) -> bool;

        fn visit_vec(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_unboxed_vec(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_evec_box(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_evec_uniq(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_evec_slice(mtbl: uint, inner: *tydesc) -> bool;
        fn visit_evec_fixed(n: uint, sz: uint, align: uint,
                            mtbl: uint, inner: *tydesc) -> bool;

        fn visit_enter_rec(n_fields: uint,
                           sz: uint, align: uint) -> bool;
        fn visit_rec_field(i: uint, name: &str,
                           mtbl: uint, inner: *tydesc) -> bool;
        fn visit_leave_rec(n_fields: uint,
                           sz: uint, align: uint) -> bool;

        fn visit_enter_class(n_fields: uint,
                             sz: uint, align: uint) -> bool;
        fn visit_class_field(i: uint, name: &str,
                             mtbl: uint, inner: *tydesc) -> bool;
        fn visit_leave_class(n_fields: uint,
                             sz: uint, align: uint) -> bool;

        fn visit_enter_tup(n_fields: uint,
                           sz: uint, align: uint) -> bool;
        fn visit_tup_field(i: uint, inner: *tydesc) -> bool;
        fn visit_leave_tup(n_fields: uint,
                           sz: uint, align: uint) -> bool;

        fn visit_enter_enum(n_variants: uint,
                            sz: uint, align: uint) -> bool;
        fn visit_enter_enum_variant(variant: uint,
                                    disr_val: int,
                                    n_fields: uint,
                                    name: &str) -> bool;
        fn visit_enum_variant_field(i: uint, inner: *tydesc) -> bool;
        fn visit_leave_enum_variant(variant: uint,
                                    disr_val: int,
                                    n_fields: uint,
                                    name: &str) -> bool;
        fn visit_leave_enum(n_variants: uint,
                            sz: uint, align: uint) -> bool;

        fn visit_enter_fn(purity: uint, proto: uint,
                          n_inputs: uint, retstyle: uint) -> bool;
        fn visit_fn_input(i: uint, mode: uint, inner: *tydesc) -> bool;
        fn visit_fn_output(retstyle: uint, inner: *tydesc) -> bool;
        fn visit_leave_fn(purity: uint, proto: uint,
                          n_inputs: uint, retstyle: uint) -> bool;

        fn visit_trait() -> bool;
        fn visit_var() -> bool;
        fn visit_var_integral() -> bool;
        fn visit_param(i: uint) -> bool;
        fn visit_self() -> bool;
        fn visit_type() -> bool;
        fn visit_opaque_box() -> bool;
        fn visit_constr(inner: *tydesc) -> bool;
        fn visit_closure_ptr(ck: uint) -> bool;
    }

    #[abi = "rust-intrinsic"]
    extern mod rusti {
        fn get_tydesc<T>() -> *();
        fn visit_tydesc(td: *tydesc, &&tv: ty_visitor);
    }
}
<|endoftext|>


<commit_before><commit_msg>2019: Day 1, part 2.<commit_after>use std::io;
use std::io::BufRead;
use std::iter;

type Mass = i32;
type Fuel = i32;

fn main() -> io::Result<()> {
    let module_masses: Vec<Mass> = io::BufReader::new(io::stdin())
        .lines()
        .map(|input| {
            input.and_then(|line| {
                line.parse::<Mass>()
                    .map_err(|err| io::Error::new(io::ErrorKind::Other, err))
            })
        })
        .collect::<io::Result<_>>()?;

    let total_fuel: Fuel = module_masses
        .iter()
        .map(|mass| {
            let initial_fuel = calculate_fuel(mass);
            let fuel_chunks = iter::successors(Some(initial_fuel), |fuel_mass| {
                Some(calculate_fuel(fuel_mass)).filter(|value| value > &0)
            });
            fuel_chunks.sum::<Fuel>()
        })
        .sum();

    println!("{}", total_fuel);

    Ok(())
}

fn calculate_fuel(mass: &i32) -> i32 {
    i32::max(mass / 3 - 2, 0)
}
<|endoftext|>


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

use std::borrow::Cow;
use std::cell::RefCell;
use std::fmt::Display;
use std::path::Path;
use std::rc::Rc;
use std::io::ErrorKind;
use std::collections::BTreeMap;
use std::fmt;

use dbus::Connection;
use dbus::BusType;
use dbus::MessageItem;
use dbus::NameFlag;
use dbus::tree::Factory;
use dbus::tree::DataType;
use dbus::tree::MethodErr;
use dbus::tree::MTFn;
use dbus::tree::MethodResult;
use dbus::tree::MethodInfo;
use dbus::tree::Tree;

use dbus_consts::*;

use engine::Engine;
use types::{StratisResult, StratisError};

#[derive(Clone)]
pub struct DbusContext {
    pub next_index: i32,
    pub pools: BTreeMap<String, String>,
    pub engine: Rc<RefCell<Engine>>,
}

// engine doesn't impl Debug, so we can't derive
impl fmt::Debug for DbusContext {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{{DBusContext {:?}, {:?}}}", self.next_index, self.pools)
    }
}

impl DbusContext {
    pub fn new(engine: &Rc<RefCell<Engine>>) -> DbusContext {
        DbusContext {
            next_index: 0,
            pools: BTreeMap::new(),
            engine: engine.clone(),
        }
    }
    pub fn get_next_id(&mut self) {
        self.next_index += 1;
    }
}

#[derive(Copy, Clone, Default, Debug)]
struct TData;
impl DataType for TData {
    type ObjectPath = Rc<RefCell<DbusContext>>;
    type Property = ();
    type Interface = ();
    type Method = ();
    type Signal = ();
}

fn internal_to_dbus_err(err: &StratisError) -> StratisErrorEnum {
    match *err {
        StratisError::Stratis(_) => StratisErrorEnum::STRATIS_ERROR,
        StratisError::Io(ref err) => {
            match err.kind() {
                ErrorKind::NotFound => StratisErrorEnum::STRATIS_NOTFOUND,
                ErrorKind::AlreadyExists => StratisErrorEnum::STRATIS_ALREADY_EXISTS,
                _ => StratisErrorEnum::STRATIS_ERROR,
            }
        }
        _ => StratisErrorEnum::STRATIS_ERROR,
    }
}

fn list_pools(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    let dbus_context = m.path.get_data();
    let ref engine = dbus_context.borrow().engine;
    let result = engine.borrow().list_pools();

    let mut msg_vec = Vec::new();

    // TODO: deal with failure
    let pool_tree = result.unwrap();

    for (name, pool) in pool_tree {
        let entry = vec![MessageItem::Str(format!("{}", name)),
                         MessageItem::UInt16(0),
                         MessageItem::Str(String::from("Ok"))];
        msg_vec.push(MessageItem::Struct(entry));
    }

    let item_array = MessageItem::Array(msg_vec, Cow::Borrowed("(sqs)"));

    Ok(vec![m.msg.method_return().append1(item_array)])
}

fn create_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    let dbus_context = m.path.get_data();
    let ref mut engine = dbus_context.borrow_mut().engine;

    let message: (Option<MessageItem>, Option<MessageItem>, Option<MessageItem>) = m.msg.get3();

    let item0: MessageItem = try!(message.0.ok_or_else(MethodErr::no_arg));
    let name: &String = try!(item0.inner().map_err(|_| MethodErr::invalid_arg(&item0)));

    let item1: MessageItem = try!(message.1.ok_or_else(MethodErr::no_arg));
    let devs: &Vec<MessageItem> = try!(item1.inner().map_err(|_| MethodErr::invalid_arg(&item1)));
    let mut devstrings = devs.iter().map(|x| x.inner::<&String>());
    if devstrings.any(|x| x.is_err()) {
        return Err(MethodErr::invalid_arg(&item1));
    }
    let blockdevs = devstrings.map(|x| Path::new(x.unwrap())).collect::<Vec<&Path>>();

    let item2: MessageItem = try!(message.2.ok_or_else(MethodErr::no_arg));
    let raid_level: u16 = try!(item2.inner().map_err(|_| MethodErr::invalid_arg(&item2)));

    let result = engine.borrow_mut().create_pool(name, &blockdevs, raid_level);
    match result {
        Ok(_) => Ok(vec![m.msg.method_return().append3("/dbus/newpool/path", 0, "Ok")]),
        Err(x) => {
            let dbus_err = internal_to_dbus_err(&x);
            Ok(vec![m.msg
                        .method_return()
                        .append3("", dbus_err.get_error_int(), dbus_err.get_error_string())])
        }
    }
}

fn destroy_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    let dbus_context = m.path.get_data();
    let ref engine = dbus_context.borrow().engine;

    let item: MessageItem = try!(m.msg.get1().ok_or_else(MethodErr::no_arg));

    let name: &String = try!(item.inner().map_err(|_| MethodErr::invalid_arg(&item)));

    let result = engine.borrow_mut().destroy_pool(&name);

    let message = m.msg.method_return();

    let msg = match result {
        Ok(_) => {
            message.append2(MessageItem::UInt16(0),
                            MessageItem::Str(format!("{}", "Ok")))
        }
        Err(err) => {
            message.append2(MessageItem::UInt16(0),
                            MessageItem::Str(format!("{}", "Ok")))
        }
    };

    Ok(vec![msg])
}

fn get_pool_object_path(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    Ok(vec![m.msg.method_return().append3("/dbus/pool/path", 0, "Ok")])
}

fn get_volume_object_path(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    Ok(vec![m.msg.method_return().append3("/dbus/volume/path", 0, "Ok")])
}

fn get_dev_object_path(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    Ok(vec![m.msg.method_return().append3("/dbus/dev/path", 0, "Ok")])
}

fn get_cache_object_path(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    Ok(vec![m.msg.method_return().append3("/dbus/cache/path", 0, "Ok")])
}

fn get_list_items<T, I>(m: &MethodInfo<MTFn<TData>, TData>, iter: I) -> MethodResult
    where T: HasCodes + Display,
          I: Iterator<Item = T>
{
    let msg_vec = iter.map(|item| {
            MessageItem::Struct(vec![MessageItem::Str(format!("{}", item)),
                                     MessageItem::UInt16(item.get_error_int()),
                                     MessageItem::Str(format!("{}", item.get_error_string()))])
        })
        .collect::<Vec<MessageItem>>();

    let item_array = MessageItem::Array(msg_vec, Cow::Borrowed("(sqs)"));
    Ok(vec![m.msg.method_return().append1(item_array)])
}

fn get_error_codes(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    get_list_items(m, StratisErrorEnum::iter_variants())
}

fn get_raid_levels(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    get_list_items(m, StratisRaidType::iter_variants())
}

fn get_dev_types(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let mut items = m.msg.get_items();
    if items.len() < 1 {
        return Err(MethodErr::no_arg());
    }

    let _name = try!(items.pop()
        .ok_or_else(MethodErr::no_arg)
        .and_then(|i| {
            i.inner::<&str>()
                .map_err(|_| MethodErr::invalid_arg(&i))
                .map(|i| i.to_owned())
        }));

    println!("method called");

    Ok(vec![m.msg.method_return()])
}

fn get_base_tree<'a>(dbus_context: Rc<RefCell<DbusContext>>)
                     -> StratisResult<Tree<MTFn<TData>, TData>> {

    let f = Factory::new_fn();

    let base_tree = f.tree();

    let createpool_method = f.method(CREATE_POOL, (), create_pool)
        .in_arg(("pool_name", "s"))
        .in_arg(("dev_list", "as"))
        .in_arg(("raid_type", "q"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let destroypool_method = f.method(DESTROY_POOL, (), destroy_pool)
        .in_arg(("pool_name", "s"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let listpools_method = f.method(LIST_POOLS, (), list_pools)
        .out_arg(("pool_names", "as"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let getpoolobjectpath_method = f.method(GET_POOL_OBJECT_PATH, (), get_pool_object_path)
        .in_arg(("pool_name", "s"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let getvolumeobjectpath_method = f.method(GET_VOLUME_OBJECT_PATH, (), get_volume_object_path)
        .in_arg(("pool_name", "s"))
        .in_arg(("volume_name", "s"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let getdevobjectpath_method = f.method(GET_DEV_OBJECT_PATH, (), get_dev_object_path)
        .in_arg(("dev_name", "s"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let getcacheobjectpath_method = f.method(GET_CACHE_OBJECT_PATH, (), get_cache_object_path)
        .in_arg(("cache_dev_name", "s"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let geterrorcodes_method = f.method(GET_ERROR_CODES, (), get_error_codes)
        .out_arg(("error_codes", "a(sqs)"));

    let getraidlevels_method = f.method(GET_RAID_LEVELS, (), get_raid_levels)
        .out_arg(("error_codes", "a(sqs)"));

    let getdevtypes_method = f.method(GET_DEV_TYPES, (), get_dev_types);

    let obj_path = f.object_path(STRATIS_BASE_PATH, dbus_context)
        .introspectable()
        .add(f.interface(STRATIS_MANAGER_INTERFACE, ())
            .add_m(listpools_method)
            .add_m(createpool_method)
            .add_m(destroypool_method)
            .add_m(getpoolobjectpath_method)
            .add_m(getvolumeobjectpath_method)
            .add_m(getdevobjectpath_method)
            .add_m(getcacheobjectpath_method)
            .add_m(geterrorcodes_method)
            .add_m(getraidlevels_method)
            .add_m(getdevtypes_method));

    let base_tree = base_tree.add(obj_path);

    Ok(base_tree)
}

pub fn run(engine: Rc<RefCell<Engine>>) -> StratisResult<()> {
    let dbus_context = Rc::new(RefCell::new(DbusContext::new(&engine)));
    let tree = get_base_tree(dbus_context.clone()).unwrap();

    // Setup DBus connection
    let c = try!(Connection::get_private(BusType::Session));
    c.register_name(STRATIS_BASE_SERVICE, NameFlag::ReplaceExisting as u32).unwrap();
    try!(tree.set_registered(&c, true));

    // ...and serve incoming requests.
    for _ in tree.run(&c, c.iter(1000)) {
    }

    Ok(())
}
<commit_msg>Get rid of obsolete code that had become distracting.<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/.

use std::borrow::Cow;
use std::cell::RefCell;
use std::fmt::Display;
use std::path::Path;
use std::rc::Rc;
use std::io::ErrorKind;
use std::collections::BTreeMap;
use std::fmt;

use dbus::Connection;
use dbus::BusType;
use dbus::MessageItem;
use dbus::NameFlag;
use dbus::tree::Factory;
use dbus::tree::DataType;
use dbus::tree::MethodErr;
use dbus::tree::MTFn;
use dbus::tree::MethodResult;
use dbus::tree::MethodInfo;
use dbus::tree::Tree;

use dbus_consts::*;

use engine::Engine;
use types::{StratisResult, StratisError};

#[derive(Clone)]
pub struct DbusContext {
    pub next_index: i32,
    pub pools: BTreeMap<String, String>,
    pub engine: Rc<RefCell<Engine>>,
}

// engine doesn't impl Debug, so we can't derive
impl fmt::Debug for DbusContext {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{{DBusContext {:?}, {:?}}}", self.next_index, self.pools)
    }
}

impl DbusContext {
    pub fn new(engine: &Rc<RefCell<Engine>>) -> DbusContext {
        DbusContext {
            next_index: 0,
            pools: BTreeMap::new(),
            engine: engine.clone(),
        }
    }
    pub fn get_next_id(&mut self) {
        self.next_index += 1;
    }
}

#[derive(Copy, Clone, Default, Debug)]
struct TData;
impl DataType for TData {
    type ObjectPath = Rc<RefCell<DbusContext>>;
    type Property = ();
    type Interface = ();
    type Method = ();
    type Signal = ();
}

fn internal_to_dbus_err(err: &StratisError) -> StratisErrorEnum {
    match *err {
        StratisError::Stratis(_) => StratisErrorEnum::STRATIS_ERROR,
        StratisError::Io(ref err) => {
            match err.kind() {
                ErrorKind::NotFound => StratisErrorEnum::STRATIS_NOTFOUND,
                ErrorKind::AlreadyExists => StratisErrorEnum::STRATIS_ALREADY_EXISTS,
                _ => StratisErrorEnum::STRATIS_ERROR,
            }
        }
        _ => StratisErrorEnum::STRATIS_ERROR,
    }
}

fn list_pools(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    let dbus_context = m.path.get_data();
    let ref engine = dbus_context.borrow().engine;
    let result = engine.borrow().list_pools();

    let mut msg_vec = Vec::new();

    // TODO: deal with failure
    let pool_tree = result.unwrap();

    for (name, pool) in pool_tree {
        let entry = vec![MessageItem::Str(format!("{}", name)),
                         MessageItem::UInt16(0),
                         MessageItem::Str(String::from("Ok"))];
        msg_vec.push(MessageItem::Struct(entry));
    }

    let item_array = MessageItem::Array(msg_vec, Cow::Borrowed("(sqs)"));

    Ok(vec![m.msg.method_return().append1(item_array)])
}

fn create_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    let dbus_context = m.path.get_data();
    let ref mut engine = dbus_context.borrow_mut().engine;

    let message: (Option<MessageItem>, Option<MessageItem>, Option<MessageItem>) = m.msg.get3();

    let item0: MessageItem = try!(message.0.ok_or_else(MethodErr::no_arg));
    let name: &String = try!(item0.inner().map_err(|_| MethodErr::invalid_arg(&item0)));

    let item1: MessageItem = try!(message.1.ok_or_else(MethodErr::no_arg));
    let devs: &Vec<MessageItem> = try!(item1.inner().map_err(|_| MethodErr::invalid_arg(&item1)));
    let mut devstrings = devs.iter().map(|x| x.inner::<&String>());
    if devstrings.any(|x| x.is_err()) {
        return Err(MethodErr::invalid_arg(&item1));
    }
    let blockdevs = devstrings.map(|x| Path::new(x.unwrap())).collect::<Vec<&Path>>();

    let item2: MessageItem = try!(message.2.ok_or_else(MethodErr::no_arg));
    let raid_level: u16 = try!(item2.inner().map_err(|_| MethodErr::invalid_arg(&item2)));

    let result = engine.borrow_mut().create_pool(name, &blockdevs, raid_level);
    match result {
        Ok(_) => Ok(vec![m.msg.method_return().append3("/dbus/newpool/path", 0, "Ok")]),
        Err(x) => {
            let dbus_err = internal_to_dbus_err(&x);
            Ok(vec![m.msg
                        .method_return()
                        .append3("", dbus_err.get_error_int(), dbus_err.get_error_string())])
        }
    }
}

fn destroy_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    let dbus_context = m.path.get_data();
    let ref engine = dbus_context.borrow().engine;

    let item: MessageItem = try!(m.msg.get1().ok_or_else(MethodErr::no_arg));

    let name: &String = try!(item.inner().map_err(|_| MethodErr::invalid_arg(&item)));

    let result = engine.borrow_mut().destroy_pool(&name);

    let message = m.msg.method_return();

    let msg = match result {
        Ok(_) => {
            message.append2(MessageItem::UInt16(0),
                            MessageItem::Str(format!("{}", "Ok")))
        }
        Err(err) => {
            message.append2(MessageItem::UInt16(0),
                            MessageItem::Str(format!("{}", "Ok")))
        }
    };

    Ok(vec![msg])
}

fn get_pool_object_path(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    Ok(vec![m.msg.method_return().append3("/dbus/pool/path", 0, "Ok")])
}

fn get_volume_object_path(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    Ok(vec![m.msg.method_return().append3("/dbus/volume/path", 0, "Ok")])
}

fn get_dev_object_path(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    Ok(vec![m.msg.method_return().append3("/dbus/dev/path", 0, "Ok")])
}

fn get_cache_object_path(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    Ok(vec![m.msg.method_return().append3("/dbus/cache/path", 0, "Ok")])
}

fn get_list_items<T, I>(m: &MethodInfo<MTFn<TData>, TData>, iter: I) -> MethodResult
    where T: HasCodes + Display,
          I: Iterator<Item = T>
{
    let msg_vec = iter.map(|item| {
            MessageItem::Struct(vec![MessageItem::Str(format!("{}", item)),
                                     MessageItem::UInt16(item.get_error_int()),
                                     MessageItem::Str(format!("{}", item.get_error_string()))])
        })
        .collect::<Vec<MessageItem>>();

    let item_array = MessageItem::Array(msg_vec, Cow::Borrowed("(sqs)"));
    Ok(vec![m.msg.method_return().append1(item_array)])
}

fn get_error_codes(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    get_list_items(m, StratisErrorEnum::iter_variants())
}

fn get_raid_levels(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    get_list_items(m, StratisRaidType::iter_variants())
}

fn get_dev_types(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    Ok(vec![m.msg.method_return()])
}

fn get_base_tree<'a>(dbus_context: Rc<RefCell<DbusContext>>)
                     -> StratisResult<Tree<MTFn<TData>, TData>> {

    let f = Factory::new_fn();

    let base_tree = f.tree();

    let createpool_method = f.method(CREATE_POOL, (), create_pool)
        .in_arg(("pool_name", "s"))
        .in_arg(("dev_list", "as"))
        .in_arg(("raid_type", "q"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let destroypool_method = f.method(DESTROY_POOL, (), destroy_pool)
        .in_arg(("pool_name", "s"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let listpools_method = f.method(LIST_POOLS, (), list_pools)
        .out_arg(("pool_names", "as"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let getpoolobjectpath_method = f.method(GET_POOL_OBJECT_PATH, (), get_pool_object_path)
        .in_arg(("pool_name", "s"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let getvolumeobjectpath_method = f.method(GET_VOLUME_OBJECT_PATH, (), get_volume_object_path)
        .in_arg(("pool_name", "s"))
        .in_arg(("volume_name", "s"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let getdevobjectpath_method = f.method(GET_DEV_OBJECT_PATH, (), get_dev_object_path)
        .in_arg(("dev_name", "s"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let getcacheobjectpath_method = f.method(GET_CACHE_OBJECT_PATH, (), get_cache_object_path)
        .in_arg(("cache_dev_name", "s"))
        .out_arg(("object_path", "o"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let geterrorcodes_method = f.method(GET_ERROR_CODES, (), get_error_codes)
        .out_arg(("error_codes", "a(sqs)"));

    let getraidlevels_method = f.method(GET_RAID_LEVELS, (), get_raid_levels)
        .out_arg(("error_codes", "a(sqs)"));

    let getdevtypes_method = f.method(GET_DEV_TYPES, (), get_dev_types);

    let obj_path = f.object_path(STRATIS_BASE_PATH, dbus_context)
        .introspectable()
        .add(f.interface(STRATIS_MANAGER_INTERFACE, ())
            .add_m(listpools_method)
            .add_m(createpool_method)
            .add_m(destroypool_method)
            .add_m(getpoolobjectpath_method)
            .add_m(getvolumeobjectpath_method)
            .add_m(getdevobjectpath_method)
            .add_m(getcacheobjectpath_method)
            .add_m(geterrorcodes_method)
            .add_m(getraidlevels_method)
            .add_m(getdevtypes_method));

    let base_tree = base_tree.add(obj_path);

    Ok(base_tree)
}

pub fn run(engine: Rc<RefCell<Engine>>) -> StratisResult<()> {
    let dbus_context = Rc::new(RefCell::new(DbusContext::new(&engine)));
    let tree = get_base_tree(dbus_context.clone()).unwrap();

    // Setup DBus connection
    let c = try!(Connection::get_private(BusType::Session));
    c.register_name(STRATIS_BASE_SERVICE, NameFlag::ReplaceExisting as u32).unwrap();
    try!(tree.set_registered(&c, true));

    // ...and serve incoming requests.
    for _ in tree.run(&c, c.iter(1000)) {
    }

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Refactor `build_time, handle_source`<commit_after><|endoftext|>


<commit_before><commit_msg>Improve the fileutils dump code and make it available external to the module for debugging<commit_after><|endoftext|>


<commit_before><commit_msg>Test case for issue #435.<commit_after>//xfail-stage0
//xfail-stage1
//xfail-stage2
//xfail-stage3

// Test case for issue #435.
obj foo() {
    fn add5(n: int) -> int {
        ret n + 5;
    }
}

fn add5(n: int) -> int {
    ret n + 5;
}

fn main() {
    let fiveplusseven = bind add5(7);
    assert add5(7) == 12;
    assert fiveplusseven() == 12;

    let my_foo = foo();
    let fiveplusseven_too = bind my_foo.add5(7);
    assert my_foo.add5(7) == 12;
    assert fiveplusseven_too() == 12;
}

<|endoftext|>


<commit_before>use std::mem::replace;

struct Fibonacci {
    curr: uint,
    next: uint,
}

// implement Iterator for Fibonacci
impl Iterator<uint> for Fibonacci {
    // the Iterator trait only requires the next() method to be defined the
    // return value is Option<T>, None is returned when the Iterator is
    // over, otherwise the next value is returned wrapped in Some
    fn next(&mut self) -> Option<uint> {
        let new_next = self.curr + self.next;
        let new_curr = replace(&mut self.next, new_next);

        // Some is always returned, this is an infinite value generator
        Some(replace(&mut self.curr, new_curr))
    }
}

// returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
    Fibonacci { curr: 1, next: 1 }
}

fn main() {
    // iterator that generates: 0, 1 and 2
    let mut sequence = range(0, 3);

    println!("next in range(0, 3): {}", sequence.next());
    println!("next in range(0, 3): {}", sequence.next());
    println!("next in range(0, 3): {}", sequence.next());
    println!("next in range(0, 3): {}", sequence.next());

    // the for construct will iterate an Iterator until in returns None,
    // all the Some values are unwrapped and bind to a variable
    println!("iterate over range(0, 3) using for");
    for i in range(0, 3) {
        println!("{}", i);
    }

    // the take(n) method will reduce an iterator to its first n terms,
    // pretty useful for infinite value generators
    println!("The first ten terms of the fibonacci sequence are: ");
    for i in fibonacci().take(10) {
        println!("{}", i);
    }

    // the skip(n) method will shorten an iterator by dropping its first n
    // terms
    println!("The next ten terms of the fibonacci sequence are: ");
    for i in fibonacci().skip(10).take(10) {
        println!("{}", i);
    }

    let array = [1, 3, 3, 7];

    // the iter() method produces an iterator over an array/slice
    println!("iterate the following array {}", array.as_slice());
    for i in array.iter() {
        println!("{}", i);
    }
}
<commit_msg>iter: reduce length of the example output<commit_after>use std::mem::replace;

struct Fibonacci {
    curr: uint,
    next: uint,
}

// implement Iterator for Fibonacci
impl Iterator<uint> for Fibonacci {
    // the Iterator trait only requires the next() method to be defined the
    // return value is Option<T>, None is returned when the Iterator is
    // over, otherwise the next value is returned wrapped in Some
    fn next(&mut self) -> Option<uint> {
        let new_next = self.curr + self.next;
        let new_curr = replace(&mut self.next, new_next);

        // Some is always returned, this is an infinite value generator
        Some(replace(&mut self.curr, new_curr))
    }
}

// returns a fibonacci sequence generator
fn fibonacci() -> Fibonacci {
    Fibonacci { curr: 1, next: 1 }
}

fn main() {
    // iterator that generates: 0, 1 and 2
    let mut sequence = range(0, 3);

    println!("next in range(0, 3): {}", sequence.next());
    println!("next in range(0, 3): {}", sequence.next());
    println!("next in range(0, 3): {}", sequence.next());
    println!("next in range(0, 3): {}", sequence.next());

    // the for construct will iterate an Iterator until it returns None,
    // all the Some values are unwrapped and bind to a variable
    println!("iterate over range(0, 3) using for");
    for i in range(0, 3) {
        println!("{}", i);
    }

    // the take(n) method will reduce an iterator to its first n terms,
    // pretty useful for infinite value generators
    println!("The first five terms of the fibonacci sequence are: ");
    for i in fibonacci().take(5) {
        println!("{}", i);
    }

    // the skip(n) method will shorten an iterator by dropping its first n
    // terms
    println!("The next five terms of the fibonacci sequence are: ");
    for i in fibonacci().skip(5).take(5) {
        println!("{}", i);
    }

    let array = [1, 3, 3, 7];

    // the iter() method produces an iterator over an array/slice
    println!("iterate the following array {}", array.as_slice());
    for i in array.iter() {
        println!("{}", i);
    }
}
<|endoftext|>


<commit_before><commit_msg>fix timer tests<commit_after><|endoftext|>


<commit_before><commit_msg>add the missing sink.rs<commit_after>use base::Sink;

use std::ptr;
use std::marker::PhantomData;

impl<T> Sink<T> for Vec<T> {
    #[inline(always)] fn consume(&mut self, x: T) {
        self.push(x);
    }
}

#[derive(new)]
pub struct UncheckedVecSink<T> {
    output: Vec<T>
}

impl<T> Sink<T> for UncheckedVecSink<T> {
    #[inline(always)] fn consume(&mut self, item: T) {
        consume_unchecked(&mut self.output, item);
    }
}

#[derive(new)]
pub struct UncheckedVecRefSink<'a, T: 'a> {
    pub output: &'a mut Vec<T>
}

impl<'a, T: 'a> Sink<T> for UncheckedVecRefSink<'a, T> {
    #[inline(always)] fn consume(&mut self, item: T) {
        consume_unchecked(&mut self.output, item);
    }
}

pub struct RefCopyingSink<T: Copy, S: Sink<T>> {
    pub sink: S,
    _ph: PhantomData<T>
}

impl<T, S> RefCopyingSink<T, S>
    where T: Copy, S: Sink<T>
{
    pub fn new(sink: S) -> Self {
        RefCopyingSink { sink:sink, _ph: PhantomData }
    }
}

impl<'a, T, S> Sink<&'a T> for RefCopyingSink<T, S>
    where T: Copy+'a, S: Sink<T>
{
    #[inline(always)] fn consume(&mut self, x: &'a T) {
        self.sink.consume(*x);
    }
}

pub struct RefCloningSink<T: Clone, S: Sink<T>> {
    pub sink: S,
    _ph: PhantomData<T>
}

impl<T, S> RefCloningSink<T, S>
    where T: Clone, S: Sink<T>
{
    pub fn new(sink: S) -> Self {
        RefCloningSink { sink:sink, _ph: PhantomData }
    }
}

impl<'a, T, S> Sink<&'a T> for RefCloningSink<T, S>
    where T: Clone+'a, S: Sink<T>
{
    #[inline(always)] fn consume(&mut self, x: &'a T) {
        self.sink.consume(x.clone());
    }
}

#[inline(always)]
pub fn consume_unchecked<T>(output: &mut Vec<T>, item: T) {
    unsafe {
        let len = output.len();
        debug_assert!(len < output.capacity());
        output.set_len(len + 1);
        let p = output.get_unchecked_mut(len);

        ptr::write(p, item);
    }
}
<|endoftext|>


<commit_before>

/*
 * A SHA-1 implementation derived from Paul E. Jones's reference
 * implementation, which is written for clarity, not speed. At some
 * point this will want to be rewritten.
 */
export sha1;
export mk_sha1;

type sha1 =
    // Provide message input as bytes

    // Provide message input as string

    // Read the digest as a vector of 20 bytes. After
    // calling this no further input may provided
    // until reset is called

    // Same as above, just a hex-string version.

    // Reset the sha1 state for reuse. This is called
    // automatically during construction
    obj {
        fn input(&[u8]);
        fn input_str(&str);
        fn result() -> [u8];
        fn result_str() -> str;
        fn reset();
    };

// Some unexported constants
const digest_buf_len: uint = 5u;

const msg_block_len: uint = 64u;

const work_buf_len: uint = 80u;

const k0: u32 = 0x5A827999u32;

const k1: u32 = 0x6ED9EBA1u32;

const k2: u32 = 0x8F1BBCDCu32;

const k3: u32 = 0xCA62C1D6u32;

// Builds a sha1 object
fn mk_sha1() -> sha1 {
    type sha1state =
        {h: [mutable u32],
         mutable len_low: u32,
         mutable len_high: u32,
         msg_block: [mutable u8],
         mutable msg_block_idx: uint,
         mutable computed: bool,
         work_buf: [mutable u32]};

    fn add_input(st: &sha1state, msg: &[u8]) {
        // FIXME: Should be typestate precondition

        assert (!st.computed);
        for element: u8 in msg {
            st.msg_block[st.msg_block_idx] = element;
            st.msg_block_idx += 1u;
            st.len_low += 8u32;
            if st.len_low == 0u32 {
                st.len_high += 1u32;
                if st.len_high == 0u32 {
                    // FIXME: Need better failure mode

                    fail;
                }
            }
            if st.msg_block_idx == msg_block_len { process_msg_block(st); }
        }
    }
    fn process_msg_block(st: &sha1state) {
        // FIXME: Make precondition

        assert (vec::len(st.h) == digest_buf_len);
        assert (vec::len(st.work_buf) == work_buf_len);
        let t: int; // Loop counter

        let w = st.work_buf;
        // Initialize the first 16 words of the vector w

        t = 0;
        while t < 16 {
            let tmp;
            tmp = (st.msg_block[t * 4] as u32) << 24u32;
            tmp = tmp | (st.msg_block[t * 4 + 1] as u32) << 16u32;
            tmp = tmp | (st.msg_block[t * 4 + 2] as u32) << 8u32;
            tmp = tmp | (st.msg_block[t * 4 + 3] as u32);
            w[t] = tmp;
            t += 1;
        }
        // Initialize the rest of vector w

        while t < 80 {
            let val = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
            w[t] = circular_shift(1u32, val);
            t += 1;
        }
        let a = st.h[0];
        let b = st.h[1];
        let c = st.h[2];
        let d = st.h[3];
        let e = st.h[4];
        let temp: u32;
        t = 0;
        while t < 20 {
            temp = circular_shift(5u32, a) + (b & c | !b & d) + e + w[t] + k0;
            e = d;
            d = c;
            c = circular_shift(30u32, b);
            b = a;
            a = temp;
            t += 1;
        }
        while t < 40 {
            temp = circular_shift(5u32, a) + (b ^ c ^ d) + e + w[t] + k1;
            e = d;
            d = c;
            c = circular_shift(30u32, b);
            b = a;
            a = temp;
            t += 1;
        }
        while t < 60 {
            temp =
                circular_shift(5u32, a) + (b & c | b & d | c & d) + e + w[t] +
                    k2;
            e = d;
            d = c;
            c = circular_shift(30u32, b);
            b = a;
            a = temp;
            t += 1;
        }
        while t < 80 {
            temp = circular_shift(5u32, a) + (b ^ c ^ d) + e + w[t] + k3;
            e = d;
            d = c;
            c = circular_shift(30u32, b);
            b = a;
            a = temp;
            t += 1;
        }
        st.h[0] = st.h[0] + a;
        st.h[1] = st.h[1] + b;
        st.h[2] = st.h[2] + c;
        st.h[3] = st.h[3] + d;
        st.h[4] = st.h[4] + e;
        st.msg_block_idx = 0u;
    }
    fn circular_shift(bits: u32, word: u32) -> u32 {
        ret word << bits | word >> 32u32 - bits;
    }
    fn mk_result(st: &sha1state) -> [u8] {
        if !st.computed { pad_msg(st); st.computed = true; }
        let rs: [u8] = [];
        for hpart: u32 in st.h {
            let a = hpart >> 24u32 & 0xFFu32 as u8;
            let b = hpart >> 16u32 & 0xFFu32 as u8;
            let c = hpart >> 8u32 & 0xFFu32 as u8;
            let d = hpart & 0xFFu32 as u8;
            rs += [a, b, c, d];
        }
        ret rs;
    }
    /*
     * According to the standard, the message must be padded to an even
     * 512 bits.  The first padding bit must be a '1'.  The last 64 bits
     * represent the length of the original message.  All bits in between
     * should be 0.  This function will pad the message according to those
     * rules by filling the msg_block vector accordingly.  It will also
     * call process_msg_block() appropriately.  When it returns, it
     * can be assumed that the message digest has been computed.
     */

    fn pad_msg(st: &sha1state) {
        // FIXME: Should be a precondition

        assert (vec::len(st.msg_block) == msg_block_len);
        /*
         * Check to see if the current message block is too small to hold
         * the initial padding bits and length.  If so, we will pad the
         * block, process it, and then continue padding into a second block.
         */

        if st.msg_block_idx > 55u {
            st.msg_block[st.msg_block_idx] = 0x80u8;
            st.msg_block_idx += 1u;
            while st.msg_block_idx < msg_block_len {
                st.msg_block[st.msg_block_idx] = 0u8;
                st.msg_block_idx += 1u;
            }
            process_msg_block(st);
        } else {
            st.msg_block[st.msg_block_idx] = 0x80u8;
            st.msg_block_idx += 1u;
        }
        while st.msg_block_idx < 56u {
            st.msg_block[st.msg_block_idx] = 0u8;
            st.msg_block_idx += 1u;
        }
        // Store the message length as the last 8 octets

        st.msg_block[56] = st.len_high >> 24u32 & 0xFFu32 as u8;
        st.msg_block[57] = st.len_high >> 16u32 & 0xFFu32 as u8;
        st.msg_block[58] = st.len_high >> 8u32 & 0xFFu32 as u8;
        st.msg_block[59] = st.len_high & 0xFFu32 as u8;
        st.msg_block[60] = st.len_low >> 24u32 & 0xFFu32 as u8;
        st.msg_block[61] = st.len_low >> 16u32 & 0xFFu32 as u8;
        st.msg_block[62] = st.len_low >> 8u32 & 0xFFu32 as u8;
        st.msg_block[63] = st.len_low & 0xFFu32 as u8;
        process_msg_block(st);
    }
    obj sha1(st: sha1state) {
        fn reset() {
            // FIXME: Should be typestate precondition

            assert (vec::len(st.h) == digest_buf_len);
            st.len_low = 0u32;
            st.len_high = 0u32;
            st.msg_block_idx = 0u;
            st.h[0] = 0x67452301u32;
            st.h[1] = 0xEFCDAB89u32;
            st.h[2] = 0x98BADCFEu32;
            st.h[3] = 0x10325476u32;
            st.h[4] = 0xC3D2E1F0u32;
            st.computed = false;
        }
        fn input(msg: &[u8]) { add_input(st, msg); }
        fn input_str(msg: &str) { add_input(st, str::bytes(msg)); }
        fn result() -> [u8] { ret mk_result(st); }
        fn result_str() -> str {
            let r = mk_result(st);
            let s = "";
            for b: u8 in r { s += uint::to_str(b as uint, 16u); }
            ret s;
        }
    }
    let st =
        {h: vec::init_elt_mut::<u32>(0u32, digest_buf_len),
         mutable len_low: 0u32,
         mutable len_high: 0u32,
         msg_block: vec::init_elt_mut::<u8>(0u8, msg_block_len),
         mutable msg_block_idx: 0u,
         mutable computed: false,
         work_buf: vec::init_elt_mut::<u32>(0u32, work_buf_len)};
    let sh = sha1(st);
    sh.reset();
    ret sh;
}
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>Cleanup formatting in std::sha1<commit_after>/*
 * A SHA-1 implementation derived from Paul E. Jones's reference
 * implementation, which is written for clarity, not speed. At some
 * point this will want to be rewritten.
 */
export sha1;
export mk_sha1;

type sha1 = obj {
    // Provide message input as bytes
    fn input(&[u8]);
    // Provide message input as string
    fn input_str(&str);
    // Read the digest as a vector of 20 bytes. After calling this no further
    // input may provided until reset is called
    fn result() -> [u8];
    // Same as above, just a hex-string version.
    fn result_str() -> str;
    // Reset the sha1 state for reuse. This is called
    // automatically during construction
    fn reset();
};

// Some unexported constants
const digest_buf_len: uint = 5u;
const msg_block_len: uint = 64u;
const work_buf_len: uint = 80u;
const k0: u32 = 0x5A827999u32;
const k1: u32 = 0x6ED9EBA1u32;
const k2: u32 = 0x8F1BBCDCu32;
const k3: u32 = 0xCA62C1D6u32;

// Builds a sha1 object
fn mk_sha1() -> sha1 {
    type sha1state =
        {h: [mutable u32],
         mutable len_low: u32,
         mutable len_high: u32,
         msg_block: [mutable u8],
         mutable msg_block_idx: uint,
         mutable computed: bool,
         work_buf: [mutable u32]};

    fn add_input(st: &sha1state, msg: &[u8]) {
        // FIXME: Should be typestate precondition
        assert (!st.computed);
        for element: u8 in msg {
            st.msg_block[st.msg_block_idx] = element;
            st.msg_block_idx += 1u;
            st.len_low += 8u32;
            if st.len_low == 0u32 {
                st.len_high += 1u32;
                if st.len_high == 0u32 {
                    // FIXME: Need better failure mode

                    fail;
                }
            }
            if st.msg_block_idx == msg_block_len { process_msg_block(st); }
        }
    }
    fn process_msg_block(st: &sha1state) {
        // FIXME: Make precondition
        assert (vec::len(st.h) == digest_buf_len);
        assert (vec::len(st.work_buf) == work_buf_len);
        let t: int; // Loop counter
        let w = st.work_buf;

        // Initialize the first 16 words of the vector w
        t = 0;
        while t < 16 {
            let tmp;
            tmp = (st.msg_block[t * 4] as u32) << 24u32;
            tmp = tmp | (st.msg_block[t * 4 + 1] as u32) << 16u32;
            tmp = tmp | (st.msg_block[t * 4 + 2] as u32) << 8u32;
            tmp = tmp | (st.msg_block[t * 4 + 3] as u32);
            w[t] = tmp;
            t += 1;
        }

        // Initialize the rest of vector w
        while t < 80 {
            let val = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
            w[t] = circular_shift(1u32, val);
            t += 1;
        }
        let a = st.h[0];
        let b = st.h[1];
        let c = st.h[2];
        let d = st.h[3];
        let e = st.h[4];
        let temp: u32;
        t = 0;
        while t < 20 {
            temp = circular_shift(5u32, a) + (b & c | !b & d) + e + w[t] + k0;
            e = d;
            d = c;
            c = circular_shift(30u32, b);
            b = a;
            a = temp;
            t += 1;
        }
        while t < 40 {
            temp = circular_shift(5u32, a) + (b ^ c ^ d) + e + w[t] + k1;
            e = d;
            d = c;
            c = circular_shift(30u32, b);
            b = a;
            a = temp;
            t += 1;
        }
        while t < 60 {
            temp =
                circular_shift(5u32, a) + (b & c | b & d | c & d) + e + w[t] +
                    k2;
            e = d;
            d = c;
            c = circular_shift(30u32, b);
            b = a;
            a = temp;
            t += 1;
        }
        while t < 80 {
            temp = circular_shift(5u32, a) + (b ^ c ^ d) + e + w[t] + k3;
            e = d;
            d = c;
            c = circular_shift(30u32, b);
            b = a;
            a = temp;
            t += 1;
        }
        st.h[0] = st.h[0] + a;
        st.h[1] = st.h[1] + b;
        st.h[2] = st.h[2] + c;
        st.h[3] = st.h[3] + d;
        st.h[4] = st.h[4] + e;
        st.msg_block_idx = 0u;
    }
    fn circular_shift(bits: u32, word: u32) -> u32 {
        ret word << bits | word >> 32u32 - bits;
    }
    fn mk_result(st: &sha1state) -> [u8] {
        if !st.computed { pad_msg(st); st.computed = true; }
        let rs: [u8] = [];
        for hpart: u32 in st.h {
            let a = hpart >> 24u32 & 0xFFu32 as u8;
            let b = hpart >> 16u32 & 0xFFu32 as u8;
            let c = hpart >> 8u32 & 0xFFu32 as u8;
            let d = hpart & 0xFFu32 as u8;
            rs += [a, b, c, d];
        }
        ret rs;
    }

    /*
     * According to the standard, the message must be padded to an even
     * 512 bits.  The first padding bit must be a '1'.  The last 64 bits
     * represent the length of the original message.  All bits in between
     * should be 0.  This function will pad the message according to those
     * rules by filling the msg_block vector accordingly.  It will also
     * call process_msg_block() appropriately.  When it returns, it
     * can be assumed that the message digest has been computed.
     */
    fn pad_msg(st: &sha1state) {
        // FIXME: Should be a precondition
        assert (vec::len(st.msg_block) == msg_block_len);

        /*
         * Check to see if the current message block is too small to hold
         * the initial padding bits and length.  If so, we will pad the
         * block, process it, and then continue padding into a second block.
         */
        if st.msg_block_idx > 55u {
            st.msg_block[st.msg_block_idx] = 0x80u8;
            st.msg_block_idx += 1u;
            while st.msg_block_idx < msg_block_len {
                st.msg_block[st.msg_block_idx] = 0u8;
                st.msg_block_idx += 1u;
            }
            process_msg_block(st);
        } else {
            st.msg_block[st.msg_block_idx] = 0x80u8;
            st.msg_block_idx += 1u;
        }
        while st.msg_block_idx < 56u {
            st.msg_block[st.msg_block_idx] = 0u8;
            st.msg_block_idx += 1u;
        }

        // Store the message length as the last 8 octets
        st.msg_block[56] = st.len_high >> 24u32 & 0xFFu32 as u8;
        st.msg_block[57] = st.len_high >> 16u32 & 0xFFu32 as u8;
        st.msg_block[58] = st.len_high >> 8u32 & 0xFFu32 as u8;
        st.msg_block[59] = st.len_high & 0xFFu32 as u8;
        st.msg_block[60] = st.len_low >> 24u32 & 0xFFu32 as u8;
        st.msg_block[61] = st.len_low >> 16u32 & 0xFFu32 as u8;
        st.msg_block[62] = st.len_low >> 8u32 & 0xFFu32 as u8;
        st.msg_block[63] = st.len_low & 0xFFu32 as u8;
        process_msg_block(st);
    }
    obj sha1(st: sha1state) {
        fn reset() {
            // FIXME: Should be typestate precondition
            assert (vec::len(st.h) == digest_buf_len);
            st.len_low = 0u32;
            st.len_high = 0u32;
            st.msg_block_idx = 0u;
            st.h[0] = 0x67452301u32;
            st.h[1] = 0xEFCDAB89u32;
            st.h[2] = 0x98BADCFEu32;
            st.h[3] = 0x10325476u32;
            st.h[4] = 0xC3D2E1F0u32;
            st.computed = false;
        }
        fn input(msg: &[u8]) { add_input(st, msg); }
        fn input_str(msg: &str) { add_input(st, str::bytes(msg)); }
        fn result() -> [u8] { ret mk_result(st); }
        fn result_str() -> str {
            let r = mk_result(st);
            let s = "";
            for b: u8 in r { s += uint::to_str(b as uint, 16u); }
            ret s;
        }
    }
    let st =
        {h: vec::init_elt_mut::<u32>(0u32, digest_buf_len),
         mutable len_low: 0u32,
         mutable len_high: 0u32,
         msg_block: vec::init_elt_mut::<u8>(0u8, msg_block_len),
         mutable msg_block_idx: 0u,
         mutable computed: false,
         work_buf: vec::init_elt_mut::<u32>(0u32, work_buf_len)};
    let sh = sha1(st);
    sh.reset();
    ret sh;
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before><commit_msg>(fix) Chain is now cloneable where it needs to be.<commit_after><|endoftext|>


<commit_before><commit_msg>Make NextChar a type alias for Option<char>.<commit_after><|endoftext|>


<commit_before>#[doc = "

NativeFont encapsulates access to the platform's font API,
e.g. quartz, FreeType. It provides access to metrics and tables
needed by the text shaper as well as access to the underlying
font resources needed by the graphics layer to draw glyphs.

"];

export NativeFont, create;

use font_library::native::NativeFontLibrary;

#[cfg(target_os = "macos")]
type NativeFont/& = quartz_native_font::QuartzNativeFont;

#[cfg(target_os = "linux")]
type NativeFont/& = ft_native_font::FreeTypeNativeFont;

#[cfg(target_os = "macos")]
fn create(_native_lib: &NativeFontLibrary, buf: &~[u8]) -> Result<NativeFont, ()> {
    quartz_native_font::create(buf)
}

#[cfg(target_os = "linux")]
fn create(native_lib: &NativeFontLibrary, buf: &~[u8]) -> Result<NativeFont, ()> {
    ft_native_font::create(*native_lib, buf)
}

#[cfg(target_os = "macos")]
fn with_test_native_font(f: fn@(nf: &NativeFont)) {
    quartz_native_font::with_test_native_font(f);
}

#[cfg(target_os = "linux")]
fn with_test_native_font(f: fn@(nf: &NativeFont)) {
    ft_native_font::with_test_native_font(f);
}

#[test]
fn should_get_glyph_indexes() {
    with_test_native_font(|font| {
        let idx = font.glyph_index('w');
        assert idx == Some(40u);
    })
}

#[test]
fn should_return_none_glyph_index_for_bad_codepoints() {
    with_test_native_font(|font| {
        let idx = font.glyph_index(0 as char);
        assert idx == None;
    })
}

#[test]
#[ignore(cfg(target_os = "macos"))]
fn should_get_glyph_h_advance() {
    with_test_native_font(|font| {
        let adv = font.glyph_h_advance(40u);
        error!("%?", adv);
        assert adv == Some(15);
    })
}

#[test]
#[ignore(cfg(target_os = "macos"))]
fn should_return_none_glyph_h_advance_for_bad_codepoints() {
    with_test_native_font(|font| {
        let adv = font.glyph_h_advance(-1 as uint);
        error!("%?", adv);
        assert adv == None;
    })
}
<commit_msg>Remove some debug logging<commit_after>#[doc = "

NativeFont encapsulates access to the platform's font API,
e.g. quartz, FreeType. It provides access to metrics and tables
needed by the text shaper as well as access to the underlying
font resources needed by the graphics layer to draw glyphs.

"];

export NativeFont, create;

use font_library::native::NativeFontLibrary;

#[cfg(target_os = "macos")]
type NativeFont/& = quartz_native_font::QuartzNativeFont;

#[cfg(target_os = "linux")]
type NativeFont/& = ft_native_font::FreeTypeNativeFont;

#[cfg(target_os = "macos")]
fn create(_native_lib: &NativeFontLibrary, buf: &~[u8]) -> Result<NativeFont, ()> {
    quartz_native_font::create(buf)
}

#[cfg(target_os = "linux")]
fn create(native_lib: &NativeFontLibrary, buf: &~[u8]) -> Result<NativeFont, ()> {
    ft_native_font::create(*native_lib, buf)
}

#[cfg(target_os = "macos")]
fn with_test_native_font(f: fn@(nf: &NativeFont)) {
    quartz_native_font::with_test_native_font(f);
}

#[cfg(target_os = "linux")]
fn with_test_native_font(f: fn@(nf: &NativeFont)) {
    ft_native_font::with_test_native_font(f);
}

#[test]
fn should_get_glyph_indexes() {
    with_test_native_font(|font| {
        let idx = font.glyph_index('w');
        assert idx == Some(40u);
    })
}

#[test]
fn should_return_none_glyph_index_for_bad_codepoints() {
    with_test_native_font(|font| {
        let idx = font.glyph_index(0 as char);
        assert idx == None;
    })
}

#[test]
#[ignore(cfg(target_os = "macos"))]
fn should_get_glyph_h_advance() {
    with_test_native_font(|font| {
        let adv = font.glyph_h_advance(40u);
        assert adv == Some(15);
    })
}

#[test]
#[ignore(cfg(target_os = "macos"))]
fn should_return_none_glyph_h_advance_for_bad_codepoints() {
    with_test_native_font(|font| {
        let adv = font.glyph_h_advance(-1 as uint);
        assert adv == None;
    })
}
<|endoftext|>


<commit_before><commit_msg>Make the empty rustc-wrapper test more explicit.<commit_after><|endoftext|>


<commit_before><commit_msg>autocommit 2015-06-02 04:51:16 CEST<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/.

#![feature(plugin, no_std)]
#![plugin(lrs_core_plugin)]
#![no_std]

#[macro_use] extern crate lrs;
mod core { pub use lrs::core::*; }
#[prelude_import] use lrs::prelude::*;

use lrs::process::{self};

fn main() {
    for i in 0..100000000 { }
    let usage = process::resource_usage(process::res_user::Process).unwrap();
    println!("{:?}", usage);
}

<|endoftext|>


<commit_before><commit_msg>start cleaning up and refactoring control<commit_after><|endoftext|>


<commit_before><commit_msg>Added partial implementation for a stack "vector"<commit_after>use std::io;

pub struct StackVec<'a, T: 'a> {
    data: &'a mut [T],
    length: usize,
}

impl<'a, T> StackVec<'a, T> {
    pub fn from(data: &mut [T]) -> StackVec<T> {
        StackVec{
            data,
            length: 0,
        }
    }
}

impl<'a, T> StackVec<'a, T> {
    pub fn len(&self) -> usize {
        self.length
    }
}

impl<'a> io::Write for StackVec<'a, u8> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if buf.len() > (self.data.len() - self.length) {
            // not enough space on buffer.
            return Err(io::Error::from(io::ErrorKind::WriteZero));
        }
        let mut writable = &mut self.data[self.length..][0..buf.len()];
        writable.copy_from_slice(buf);
        self.length += buf.len();
        Ok(buf.len())
    }

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

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

    #[test]
    fn vec_write() {
        use std::io::Write;

        let mut buf = [0u8; 200];
        {
            let mut vec = StackVec::from(&mut buf);
            assert!(vec.write("Hello World!".as_bytes()).is_ok());
        }
        assert_eq!(buf[1] as char, 'e');
    }

    fn add_values<T: io::Write>(vec: &mut T) {
        for i in 0..BUF_LEN {
            assert!(vec.write(&[((i % 256) & 0xff) as u8]).is_ok());
        }
    }

    use test::Bencher;

    const BUF_LEN : usize = 1024 * 1024 * 1; // 10MB

    #[bench]
    fn vec_stack(bencher: &mut Bencher) {
        bencher.iter(|| {
            let mut buff = [0u8; BUF_LEN];
            let mut v = StackVec::from(&mut buff);
            add_values(&mut v);
        });
    }

    #[bench]
    fn vec_heap(bencher: &mut Bencher) {
        bencher.iter(|| {
            let mut v = Vec::new();

            add_values(&mut v);
        });
    }

    #[bench]
    fn vec_heap_cap(bencher: &mut Bencher) {
        bencher.iter(|| {
            let mut v = Vec::with_capacity(BUF_LEN);
            add_values(&mut v);
        });
    }
}<|endoftext|>


<commit_before><commit_msg>Provide a better explanation of stripped events.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed wrong branch_offset calculation<commit_after><|endoftext|>


<commit_before><commit_msg>Make all gradebook-related struct fields public<commit_after><|endoftext|>


<commit_before><commit_msg>Added missing value use file<commit_after>//! TODO

use values::{BasicValueEnum, InstructionValue};
use llvm_sys::core::{LLVMGetNextUse, LLVMGetUser, LLVMGetUsedValue};
use llvm_sys::prelude::LLVMUseRef;

/// TODO
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ValueUse(LLVMUseRef);

impl ValueUse {
    pub(crate) fn new(use_: LLVMUseRef) -> Self {
        debug_assert!(!use_.is_null());

        ValueUse(use_)
    }

    /// TODO
    pub fn get_next_use(&self) -> Option<Self> {
        let use_ = unsafe {
            LLVMGetNextUse(self.0)
        };

        if use_.is_null() {
            return None;
        }

        Some(ValueUse::new(use_))
    }

    /// TODO
    pub fn get_user(&self) -> InstructionValue {
        let user = unsafe {
            LLVMGetUser(self.0)
        };

        InstructionValue::new(user)
    }

    /// TODO
    pub fn get_used_value(&self) -> BasicValueEnum {
        let used_value = unsafe {
            LLVMGetUsedValue(self.0)
        };

        BasicValueEnum::new(used_value)
    }
}
<|endoftext|>


<commit_before><commit_msg>Added support for digits in symbols.<commit_after><|endoftext|>


<commit_before><commit_msg>Only update the progress bar every ~100ms.<commit_after><|endoftext|>


<commit_before><commit_msg>Allow build number to be modified<commit_after><|endoftext|>


<commit_before><commit_msg>Fix missing space in PacketType::unwrap<commit_after><|endoftext|>


<commit_before><commit_msg>While over an array<commit_after><|endoftext|>


<commit_before><commit_msg>/rooms/{room_id}/members requires authentication it was just an omission from the spec. See https://github.com/matrix-org/matrix-doc/pull/1244<commit_after><|endoftext|>


<commit_before><commit_msg>Invert pixel loops in background drawing routines<commit_after><|endoftext|>


<commit_before><commit_msg>Remove DC offset from VSU output<commit_after><|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.

// ! Check for external package sources. Allow only vendorable packages.

use std::fs::File;
use std::io::Read;
use std::path::Path;

/// List of whitelisted sources for packages
static WHITELISTED_SOURCES: &'static [&'static str] = &[
    "\"registry+https://github.com/rust-lang/crates.io-index\"",
];

/// check for external package sources
pub fn check(path: &Path, bad: &mut bool) {
    // Cargo.lock of rust: src/Cargo.lock
    let path = path.join("Cargo.lock");

    // open and read the whole file
    let mut cargo_lock = String::new();
    t!(t!(File::open(path)).read_to_string(&mut cargo_lock));

    // process each line
    for line in cargo_lock.lines() {

        // consider only source entries
        if ! line.starts_with("source = ") {
            continue;
        }

        // extract source value
        let parts: Vec<&str> = line.splitn(2, '=').collect();
        let source = parts[1].trim();

        // ensure source is whitelisted
        if !WHITELISTED_SOURCES.contains(&&*source) {
            println!("invalid source: {}", source);
            *bad = true;
        }
    }
}
<commit_msg>tidy: extdeps.rs: Avoid an unnecessary collect()<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.

// ! Check for external package sources. Allow only vendorable packages.

use std::fs::File;
use std::io::Read;
use std::path::Path;

/// List of whitelisted sources for packages
static WHITELISTED_SOURCES: &'static [&'static str] = &[
    "\"registry+https://github.com/rust-lang/crates.io-index\"",
];

/// check for external package sources
pub fn check(path: &Path, bad: &mut bool) {
    // Cargo.lock of rust: src/Cargo.lock
    let path = path.join("Cargo.lock");

    // open and read the whole file
    let mut cargo_lock = String::new();
    t!(t!(File::open(path)).read_to_string(&mut cargo_lock));

    // process each line
    for line in cargo_lock.lines() {

        // consider only source entries
        if ! line.starts_with("source = ") {
            continue;
        }

        // extract source value
        let source = line.splitn(2, '=').nth(1).unwrap().trim();

        // ensure source is whitelisted
        if !WHITELISTED_SOURCES.contains(&&*source) {
            println!("invalid source: {}", source);
            *bad = true;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #56746 - pnkfelix:issue-56537-add-test-of-closure-using-region-from-containing-fn, r=nikomatsakis<commit_after>// This is a collection of examples where a function's formal
// parameter has an explicit lifetime and a closure within that
// function returns that formal parameter. The closure's return type,
// to be correctly inferred, needs to include the lifetime introduced
// by the function.
//
// This works today, which precludes changing things so that closures
// follow the same lifetime-elision rules used elsehwere. See
// rust-lang/rust#56537

// compile-pass
// We are already testing NLL explicitly via the revision system below.
// ignore-compare-mode-nll

// revisions: ll nll migrate
//[ll] compile-flags:-Zborrowck=ast
//[nll] compile-flags:-Zborrowck=mir -Z two-phase-borrows
//[migrate] compile-flags:-Zborrowck=migrate -Z two-phase-borrows

fn willy_no_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x| { p }; // no type annotation at all
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn willy_ret_type_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x| -> &str { p }; // type annotation on the return type
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn willy_ret_region_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x| -> &'w str { p }; // type+region annotation on return type
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn willy_arg_type_ret_type_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x: &str| -> &str { p }; // type annotation on arg and return types
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn willy_arg_type_ret_region_annot<'w>(p: &'w str, q: &str) -> &'w str {
    let free_dumb = |_x: &str| -> &'w str { p }; // fully annotated
    let hello = format!("Hello");
    free_dumb(&hello)
}

fn main() {
    let world = format!("World");
    let w1: &str = {
        let hello = format!("He11o");
        willy_no_annot(&world, &hello)
    };
    let w2: &str = {
        let hello = format!("He22o");
        willy_ret_type_annot(&world, &hello)
    };
    let w3: &str = {
        let hello = format!("He33o");
        willy_ret_region_annot(&world, &hello)
    };
    let w4: &str = {
        let hello = format!("He44o");
        willy_arg_type_ret_type_annot(&world, &hello)
    };
    let w5: &str = {
        let hello = format!("He55o");
        willy_arg_type_ret_region_annot(&world, &hello)
    };
    assert_eq!((w1, w2, w3, w4, w5),
               ("World","World","World","World","World"));
}
<|endoftext|>


<commit_before><commit_msg>resize event<commit_after><|endoftext|>


<commit_before><commit_msg>add test for #5238<commit_after>// Regression test for #5238 / https://github.com/rust-lang/rust/pull/69562

#![feature(generators, generator_trait)]

fn main() {
    let _ = || {
        yield;
    };
}
<|endoftext|>


<commit_before><commit_msg>writer mod: Correct the offset entry calculation<commit_after><|endoftext|>


<commit_before><commit_msg>Add some functions/methods to `Response`<commit_after><|endoftext|>


<commit_before><commit_msg>Add alias Ap0<commit_after><|endoftext|>


<commit_before><commit_msg>Add dc:creator support for rss entries<commit_after><|endoftext|>


<commit_before><commit_msg>libcore: Add missing ops.rs<commit_after>// Core operators and kinds.

#[lang="const"]
trait const {
    // Empty.
}

#[lang="copy"]
trait copy {
    // Empty.
}

#[lang="send"]
trait send {
    // Empty.
}

#[lang="owned"]
trait owned {
    // Empty.
}

#[lang="add"]
trait add<RHS,Result> {
    pure fn add(rhs: RHS) -> Result;
}

#[lang="sub"]
trait sub<RHS,Result> {
    pure fn sub(rhs: RHS) -> Result;
}

#[lang="mul"]
trait mul<RHS,Result> {
    pure fn mul(rhs: RHS) -> Result;
}

#[lang="div"]
trait div<RHS,Result> {
    pure fn div(rhs: RHS) -> Result;
}

#[lang="modulo"]
trait modulo<RHS,Result> {
    pure fn modulo(rhs: RHS) -> Result;
}

#[lang="neg"]
trait neg<RHS,Result> {
    pure fn neg(rhs: RHS) -> Result;
}

#[lang="bitops"]
trait bitops<RHS,BitCount,Result> {
    pure fn and(rhs: RHS) -> Result;
    pure fn or(rhs: RHS) -> Result;
    pure fn xor(rhs: RHS) -> Result;
    pure fn shl(n: BitCount) -> Result;
    pure fn shr(n: BitCount) -> Result;
}

#[lang="index"]
trait index<Index,Result> {
    pure fn index(index: Index) -> Result;
}

<|endoftext|>


<commit_before><commit_msg>cargo: cache already-parsed Cargo.toml/Cargo.lock<commit_after><|endoftext|>


<commit_before>#![crate_name = "fold"]

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Arcterus <arcterus@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#![feature(macro_rules)]

extern crate getopts;
extern crate libc;

use std::io;
use std::io::fs::File;
use std::io::BufferedReader;
use std::uint;

#[path = "../common/util.rs"]
mod util;

static NAME: &'static str = "fold";
static VERSION: &'static str = "1.0.0";

pub fn uumain(args: Vec<String>) -> int {
    let (args, obs_width) = handle_obsolete(args.as_slice());
    let program = args[0].clone();

    let opts = [
        getopts::optflag("b", "bytes", "count using bytes rather than columns (meaning control characters such as newline are not treated specially)"),
        getopts::optflag("s", "spaces", "break lines at word boundaries rather than a hard cut-off"),
        getopts::optopt("w", "width", "set WIDTH as the maximum line width rather than 80", "WIDTH"),
        getopts::optflag("h", "help", "display this help and exit"),
        getopts::optflag("V", "version", "output version information and exit")
    ];

    let matches = match getopts::getopts(args.tail(), opts) {
        Ok(m) => m,
        Err(f) => crash!(1, "{}", f)
    };

    if matches.opt_present("h") {
        println!("{} v{}", NAME, VERSION);
        println!("");
        println!("Usage:");
        println!("  {} [OPTION]... [FILE]...", program);
        println!("");
        print!("{}", getopts::usage("Writes each file (or standard input if no files are given) to standard output whilst breaking long lines", opts));
    } else if matches.opt_present("V") {
        println!("{} v{}", NAME, VERSION);
    } else {
        let bytes = matches.opt_present("b");
        let spaces = matches.opt_present("s");
        let poss_width =
            if matches.opt_present("w") {
                matches.opt_str("w")
            } else {
                match obs_width {
                    Some(v) => Some(v.to_string()),
                    None => None,
                }
            };
        let width = match poss_width {
            Some(inp_width) => match uint::parse_bytes(inp_width.as_bytes(), 10) {
                Some(width) => width,
                None => crash!(1, "illegal width value (\"{}\")", inp_width)
            },
            None => 80
        };
        let files = if matches.free.is_empty() {
            vec!("-".to_string())
        } else {
            matches.free
        };
        fold(files, bytes, spaces, width);
    }

    0
}

fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
    let mut args = args.to_vec();
    let mut i = 0;
    while i < args.len() {
        if args[i].as_slice().char_at(0) == '-' && args[i].len() > 1 && args[i].as_slice().char_at(1).is_digit() {
            return (args.clone(),
                    Some(args.remove(i).unwrap().as_slice().slice_from(1).to_string()));
        }
        i += 1;
    }
    (args, None)
}

#[inline]
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: uint) {
    for filename in filenames.iter() {
        let filename: &str = filename.as_slice();
        let mut stdin_buf;
        let mut file_buf;
        let buffer = BufferedReader::new(
            if filename == "-" {
                stdin_buf = io::stdio::stdin_raw();
                &mut stdin_buf as &mut Reader
            } else {
                file_buf = safe_unwrap!(File::open(&Path::new(filename)));
                &mut file_buf as &mut Reader
            }
        );
        fold_file(buffer, bytes, spaces, width);
    }
}

#[inline]
fn fold_file<T: io::Reader>(file: BufferedReader<T>, bytes: bool, spaces: bool, width: uint) {
    let mut file = file;
    for line in file.lines() {
        let line_string = safe_unwrap!(line);
        let mut line = line_string.as_slice();
        if bytes {
            let len = line.len();
            let mut i = 0;
            while i < len {
                let width = if len - i >= width { width } else { len - i };
                let slice = {
                    let slice = line.slice(i, i + width);
                    if spaces && i + width < len {
                        match slice.rfind(|ch: char| ch.is_whitespace()) {
                            Some(m) => slice.slice_to(m + 1),
                            None => slice
                        }
                    } else {
                        slice
                    }
                };
                print!("{}", slice);
                i += slice.len();
            }
        } else {
            let mut len = line.char_len();
            let newline =
                if len == 0 {
                    continue;
                } else if len == 1 && line.char_at(len - 1) == '\n' {
                    println!("");
                    continue;
                } else if line.char_at(len - 1) == '\n' {
                    line = line.slice_to(line.len() - 1);
                    len -= 1;
                    true
                } else {
                    false
                };
            let mut output = String::new();
            let mut count = 0;
            for (i, ch) in line.chars().enumerate() {
                if count >= width {
                    let (val, ncount) = {
                        let slice = output.as_slice();
                        let (out, val, ncount) =
                            if spaces && i + 1 < len {
                                match rfind_whitespace(slice) {
                                    Some(m) => {
                                        let routput = slice.slice_chars(m + 1, slice.char_len());
                                        let ncount = routput.chars().fold(0u, |out, ch: char| {
                                            out + match ch {
                                                '\t' => 8,
                                                '\x08' => if out > 0 { -1 } else { 0 },
                                                '\r' => return 0,
                                                _ => 1
                                            }
                                        });
                                        (slice.slice_chars(0, m + 1), routput, ncount)
                                    },
                                    None => (slice, "", 0)
                                }
                            } else {
                                (slice, "", 0)
                            };
                        println!("{}", out);
                        (val.into_string(), ncount)
                    };
                    output = val;
                    count = ncount;
                }
                match ch {
                    '\t' => {
                        count += 8;
                        if count > width {
                            println!("{}", output);
                            output.truncate(0);
                            count = 8;
                        }
                    }
                    '\x08' => {
                        if count > 0 {
                            count -= 1;
                            let len = output.len() - 1;
                            output.truncate(len);
                        }
                        continue;
                    }
                    '\r' => {
                        output.truncate(0);
                        count = 0;
                        continue;
                    }
                    _ => count += 1
                };
                output.push(ch);
            }
            if count > 0 {
                if newline {
                    println!("{}", output);
                } else {
                    print!("{}", output);
                }
            }
        }
    }
}

#[inline]
fn rfind_whitespace(slice: &str) -> Option<uint> {
    for (i, ch) in slice.chars().rev().enumerate() {
        if ch.is_whitespace() {
            return Some(slice.char_len() - (i + 1));
        }
    }
    None
}
<commit_msg>Pass the Busybox's Unicode test for fold<commit_after>#![crate_name = "fold"]

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Arcterus <arcterus@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#![feature(macro_rules)]

extern crate getopts;
extern crate libc;

use std::io;
use std::io::fs::File;
use std::io::BufferedReader;
use std::uint;

#[path = "../common/util.rs"]
mod util;

static NAME: &'static str = "fold";
static VERSION: &'static str = "1.0.0";

pub fn uumain(args: Vec<String>) -> int {
    let (args, obs_width) = handle_obsolete(args.as_slice());
    let program = args[0].clone();

    let opts = [
        getopts::optflag("b", "bytes", "count using bytes rather than columns (meaning control characters such as newline are not treated specially)"),
        getopts::optflag("s", "spaces", "break lines at word boundaries rather than a hard cut-off"),
        getopts::optopt("w", "width", "set WIDTH as the maximum line width rather than 80", "WIDTH"),
        getopts::optflag("h", "help", "display this help and exit"),
        getopts::optflag("V", "version", "output version information and exit")
    ];

    let matches = match getopts::getopts(args.tail(), opts) {
        Ok(m) => m,
        Err(f) => crash!(1, "{}", f)
    };

    if matches.opt_present("h") {
        println!("{} v{}", NAME, VERSION);
        println!("");
        println!("Usage:");
        println!("  {} [OPTION]... [FILE]...", program);
        println!("");
        print!("{}", getopts::usage("Writes each file (or standard input if no files are given) to standard output whilst breaking long lines", opts));
    } else if matches.opt_present("V") {
        println!("{} v{}", NAME, VERSION);
    } else {
        let bytes = matches.opt_present("b");
        let spaces = matches.opt_present("s");
        let poss_width =
            if matches.opt_present("w") {
                matches.opt_str("w")
            } else {
                match obs_width {
                    Some(v) => Some(v.to_string()),
                    None => None,
                }
            };
        let width = match poss_width {
            Some(inp_width) => match uint::parse_bytes(inp_width.as_bytes(), 10) {
                Some(width) => width,
                None => crash!(1, "illegal width value (\"{}\")", inp_width)
            },
            None => 80
        };
        let files = if matches.free.is_empty() {
            vec!("-".to_string())
        } else {
            matches.free
        };
        fold(files, bytes, spaces, width);
    }

    0
}

fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
    let mut args = args.to_vec();
    let mut i = 0;
    while i < args.len() {
        if args[i].as_slice().char_at(0) == '-' && args[i].len() > 1 && args[i].as_slice().char_at(1).is_digit() {
            return (args.clone(),
                    Some(args.remove(i).unwrap().as_slice().slice_from(1).to_string()));
        }
        i += 1;
    }
    (args, None)
}

#[inline]
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: uint) {
    for filename in filenames.iter() {
        let filename: &str = filename.as_slice();
        let mut stdin_buf;
        let mut file_buf;
        let buffer = BufferedReader::new(
            if filename == "-" {
                stdin_buf = io::stdio::stdin_raw();
                &mut stdin_buf as &mut Reader
            } else {
                file_buf = safe_unwrap!(File::open(&Path::new(filename)));
                &mut file_buf as &mut Reader
            }
        );
        fold_file(buffer, bytes, spaces, width);
    }
}

#[inline]
fn fold_file<T: io::Reader>(file: BufferedReader<T>, bytes: bool, spaces: bool, width: uint) {
    let mut file = file;
    for line in file.lines() {
        let line_string = safe_unwrap!(line);
        let mut line = line_string.as_slice();
        if bytes {
            let len = line.len();
            let mut i = 0;
            while i < len {
                let width = if len - i >= width { width } else { len - i };
                let slice = {
                    let slice = line.slice(i, i + width);
                    if spaces && i + width < len {
                        match slice.rfind(|ch: char| ch.is_whitespace()) {
                            Some(m) => slice.slice_to(m + 1),
                            None => slice
                        }
                    } else {
                        slice
                    }
                };
                print!("{}", slice);
                i += slice.len();
            }
        } else {
            let mut len = line.char_len();
            let newline = line.ends_with("\n");
            if newline {
                line = line.slice_to(line.len() - 1);
                len -= 1;
            }
            let mut output = String::new();
            let mut count = 0;
            for (i, ch) in line.chars().enumerate() {
                if count >= width {
                    let (val, ncount) = {
                        let slice = output.as_slice();
                        let (out, val, ncount) =
                            if spaces && i + 1 < len {
                                match rfind_whitespace(slice) {
                                    Some(m) => {
                                        let routput = slice.slice_chars(m + 1, slice.char_len());
                                        let ncount = routput.chars().fold(0u, |out, ch: char| {
                                            out + match ch {
                                                '\t' => 8,
                                                '\x08' => if out > 0 { -1 } else { 0 },
                                                '\r' => return 0,
                                                _ => 1
                                            }
                                        });
                                        (slice.slice_chars(0, m + 1), routput, ncount)
                                    },
                                    None => (slice, "", 0)
                                }
                            } else {
                                (slice, "", 0)
                            };
                        println!("{}", out);
                        (val.into_string(), ncount)
                    };
                    output = val;
                    count = ncount;
                }
                match ch {
                    '\t' => {
                        count += 8;
                        if count > width {
                            println!("{}", output);
                            output.truncate(0);
                            count = 8;
                        }
                    }
                    '\x08' => {
                        if count > 0 {
                            count -= 1;
                            let len = output.len() - 1;
                            output.truncate(len);
                        }
                        continue;
                    }
                    '\r' => {
                        output.truncate(0);
                        count = 0;
                        continue;
                    }
                    _ => count += 1
                };
                output.push(ch);
            }
            if count > 0 {
                if newline {
                    println!("{}", output);
                } else {
                    print!("{}", output);
                }
            }
        }
    }
}

#[inline]
fn rfind_whitespace(slice: &str) -> Option<uint> {
    for (i, ch) in slice.chars().rev().enumerate() {
        if ch.is_whitespace() {
            return Some(slice.char_len() - (i + 1));
        }
    }
    None
}
<|endoftext|>


<commit_before><commit_msg>Ignore render example due to broken upstream crate.<commit_after><|endoftext|>


<commit_before><commit_msg>rust - refactor word_count tests<commit_after><|endoftext|>


<commit_before><commit_msg>Add assembler<commit_after>use std::os;
use std::io::{File, BufferedReader};
use std::string::String;

fn main() {
    let args = os::args();
    if args.len() != 2 {
        fail!("Usage: simpleasm infile");
    }

    let path = Path::new(args[1].clone());
    let mut file = BufferedReader::new(File::open(&path));
    let lines : Vec<String> = file.lines().map(|x| x.unwrap()).collect();

    for line in lines.iter() {
        print!("{}", line);
    }
}
<|endoftext|>


<commit_before><commit_msg>Теперь итоговое сообщение зависит от наличия ошибок в тестах<commit_after><|endoftext|>


<commit_before><commit_msg>Add a generic sphinx_packet_unwrap<commit_after><|endoftext|>


<commit_before><commit_msg>Using camel case for u24LittleEndian<commit_after><|endoftext|>


<commit_before><commit_msg>added missing json example<commit_after>extern crate codespawn;

fn main()
{
    // Example of parsing a simplified JSON definition.
    // 'name' and 'type' can be omitted and will be automatically deduced by the parser.
    let raw_code = codespawn::from_json("examples/sample2.json").unwrap();

    println!("\n*** Language specific configs (if defined):");
    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("*** Structure of raw (unformatted) code data:\n{}", raw_code);
    println!("*** Structure of C++ code generated from raw code data:\n{}", raw_code.to_cpp());
    println!("*** Structure of Rust code generated from raw code data:\n{}", raw_code.to_rust());
    println!("*** Generated C++ code:\n\n{}", raw_code.to_cpp().to_string());
    println!("*** Generated Rust code:\n\n{}", raw_code.to_rust().to_string());

    // save generated code to file
    let _ = raw_code.to_cpp().to_file("sample2.cpp");
    let _ = raw_code.to_rust().to_file("sample2.rs");
}
<|endoftext|>


<commit_before><commit_msg>feat(Path): Collect the pane path<commit_after><|endoftext|>


<commit_before><commit_msg>added delay operator for prioritization<commit_after>use std::collections::HashMap;

use communication::*;
use communication::pact::Pipeline;

use example_static::stream::ActiveStream;
use example_static::unary::*;
use example_static::builder::*;

pub trait DelayExt<G: GraphBuilder, D: Data> { fn delay<F: Fn(&D, &G::Timestamp)->G::Timestamp+'static>(self, F) -> Self; }

impl<G: GraphBuilder, D: Data> DelayExt<G, D> for ActiveStream<G, D> {
    fn delay<F: Fn(&D, &G::Timestamp)->G::Timestamp+'static>(self, func: F) -> ActiveStream<G, D> {
        let _threshold = 256; // TODO : make more "streaming" by flushing
        let mut elements = HashMap::new();
        self.unary_notify(Pipeline, format!("Delay"), vec![], move |handle| {
            while let Some((time, data)) = handle.input.pull() {
                for datum in data {
                    let mut new_time = func(&datum, &time);
                    if !(new_time >= time) {
                        new_time = time;
                    }

                    let mut list = elements.entry(new_time.clone()).or_insert_with(|| {
                        handle.notificator.notify_at(&new_time);
                        Vec::new()
                    });
                    list.push(datum);
                }
            }
            // for each available notification, send corresponding set
            while let Some((time, _count)) = handle.notificator.next() {
                if let Some(data) = elements.remove(&time) {
                    // println!("releasing delayed data at {:?}, {} records", time, data.len());
                    handle.output.give_at(&time, data.into_iter());
                }
            }
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove map method<commit_after><|endoftext|>


<commit_before><commit_msg>put back implementation of ToTableName to Table object<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed formatting.<commit_after><|endoftext|>