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

use error::InteractionErrorKind as IEK;
use error::MapErrInto;

use toml::Value;

use rustyline::{Config, Editor};

pub struct Readline {
    editor: Editor,
    history_file: PathBuf,
    prompt: String,
}

impl Readline {

    pub fn new(rt: &Runtime) -> Result<Readline> {
        let cfg = try!(rt.config().ok_or(IEK::NoConfigError));

        let c = cfg.config();
        let histfile     = try!(c.lookup("ui.cli.readline_history_file").ok_or(IEK::ConfigError));
        let histsize     = try!(c.lookup("ui.cli.readline_history_size").ok_or(IEK::ConfigError));
        let histigndups  = try!(c.lookup("ui.cli.readline_history_ignore_dups").ok_or(IEK::ConfigError));
        let histignspace = try!(c.lookup("ui.cli.readline_history_ignore_space").ok_or(IEK::ConfigError));
        let prompt       = try!(c.lookup("ui.cli.readline_prompt").ok_or(IEK::ConfigError));

        let histfile = try!(match histfile {
            Value::String(s) => PathBuf::from(s),
            _ => Err(IEK::ConfigTypeError.into_error())
                .map_err_into(IEK::ConfigError)
                .map_err_into(IEK::ReadlineError)
        });

        let histsize = try!(match histsize {
            Value::Integer(i) => i,
            _ => Err(IEK::ConfigTypeError.into_error())
                .map_err_into(IEK::ConfigError)
                .map_err_into(IEK::ReadlineError)
        });

        let histigndups = try!(match histigndups {
            Value::Boolean(b) => b,
            _ => Err(IEK::ConfigTypeError.into_error())
                .map_err_into(IEK::ConfigError)
                .map_err_into(IEK::ReadlineError)
        });

        let histignspace = try!(match histignspace {
            Value::Boolean(b) => b,
            _ => Err(IEK::ConfigTypeError.into_error())
                .map_err_into(IEK::ConfigError)
                .map_err_into(IEK::ReadlineError)
        });

        let prompt = try!(match prompt {
            Value::String(s) => s,
            _ => Err(IEK::ConfigTypeError.into_error())
                .map_err_into(IEK::ConfigError)
                .map_err_into(IEK::ReadlineError)
        });

        let config = Config::builder().
            .max_history_size(histsize)
            .history_ignore_dups(histigndups)
            .history_ignore_space(histignspace)
            .build();

        let mut editor = Editor::new(config);
        let _ = try!(editor.load_history(&histfile).map_err_into(ReadlineError));

        Ok(Readline {
            editor: editor,
            history_file: histfile,
            prompt: prompt,
        })
    }

    pub fn read_line(&mut self) -> Result<Option<String>> {
        use rustyline::ReadlineError;
        use libimagutil::warn_result::*;

        match self.editor.readline(&self.prompt) {
            Ok(line) => {
                self.editor.add_history_line(&line);
                self.editor
                    .save_history(&self.history_file)
                    .map_warn_err_str(|e| format!("Could not save history file {} -> {:?}",
                                                  self.history_file.display(), e));
                return line;
            },
            Err(ReadlineError::Interrupted) => {
                info!("CTRL-C");
                Ok(None)
            },
            Err(ReadlineError::Eof) => {
                info!("CTRL-D");
                Ok(None)
            },
            Err(err) => Err(err).map_err_into(ReadlineError),

        }
    }

}

<|endoftext|>


<commit_before><commit_msg>add test for sketchy vtable<commit_after>trait Empty {}

#[repr(transparent)]
pub struct FunnyPointer(dyn Empty);

#[repr(C)]
pub struct Meta {
    drop_fn: fn(&mut ()),
    size: usize,
    align: usize,
}

impl Meta {
    pub fn new() -> Self {
        Meta {
            drop_fn: |_| {},
            size: 0,
            align: 1,
        }
    }
}

#[repr(C)]
pub struct FatPointer {
    pub data: *const (),
    pub vtable: *const (),
}

impl FunnyPointer {
    pub unsafe fn from_data_ptr(data: &String, ptr: *const Meta) -> &Self {
        let obj = FatPointer {
            data: data as *const _ as *const (),
            vtable: ptr as *const _ as *const (),
        };
        let obj = std::mem::transmute::<FatPointer, *mut FunnyPointer>(obj); //~ ERROR invalid drop fn in vtable
        &*obj
    }
}

fn main() {
    unsafe {
        let meta = Meta::new();
        let hello = "hello".to_string();
        let _raw: &FunnyPointer = FunnyPointer::from_data_ptr(&hello, &meta as *const _);
    }
}
<|endoftext|>


<commit_before><commit_msg>Properly handle cyclical references<commit_after><|endoftext|>


<commit_before><commit_msg>Add rust code for etl case<commit_after>use std::collections::BTreeMap;
use std::ascii::AsciiExt;

pub fn transform(input: &BTreeMap<i32, Vec<char>>) -> BTreeMap<char, i32> {
    let mut result: BTreeMap<char, i32> = BTreeMap::new();

    for (k, v) in input {
        for c in v {
            result.entry((*c).to_ascii_lowercase()).or_insert(*k);
        }
    }

    result
}
<|endoftext|>


<commit_before><commit_msg>Add an HList bound<commit_after><|endoftext|>


<commit_before><commit_msg>Fix struct initializer for balls.<commit_after><|endoftext|>


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

use syntax_pos::symbol::Symbol;
use back::write::create_target_machine;
use llvm;
use rustc::session::Session;
use rustc::session::config::PrintRequest;
use libc::c_int;
use std::ffi::CString;
use syntax::feature_gate::UnstableFeatures;

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Once;

static POISONED: AtomicBool = AtomicBool::new(false);
static INIT: Once = Once::new();

pub(crate) fn init(sess: &Session) {
    unsafe {
        // Before we touch LLVM, make sure that multithreading is enabled.
        INIT.call_once(|| {
            if llvm::LLVMStartMultithreaded() != 1 {
                // use an extra bool to make sure that all future usage of LLVM
                // cannot proceed despite the Once not running more than once.
                POISONED.store(true, Ordering::SeqCst);
            }

            configure_llvm(sess);
        });

        if POISONED.load(Ordering::SeqCst) {
            bug!("couldn't enable multi-threaded LLVM");
        }
    }
}

fn require_inited() {
    INIT.call_once(|| bug!("llvm is not initialized"));
    if POISONED.load(Ordering::SeqCst) {
        bug!("couldn't enable multi-threaded LLVM");
    }
}

unsafe fn configure_llvm(sess: &Session) {
    let mut llvm_c_strs = Vec::new();
    let mut llvm_args = Vec::new();

    {
        let mut add = |arg: &str| {
            let s = CString::new(arg).unwrap();
            llvm_args.push(s.as_ptr());
            llvm_c_strs.push(s);
        };
        add("rustc"); // fake program name
        if sess.time_llvm_passes() { add("-time-passes"); }
        if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
        if sess.opts.debugging_opts.disable_instrumentation_preinliner {
            add("-disable-preinline");
        }

        for arg in &sess.opts.cg.llvm_args {
            add(&(*arg));
        }
    }

    llvm::LLVMInitializePasses();

    llvm::initialize_available_targets();

    llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
                                 llvm_args.as_ptr());
}

// WARNING: the features after applying `to_llvm_feature` must be known
// to LLVM or the feature detection code will walk past the end of the feature
// array, leading to crashes.

const ARM_WHITELIST: &[(&str, Option<&str>)] = &[
    ("mclass", Some("arm_target_feature")),
    ("neon", Some("arm_target_feature")),
    ("v7", Some("arm_target_feature")),
    ("vfp2", Some("arm_target_feature")),
    ("vfp3", Some("arm_target_feature")),
    ("vfp4", Some("arm_target_feature")),
];

const AARCH64_WHITELIST: &[(&str, Option<&str>)] = &[
    ("fp", Some("aarch64_target_feature")),
    ("neon", Some("aarch64_target_feature")),
    ("sve", Some("aarch64_target_feature")),
    ("crc", Some("aarch64_target_feature")),
    ("crypto", Some("aarch64_target_feature")),
    ("ras", Some("aarch64_target_feature")),
    ("lse", Some("aarch64_target_feature")),
    ("rdm", Some("aarch64_target_feature")),
    ("fp16", Some("aarch64_target_feature")),
    ("rcpc", Some("aarch64_target_feature")),
    ("dotprod", Some("aarch64_target_feature")),
    ("v8.1a", Some("aarch64_target_feature")),
    ("v8.2a", Some("aarch64_target_feature")),
    ("v8.3a", Some("aarch64_target_feature")),
];

const X86_WHITELIST: &[(&str, Option<&str>)] = &[
    ("aes", None),
    ("avx", None),
    ("avx2", None),
    ("avx512bw", Some("avx512_target_feature")),
    ("avx512cd", Some("avx512_target_feature")),
    ("avx512dq", Some("avx512_target_feature")),
    ("avx512er", Some("avx512_target_feature")),
    ("avx512f", Some("avx512_target_feature")),
    ("avx512ifma", Some("avx512_target_feature")),
    ("avx512pf", Some("avx512_target_feature")),
    ("avx512vbmi", Some("avx512_target_feature")),
    ("avx512vl", Some("avx512_target_feature")),
    ("avx512vpopcntdq", Some("avx512_target_feature")),
    ("bmi1", None),
    ("bmi2", None),
    ("fma", None),
    ("fxsr", None),
    ("lzcnt", None),
    ("mmx", Some("mmx_target_feature")),
    ("pclmulqdq", None),
    ("popcnt", None),
    ("rdrand", None),
    ("rdseed", None),
    ("sha", None),
    ("sse", None),
    ("sse2", None),
    ("sse3", None),
    ("sse4.1", None),
    ("sse4.2", None),
    ("sse4a", Some("sse4a_target_feature")),
    ("ssse3", None),
    ("tbm", Some("tbm_target_feature")),
    ("xsave", None),
    ("xsavec", None),
    ("xsaveopt", None),
    ("xsaves", None),
];

const HEXAGON_WHITELIST: &[(&str, Option<&str>)] = &[
    ("hvx", Some("hexagon_target_feature")),
    ("hvx-double", Some("hexagon_target_feature")),
];

const POWERPC_WHITELIST: &[(&str, Option<&str>)] = &[
    ("altivec", Some("powerpc_target_feature")),
    ("power8-altivec", Some("powerpc_target_feature")),
    ("power9-altivec", Some("powerpc_target_feature")),
    ("power8-vector", Some("powerpc_target_feature")),
    ("power9-vector", Some("powerpc_target_feature")),
    ("vsx", Some("powerpc_target_feature")),
];

const MIPS_WHITELIST: &[(&str, Option<&str>)] = &[
    ("fp64", Some("mips_target_feature")),
    ("msa", Some("mips_target_feature")),
];

/// When rustdoc is running, provide a list of all known features so that all their respective
/// primtives may be documented.
///
/// IMPORTANT: If you're adding another whitelist to the above lists, make sure to add it to this
/// iterator!
pub fn all_known_features() -> impl Iterator<Item=(&'static str, Option<&'static str>)> {
    ARM_WHITELIST.iter().cloned()
        .chain(AARCH64_WHITELIST.iter().cloned())
        .chain(X86_WHITELIST.iter().cloned())
        .chain(HEXAGON_WHITELIST.iter().cloned())
        .chain(POWERPC_WHITELIST.iter().cloned())
        .chain(MIPS_WHITELIST.iter().cloned())
}

pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
    let arch = if sess.target.target.arch == "x86_64" {
        "x86"
    } else {
        &*sess.target.target.arch
    };
    match (arch, s) {
        ("x86", "pclmulqdq") => "pclmul",
        ("x86", "rdrand") => "rdrnd",
        ("x86", "bmi1") => "bmi",
        ("aarch64", "fp") => "fp-armv8",
        ("aarch64", "fp16") => "fullfp16",
        (_, s) => s,
    }
}

pub fn target_features(sess: &Session) -> Vec<Symbol> {
    let target_machine = create_target_machine(sess, true);
    target_feature_whitelist(sess)
        .iter()
        .filter_map(|&(feature, gate)| {
            if UnstableFeatures::from_environment().is_nightly_build() || gate.is_none() {
                Some(feature)
            } else {
                None
            }
        })
        .filter(|feature| {
            let llvm_feature = to_llvm_feature(sess, feature);
            let cstr = CString::new(llvm_feature).unwrap();
            unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
        })
        .map(|feature| Symbol::intern(feature)).collect()
}

pub fn target_feature_whitelist(sess: &Session)
    -> &'static [(&'static str, Option<&'static str>)]
{
    match &*sess.target.target.arch {
        "arm" => ARM_WHITELIST,
        "aarch64" => AARCH64_WHITELIST,
        "x86" | "x86_64" => X86_WHITELIST,
        "hexagon" => HEXAGON_WHITELIST,
        "mips" | "mips64" => MIPS_WHITELIST,
        "powerpc" | "powerpc64" => POWERPC_WHITELIST,
        _ => &[],
    }
}

pub fn print_version() {
    // Can be called without initializing LLVM
    unsafe {
        println!("LLVM version: {}.{}",
                 llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
    }
}

pub fn print_passes() {
    // Can be called without initializing LLVM
    unsafe { llvm::LLVMRustPrintPasses(); }
}

pub(crate) fn print(req: PrintRequest, sess: &Session) {
    require_inited();
    let tm = create_target_machine(sess, true);
    unsafe {
        match req {
            PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
            PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
            _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
        }
    }
}
<commit_msg>Rollup merge of #52690 - paoloteti:rclass-dsp, r=alexcrichton<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use syntax_pos::symbol::Symbol;
use back::write::create_target_machine;
use llvm;
use rustc::session::Session;
use rustc::session::config::PrintRequest;
use libc::c_int;
use std::ffi::CString;
use syntax::feature_gate::UnstableFeatures;

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Once;

static POISONED: AtomicBool = AtomicBool::new(false);
static INIT: Once = Once::new();

pub(crate) fn init(sess: &Session) {
    unsafe {
        // Before we touch LLVM, make sure that multithreading is enabled.
        INIT.call_once(|| {
            if llvm::LLVMStartMultithreaded() != 1 {
                // use an extra bool to make sure that all future usage of LLVM
                // cannot proceed despite the Once not running more than once.
                POISONED.store(true, Ordering::SeqCst);
            }

            configure_llvm(sess);
        });

        if POISONED.load(Ordering::SeqCst) {
            bug!("couldn't enable multi-threaded LLVM");
        }
    }
}

fn require_inited() {
    INIT.call_once(|| bug!("llvm is not initialized"));
    if POISONED.load(Ordering::SeqCst) {
        bug!("couldn't enable multi-threaded LLVM");
    }
}

unsafe fn configure_llvm(sess: &Session) {
    let mut llvm_c_strs = Vec::new();
    let mut llvm_args = Vec::new();

    {
        let mut add = |arg: &str| {
            let s = CString::new(arg).unwrap();
            llvm_args.push(s.as_ptr());
            llvm_c_strs.push(s);
        };
        add("rustc"); // fake program name
        if sess.time_llvm_passes() { add("-time-passes"); }
        if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
        if sess.opts.debugging_opts.disable_instrumentation_preinliner {
            add("-disable-preinline");
        }

        for arg in &sess.opts.cg.llvm_args {
            add(&(*arg));
        }
    }

    llvm::LLVMInitializePasses();

    llvm::initialize_available_targets();

    llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
                                 llvm_args.as_ptr());
}

// WARNING: the features after applying `to_llvm_feature` must be known
// to LLVM or the feature detection code will walk past the end of the feature
// array, leading to crashes.

const ARM_WHITELIST: &[(&str, Option<&str>)] = &[
    ("mclass", Some("arm_target_feature")),
    ("rclass", Some("arm_target_feature")),
    ("dsp", Some("arm_target_feature")),
    ("neon", Some("arm_target_feature")),
    ("v7", Some("arm_target_feature")),
    ("vfp2", Some("arm_target_feature")),
    ("vfp3", Some("arm_target_feature")),
    ("vfp4", Some("arm_target_feature")),
];

const AARCH64_WHITELIST: &[(&str, Option<&str>)] = &[
    ("fp", Some("aarch64_target_feature")),
    ("neon", Some("aarch64_target_feature")),
    ("sve", Some("aarch64_target_feature")),
    ("crc", Some("aarch64_target_feature")),
    ("crypto", Some("aarch64_target_feature")),
    ("ras", Some("aarch64_target_feature")),
    ("lse", Some("aarch64_target_feature")),
    ("rdm", Some("aarch64_target_feature")),
    ("fp16", Some("aarch64_target_feature")),
    ("rcpc", Some("aarch64_target_feature")),
    ("dotprod", Some("aarch64_target_feature")),
    ("v8.1a", Some("aarch64_target_feature")),
    ("v8.2a", Some("aarch64_target_feature")),
    ("v8.3a", Some("aarch64_target_feature")),
];

const X86_WHITELIST: &[(&str, Option<&str>)] = &[
    ("aes", None),
    ("avx", None),
    ("avx2", None),
    ("avx512bw", Some("avx512_target_feature")),
    ("avx512cd", Some("avx512_target_feature")),
    ("avx512dq", Some("avx512_target_feature")),
    ("avx512er", Some("avx512_target_feature")),
    ("avx512f", Some("avx512_target_feature")),
    ("avx512ifma", Some("avx512_target_feature")),
    ("avx512pf", Some("avx512_target_feature")),
    ("avx512vbmi", Some("avx512_target_feature")),
    ("avx512vl", Some("avx512_target_feature")),
    ("avx512vpopcntdq", Some("avx512_target_feature")),
    ("bmi1", None),
    ("bmi2", None),
    ("fma", None),
    ("fxsr", None),
    ("lzcnt", None),
    ("mmx", Some("mmx_target_feature")),
    ("pclmulqdq", None),
    ("popcnt", None),
    ("rdrand", None),
    ("rdseed", None),
    ("sha", None),
    ("sse", None),
    ("sse2", None),
    ("sse3", None),
    ("sse4.1", None),
    ("sse4.2", None),
    ("sse4a", Some("sse4a_target_feature")),
    ("ssse3", None),
    ("tbm", Some("tbm_target_feature")),
    ("xsave", None),
    ("xsavec", None),
    ("xsaveopt", None),
    ("xsaves", None),
];

const HEXAGON_WHITELIST: &[(&str, Option<&str>)] = &[
    ("hvx", Some("hexagon_target_feature")),
    ("hvx-double", Some("hexagon_target_feature")),
];

const POWERPC_WHITELIST: &[(&str, Option<&str>)] = &[
    ("altivec", Some("powerpc_target_feature")),
    ("power8-altivec", Some("powerpc_target_feature")),
    ("power9-altivec", Some("powerpc_target_feature")),
    ("power8-vector", Some("powerpc_target_feature")),
    ("power9-vector", Some("powerpc_target_feature")),
    ("vsx", Some("powerpc_target_feature")),
];

const MIPS_WHITELIST: &[(&str, Option<&str>)] = &[
    ("fp64", Some("mips_target_feature")),
    ("msa", Some("mips_target_feature")),
];

/// When rustdoc is running, provide a list of all known features so that all their respective
/// primtives may be documented.
///
/// IMPORTANT: If you're adding another whitelist to the above lists, make sure to add it to this
/// iterator!
pub fn all_known_features() -> impl Iterator<Item=(&'static str, Option<&'static str>)> {
    ARM_WHITELIST.iter().cloned()
        .chain(AARCH64_WHITELIST.iter().cloned())
        .chain(X86_WHITELIST.iter().cloned())
        .chain(HEXAGON_WHITELIST.iter().cloned())
        .chain(POWERPC_WHITELIST.iter().cloned())
        .chain(MIPS_WHITELIST.iter().cloned())
}

pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
    let arch = if sess.target.target.arch == "x86_64" {
        "x86"
    } else {
        &*sess.target.target.arch
    };
    match (arch, s) {
        ("x86", "pclmulqdq") => "pclmul",
        ("x86", "rdrand") => "rdrnd",
        ("x86", "bmi1") => "bmi",
        ("aarch64", "fp") => "fp-armv8",
        ("aarch64", "fp16") => "fullfp16",
        (_, s) => s,
    }
}

pub fn target_features(sess: &Session) -> Vec<Symbol> {
    let target_machine = create_target_machine(sess, true);
    target_feature_whitelist(sess)
        .iter()
        .filter_map(|&(feature, gate)| {
            if UnstableFeatures::from_environment().is_nightly_build() || gate.is_none() {
                Some(feature)
            } else {
                None
            }
        })
        .filter(|feature| {
            let llvm_feature = to_llvm_feature(sess, feature);
            let cstr = CString::new(llvm_feature).unwrap();
            unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
        })
        .map(|feature| Symbol::intern(feature)).collect()
}

pub fn target_feature_whitelist(sess: &Session)
    -> &'static [(&'static str, Option<&'static str>)]
{
    match &*sess.target.target.arch {
        "arm" => ARM_WHITELIST,
        "aarch64" => AARCH64_WHITELIST,
        "x86" | "x86_64" => X86_WHITELIST,
        "hexagon" => HEXAGON_WHITELIST,
        "mips" | "mips64" => MIPS_WHITELIST,
        "powerpc" | "powerpc64" => POWERPC_WHITELIST,
        _ => &[],
    }
}

pub fn print_version() {
    // Can be called without initializing LLVM
    unsafe {
        println!("LLVM version: {}.{}",
                 llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
    }
}

pub fn print_passes() {
    // Can be called without initializing LLVM
    unsafe { llvm::LLVMRustPrintPasses(); }
}

pub(crate) fn print(req: PrintRequest, sess: &Session) {
    require_inited();
    let tm = create_target_machine(sess, true);
    unsafe {
        match req {
            PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
            PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
            _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Provide an example of a crossover<commit_after>extern crate rand;
#[macro_use]
extern crate nadezhda;

use std::collections::HashSet;
use nadezhda::grammar::Program;
use nadezhda::darwin::crossover::crossover;

#[derive(Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct FingerPrint {
    f: i32,
    b: i32,
}

impl FingerPrint {
    fn new() -> FingerPrint {
    FingerPrint {
        f: 0,
        b: 0,
    }
}

fn f(&self) -> FingerPrint {
FingerPrint { f: self.f + 1, ..*self }
    }

    fn b(&self) -> FingerPrint {
        FingerPrint { b: self.b + 1, ..*self }
    }
}

trait FingerPrintable {
    fn finger_print(&self) -> FingerPrint;
}

impl FingerPrintable for Program {
    fn finger_print(&self) -> FingerPrint {
        match *self {
            Program::Forward(ref contained_program) => contained_program.finger_print().f(),
            Program::Backward(ref contained_program) => contained_program.finger_print().b(),
            Program::Stop => FingerPrint::new(),
        }
    }
}

fn main() {
    let mut finger_prints: HashSet<FingerPrint> = HashSet::new();
    let mut rng = rand::thread_rng();
    let left: Program = forward!(forward!(forward!(stop!())));
    let right: Program = backward!(backward!(backward!(stop!())));

    let mut count = 0;
    loop {
        let crossover = crossover(&mut rng, &left, &right);
        let finger_print = crossover.finger_print();
        finger_prints.insert(finger_print);
        count += 1;

        if finger_prints.len() == 16 { break; }
    }

    let mut prints: Vec<&FingerPrint> = finger_prints.iter().collect();
    prints.sort();
    println!("{}", count);
    for print in prints {
        println!("{:?}", print);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add the Fd definition file.<commit_after>/// A file descriptor.
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Fd {
    inner: usize,
}
<|endoftext|>


<commit_before><commit_msg>Add a test for generator discriminants<commit_after>//! Tests that generator discriminant sizes and ranges are chosen optimally and that they are
//! reflected in the output of `mem::discriminant`.

// run-pass

#![feature(generators, generator_trait, core_intrinsics)]

use std::intrinsics::discriminant_value;
use std::marker::Unpin;
use std::mem::size_of_val;
use std::{cmp, ops::*};

macro_rules! yield25 {
    ($e:expr) => {
        yield $e;
        yield $e;
        yield $e;
        yield $e;
        yield $e;

        yield $e;
        yield $e;
        yield $e;
        yield $e;
        yield $e;

        yield $e;
        yield $e;
        yield $e;
        yield $e;
        yield $e;

        yield $e;
        yield $e;
        yield $e;
        yield $e;
        yield $e;

        yield $e;
        yield $e;
        yield $e;
        yield $e;
        yield $e;
    };
}

/// Yields 250 times.
macro_rules! yield250 {
    () => {
        yield250!(())
    };

    ($e:expr) => {
        yield25!($e);
        yield25!($e);
        yield25!($e);
        yield25!($e);
        yield25!($e);

        yield25!($e);
        yield25!($e);
        yield25!($e);
        yield25!($e);
        yield25!($e);
    };
}

fn cycle(gen: impl Generator<()> + Unpin, expected_max_discr: u64) {
    let mut gen = Box::pin(gen);
    let mut max_discr = 0;
    loop {
        max_discr = cmp::max(max_discr, discriminant_value(gen.as_mut().get_mut()));
        match gen.as_mut().resume(()) {
            GeneratorState::Yielded(_) => {}
            GeneratorState::Complete(_) => {
                assert_eq!(max_discr, expected_max_discr);
                return;
            }
        }
    }
}

fn main() {
    // Has only one invalid discr. value.
    let gen_u8_tiny_niche = || {
        || {
            // 3 reserved variants

            yield250!(); // 253 variants

            yield; // 254
            yield; // 255
        }
    };

    // Uses all values in the u8 discriminant.
    let gen_u8_full = || {
        || {
            // 3 reserved variants

            yield250!(); // 253 variants

            yield; // 254
            yield; // 255
            yield; // 256
        }
    };

    // Barely needs a u16 discriminant.
    let gen_u16 = || {
        || {
            // 3 reserved variants

            yield250!(); // 253 variants

            yield; // 254
            yield; // 255
            yield; // 256
            yield; // 257
        }
    };

    assert_eq!(size_of_val(&gen_u8_tiny_niche()), 1);
    assert_eq!(size_of_val(&Some(gen_u8_tiny_niche())), 1); // uses niche
    assert_eq!(size_of_val(&Some(Some(gen_u8_tiny_niche()))), 2); // cannot use niche anymore
    assert_eq!(size_of_val(&gen_u8_full()), 1);
    assert_eq!(size_of_val(&Some(gen_u8_full())), 2); // cannot use niche
    assert_eq!(size_of_val(&gen_u16()), 2);
    assert_eq!(size_of_val(&Some(gen_u16())), 2); // uses niche

    cycle(gen_u8_tiny_niche(), 254);
    cycle(gen_u8_full(), 255);
    cycle(gen_u16(), 256);
}
<|endoftext|>


<commit_before><commit_msg>Use push_layer_with_blend() only when necessary<commit_after><|endoftext|>


<commit_before><commit_msg>Add example: Hangman game<commit_after>//! A hangman game to guess the hidden word.

use turtle::{Drawing, Point, Speed, Turtle};

// To run this example, use the command: cargo run --features unstable --example flower
#[cfg(all(not(feature = "unstable")))]
compile_error!("This example relies on unstable features. Run with `--features unstable`");

fn main() {
    let mut drawing = Drawing::new();
    let mut hangman = drawing.add_turtle();
    let mut lines = drawing.add_turtle();

    let secret = "trainstation";

    hangman.hide();
    hangman.set_speed(Speed::instant());
    hangman.set_pen_size(10.0);
    hangman.pen_up();
    hangman.go_to(Point { x: -300.0, y: -300.0 });
    hangman.pen_down();

    let list = &[hill, mast, bar, support, rope, head, arms, body, legs];

    for step in list.iter() {
        step(&mut hangman);
    }

    lines.hide();
    lines.set_speed(Speed::instant());
    lines.right(90.0);
    lines.pen_up();
    lines.go_to(Point{x:-300.0, y:200.0});
    lines.pen_down();

    for _letter in secret.chars(){
        lines.forward(20.0);
        lines.pen_up();
        lines.forward(20.0);
        lines.pen_down();
    }
}

fn hill(hangman: &mut Turtle) {
    hangman.arc_right(100.0, 180.0);
    hangman.left(180.0);
    hangman.arc_left(100.0, 90.0);
    hangman.right(90.0);
}

fn mast(hangman: &mut Turtle) {
    hangman.forward(300.0);
    //turtle.
}

fn bar(hangman: &mut Turtle) {
    hangman.right(90.0);
    hangman.forward(150.0);
}

fn support(hangman: &mut Turtle) {
    hangman.backward(100.0);
    hangman.right(135.0);
    hangman.forward(70.710678119);
    hangman.backward(70.710678119);
    hangman.left(135.0);
    hangman.forward(100.0);
}

fn rope(hangman: &mut Turtle) {
    hangman.set_pen_size(3.0);
    hangman.right(90.0);
    hangman.forward(70.0);
}

fn head(hangman: &mut Turtle) {
    hangman.left(90.0);
    hangman.arc_right(30.0, 540.0);
}

fn arms(hangman: &mut Turtle){
    hangman.left(60.0);
    hangman.forward(100.0);
    hangman.backward(100.0);
    hangman.left(60.0);
    hangman.forward(100.0);
    hangman.backward(100.0);
    hangman.right(30.0);
}

fn body(hangman: &mut Turtle){
    hangman.forward(100.0);
}

fn legs(hangman: &mut Turtle){
    hangman.right(20.0);
    hangman.forward(120.0);
    hangman.backward(120.0);
    hangman.left(40.0);
    hangman.forward(120.0);
    hangman.backward(120.0);
    hangman.right(20.0);
}
<|endoftext|>


<commit_before><commit_msg>build: deprecate `prefix`<commit_after><|endoftext|>


<commit_before><commit_msg>build: move status handling block<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test case for const fn sizing, just to be safe.<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.

/*!
 * Try to double-check that const fns have the right size (with or
 * without dummy env ptr, as appropriate) by iterating a size-2 array.
 * If the const size differs from the runtime size, the second element
 * should be read as a null or otherwise wrong pointer and crash.
 */

fn f() { }
const bare_fns: &[extern fn()] = &[f, f];
// NOTE Why does this not type without the struct?
struct S(&fn());
const closures: &[S] = &[S(f), S(f)];

pub fn main() {
    for bare_fns.each |&bare_fn| { bare_fn() }
    for closures.each |&closure| { (*closure)() }
}
<|endoftext|>


<commit_before><commit_msg>Add tests for subroutine uniforms<commit_after>#[macro_use]
extern crate glium;

use glium::{index, Surface};
use glium::index::PrimitiveType;
use glium::program::ShaderStage;
use glium::backend::Facade;
use glium::CapabilitiesSource;
use glium::DrawError;

mod support;

#[derive(Copy, Clone)]
struct Vertex {
    position: [f32; 2],
}

implement_vertex!(Vertex, position);

#[test]
fn subroutine_bindings_simple() {
    let display = support::build_display();
    if !display.get_context().get_extensions().gl_arb_shader_subroutine {
        println!("Backend does not support subroutines");
        return
    };

    let program = program!(&display,
        330 => {
            vertex: "
                #version 330

                in vec2 position;

                void main() {
                    gl_Position = vec4(position, 0.0, 1.0);
                }
            ",

            fragment: "
                #version 330
                #extension GL_ARB_shader_subroutine : require

                out vec4 fragColor;
                subroutine vec4 color_t();

                subroutine uniform color_t Color;

                subroutine(color_t)
                vec4 ColorRed()
                {
                  return vec4(1, 0, 0, 1);
                }

                subroutine(color_t)
                vec4 ColorBlue()
                {
                  return vec4(0, 0, 1, 1);
                }

                void main()
                {
                    fragColor = Color();
                }
            "
        },
    ).unwrap();
    let vb = glium::VertexBuffer::new(&display, &[
        Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
        Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
    ]).unwrap();

    let indices = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList,
                                          &[0u16, 1, 2, 2, 1, 3]).unwrap();

    let texture = support::build_renderable_texture(&display);

    let uniforms = uniform!(
        Color: ("ColorBlue", ShaderStage::Fragment),
    );
    texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    texture.as_surface().draw(&vb, &indices, &program, &uniforms,
                              &Default::default()).unwrap();

    let data: Vec<Vec<(u8, u8, u8, u8)>> = texture.read();

    assert_eq!(data[0][0], (0, 0, 255, 255));
    assert_eq!(data.last().unwrap().last().unwrap(), &(0, 0, 255, 255));

    display.assert_no_error(None);

    let uniforms = uniform!(
        Color: ("ColorRed", ShaderStage::Fragment),
    );
    texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    texture.as_surface().draw(&vb, &indices, &program, &uniforms,
                              &Default::default()).unwrap();

    let data: Vec<Vec<(u8, u8, u8, u8)>> = texture.read();

    assert_eq!(data[0][0], (255, 0, 0, 255));
    assert_eq!(data.last().unwrap().last().unwrap(), &(255, 0, 0, 255));

    display.assert_no_error(None);
}

#[test]
fn subroutine_bindings_explicit_location() {
    let display = support::build_display();
    if !display.get_context().get_extensions().gl_arb_shader_subroutine {
        println!("Backend does not support subroutines");
        return
    };

    let program = program!(&display,
        330 => {
            vertex: "
                #version 330

                in vec2 position;

                void main() {
                    gl_Position = vec4(position, 0.0, 1.0);
                }
            ",

            fragment: "
                #version 330
                #extension GL_ARB_shader_subroutine : require
                #extension GL_ARB_explicit_uniform_location : require

                out vec4 fragColor;
                subroutine vec4 color_t();

                layout(location = 5) subroutine uniform color_t Color;

                subroutine(color_t)
                vec4 ColorRed()
                {
                  return vec4(1, 0, 0, 1);
                }

                subroutine(color_t)
                vec4 ColorBlue()
                {
                  return vec4(0, 0, 1, 1);
                }

                void main()
                {
                    fragColor = Color();
                }
            "
        },
    ).unwrap();
    let vb = glium::VertexBuffer::new(&display, &[
        Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
        Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
    ]).unwrap();

    let indices = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList,
                                          &[0u16, 1, 2, 2, 1, 3]).unwrap();

    let texture = support::build_renderable_texture(&display);

    let uniforms = uniform!(
        Color: ("ColorBlue", ShaderStage::Fragment),
    );
    texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    texture.as_surface().draw(&vb, &indices, &program, &uniforms,
                              &Default::default()).unwrap();

    let data: Vec<Vec<(u8, u8, u8, u8)>> = texture.read();

    assert_eq!(data[0][0], (0, 0, 255, 255));
    assert_eq!(data.last().unwrap().last().unwrap(), &(0, 0, 255, 255));

    display.assert_no_error(None);

    let uniforms = uniform!(
        Color: ("ColorRed", ShaderStage::Fragment),
    );
    texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    texture.as_surface().draw(&vb, &indices, &program, &uniforms,
                              &Default::default()).unwrap();

    let data: Vec<Vec<(u8, u8, u8, u8)>> = texture.read();

    assert_eq!(data[0][0], (255, 0, 0, 255));
    assert_eq!(data.last().unwrap().last().unwrap(), &(255, 0, 0, 255));

    display.assert_no_error(None);
}

// Start of more complex tests with multiple uniforms and such.
// Unfortunately, mesa has a bug which produces a segfault when compiling this fragment shader.
// https://bugs.freedesktop.org/show_bug.cgi?id=93722

fn build_program_complex(display: &glium::Display) -> glium::Program {
    let program = program!(display,
        330 => {
            vertex: "
                #version 330

                in vec2 position;

                void main() {
                    gl_Position = vec4(position, 0.0, 1.0);
                }
            ",

            fragment: "
                #version 330
                #extension GL_ARB_shader_subroutine : require

                out vec4 fragColor;
                subroutine vec4 color_t();
                subroutine vec4 modify_t(vec4 color);

                subroutine uniform color_t Color;
                subroutine uniform modify_t Modify;

                subroutine(color_t)
                vec4 ColorRed()
                {
                  return vec4(1, 0, 0, 1);
                }

                subroutine(color_t)
                vec4 ColorBlue()
                {
                  return vec4(0, 0, 1, 1);
                }

                subroutine(modify_t)
                vec4 SwapRB(vec4 color)
                {
                  return vec4(color.b, color.g, color.r, color.a);
                }

                subroutine(modify_t)
                vec4 DeleteR(vec4 color)
                {
                  return vec4(0, color.g, color.b, color.a);
                }

                void main()
                {
                    vec4 color = Color();
                    fragColor = Modify(color);
                }
            "
        },
    ).unwrap();
    program
}

#[test]
fn subroutine_bindings_multi() {
    let display = support::build_display();
    if !display.get_context().get_extensions().gl_arb_shader_subroutine {
        println!("Backend does not support subroutines");
        return
    };

    let program = build_program_complex(&display);
    let vb = glium::VertexBuffer::new(&display, &[
        Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
        Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
    ]).unwrap();

    let indices = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList,
                                          &[0u16, 1, 2, 2, 1, 3]).unwrap();

    let texture = support::build_renderable_texture(&display);

    let uniforms = uniform!(
        Color: ("ColorBlue", ShaderStage::Fragment),
        Modify: ("DeleteR", ShaderStage::Fragment),
    );
    texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    texture.as_surface().draw(&vb, &indices, &program, &uniforms,
                              &Default::default()).unwrap();

    let data: Vec<Vec<(u8, u8, u8, u8)>> = texture.read();

    assert_eq!(data[0][0], (0, 0, 255, 255));
    assert_eq!(data.last().unwrap().last().unwrap(), &(0, 0, 255, 255));

    display.assert_no_error(None);

    let uniforms = uniform!(
        Color: ("ColorRed", ShaderStage::Fragment),
        Modify: ("SwapRB", ShaderStage::Fragment),
    );
    texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    texture.as_surface().draw(&vb, &indices, &program, &uniforms,
                              &Default::default()).unwrap();

    let data: Vec<Vec<(u8, u8, u8, u8)>> = texture.read();

    assert_eq!(data[0][0], (0, 0, 255, 255));
    assert_eq!(data.last().unwrap().last().unwrap(), &(0, 0, 255, 255));

    display.assert_no_error(None);
}

#[test]
fn not_all_uniforms_set() {
    let display = support::build_display();
    if !display.get_context().get_extensions().gl_arb_shader_subroutine {
        println!("Backend does not support subroutines");
        return
    };

    let program = build_program_complex(&display);
    let vb = glium::VertexBuffer::new(&display, &[
        Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
        Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
    ]).unwrap();

    let indices = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList,
                                          &[0u16, 1, 2, 2, 1, 3]).unwrap();

    let texture = support::build_renderable_texture(&display);

    let uniforms = uniform!(
        Color: ("ColorBlue", ShaderStage::Fragment),
        // Not setting Modify on purpose
    );
    texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    match texture.as_surface().draw(&vb, &indices, &program, &uniforms,
                              &Default::default()) {
                                  Err(DrawError::SubroutineUniformMissing{ .. }) => (),
                                  _ => panic!("Drawing should have errored")
                              }

    display.assert_no_error(None);
}

#[test]
fn mismatched_subroutines() {
    let display = support::build_display();
    if !display.get_context().get_extensions().gl_arb_shader_subroutine {
        println!("Backend does not support subroutines");
        return
    };

    let program = build_program_complex(&display);
    let vb = glium::VertexBuffer::new(&display, &[
        Vertex { position: [-1.0,  1.0] }, Vertex { position: [1.0,  1.0] },
        Vertex { position: [-1.0, -1.0] }, Vertex { position: [1.0, -1.0] },
    ]).unwrap();

    let indices = glium::IndexBuffer::new(&display, PrimitiveType::TrianglesList,
                                          &[0u16, 1, 2, 2, 1, 3]).unwrap();

    let texture = support::build_renderable_texture(&display);

    let uniforms = uniform!(
        Color: ("ColorBlue", ShaderStage::Fragment),
        Modify: ("ColorBlue", ShaderStage::Fragment)
    );
    texture.as_surface().clear_color(0.0, 0.0, 0.0, 0.0);
    match texture.as_surface().draw(&vb, &indices, &program, &uniforms,
                              &Default::default()) {
                                  Err(DrawError::SubroutineNotFound{ .. }) => (),
                                  _ => panic!("Drawing should have errored")
                              }

    display.assert_no_error(None);
}
<|endoftext|>


<commit_before><commit_msg>Support regexp<commit_after><|endoftext|>


<commit_before><commit_msg>add solution to jaro_distance<commit_after>// http://rosettacode.org/wiki/Jaro_distance
use std::cmp;

fn jaro(str1: &str, str2: &str) -> f64 {
    // lengths of both strings
    let str1_len: usize = str1.len();
    let str2_len: usize = str2.len();

    // if both strings are empty return 1
    // if only one of the strings is empty return 0
    if str1_len == 0 {
        if str2_len == 0 {
            return 1.0;
        } else {
            return 0.0;
        }
    }

    // max distance between two chars to be considered matching
    let match_distance: isize = cmp::max(str1_len, str2_len) as isize / 2 - 1;

    // mutable vectors of bools that signify if that char in the matching string has a match
    let mut str1_matches: Vec<bool> = vec![false; str1_len];
    let mut str2_matches: Vec<bool> = vec![false; str2_len];

    // number of matches and transpositions
    let mut matches: f64 = 0.0;
    let mut transpositions: f64 = 0.0;

    // find the matches
    for i in 0_usize..str1_len {
        // cast new variable i_isize for clarity
        let i_isize = i as isize;
        // start and end take into account the match distance
        let start: usize = cmp::max(0, i_isize - match_distance) as usize;
        let end: usize = cmp::min(i_isize + match_distance + 1, str2_len as isize) as usize;

        for k in start..end {
            // if str2 already has a match continue
            if str2_matches[k] {
                continue;
            }
            // if str1 at i and str2 at k are not equal
            if str1.chars().nth(i).unwrap() != str2.chars().nth(k).unwrap() {
                continue;
            }
            // otherwise assume there is a match
            str1_matches[i] = true;
            str2_matches[k] = true;
            matches += 1.0;
            break;
        }
    }

    // if there are no matches return 0
    if matches == 0.0 {
        return 0.0;
    }

    // count transpositions
    let mut k = 0;
    for i in 0_usize..str1_len {
        // if there are no matches in str1 continue
        if !str1_matches[i] {
            continue;
        }
        // while there is no match in str2 increment k
        while !str2_matches[k] {
            k += 1;
        }
        // increment transpositions
        if str1.chars().nth(i).unwrap() != str2.chars().nth(k).unwrap() {
            transpositions += 1.0;
        }
        k += 1;
    }

    // deallocate variables no longer used
    drop(k);
    drop(str1_matches);
    drop(str2_matches);
    drop(match_distance);

    // divide the number of transpositions by two as per the algorithm specs
    transpositions /= 2.0;

    // return the Jaro distance
    ((matches / str1_len as f64) + (matches / str2_len as f64) +
     ((matches - transpositions) / matches)) / 3.0
}

fn main() {
    println!("{}", jaro("MARTHA", "MARHTA"));
    println!("{}", jaro("DIXON", "DICKSONX"));
    println!("{}", jaro("JELLYFISH", "SMELLYFISH"));
}

#[test]
fn test_jaro() {
    assert_eq!(jaro("MARTHA", "MARHTA"), 0.9444444444444445);
    assert_eq!(jaro("DIXON", "DICKSONX"), 0.7666666666666666);
    assert_eq!(jaro("JELLYFISH", "SMELLYFISH"), 0.8962962962962964);
}
<|endoftext|>


<commit_before><commit_msg>added most_occuring_word<commit_after>use std::io;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};

fn most_occurring_word(para:String) -> String {
    let mut m:HashMap<&str,u32>= HashMap::new();
    let mut word_pos:Vec<(&str,usize)> = vec![];
    let word_vec = para.split(" ").collect::<Vec<_>>();
    for i in 0..word_vec.len() {
        word_pos.push((word_vec[i],i));
    }

    for i in word_vec.iter() {
        match m.entry(i) {
            Occupied(mut view) => {*view.get_mut() += 1;},
            Vacant(view) => { view.insert(1); }
        }
    }

    let mut most:u32 = 0;
    let mut most_str = "";
    let mut dups:HashMap<u32,Vec<&str>> = HashMap::new();
    for i in word_vec {
        if m.get(i).unwrap() > &most {
            most =  *m.get(i).unwrap();
            match dups.entry(most) {
                Occupied(mut val) => {val.get_mut().push(i.clone())},
                Vacant(view) => {view.insert(vec![i]);},
            }
            most_str = i.clone();
        }
    }
    let mut most_w:u32 = 0;
    for (k,v) in dups.iter() {
        if k > &most_w {
            most_w = *k;
        }
    }
    let answer = format!("{:?}",dups.get(&most_w).unwrap());
    let answer = format!("{}",dups.get(&most_w).unwrap().get(0).unwrap());
return answer.to_string();
}

fn main() {
    let mut para = String::new();
    io::stdin().read_line(&mut para).ok().expect("read error");
    println!("{}",most_occurring_word(para));
}
<|endoftext|>


<commit_before><commit_msg>Color Demo is now interactive<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #37972 - bluss:iter-find-is-on-a-roll, r=sfackler<commit_after><|endoftext|>


<commit_before><commit_msg>test for overflow-checks=off<commit_after>// compile-flags: -C overflow-checks=off

// Check that we correctly implement the intended behavior of these operators
// when they are not being overflow-checked.

// FIXME: if we call the functions in `std::ops`, we still get the panics.
// Miri does not implement the codegen-time hack that backs `#[rustc_inherit_overflow_checks]`.
// use std::ops::*;

fn main() {
    assert_eq!(-{-0x80i8}, -0x80);

    assert_eq!(0xffu8 + 1, 0_u8);
    assert_eq!(0u8 - 1, 0xff_u8);
    assert_eq!(0xffu8 * 2, 0xfe_u8);
    assert_eq!(1u8 << 9, 2_u8);
    assert_eq!(2u8 >> 9, 1_u8);
}
<|endoftext|>


<commit_before><commit_msg>omit desc type<commit_after><|endoftext|>


<commit_before><commit_msg>Remove content-encoding and content-length headers from response, if we ungzip the response, and add accept-encoding: gzip header to the reqeuest when ungzipping is enabled<commit_after><|endoftext|>


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

// This test case tests the incremental compilation hash (ICH) implementation
// for exprs that can panic at runtime (e.g. because of bounds checking). For
// these expressions an error message containing their source location is
// generated, so their hash must always depend on their location in the source
// code, not just when debuginfo is enabled.

// As opposed to the panic_exprs.rs test case, this test case checks that things
// behave as expected when overflow checks are off:
//
// - Addition, subtraction, and multiplication do not change the ICH, unless
//   the function containing them is marked with rustc_inherit_overflow_checks.
// - Division by zero and bounds checks always influence the ICH

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

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph -Z force-overflow-checks=off

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

// Indexing expression ---------------------------------------------------------
#[cfg(cfail1)]
pub fn indexing(slice: &[u8]) -> u8 {
    slice[100]
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn indexing(slice: &[u8]) -> u8 {
    slice[100]
}

// Arithmetic overflow plus ----------------------------------------------------
#[cfg(cfail1)]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_plus_inherit(val: i32) -> i32 {
    val + 1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_plus_inherit(val: i32) -> i32 {
    val + 1
}

// Arithmetic overflow minus ----------------------------------------------------
#[cfg(cfail1)]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_minus_inherit(val: i32) -> i32 {
    val - 1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_minus_inherit(val: i32) -> i32 {
    val - 1
}

// Arithmetic overflow mult ----------------------------------------------------
#[cfg(cfail1)]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_mult_inherit(val: i32) -> i32 {
    val * 2
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_mult_inherit(val: i32) -> i32 {
    val * 2
}

// Arithmetic overflow negation ------------------------------------------------
#[cfg(cfail1)]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_negation_inherit(val: i32) -> i32 {
    -val
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_negation_inherit(val: i32) -> i32 {
    -val
}

// Division by zero ------------------------------------------------------------
#[cfg(cfail1)]
pub fn division_by_zero(val: i32) -> i32 {
    2 / val
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn division_by_zero(val: i32) -> i32 {
    2 / val
}

// Division by zero ------------------------------------------------------------
#[cfg(cfail1)]
pub fn mod_by_zero(val: i32) -> i32 {
    2 % val
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_dirty(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn mod_by_zero(val: i32) -> i32 {
    2 % val
}

// THE FOLLOWING ITEMS SHOULD NOT BE INFLUENCED BY THEIR SOURCE LOCATION

// bitwise ---------------------------------------------------------------------
#[cfg(cfail1)]
pub fn bitwise(val: i32) -> i32 {
    !val & 0x101010101 | 0x45689 ^ 0x2372382 << 1 >> 1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_clean(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn bitwise(val: i32) -> i32 {
    !val & 0x101010101 | 0x45689 ^ 0x2372382 << 1 >> 1
}

// logical ---------------------------------------------------------------------
#[cfg(cfail1)]
pub fn logical(val1: bool, val2: bool, val3: bool) -> bool {
    val1 && val2 || val3
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_clean(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn logical(val1: bool, val2: bool, val3: bool) -> bool {
    val1 && val2 || val3
}

// Arithmetic overflow plus ----------------------------------------------------
#[cfg(cfail1)]
pub fn arithmetic_overflow_plus(val: i32) -> i32 {
    val + 1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_clean(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn arithmetic_overflow_plus(val: i32) -> i32 {
    val + 1
}

// Arithmetic overflow minus ----------------------------------------------------
#[cfg(cfail1)]
pub fn arithmetic_overflow_minus(val: i32) -> i32 {
    val - 1
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_clean(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn arithmetic_overflow_minus(val: i32) -> i32 {
    val - 1
}

// Arithmetic overflow mult ----------------------------------------------------
#[cfg(cfail1)]
pub fn arithmetic_overflow_mult(val: i32) -> i32 {
    val * 2
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_clean(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn arithmetic_overflow_mult(val: i32) -> i32 {
    val * 2
}

// Arithmetic overflow negation ------------------------------------------------
#[cfg(cfail1)]
pub fn arithmetic_overflow_negation(val: i32) -> i32 {
    -val
}

#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_clean(label="HirBody", cfg="cfail2")]
#[rustc_clean(label="HirBody", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn arithmetic_overflow_negation(val: i32) -> i32 {
    -val
}
<commit_msg>Update panic expressions w/o overflow checks tests<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// This test case tests the incremental compilation hash (ICH) implementation
// for exprs that can panic at runtime (e.g. because of bounds checking). For
// these expressions an error message containing their source location is
// generated, so their hash must always depend on their location in the source
// code, not just when debuginfo is enabled.

// As opposed to the panic_exprs.rs test case, this test case checks that things
// behave as expected when overflow checks are off:
//
// - Addition, subtraction, and multiplication do not change the ICH, unless
//   the function containing them is marked with rustc_inherit_overflow_checks.
// - Division by zero and bounds checks always influence the ICH

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

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph -Z force-overflow-checks=off

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

// Indexing expression ---------------------------------------------------------
#[cfg(cfail1)]
pub fn indexing(slice: &[u8]) -> u8 {
    slice[100]
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn indexing(slice: &[u8]) -> u8 {
    slice[100]
}

// Arithmetic overflow plus ----------------------------------------------------
#[cfg(cfail1)]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_plus_inherit(val: i32) -> i32 {
    val + 1
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_plus_inherit(val: i32) -> i32 {
    val + 1
}

// Arithmetic overflow minus ----------------------------------------------------
#[cfg(cfail1)]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_minus_inherit(val: i32) -> i32 {
    val - 1
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_minus_inherit(val: i32) -> i32 {
    val - 1
}

// Arithmetic overflow mult ----------------------------------------------------
#[cfg(cfail1)]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_mult_inherit(val: i32) -> i32 {
    val * 2
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_mult_inherit(val: i32) -> i32 {
    val * 2
}

// Arithmetic overflow negation ------------------------------------------------
#[cfg(cfail1)]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_negation_inherit(val: i32) -> i32 {
    -val
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[rustc_inherit_overflow_checks]
pub fn arithmetic_overflow_negation_inherit(val: i32) -> i32 {
    -val
}

// Division by zero ------------------------------------------------------------
#[cfg(cfail1)]
pub fn division_by_zero(val: i32) -> i32 {
    2 / val
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn division_by_zero(val: i32) -> i32 {
    2 / val
}

// Division by zero ------------------------------------------------------------
#[cfg(cfail1)]
pub fn mod_by_zero(val: i32) -> i32 {
    2 % val
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2", except="HirBody,MirValidated,MirOptimized")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn mod_by_zero(val: i32) -> i32 {
    2 % val
}

// THE FOLLOWING ITEMS SHOULD NOT BE INFLUENCED BY THEIR SOURCE LOCATION

// bitwise ---------------------------------------------------------------------
#[cfg(cfail1)]
pub fn bitwise(val: i32) -> i32 {
    !val & 0x101010101 | 0x45689 ^ 0x2372382 << 1 >> 1
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn bitwise(val: i32) -> i32 {
    !val & 0x101010101 | 0x45689 ^ 0x2372382 << 1 >> 1
}

// logical ---------------------------------------------------------------------
#[cfg(cfail1)]
pub fn logical(val1: bool, val2: bool, val3: bool) -> bool {
    val1 && val2 || val3
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn logical(val1: bool, val2: bool, val3: bool) -> bool {
    val1 && val2 || val3
}

// Arithmetic overflow plus ----------------------------------------------------
#[cfg(cfail1)]
pub fn arithmetic_overflow_plus(val: i32) -> i32 {
    val + 1
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn arithmetic_overflow_plus(val: i32) -> i32 {
    val + 1
}

// Arithmetic overflow minus ----------------------------------------------------
#[cfg(cfail1)]
pub fn arithmetic_overflow_minus(val: i32) -> i32 {
    val - 1
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn arithmetic_overflow_minus(val: i32) -> i32 {
    val - 1
}

// Arithmetic overflow mult ----------------------------------------------------
#[cfg(cfail1)]
pub fn arithmetic_overflow_mult(val: i32) -> i32 {
    val * 2
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn arithmetic_overflow_mult(val: i32) -> i32 {
    val * 2
}

// Arithmetic overflow negation ------------------------------------------------
#[cfg(cfail1)]
pub fn arithmetic_overflow_negation(val: i32) -> i32 {
    -val
}

#[cfg(not(cfail1))]
#[rustc_clean(cfg="cfail2")]
#[rustc_clean(cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn arithmetic_overflow_negation(val: i32) -> i32 {
    -val
}
<|endoftext|>


<commit_before><commit_msg>Log tuning.<commit_after><|endoftext|>


<commit_before><commit_msg>add more examples<commit_after><|endoftext|>


<commit_before><commit_msg>Make CpalDriver's internal buffer a real ring buffer<commit_after><|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::old_io::process::{Command, ProcessExit, StdioContainer};
use std::os;

fn main() {
    let out_dir = os::getenv("OUT_DIR").unwrap();
    let result = Command::new("make")
        .args(&["-f", "makefile.cargo"])
        .stdout(StdioContainer::InheritFd(1))
        .stderr(StdioContainer::InheritFd(2))
        .status()
        .unwrap();
    assert_eq!(result, ProcessExit::ExitStatus(0));
    println!("cargo:rustc-flags=-L native={}", out_dir);
}
<commit_msg>Update gonk's build.rs.<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::env;
use std::process::{Command, Stdio};

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let result = Command::new("make")
        .args(&["-f", "makefile.cargo"])
        .status()
        .unwrap();
    assert!(result.success());
    println!("cargo:rustc-flags=-L native={}", out_dir);
}
<|endoftext|>


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

use collections::string::String;

use scheduler::context;

use schemes::{Result, KScheme, Resource, Url, VecResource};

pub struct TestScheme;

impl KScheme for TestScheme {
    fn scheme(&self) -> &str {
        "test"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        let mut string = String::new();

        macro_rules! test {
            ($ cond : expr) => (
                if ! string.is_empty() {
                    string.push('\n');
                }
                if $ cond {
                    string.push_str(&format!(concat!("\x1B[32mSUCCESS: ", stringify!($ cond), "\x1B[0m")));
                } else {
                    string.push_str(&format!(concat!("\x1B[31mFAILURE: ", stringify!($ cond), "\x1B[0m")));
                }
            );
            ($ cond : expr , $ ($ arg : tt) +) => (
                if ! string.is_empty() {
                    string.push('\n');
                }
                if $ cond {
                    string.push_str(&format!(concat!("\x1B[32mSUCCESS: ", stringify!($ cond), "\x1B[0m")));
                } else {
                    string.push_str(&format!(concat!("\x1B[31mFAILURE: ", stringify!($ cond), "\x1B[0m")));
                }
            );
        }

        {
            test!(true == true);
            test!(true == false);
        }

        Ok(box VecResource::new(Url::from_str("test:"), string.into_bytes()))
    }
}
<commit_msg>Fix format<commit_after>use alloc::boxed::Box;

use collections::string::String;

use scheduler::context;

use schemes::{Result, KScheme, Resource, Url, VecResource};

pub struct TestScheme;

impl KScheme for TestScheme {
    fn scheme(&self) -> &str {
        "test"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        let mut string = String::new();

        macro_rules! test {
            ($cond:expr) => (
                if ! string.is_empty() {
                    string.push('\n');
                }
                if $ cond {
                    string.push_str("\x1B[32mSUCCESS: ");
                } else {
                    string.push_str("\x1B[31mFAILURE: ");
                }
                string.push_str(stringify!($cond));
                string.push_str("\x1B[0m");
            );
            ($cond:expr, $($arg:tt)*) => (
                if ! string.is_empty() {
                    string.push('\n');
                }
                if $ cond {
                    string.push_str("\x1B[32mSUCCESS: ");
                } else {
                    string.push_str("\x1B[31mFAILURE: ");
                }
                string.push_str(stringify!($cond));
                string.push_str(": ");
                string.push_str(&format!($($arg)*));
                string.push_str("\x1B[0m");
            );
        }

        {
            test!(true == true);
            test!(true == false);
            test!(false, "Failing test with description");
            test!(true, "Passing test with format {:X}", 0x12345678);
        }

        Ok(box VecResource::new(Url::from_str("test:"), string.into_bytes()))
    }
}
<|endoftext|>


<commit_before><commit_msg>fun stuff<commit_after>use std::collections::VecDeque;
use std::rc::Rc;
use std::{borrow::Borrow, cmp::Ordering};
use std::{cell::RefCell, collections::HashMap};

#[derive(Debug)]
struct BTree {
    c: Option<char>,
    value: usize,
    left: Option<Rc<RefCell<BTree>>>,
    right: Option<Rc<RefCell<BTree>>>,
}

impl BTree {
    fn new(c: char, v: usize) -> Self {
        Self {
            c: Some(c),
            value: v,
            left: None,
            right: None,
        }
    }

    fn new_from_two_self_rc(a: PBTree, b: PBTree) -> Self {
        let v = a.as_ref().borrow().value + b.as_ref().borrow().value;
        Self {
            c: None,
            value: v,
            left: Some(a),
            right: Some(b),
        }
    }

    fn record_in_table(&self, table: &mut HashMap<char, Vec<String>>) {
        self.search_with_prefix(String::new(), table)
    }

    fn search_with_prefix(&self, pre: String, table: &mut HashMap<char, Vec<String>>) {
        match self.c {
            Some(cc) => {
                table.entry(cc).or_insert(vec![]).push(pre);
            }
            None => {
                let ll = self.left.as_ref().unwrap().clone();
                ll.as_ref()
                    .borrow()
                    .search_with_prefix(pre.clone() + "0", table);

                ll.as_ref()
                    .borrow()
                    .search_with_prefix(pre.clone() + "1", table);

                let rr = self.right.as_ref().unwrap().clone();
                rr.as_ref()
                    .borrow()
                    .search_with_prefix(pre.clone() + "1", table);

                rr.as_ref()
                    .borrow()
                    .search_with_prefix(pre.clone() + "0", table);
            }
        }
    }
}

impl PartialEq for BTree {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

impl PartialOrd for BTree {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.value.cmp(&other.value))
    }
}

type PBTree = Rc<RefCell<BTree>>;

fn new_huffman_tree(mut ll: Vec<PBTree>) -> Vec<Vec<PBTree>> {
    if ll.len() == 1 {
        return vec![ll];
    }
    ll.sort_by(|a, b| a.partial_cmp(b).unwrap());

    pick_smallest(ll)
        .into_iter()
        .map(|(a, tail)| make_buffman_tree(a, tail))
        .flatten()
        .map(|v| new_huffman_tree(v))
        .flatten()
        .collect() //::<Vec<Vec<PBTree>>>()
}

fn make_buffman_tree(a: PBTree, tail: Vec<PBTree>) -> Vec<Vec<PBTree>> {
    if tail.len() == 0 {
        return vec![vec![a]];
    }

    let ll = pick_smallest(tail);

    ll.into_iter()
        .map(|(new_smallest, mut new_tail)| {
            let new = BTree::new_from_two_self_rc(a.clone(), new_smallest);
            new_tail.push(Rc::new(RefCell::new(new)));
            new_tail.sort_by(|a, b| a.partial_cmp(b).unwrap());
            new_tail
        })
        .collect()
}

fn pick_smallest(ll: Vec<PBTree>) -> Vec<(PBTree, Vec<PBTree>)> {
    if ll.len() == 0 {
        return vec![];
    }

    let key = ll[0].as_ref().borrow().value;
    let mut head: VecDeque<&Rc<RefCell<BTree>>> = VecDeque::new();
    let mut tail: Vec<&Rc<RefCell<BTree>>> = vec![];
    ll.iter().for_each(|v| {
        if v.as_ref().borrow().value == key {
            head.push_back(v)
        } else {
            tail.push(v)
        }
    });

    //dbg!(&head);
    //dbg!(&tail);

    let mut result = vec![];
    for _ in 0..head.len() {
        let this = head.drain(..1).collect::<VecDeque<_>>();
        let mut new_tail = head.iter().map(|v| (*v).clone()).collect::<Vec<_>>();
        new_tail.append(&mut tail.iter().map(|v| (*v).clone()).collect::<Vec<_>>());
        result.push((this[0].clone(), new_tail));

        head.push_back(this[0]);
    }

    result
}

fn main() {
    let f = Rc::new(RefCell::new(BTree::new('f', 2)));
    let o = Rc::new(RefCell::new(BTree::new('o', 3)));
    let r = Rc::new(RefCell::new(BTree::new('r', 4)));
    let g = Rc::new(RefCell::new(BTree::new('g', 4)));
    let e = Rc::new(RefCell::new(BTree::new('e', 5)));
    let t = Rc::new(RefCell::new(BTree::new('t', 7)));

    //dbg!(new_huffman_tree(vec![f, o, r, g, e, t]));
    let aaa = new_huffman_tree(vec![f, o, r, g, e, t]);
    //dbg!(new_huffman_tree(aaa[0].clone()));
    //dbg!(pick_smallest(aaa[0].clone()));
    //dbg!(pick_smallest(vec![f, o, r, g, e, t]));
    //dbg!(make_buffman_tree(f, vec![o, r, g, e, t]));

    //let mut table = HashMap::new();

    //dbg!(aaa.len());
    aaa.iter().for_each(move |a| {
        dbg!(a);
        //a[0].as_ref().borrow().record_in_table(&mut table);
        //dbg!(&table);
    });

    //aaa[0][0].as_ref().borrow().record_in_table(&mut table);
    //dbg!(table);
}
<|endoftext|>


<commit_before>use core::mem;

use redox::*;

use super::nvpair::{DataType, NV_VERSION, NvList, NvValue};
use super::xdr;

// nvlist pack encoding
const NV_ENCODE_NATIVE: u8 = 0;
const NV_ENCODE_XDR:    u8 = 1;

// nvlist pack endian
const NV_BIG_ENDIAN:    u8 = 0;
const NV_LITTLE_ENDIAN: u8 = 1;

// nvlist persistent unique name flags, stored in nvl_nvflags
const NV_UNIQUE_NAME:      u32 = 0x1;
const NV_UNIQUE_NAME_TYPE: u32 = 0x2;

// nvlist lookup pairs related flags
const NV_FLAG_NOENTOK: isize = 0x1;

// NvList XDR format:
// - header (encoding and endian): 4 bytes
// - nvl version: 4 bytes
// - nv flags: 4 bytes
// - nv pairs:
//   - encoded size: 4 bytes
//   - decoded size: 4 bytes
//   - name: xdr string | len: 4 bytes, data: len+(4 - len%4) bytes
//   - data type: 4 bytes
//   - num elements: 4 bytes
//   - data
// - 2 terminating zeros: 4 bytes
//
// NOTE: XDR aligns all of the smaller integer types to be 4 bytes, so `encode_u8` is actually
// writing 4 bytes
//
// I don't know why the ZFS developers decided to use i32's everywhere. Even for clearly
// unsigned things like array lengths.

/// Name value stream header
pub struct NvsHeader {
    encoding: u8,  // nvs encoding method
    endian: u8,    // nvs endian
    reserved1: u8, // reserved for future use
    reserved2: u8, // reserved for future use
}

/// Encodes a NvList in XDR format
pub fn encode_nv_list(xdr: &mut xdr::Xdr, nv_list: &NvList) -> xdr::XdrResult<()> {
    try!(encode_nv_list_header(xdr));

    // Encode version and nvflag
    try!(xdr.encode_i32(nv_list.version));
    try!(xdr.encode_u32(nv_list.nvflag));

    // Encode the pairs
    for &(ref name, ref value) in &nv_list.pairs {
        // Encode encoded/decoded size
        let encoded_size = 0;
        let decoded_size = 0;

        // Encode name
        try!(xdr.encode_string(name));

        // TODO

        // Encode data type
        try!(xdr.encode_u8(value.data_type().to_u8()));

        // Encode the number of elements
        try!(xdr.encode_i32(value.num_elements() as i32));

        // Encode the value
    }

    // Encode 2 terminating zeros
    try!(xdr.encode_i32(0));
    try!(xdr.encode_i32(0));
    Ok(())
}

fn encode_nv_list_header(xdr: &mut xdr::Xdr) -> xdr::XdrResult<()> {
    let header =
        NvsHeader {
            encoding: NV_ENCODE_XDR,
            endian: NV_LITTLE_ENDIAN,
            reserved1: 0,
            reserved2: 0,
        };
    let header_bytes: [u8; 4] = unsafe { mem::transmute(header) };
    try!(xdr.encode_opaque(&header_bytes));
    Ok(())
}

/// Decodes a NvList in XDR format
pub fn decode_nv_list(xdr: &mut xdr::Xdr) -> xdr::XdrResult<NvList> {
    try!(decode_nv_list_header(xdr));

    decode_nv_list_embedded(xdr)
}

pub fn decode_nv_list_embedded(xdr: &mut xdr::Xdr) -> xdr::XdrResult<NvList> {
    // Decode version and nvflag
    let version = try!(xdr.decode_i32());
    let nvflag = try!(xdr.decode_u32());

    // TODO: Give an actual error
    if version != NV_VERSION {
        return Err(xdr::XdrError);
    }

    let mut nv_list = NvList::new(nvflag);

    // Decode the pairs
    loop {
        // Decode decoded/decoded size
        let encoded_size = try!(xdr.decode_u32());
        let decoded_size = try!(xdr.decode_u32());

        // Check for 2 terminating zeros
        if (encoded_size == 0 && decoded_size == 0) {
            break;
        }

        // Decode name
        let name = try!(xdr.decode_string());

        // Decode data type
        let data_type =
            match DataType::from_u8(try!(xdr.decode_u8())) {
                Some(dt) => dt,
                None => { return Err(xdr::XdrError); },
            };

        // Decode the number of elements
        let num_elements = try!(xdr.decode_i32()) as usize;

        // Decode the value
        let value = try!(decode_nv_value(xdr, data_type, num_elements));

        // Add the value to the list
        nv_list.pairs.push((name, value));
    }

    Ok(nv_list)
}

fn decode_nv_list_header(xdr: &mut xdr::Xdr) -> xdr::XdrResult<()> {
    let mut bytes = [0; 4];
    try!(xdr.decode_opaque(&mut bytes));
    let header: &NvsHeader = unsafe { mem::transmute(&bytes[0]) };

    if header.encoding != NV_ENCODE_XDR {
        return Err(xdr::XdrError);
    }
    Ok(())
}

fn decode_nv_value(xdr: &mut xdr::Xdr, data_type: DataType, num_elements: usize) -> xdr::XdrResult<NvValue> {
    match data_type {
        DataType::Unknown => { Ok(NvValue::Unknown) },
        DataType::Boolean => { Ok(NvValue::Boolean) },
        DataType::Byte => {
            Ok(NvValue::Byte(try!(xdr.decode_u8())))
        },
        DataType::Int16 => {
            Ok(NvValue::Int16(try!(xdr.decode_i16())))
        },
        DataType::Uint16 => {
            Ok(NvValue::Uint16(try!(xdr.decode_u16())))
        },
        DataType::Int32 => {
            Ok(NvValue::Int32(try!(xdr.decode_i32())))
        },
        DataType::Uint32 => {
            Ok(NvValue::Uint32(try!(xdr.decode_u32())))
        },
        DataType::Int64 => {
            Ok(NvValue::Int64(try!(xdr.decode_i64())))
        },
        DataType::Uint64 => {
            Ok(NvValue::Uint64(try!(xdr.decode_u64())))
        },
        DataType::String => {
            Ok(NvValue::String(try!(xdr.decode_string())))
        },
        DataType::ByteArray => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u8());
            }
            Ok(NvValue::ByteArray(v))
        },
        DataType::Int16Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_i16());
            }
            Ok(NvValue::Int16Array(v))
        },
        DataType::Uint16Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u16());
            }
            Ok(NvValue::Uint16Array(v))
        },
        DataType::Int32Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_i32());
            }
            Ok(NvValue::Int32Array(v))
        },
        DataType::Uint32Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u32());
            }
            Ok(NvValue::Uint32Array(v))
        },
        DataType::Int64Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_i64());
            }
            Ok(NvValue::Int64Array(v))
        },
        DataType::Uint64Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u64());
            }
            Ok(NvValue::Uint64Array(v))
        },
        DataType::StringArray => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u64());
            }
            Ok(NvValue::Uint64Array(v))
        },
        DataType::HrTime => {
            Ok(NvValue::HrTime)
        },
        DataType::NvList => {
            let nv_list = Box::new(try!(decode_nv_list_embedded(xdr)));
            Ok(NvValue::NvList(nv_list))
        },
        DataType::NvListArray => {
            let mut v = Vec::with_capacity(num_elements);
            for _ in 0..num_elements {
                v.push(Box::new(try!(decode_nv_list_embedded(xdr))));
            }
            Ok(NvValue::NvListArray(v))
        },
        DataType::BooleanValue => {
            Ok(NvValue::BooleanValue(try!(xdr.decode_bool())))
        },
        DataType::Int8 => {
            Ok(NvValue::Int8(try!(xdr.decode_i8())))
        },
        DataType::Uint8 => {
            Ok(NvValue::Uint8(try!(xdr.decode_u8())))
        },
        DataType::BooleanArray => {
            let mut v = vec![false; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_bool());
            }
            Ok(NvValue::BooleanArray(v))
        },
        DataType::Int8Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_i8());
            }
            Ok(NvValue::Int8Array(v))
        },
        DataType::Uint8Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u8());
            }
            Ok(NvValue::Uint8Array(v))
        },
    }
}
<commit_msg>Successfully loaded a null nvlist<commit_after>use core::mem;

use redox::*;

use super::nvpair::{DataType, NV_VERSION, NvList, NvValue};
use super::xdr;

// nvlist pack encoding
const NV_ENCODE_NATIVE: u8 = 0;
const NV_ENCODE_XDR:    u8 = 1;

// nvlist pack endian
const NV_BIG_ENDIAN:    u8 = 0;
const NV_LITTLE_ENDIAN: u8 = 1;

// nvlist persistent unique name flags, stored in nvl_nvflags
const NV_UNIQUE_NAME:      u32 = 0x1;
const NV_UNIQUE_NAME_TYPE: u32 = 0x2;

// nvlist lookup pairs related flags
const NV_FLAG_NOENTOK: isize = 0x1;

// NvList XDR format:
// - header (encoding and endian): 4 bytes
// - nvl version: 4 bytes
// - nv flags: 4 bytes
// - nv pairs:
//   - encoded size: 4 bytes
//   - decoded size: 4 bytes
//   - name: xdr string | len: 4 bytes, data: len+(4 - len%4) bytes
//   - data type: 4 bytes
//   - num elements: 4 bytes
//   - data
// - 2 terminating zeros: 4 bytes
//
// NOTE: XDR aligns all of the smaller integer types to be 4 bytes, so `encode_u8` is actually
// writing 4 bytes
//
// I don't know why the ZFS developers decided to use i32's everywhere. Even for clearly
// unsigned things like array lengths.

/// Name value stream header
#[derive(Debug)]
pub struct NvsHeader {
    encoding: u8,  // nvs encoding method
    endian: u8,    // nvs endian
    reserved1: u8, // reserved for future use
    reserved2: u8, // reserved for future use
}

/// Encodes a NvList in XDR format
pub fn encode_nv_list(xdr: &mut xdr::Xdr, nv_list: &NvList) -> xdr::XdrResult<()> {
    try!(encode_nv_list_header(xdr));

    // Encode version and nvflag
    try!(xdr.encode_i32(nv_list.version));
    try!(xdr.encode_u32(nv_list.nvflag));

    // Encode the pairs
    for &(ref name, ref value) in &nv_list.pairs {
        // Encode encoded/decoded size
        let encoded_size = 0;
        let decoded_size = 0;

        // Encode name
        try!(xdr.encode_string(name));

        // TODO

        // Encode data type
        try!(xdr.encode_u8(value.data_type().to_u8()));

        // Encode the number of elements
        try!(xdr.encode_i32(value.num_elements() as i32));

        // Encode the value
    }

    // Encode 2 terminating zeros
    try!(xdr.encode_i32(0));
    try!(xdr.encode_i32(0));
    Ok(())
}

fn encode_nv_list_header(xdr: &mut xdr::Xdr) -> xdr::XdrResult<()> {
    let header =
        NvsHeader {
            encoding: NV_ENCODE_XDR,
            endian: NV_LITTLE_ENDIAN,
            reserved1: 0,
            reserved2: 0,
        };
    let header_bytes: [u8; 4] = unsafe { mem::transmute(header) };
    try!(xdr.encode_opaque(&header_bytes));
    Ok(())
}

/// Decodes a NvList in XDR format
pub fn decode_nv_list(xdr: &mut xdr::Xdr) -> xdr::XdrResult<NvList> {
    println!("Decoding NvList...");

    try!(decode_nv_list_header(xdr));

    println!("Decoded header");

    decode_nv_list_embedded(xdr)
}

pub fn decode_nv_list_embedded(xdr: &mut xdr::Xdr) -> xdr::XdrResult<NvList> {
    // Decode version and nvflag
    let version = try!(xdr.decode_i32());
    let nvflag = try!(xdr.decode_u32());

    println!("Decoded version and nvflag: {}\t{}", version, nvflag);

    // TODO: Give an actual error
    if version != NV_VERSION {
        return Err(xdr::XdrError);
    }

    let mut nv_list = NvList::new(nvflag);

    // Decode the pairs
    loop {
        // Decode decoded/decoded size
        let encoded_size = try!(xdr.decode_u32());
        let decoded_size = try!(xdr.decode_u32());

        println!("Decoded sizes: {}\t{}", encoded_size, decoded_size);

        // Check for 2 terminating zeros
        if (encoded_size == 0 && decoded_size == 0) {
            break;
        }

        // Decode name
        let name = try!(xdr.decode_string());

        println!("Decoded name: {}", name);

        // Decode data type
        let data_type =
            match DataType::from_u8(try!(xdr.decode_u8())) {
                Some(dt) => dt,
                None => { return Err(xdr::XdrError); },
            };

        // Decode the number of elements
        let num_elements = try!(xdr.decode_i32()) as usize;

        // Decode the value
        let value = try!(decode_nv_value(xdr, data_type, num_elements));

        // Add the value to the list
        nv_list.pairs.push((name, value));
    }

    Ok(nv_list)
}

fn decode_nv_list_header(xdr: &mut xdr::Xdr) -> xdr::XdrResult<()> {
    println!("Decoding header...");

    let mut bytes = [0; 4];
    try!(xdr.decode_opaque(&mut bytes));
    let header: &NvsHeader = unsafe { mem::transmute(&bytes[0]) };

    println!("header: {:?}", header);

    /*if header.encoding != NV_ENCODE_XDR {
        return Err(xdr::XdrError);
    }*/
    Ok(())
}

fn decode_nv_value(xdr: &mut xdr::Xdr, data_type: DataType, num_elements: usize) -> xdr::XdrResult<NvValue> {
    match data_type {
        DataType::Unknown => { Ok(NvValue::Unknown) },
        DataType::Boolean => { Ok(NvValue::Boolean) },
        DataType::Byte => {
            Ok(NvValue::Byte(try!(xdr.decode_u8())))
        },
        DataType::Int16 => {
            Ok(NvValue::Int16(try!(xdr.decode_i16())))
        },
        DataType::Uint16 => {
            Ok(NvValue::Uint16(try!(xdr.decode_u16())))
        },
        DataType::Int32 => {
            Ok(NvValue::Int32(try!(xdr.decode_i32())))
        },
        DataType::Uint32 => {
            Ok(NvValue::Uint32(try!(xdr.decode_u32())))
        },
        DataType::Int64 => {
            Ok(NvValue::Int64(try!(xdr.decode_i64())))
        },
        DataType::Uint64 => {
            Ok(NvValue::Uint64(try!(xdr.decode_u64())))
        },
        DataType::String => {
            Ok(NvValue::String(try!(xdr.decode_string())))
        },
        DataType::ByteArray => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u8());
            }
            Ok(NvValue::ByteArray(v))
        },
        DataType::Int16Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_i16());
            }
            Ok(NvValue::Int16Array(v))
        },
        DataType::Uint16Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u16());
            }
            Ok(NvValue::Uint16Array(v))
        },
        DataType::Int32Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_i32());
            }
            Ok(NvValue::Int32Array(v))
        },
        DataType::Uint32Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u32());
            }
            Ok(NvValue::Uint32Array(v))
        },
        DataType::Int64Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_i64());
            }
            Ok(NvValue::Int64Array(v))
        },
        DataType::Uint64Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u64());
            }
            Ok(NvValue::Uint64Array(v))
        },
        DataType::StringArray => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u64());
            }
            Ok(NvValue::Uint64Array(v))
        },
        DataType::HrTime => {
            Ok(NvValue::HrTime)
        },
        DataType::NvList => {
            let nv_list = Box::new(try!(decode_nv_list_embedded(xdr)));
            Ok(NvValue::NvList(nv_list))
        },
        DataType::NvListArray => {
            let mut v = Vec::with_capacity(num_elements);
            for _ in 0..num_elements {
                v.push(Box::new(try!(decode_nv_list_embedded(xdr))));
            }
            Ok(NvValue::NvListArray(v))
        },
        DataType::BooleanValue => {
            Ok(NvValue::BooleanValue(try!(xdr.decode_bool())))
        },
        DataType::Int8 => {
            Ok(NvValue::Int8(try!(xdr.decode_i8())))
        },
        DataType::Uint8 => {
            Ok(NvValue::Uint8(try!(xdr.decode_u8())))
        },
        DataType::BooleanArray => {
            let mut v = vec![false; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_bool());
            }
            Ok(NvValue::BooleanArray(v))
        },
        DataType::Int8Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_i8());
            }
            Ok(NvValue::Int8Array(v))
        },
        DataType::Uint8Array => {
            let mut v = vec![0; num_elements];
            for v in &mut v {
                *v = try!(xdr.decode_u8());
            }
            Ok(NvValue::Uint8Array(v))
        },
    }
}
<|endoftext|>


<commit_before><commit_msg>Add tests for HttpOnly flag.<commit_after><|endoftext|>


<commit_before><commit_msg>Adjust conditional compilation attributes so default + gui can be used together<commit_after><|endoftext|>


<commit_before><commit_msg>Added a test between rectangles and circles<commit_after><|endoftext|>