<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 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"); }

        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 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: &'static [&'static str] = &["neon", "v7", "vfp2", "vfp3", "vfp4"];

const AARCH64_WHITELIST: &'static [&'static str] = &["neon", "v7"];

const X86_WHITELIST: &'static [&'static str] = &["avx", "avx2", "bmi", "bmi2", "sse",
                                                 "sse2", "sse3", "sse4.1", "sse4.2",
                                                 "ssse3", "tbm", "lzcnt", "popcnt",
                                                 "sse4a", "rdrnd", "rdseed", "fma",
                                                 "xsave", "xsaveopt", "xsavec",
                                                 "xsaves", "aes", "pclmulqdq",
                                                 "avx512bw", "avx512cd",
                                                 "avx512dq", "avx512er",
                                                 "avx512f", "avx512ifma",
                                                 "avx512pf", "avx512vbmi",
                                                 "avx512vl", "avx512vpopcntdq",
                                                 "mmx", "fxsr"];

const HEXAGON_WHITELIST: &'static [&'static str] = &["hvx", "hvx-double"];

const POWERPC_WHITELIST: &'static [&'static str] = &["altivec",
                                                     "power8-altivec", "power9-altivec",
                                                     "power8-vector", "power9-vector",
                                                     "vsx"];

const MIPS_WHITELIST: &'static [&'static str] = &["msa"];

pub fn to_llvm_feature(s: &str) -> &str {
    match s {
        "pclmulqdq" => "pclmul",
        s => s,
    }
}

pub fn target_features(sess: &Session) -> Vec<Symbol> {
    let target_machine = create_target_machine(sess);
    target_feature_whitelist(sess)
        .iter()
        .filter(|feature| {
            let llvm_feature = to_llvm_feature(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] {
    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);
    unsafe {
        match req {
            PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
            PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
            _ => bug!("rustc_trans can't handle print request: {:?}", req),
        }
    }
}
<commit_msg>added rdrand feature and removed rdrnd feature<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 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"); }

        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 aplpying `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: &'static [&'static str] = &["neon", "v7", "vfp2", "vfp3", "vfp4"];

const AARCH64_WHITELIST: &'static [&'static str] = &["neon", "v7"];

const X86_WHITELIST: &'static [&'static str] = &["avx", "avx2", "bmi", "bmi2", "sse",
                                                 "sse2", "sse3", "sse4.1", "sse4.2",
                                                 "ssse3", "tbm", "lzcnt", "popcnt",
                                                 "sse4a","fma", "rdrand", "rdseed",
                                                 "xsave", "xsaveopt", "xsavec",
                                                 "xsaves", "aes", "pclmulqdq",
                                                 "avx512bw", "avx512cd",
                                                 "avx512dq", "avx512er",
                                                 "avx512f", "avx512ifma",
                                                 "avx512pf", "avx512vbmi",
                                                 "avx512vl", "avx512vpopcntdq",
                                                 "mmx", "fxsr"];

const HEXAGON_WHITELIST: &'static [&'static str] = &["hvx", "hvx-double"];

const POWERPC_WHITELIST: &'static [&'static str] = &["altivec",
                                                     "power8-altivec", "power9-altivec",
                                                     "power8-vector", "power9-vector",
                                                     "vsx"];

const MIPS_WHITELIST: &'static [&'static str] = &["msa"];

pub fn to_llvm_feature(s: &str) -> &str {
    match s {
        "pclmulqdq" => "pclmul",
        "rdrand" => "rdrnd",
        s => s,
    }
}

pub fn target_features(sess: &Session) -> Vec<Symbol> {
    let target_machine = create_target_machine(sess);
    target_feature_whitelist(sess)
        .iter()
        .filter(|feature| {
            let llvm_feature = to_llvm_feature(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] {
    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);
    unsafe {
        match req {
            PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
            PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
            _ => bug!("rustc_trans can't handle print request: {:?}", req),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>added Sticker object<commit_after>use objects::PhotoSize;

/// Represents a sticker
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Audio {
    pub file_id: String,
    pub width: i64,
    pub heigh: i64,
    pub thump: Option<PhotoSize>,
    pub emoji: Option<String>,
    pub file_size: Option<i64>,
}
<|endoftext|>


<commit_before><commit_msg>feat(scores): add PAM120 score matrix<commit_after>// Copyright 2015 M. Rizky Luthfianto.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

#[macro_use]
extern crate lazy_static;

extern crate nalgebra;

use nalgebra::DMat;

lazy_static! {

	// taken from https://github.com/seqan/seqan/blob/master/include%2Fseqan%2Fscore%2Fscore_matrix_data.h#L614
	static ref ARRAY: [i32;729]=[
		 3,  0, -3,  0,  0, -4,  1, -3, -1, -2, -2, -3, -2, -1, -1,  1, -1, -3,  1,  1, -1,  0, -7, -4, -1, -1, -8,
		 0,  4, -6,  4,  3, -5,  0,  1, -3, -4,  0, -4, -4,  3, -1, -2,  0, -2,  0,  0, -1, -3, -6, -3,  2, -1, -8,
		-3, -6,  9, -7, -7, -6, -4, -4, -3, -5, -7, -7, -6, -5, -4, -4, -7, -4,  0, -3, -4, -3, -8, -1, -7, -4, -8,
		 0,  4, -7,  5,  3, -7,  0,  0, -3, -4, -1, -5, -4,  2, -2, -3,  1, -3,  0, -1, -2, -3, -8, -5,  3, -2, -8,
		 0,  3, -7,  3,  5, -7, -1, -1, -3, -4, -1, -4, -3,  1, -1, -2,  2, -3, -1, -2, -1, -3, -8, -5,  4, -1, -8,
		-4, -5, -6, -7, -7,  8, -5, -3,  0,  0, -7,  0, -1, -4, -3, -5, -6, -5, -3, -4, -3, -3, -1,  4, -6, -3, -8,
		 1,  0, -4,  0, -1, -5,  5, -4, -4, -5, -3, -5, -4,  0, -2, -2, -3, -4,  1, -1, -2, -2, -8, -6, -2, -2, -8,
		-3,  1, -4,  0, -1, -3, -4,  7, -4, -4, -2, -3, -4,  2, -2, -1,  3,  1, -2, -3, -2, -3, -3, -1,  1, -2, -8,
		-1, -3, -3, -3, -3,  0, -4, -4,  6,  4, -3,  1,  1, -2, -1, -3, -3, -2, -2,  0, -1,  3, -6, -2, -3, -1, -8,
		-2, -4, -5, -4, -4,  0, -5, -4,  4,  4, -4,  3,  2, -3, -2, -3, -3, -3, -3, -2, -2,  2, -5, -2, -3, -2, -8,
		-2,  0, -7, -1, -1, -7, -3, -2, -3, -4,  5, -4,  0,  1, -2, -2,  0,  2, -1, -1, -2, -4, -5, -5, -1, -2, -8,
		-3, -4, -7, -5, -4,  0, -5, -3,  1,  3, -4,  5,  3, -4, -2, -3, -2, -4, -4, -3, -2,  1, -3, -2, -3, -2, -8,
		-2, -4, -6, -4, -3, -1, -4, -4,  1,  2,  0,  3,  8, -3, -2, -3, -1, -1, -2, -1, -2,  1, -6, -4, -2, -2, -8,
		-1,  3, -5,  2,  1, -4,  0,  2, -2, -3,  1, -4, -3,  4, -1, -2,  0, -1,  1,  0, -1, -3, -4, -2,  0, -1, -8,
		-1, -1, -4, -2, -1, -3, -2, -2, -1, -2, -2, -2, -2, -1, -2, -2, -1, -2, -1, -1, -2, -1, -5, -3, -1, -2, -8,
		 1, -2, -4, -3, -2, -5, -2, -1, -3, -3, -2, -3, -3, -2, -2,  6,  0, -1,  1, -1, -2, -2, -7, -6, -1, -2, -8,
		-1,  0, -7,  1,  2, -6, -3,  3, -3, -3,  0, -2, -1,  0, -1,  0,  6,  1, -2, -2, -1, -3, -6, -5,  4, -1, -8,
		-3, -2, -4, -3, -3, -5, -4,  1, -2, -3,  2, -4, -1, -1, -2, -1,  1,  6, -1, -2, -2, -3,  1, -5, -1, -2, -8,
		 1,  0,  0,  0, -1, -3,  1, -2, -2, -3, -1, -4, -2,  1, -1,  1, -2, -1,  3,  2, -1, -2, -2, -3, -1, -1, -8,
		 1,  0, -3, -1, -2, -4, -1, -3,  0, -2, -1, -3, -1,  0, -1, -1, -2, -2,  2,  4, -1,  0, -6, -3, -2, -1, -8,
		-1, -1, -4, -2, -1, -3, -2, -2, -1, -2, -2, -2, -2, -1, -2, -2, -1, -2, -1, -1, -2, -1, -5, -3, -1, -2, -8,
		 0, -3, -3, -3, -3, -3, -2, -3,  3,  2, -4,  1,  1, -3, -1, -2, -3, -3, -2,  0, -1,  5, -8, -3, -3, -1, -8,
		-7, -6, -8, -8, -8, -1, -8, -3, -6, -5, -5, -3, -6, -4, -5, -7, -6,  1, -2, -6, -5, -8, 12, -2, -7, -5, -8,
		-4, -3, -1, -5, -5,  4, -6, -1, -2, -2, -5, -2, -4, -2, -3, -6, -5, -5, -3, -3, -3, -3, -2,  8, -5, -3, -8,
		-1,  2, -7,  3,  4, -6, -2,  1, -3, -3, -1, -3, -2,  0, -1, -1,  4, -1, -1, -2, -1, -3, -7, -5,  4, -1, -8,
		-1, -1, -4, -2, -1, -3, -2, -2, -1, -2, -2, -2, -2, -1, -2, -2, -1, -2, -1, -1, -2, -1, -5, -3, -1, -2, -8,
		-8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8,  1
	];

	static ref MAT: DMat<i32> = DMat::from_col_vec(27, 27, &*ARRAY);
}

#[inline]
fn lookup(number: u8) -> usize {
	if      number==b'Y' { 23 as usize }
	else if number==b'Z' { 24 as usize }
	else if number==b'X' { 25 as usize }
	else if number==b'*' { 26 as usize }
	else { (number-65) as usize }
}

pub fn pam120(a: u8, b: u8) -> i32 {
	let a = lookup(a);
	let b = lookup(b);

	MAT[(a, b)]
}

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

	#[test]
	fn test_pam120() {
		let score1 = pam120(b'A',b'A');
		assert_eq!(score1, 3);
		let score2 = pam120(b'*',b'*');
		assert_eq!(score2, 1);
		let score3 = pam120(b'A',b'*');
		assert_eq!(score3, -8);
		let score4 = pam120(b'*',b'*');
		assert_eq!(score4, 1);
		let score5 = pam120(b'X',b'X');
		assert_eq!(score5, -2);
		let score6 = pam120(b'X',b'Z');
		assert_eq!(score6, -1);
	}
}
<|endoftext|>


<commit_before><commit_msg>Implement VolumeHeader::write().<commit_after><|endoftext|>


<commit_before><commit_msg>sorting partially done for Step 6 of SupportedPropertyNames<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test for #90752<commit_after>// run-pass

use std::cell::RefCell;

struct S<'a>(i32, &'a RefCell<Vec<i32>>);

impl<'a> Drop for S<'a> {
    fn drop(&mut self) {
        self.1.borrow_mut().push(self.0);
    }
}

fn test(drops: &RefCell<Vec<i32>>) {
    let mut foo = None;
    match foo {
        None => (),
        _ => return,
    }

    *(&mut foo) = Some((S(0, drops), S(1, drops))); // Both S(0) and S(1) should be dropped

    match foo {
        Some((_x, _)) => {}
        _ => {}
    }
}

fn main() {
    let drops = RefCell::new(Vec::new());
    test(&drops);
    assert_eq!(*drops.borrow(), &[0, 1]);
}
<|endoftext|>


<commit_before><commit_msg>Test key vs value counts<commit_after><|endoftext|>


<commit_before>use std::collections::HashMap;

fn call(number: &str) -> &str {
    match number {
        "798-1364" => "We're sorry, the call cannot be completed as dialed.
            Please hang up and try again.",
        "645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
            What can I get for you today?",
        _ => "Hi! Who is this again?"
    }
}

fn main() {
    let mut contacts = HashMap::new();

    contacts.insert("Daniel", "798-1364");
    contacts.insert("Ashley", "645-7689");
    contacts.insert("Katie", "435-8291");
    contacts.insert("Robert", "956-1745");

    // Takes a reference and returns Option<&V>
    match contacts.get(&"Daniel") {
        Some(&number) => println!("Calling Daniel: {}", call(number)),
        _ => println!("Don't have Daniel's number."),
    }

    // `HashMap::insert()` returns true
    // if the inserted value is new, false otherwise
    contacts.insert("Daniel", "164-6743");

    match contacts.get(&"Ashley") {
        Some(&number) => println!("Calling Ashley: {}", call(number)),
        _ => println!("Don't have Ashley's number."),
    }

    contacts.remove(&("Ashley"));

    // `HashMap::iter()` returns an iterator that yields
    // (&'a key, &'a value) pairs in arbitrary order.
    for (contact, &number) in contacts.iter() {
        println!("Calling {}: {}", contact, call(number));
    }
}
<commit_msg>std/hash: HashMap::insert() returns Option<V>, not bool<commit_after>use std::collections::HashMap;

fn call(number: &str) -> &str {
    match number {
        "798-1364" => "We're sorry, the call cannot be completed as dialed.
            Please hang up and try again.",
        "645-7689" => "Hello, this is Mr. Awesome's Pizza. My name is Fred.
            What can I get for you today?",
        _ => "Hi! Who is this again?"
    }
}

fn main() {
    let mut contacts = HashMap::new();

    contacts.insert("Daniel", "798-1364");
    contacts.insert("Ashley", "645-7689");
    contacts.insert("Katie", "435-8291");
    contacts.insert("Robert", "956-1745");

    // Takes a reference and returns Option<&V>
    match contacts.get(&"Daniel") {
        Some(&number) => println!("Calling Daniel: {}", call(number)),
        _ => println!("Don't have Daniel's number."),
    }

    // `HashMap::insert()` returns `None`
    // if the inserted value is new, `Some(value)` otherwise
    contacts.insert("Daniel", "164-6743");

    match contacts.get(&"Ashley") {
        Some(&number) => println!("Calling Ashley: {}", call(number)),
        _ => println!("Don't have Ashley's number."),
    }

    contacts.remove(&("Ashley"));

    // `HashMap::iter()` returns an iterator that yields
    // (&'a key, &'a value) pairs in arbitrary order.
    for (contact, &number) in contacts.iter() {
        println!("Calling {}: {}", contact, call(number));
    }
}
<|endoftext|>


<commit_before><commit_msg>Introduce benchmark tests<commit_after>#![feature(test)]

extern crate test;
extern crate protobuf;

use protobuf::stream;

use self::test::Bencher;

#[inline]
fn buffer_write_byte(os: &mut stream::CodedOutputStream) {
    for i in 0..10 {
        os.write_raw_byte(i as u8).unwrap();
    }
    os.flush().unwrap();
}

#[inline]
fn buffer_write_bytes(os: &mut stream::CodedOutputStream) {
    for _ in 0..10 {
        os.write_raw_bytes(b"1234567890").unwrap();
    }
    os.flush().unwrap();
}

#[bench]
fn bench_buffer(b: &mut Bencher) {
    b.iter(|| {
        let mut v = Vec::new();
        let mut os = stream::CodedOutputStream::new(&mut v);
        buffer_write_byte(&mut os);
    });
}

#[bench]
fn bench_buffer_bytes(b: &mut Bencher) {
    b.iter(|| {
        let mut v = Vec::new();
        let mut os = stream::CodedOutputStream::new(&mut v);
        buffer_write_bytes(&mut os);
    });
}
<|endoftext|>


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

enum E { V1(int), V0 }
const C: &static/[E] = &[V0, V1(0xDEADBEE), V0];

fn main() {
    match C[1] {
        V1(n) => assert(n == 0xDEADBEE),
        _ => die!()
    }
    match C[2] {
        V0 => (),
        _ => die!()
    }
}
<|endoftext|>


<commit_before><commit_msg>Start of menu service<commit_after>use std::ptr;

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/*
    create_menu: extern "C" fn(title: *const c_char) -> u64,
    destroy_menu: extern "C" fn(handle: u64),

    add_menu_item: extern "C" fn(menu: u64, name: *const c_char, id: c_uint) -> PDMenuItem,
    remove_menu_item: extern "C" fn(item: u64),

    set_flags: extern "C" fn(item: u64, flags: c_uint),
    set_shortcut_key: extern "C" fn(item: u64, accel_key: c_uint, modifier: c_uint),
*/

pub fn get_menu_funcs1() -> *mut c_void {
    ptr::null_mut();

}
<|endoftext|>


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

/*!

Synchronous Timers

This module exposes the functionality to create timers, block the current task,
and create receivers which will receive notifications after a period of time.

*/

use comm::{Receiver, Sender, channel};
use io::{IoResult, IoError};
use kinds::Send;
use owned::Box;
use rt::rtio::{IoFactory, LocalIo, RtioTimer, Callback};

/// A synchronous timer object
///
/// Values of this type can be used to put the current task to sleep for a
/// period of time. Handles to this timer can also be created in the form of
/// receivers which will receive notifications over time.
///
/// # Example
///
/// ```
/// # fn main() {}
/// # fn foo() {
/// use std::io::Timer;
///
/// let mut timer = Timer::new().unwrap();
/// timer.sleep(10); // block the task for awhile
///
/// let timeout = timer.oneshot(10);
/// // do some work
/// timeout.recv(); // wait for the timeout to expire
///
/// let periodic = timer.periodic(10);
/// loop {
///     periodic.recv();
///     // this loop is only executed once every 10ms
/// }
/// # }
/// ```
///
/// If only sleeping is necessary, then a convenience API is provided through
/// the `io::timer` module.
///
/// ```
/// # fn main() {}
/// # fn foo() {
/// use std::io::timer;
///
/// // Put this task to sleep for 5 seconds
/// timer::sleep(5000);
/// # }
/// ```
pub struct Timer {
    obj: Box<RtioTimer:Send>,
}

struct TimerCallback { tx: Sender<()> }

/// Sleep the current task for `msecs` milliseconds.
pub fn sleep(msecs: u64) {
    let timer = Timer::new();
    let mut timer = timer.ok().expect("timer::sleep: could not create a Timer");

    timer.sleep(msecs)
}

impl Timer {
    /// Creates a new timer which can be used to put the current task to sleep
    /// for a number of milliseconds, or to possibly create channels which will
    /// get notified after an amount of time has passed.
    pub fn new() -> IoResult<Timer> {
        LocalIo::maybe_raise(|io| {
            io.timer_init().map(|t| Timer { obj: t })
        }).map_err(IoError::from_rtio_error)
    }

    /// Blocks the current task for `msecs` milliseconds.
    ///
    /// Note that this function will cause any other receivers for this timer to
    /// be invalidated (the other end will be closed).
    pub fn sleep(&mut self, msecs: u64) {
        self.obj.sleep(msecs);
    }

    /// Creates a oneshot receiver which will have a notification sent when
    /// `msecs` milliseconds has elapsed. This does *not* block the current
    /// task, but instead returns immediately.
    ///
    /// Note that this invalidates any previous receiver which has been created
    /// by this timer, and that the returned receiver will be invalidated once
    /// the timer is destroyed (when it falls out of scope).
    pub fn oneshot(&mut self, msecs: u64) -> Receiver<()> {
        let (tx, rx) = channel();
        self.obj.oneshot(msecs, box TimerCallback { tx: tx });
        return rx
    }

    /// Creates a receiver which will have a continuous stream of notifications
    /// being sent every `msecs` milliseconds. This does *not* block the
    /// current task, but instead returns immediately. The first notification
    /// will not be received immediately, but rather after `msec` milliseconds
    /// have passed.
    ///
    /// Note that this invalidates any previous receiver which has been created
    /// by this timer, and that the returned receiver will be invalidated once
    /// the timer is destroyed (when it falls out of scope).
    pub fn periodic(&mut self, msecs: u64) -> Receiver<()> {
        let (tx, rx) = channel();
        self.obj.period(msecs, box TimerCallback { tx: tx });
        return rx
    }
}

impl Callback for TimerCallback {
    fn call(&mut self) {
        let _ = self.tx.send_opt(());
    }
}

#[cfg(test)]
mod test {
    iotest!(fn test_io_timer_sleep_simple() {
        let mut timer = Timer::new().unwrap();
        timer.sleep(1);
    })

    iotest!(fn test_io_timer_sleep_oneshot() {
        let mut timer = Timer::new().unwrap();
        timer.oneshot(1).recv();
    })

    iotest!(fn test_io_timer_sleep_oneshot_forget() {
        let mut timer = Timer::new().unwrap();
        timer.oneshot(100000000000);
    })

    iotest!(fn oneshot_twice() {
        let mut timer = Timer::new().unwrap();
        let rx1 = timer.oneshot(10000);
        let rx = timer.oneshot(1);
        rx.recv();
        assert_eq!(rx1.recv_opt(), Err(()));
    })

    iotest!(fn test_io_timer_oneshot_then_sleep() {
        let mut timer = Timer::new().unwrap();
        let rx = timer.oneshot(100000000000);
        timer.sleep(1); // this should inalidate rx

        assert_eq!(rx.recv_opt(), Err(()));
    })

    iotest!(fn test_io_timer_sleep_periodic() {
        let mut timer = Timer::new().unwrap();
        let rx = timer.periodic(1);
        rx.recv();
        rx.recv();
        rx.recv();
    })

    iotest!(fn test_io_timer_sleep_periodic_forget() {
        let mut timer = Timer::new().unwrap();
        timer.periodic(100000000000);
    })

    iotest!(fn test_io_timer_sleep_standalone() {
        sleep(1)
    })

    iotest!(fn oneshot() {
        let mut timer = Timer::new().unwrap();

        let rx = timer.oneshot(1);
        rx.recv();
        assert!(rx.recv_opt().is_err());

        let rx = timer.oneshot(1);
        rx.recv();
        assert!(rx.recv_opt().is_err());
    })

    iotest!(fn override() {
        let mut timer = Timer::new().unwrap();
        let orx = timer.oneshot(100);
        let prx = timer.periodic(100);
        timer.sleep(1);
        assert_eq!(orx.recv_opt(), Err(()));
        assert_eq!(prx.recv_opt(), Err(()));
        timer.oneshot(1).recv();
    })

    iotest!(fn period() {
        let mut timer = Timer::new().unwrap();
        let rx = timer.periodic(1);
        rx.recv();
        rx.recv();
        let rx2 = timer.periodic(1);
        rx2.recv();
        rx2.recv();
    })

    iotest!(fn sleep() {
        let mut timer = Timer::new().unwrap();
        timer.sleep(1);
        timer.sleep(1);
    })

    iotest!(fn oneshot_fail() {
        let mut timer = Timer::new().unwrap();
        let _rx = timer.oneshot(1);
        fail!();
    } #[should_fail])

    iotest!(fn period_fail() {
        let mut timer = Timer::new().unwrap();
        let _rx = timer.periodic(1);
        fail!();
    } #[should_fail])

    iotest!(fn normal_fail() {
        let _timer = Timer::new().unwrap();
        fail!();
    } #[should_fail])

    iotest!(fn closing_channel_during_drop_doesnt_kill_everything() {
        // see issue #10375
        let mut timer = Timer::new().unwrap();
        let timer_rx = timer.periodic(1000);

        spawn(proc() {
            let _ = timer_rx.recv_opt();
        });

        // when we drop the TimerWatcher we're going to destroy the channel,
        // which must wake up the task on the other end
    })

    iotest!(fn reset_doesnt_switch_tasks() {
        // similar test to the one above.
        let mut timer = Timer::new().unwrap();
        let timer_rx = timer.periodic(1000);

        spawn(proc() {
            let _ = timer_rx.recv_opt();
        });

        timer.oneshot(1);
    })

    iotest!(fn reset_doesnt_switch_tasks2() {
        // similar test to the one above.
        let mut timer = Timer::new().unwrap();
        let timer_rx = timer.periodic(1000);

        spawn(proc() {
            let _ = timer_rx.recv_opt();
        });

        timer.sleep(1);
    })

    iotest!(fn sender_goes_away_oneshot() {
        let rx = {
            let mut timer = Timer::new().unwrap();
            timer.oneshot(1000)
        };
        assert_eq!(rx.recv_opt(), Err(()));
    })

    iotest!(fn sender_goes_away_period() {
        let rx = {
            let mut timer = Timer::new().unwrap();
            timer.periodic(1000)
        };
        assert_eq!(rx.recv_opt(), Err(()));
    })

    iotest!(fn receiver_goes_away_oneshot() {
        let mut timer1 = Timer::new().unwrap();
        timer1.oneshot(1);
        let mut timer2 = Timer::new().unwrap();
        // while sleeping, the prevous timer should fire and not have its
        // callback do something terrible.
        timer2.sleep(2);
    })

    iotest!(fn receiver_goes_away_period() {
        let mut timer1 = Timer::new().unwrap();
        timer1.periodic(1);
        let mut timer2 = Timer::new().unwrap();
        // while sleeping, the prevous timer should fire and not have its
        // callback do something terrible.
        timer2.sleep(2);
    })
}
<commit_msg>std::io: expand the oneshot/periodic docs.<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.

/*!

Synchronous Timers

This module exposes the functionality to create timers, block the current task,
and create receivers which will receive notifications after a period of time.

*/

use comm::{Receiver, Sender, channel};
use io::{IoResult, IoError};
use kinds::Send;
use owned::Box;
use rt::rtio::{IoFactory, LocalIo, RtioTimer, Callback};

/// A synchronous timer object
///
/// Values of this type can be used to put the current task to sleep for a
/// period of time. Handles to this timer can also be created in the form of
/// receivers which will receive notifications over time.
///
/// # Example
///
/// ```
/// # fn main() {}
/// # fn foo() {
/// use std::io::Timer;
///
/// let mut timer = Timer::new().unwrap();
/// timer.sleep(10); // block the task for awhile
///
/// let timeout = timer.oneshot(10);
/// // do some work
/// timeout.recv(); // wait for the timeout to expire
///
/// let periodic = timer.periodic(10);
/// loop {
///     periodic.recv();
///     // this loop is only executed once every 10ms
/// }
/// # }
/// ```
///
/// If only sleeping is necessary, then a convenience API is provided through
/// the `io::timer` module.
///
/// ```
/// # fn main() {}
/// # fn foo() {
/// use std::io::timer;
///
/// // Put this task to sleep for 5 seconds
/// timer::sleep(5000);
/// # }
/// ```
pub struct Timer {
    obj: Box<RtioTimer:Send>,
}

struct TimerCallback { tx: Sender<()> }

/// Sleep the current task for `msecs` milliseconds.
pub fn sleep(msecs: u64) {
    let timer = Timer::new();
    let mut timer = timer.ok().expect("timer::sleep: could not create a Timer");

    timer.sleep(msecs)
}

impl Timer {
    /// Creates a new timer which can be used to put the current task to sleep
    /// for a number of milliseconds, or to possibly create channels which will
    /// get notified after an amount of time has passed.
    pub fn new() -> IoResult<Timer> {
        LocalIo::maybe_raise(|io| {
            io.timer_init().map(|t| Timer { obj: t })
        }).map_err(IoError::from_rtio_error)
    }

    /// Blocks the current task for `msecs` milliseconds.
    ///
    /// Note that this function will cause any other receivers for this timer to
    /// be invalidated (the other end will be closed).
    pub fn sleep(&mut self, msecs: u64) {
        self.obj.sleep(msecs);
    }

    /// Creates a oneshot receiver which will have a notification sent when
    /// `msecs` milliseconds has elapsed.
    ///
    /// This does *not* block the current task, but instead returns immediately.
    ///
    /// Note that this invalidates any previous receiver which has been created
    /// by this timer, and that the returned receiver will be invalidated once
    /// the timer is destroyed (when it falls out of scope). In particular, if
    /// this is called in method-chaining style, the receiver will be
    /// invalidated at the end of that statement, and all `recv` calls will
    /// fail.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::io::timer::Timer;
    ///
    /// let mut timer = Timer::new().unwrap();
    /// let ten_milliseconds = timer.oneshot(10);
    ///
    /// for _ in range(0, 100) { /* do work */ }
    ///
    /// // blocks until 10 ms after the `oneshot` call
    /// ten_milliseconds.recv();
    /// ```
    ///
    /// ```rust
    /// use std::io::timer::Timer;
    ///
    /// // Incorrect, method chaining-style:
    /// let mut five_ms = Timer::new().unwrap().oneshot(5);
    /// // The timer object was destroyed, so this will always fail:
    /// // five_ms.recv()
    /// ```
    pub fn oneshot(&mut self, msecs: u64) -> Receiver<()> {
        let (tx, rx) = channel();
        self.obj.oneshot(msecs, box TimerCallback { tx: tx });
        return rx
    }

    /// Creates a receiver which will have a continuous stream of notifications
    /// being sent every `msecs` milliseconds.
    ///
    /// This does *not* block the current task, but instead returns
    /// immediately. The first notification will not be received immediately,
    /// but rather after `msec` milliseconds have passed.
    ///
    /// Note that this invalidates any previous receiver which has been created
    /// by this timer, and that the returned receiver will be invalidated once
    /// the timer is destroyed (when it falls out of scope). In particular, if
    /// this is called in method-chaining style, the receiver will be
    /// invalidated at the end of that statement, and all `recv` calls will
    /// fail.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::io::timer::Timer;
    ///
    /// let mut timer = Timer::new().unwrap();
    /// let ten_milliseconds = timer.periodic(10);
    ///
    /// for _ in range(0, 100) { /* do work */ }
    ///
    /// // blocks until 10 ms after the `periodic` call
    /// ten_milliseconds.recv();
    ///
    /// for _ in range(0, 100) { /* do work */ }
    ///
    /// // blocks until 20 ms after the `periodic` call (*not* 10ms after the
    /// // previous `recv`)
    /// ten_milliseconds.recv();
    /// ```
    ///
    /// ```rust
    /// use std::io::timer::Timer;
    ///
    /// // Incorrect, method chaining-style.
    /// let mut five_ms = Timer::new().unwrap().periodic(5);
    /// // The timer object was destroyed, so this will always fail:
    /// // five_ms.recv()
    /// ```
    pub fn periodic(&mut self, msecs: u64) -> Receiver<()> {
        let (tx, rx) = channel();
        self.obj.period(msecs, box TimerCallback { tx: tx });
        return rx
    }
}

impl Callback for TimerCallback {
    fn call(&mut self) {
        let _ = self.tx.send_opt(());
    }
}

#[cfg(test)]
mod test {
    iotest!(fn test_io_timer_sleep_simple() {
        let mut timer = Timer::new().unwrap();
        timer.sleep(1);
    })

    iotest!(fn test_io_timer_sleep_oneshot() {
        let mut timer = Timer::new().unwrap();
        timer.oneshot(1).recv();
    })

    iotest!(fn test_io_timer_sleep_oneshot_forget() {
        let mut timer = Timer::new().unwrap();
        timer.oneshot(100000000000);
    })

    iotest!(fn oneshot_twice() {
        let mut timer = Timer::new().unwrap();
        let rx1 = timer.oneshot(10000);
        let rx = timer.oneshot(1);
        rx.recv();
        assert_eq!(rx1.recv_opt(), Err(()));
    })

    iotest!(fn test_io_timer_oneshot_then_sleep() {
        let mut timer = Timer::new().unwrap();
        let rx = timer.oneshot(100000000000);
        timer.sleep(1); // this should inalidate rx

        assert_eq!(rx.recv_opt(), Err(()));
    })

    iotest!(fn test_io_timer_sleep_periodic() {
        let mut timer = Timer::new().unwrap();
        let rx = timer.periodic(1);
        rx.recv();
        rx.recv();
        rx.recv();
    })

    iotest!(fn test_io_timer_sleep_periodic_forget() {
        let mut timer = Timer::new().unwrap();
        timer.periodic(100000000000);
    })

    iotest!(fn test_io_timer_sleep_standalone() {
        sleep(1)
    })

    iotest!(fn oneshot() {
        let mut timer = Timer::new().unwrap();

        let rx = timer.oneshot(1);
        rx.recv();
        assert!(rx.recv_opt().is_err());

        let rx = timer.oneshot(1);
        rx.recv();
        assert!(rx.recv_opt().is_err());
    })

    iotest!(fn override() {
        let mut timer = Timer::new().unwrap();
        let orx = timer.oneshot(100);
        let prx = timer.periodic(100);
        timer.sleep(1);
        assert_eq!(orx.recv_opt(), Err(()));
        assert_eq!(prx.recv_opt(), Err(()));
        timer.oneshot(1).recv();
    })

    iotest!(fn period() {
        let mut timer = Timer::new().unwrap();
        let rx = timer.periodic(1);
        rx.recv();
        rx.recv();
        let rx2 = timer.periodic(1);
        rx2.recv();
        rx2.recv();
    })

    iotest!(fn sleep() {
        let mut timer = Timer::new().unwrap();
        timer.sleep(1);
        timer.sleep(1);
    })

    iotest!(fn oneshot_fail() {
        let mut timer = Timer::new().unwrap();
        let _rx = timer.oneshot(1);
        fail!();
    } #[should_fail])

    iotest!(fn period_fail() {
        let mut timer = Timer::new().unwrap();
        let _rx = timer.periodic(1);
        fail!();
    } #[should_fail])

    iotest!(fn normal_fail() {
        let _timer = Timer::new().unwrap();
        fail!();
    } #[should_fail])

    iotest!(fn closing_channel_during_drop_doesnt_kill_everything() {
        // see issue #10375
        let mut timer = Timer::new().unwrap();
        let timer_rx = timer.periodic(1000);

        spawn(proc() {
            let _ = timer_rx.recv_opt();
        });

        // when we drop the TimerWatcher we're going to destroy the channel,
        // which must wake up the task on the other end
    })

    iotest!(fn reset_doesnt_switch_tasks() {
        // similar test to the one above.
        let mut timer = Timer::new().unwrap();
        let timer_rx = timer.periodic(1000);

        spawn(proc() {
            let _ = timer_rx.recv_opt();
        });

        timer.oneshot(1);
    })

    iotest!(fn reset_doesnt_switch_tasks2() {
        // similar test to the one above.
        let mut timer = Timer::new().unwrap();
        let timer_rx = timer.periodic(1000);

        spawn(proc() {
            let _ = timer_rx.recv_opt();
        });

        timer.sleep(1);
    })

    iotest!(fn sender_goes_away_oneshot() {
        let rx = {
            let mut timer = Timer::new().unwrap();
            timer.oneshot(1000)
        };
        assert_eq!(rx.recv_opt(), Err(()));
    })

    iotest!(fn sender_goes_away_period() {
        let rx = {
            let mut timer = Timer::new().unwrap();
            timer.periodic(1000)
        };
        assert_eq!(rx.recv_opt(), Err(()));
    })

    iotest!(fn receiver_goes_away_oneshot() {
        let mut timer1 = Timer::new().unwrap();
        timer1.oneshot(1);
        let mut timer2 = Timer::new().unwrap();
        // while sleeping, the prevous timer should fire and not have its
        // callback do something terrible.
        timer2.sleep(2);
    })

    iotest!(fn receiver_goes_away_period() {
        let mut timer1 = Timer::new().unwrap();
        timer1.periodic(1);
        let mut timer2 = Timer::new().unwrap();
        // while sleeping, the prevous timer should fire and not have its
        // callback do something terrible.
        timer2.sleep(2);
    })
}
<|endoftext|>


<commit_before><commit_msg>Add Figure 1.10<commit_after>/// Figure 1.10 Read commands from standard input and execute them
/// source from Figure 1.7 and added the signal handling

extern crate libc;
#[macro_use(cstr, as_char)]
extern crate apue;

use libc::{STDIN_FILENO, SIGINT, SIG_ERR, c_char, c_int, printf, strlen, fgets, fdopen, fork, waitpid, signal};
use apue::{array_to_string, LibcResult};

extern "C" {
    pub fn execlp(file: *const c_char, arg0: *const c_char, ...) -> c_int;
}

extern "C" fn sig_int(_:c_int) {
    unsafe {
        printf(cstr!("interrupted..\n"));
        printf(cstr!("%% "));
    }
}

const MAXLINE: usize = 100;

fn main() {
    unsafe {
        let mut buf: [c_char; MAXLINE] = std::mem::uninitialized();
        let stdin = fdopen(STDIN_FILENO, &('r' as c_char));
        let mut status = 0;
        let s = sig_int;
        if signal(SIGINT, s as usize) == SIG_ERR {
            panic!("signal error");
        }
        printf(cstr!("%% ")); // print prompt (printf requires %% to print %)
        while !fgets(as_char!(buf), MAXLINE as _, stdin).is_null() {
            let len = strlen(as_char!(buf));
            if buf[len - 1] == '\n' as _ {
                buf[len - 1] = 0;
            }
            if let Some(pid) = fork().to_option() {
                if pid == 0 {
                    // child
                    execlp(as_char!(buf), as_char!(buf), 0);
                    panic!("could not execute {}", array_to_string(&buf));
                } else {
                    // parent
                    if let Some(_) = waitpid(pid, &mut status, 0).to_option() {
                        printf(cstr!("%% "));
                    } else {
                        panic!("waitpid error");
                    }
                }
            } else {
                panic!("fork error");
            }
        }
    }
}<|endoftext|>


<commit_before><commit_msg>add test for lattice specialization<commit_after>// build-pass

// Check that a reservation impl does not force other impls to follow
// a lattice discipline.

// Why did we ever want to do this?
//
// We want to eventually add a `impl<T> From<!> for T` impl. That impl conflicts
// with existing impls - at least the `impl<T> From<T> for T` impl. There are
// 2 ways we thought of for dealing with that conflict:
//
// 1. Using specialization and doing some handling for the overlap. The current
// thought is for something like "lattice specialization", which means providing
// an (higher-priority) impl for the intersection of every 2 conflicting impls
// that determines what happens in the intersection case. That's the first
// thing we thought about - see e.g.
// https://github.com/rust-lang/rust/issues/57012#issuecomment-452150775
//
// 2. The other way is to notice that `impl From<!> for T` is basically a marker
// trait, as you say since its only method is uninhabited, and allow for "marker
// trait overlap", where the conflict "doesn't matter" as there is nothing that
// can cause a conflict.
//
// Now it turned out lattice specialization doesn't work it, because an
// `impl<T> From<T> for Smaht<T>` would require a `impl From<!> for Smaht<!>`,
// breaking backwards-compatibility in a fairly painful way. So if we want to
// go with a known approach, we should go with a "marker trait overlap"-style
// approach.

#![feature(rustc_attrs, never_type)]

trait MyTrait {}

impl MyTrait for ! {}

trait MyFrom<T> {
    fn my_from(x: T) -> Self;
}

// Given the "normal" impls for From
#[rustc_reservation_impl="this impl is reserved"]
impl<T> MyFrom<!> for T {
    fn my_from(x: !) -> Self { match x {} }
}

impl<T> MyFrom<T> for T {
    fn my_from(x: T) -> Self { x }
}

// ... we *do* want to allow this common pattern, of `From<!> for MySmaht<T>`
struct MySmaht<T>(T);
impl<T> MyFrom<T> for MySmaht<T> {
    fn my_from(x: T) -> Self { MySmaht(x) }
}

fn main() {}
<|endoftext|>


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

// xfail-fast

#[deny(unused_variable)];

extern mod syntax;

use syntax::ext::base::ExtCtxt;

fn test(cx: &mut ExtCtxt) {
    let foo = 10i;
    let _e = quote_expr!(cx, $foo);
}

pub fn main() { }
<commit_msg>auto merge of #11719 : brson/rust/bleh, r=alexcrichton<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// xfail-fast
// xfail-android

#[deny(unused_variable)];

extern mod syntax;

use syntax::ext::base::ExtCtxt;

fn test(cx: &mut ExtCtxt) {
    let foo = 10i;
    let _e = quote_expr!(cx, $foo);
}

pub fn main() { }
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #78962 - poliorcetics:rustdoc-raw-ident-test, r=jyn514<commit_after>// ignore-tidy-linelength

#![crate_type="lib"]

pub mod internal {
    // @has 'raw_ident_eliminate_r_hashtag/internal/struct.mod.html'
    pub struct r#mod;

    /// See [name], [other name]
    ///
    /// [name]: mod
    /// [other name]: crate::internal::mod
    // @has 'raw_ident_eliminate_r_hashtag/internal/struct.B.html' '//*a[@href="../../raw_ident_eliminate_r_hashtag/internal/struct.mod.html"]' 'name'
    // @has 'raw_ident_eliminate_r_hashtag/internal/struct.B.html' '//*a[@href="../../raw_ident_eliminate_r_hashtag/internal/struct.mod.html"]' 'other name'
    pub struct B;
}

/// See [name].
///
/// [name]: internal::mod
// @has 'raw_ident_eliminate_r_hashtag/struct.A.html' '//*a[@href="../raw_ident_eliminate_r_hashtag/internal/struct.mod.html"]' 'name'
pub struct A;
<|endoftext|>


<commit_before><commit_msg>Document codegen lints.<commit_after><|endoftext|>


<commit_before><commit_msg>std/Options<commit_after>
fn check_dividing(divident: i32, divisor: i32) -> Option<i32> {
    if (divisor == 0) {
        None
    } else {
        Some(divident/divisor)
    }
}

fn divide(divident: i32, divisor: i32) {
    match check_dividing(divident, divisor) {
        None => println!("Division by zero"),
        Some(quotient) => println!("Quotient: {}", quotient)
    }
}

fn main() {

    divide(5,0);
    divide(5, 10);
}<|endoftext|>


<commit_before><commit_msg>Silence warning re:dead-code<commit_after><|endoftext|>


<commit_before><commit_msg>start dir work<commit_after><|endoftext|>


<commit_before><commit_msg>Solve conflicts<commit_after>use core::{Entity, Vec2};

/// The camera
struct Cam<'a> {
  /// The former camera pos
  former_pos: Vec2<i64>,
  /// The entity in focus
  in_focus: &'a Entity,
  /// The transition state
  trans_state: f64,
}

// TODO: Make the camera locked to the player? (Or is this a bad idea?)

const VELOCITY: f64 = 0.1;

impl<'a> Cam<'a> {
  /// Creates a new Cam
  fn new(focus: &'a Entity) -> Cam {
    Cam {
      former_pos: focus.get_pos(),
      in_focus: focus,
      trans_state: 0.0,
    }
  }
  /// Updates the Cam
  fn update(&mut self, dt: f64) {
    self.trans_state += dt * VELOCITY;
    if self.trans_state > 1.0 {
      self.trans_state = 0.0;
      self.former_pos = self.in_focus.get_pos();
    }
  }
  /// Get position
  fn get_pos(&self) -> Vec2<f64> {
    let pos = Vec2(self.get_pos().x() as f64, self.get_pos().y() as f64);
    pos * self.trans_state
    + pos * (1.0 - self.trans_state)
  }
}
<|endoftext|>


<commit_before><commit_msg>Fixed traversal algorithm, added test<commit_after><|endoftext|>


<commit_before>import rustrt.sbuf;

import std._vec.rustrt.vbuf;

native "rust" mod rustrt {
  type sbuf;
  fn str_buf(str s) -> sbuf;
  fn str_byte_len(str s) -> uint;
  fn str_alloc(uint n_bytes) -> str;
  fn str_from_vec(vec[u8] b) -> str;
  fn refcount[T](str s) -> uint;
}

fn eq(str a, str b) -> bool {
  let uint i = byte_len(a);
  if (byte_len(b) != i) {
    ret false;
  }
  while (i > 0u) {
    i -= 1u;
    auto cha = a.(i);
    auto chb = b.(i);
    if (cha != chb) {
      ret false;
    }
  }
  ret true;
}

fn is_utf8(vec[u8] v) -> bool {
  fail; // FIXME
}

fn is_ascii(str s) -> bool {
  let uint i = byte_len(s);
  while (i > 0u) {
    i -= 1u;
    if ((s.(i) & 0x80u8) != 0u8) {
      ret false;
    }
  }
  ret true;
}

fn alloc(uint n_bytes) -> str {
  ret rustrt.str_alloc(n_bytes);
}

// Returns the number of bytes (a.k.a. UTF-8 code units) in s.
// Contrast with a function that would return the number of code
// points (char's), combining character sequences, words, etc.  See
// http://icu-project.org/apiref/icu4c/classBreakIterator.html for a
// way to implement those.
fn byte_len(str s) -> uint {
  ret rustrt.str_byte_len(s);
}

fn buf(str s) -> sbuf {
  ret rustrt.str_buf(s);
}

fn bytes(str s) -> vec[u8] {
  /* FIXME (issue #58):
   * Should be...
   *
   *  fn ith(str s, uint i) -> u8 {
   *      ret s.(i);
   *  }
   *  ret _vec.init_fn[u8](bind ith(s, _), byte_len(s));
   *
   * but we do not correctly decrement refcount of s when
   * the binding dies, so we have to do this manually.
   */
  let uint n = _str.byte_len(s);
  let vec[u8] v = _vec.alloc[u8](n);
  let uint i = 0u;
  while (i < n) {
    v += vec(s.(i));
    i += 1u;
  }
  ret v;
}

fn from_bytes(vec[u8] v) : is_utf8(v) -> str {
  ret rustrt.str_from_vec(v);
}

fn refcount(str s) -> uint {
  // -1 because calling this function incremented the refcount.
  ret rustrt.refcount[u8](s) - 1u;
}
<commit_msg>Make _str.eq suitable for map.hashmap; add _str.hash that does simple djb-hash.<commit_after>import rustrt.sbuf;

import std._vec.rustrt.vbuf;

native "rust" mod rustrt {
  type sbuf;
  fn str_buf(str s) -> sbuf;
  fn str_byte_len(str s) -> uint;
  fn str_alloc(uint n_bytes) -> str;
  fn str_from_vec(vec[u8] b) -> str;
  fn refcount[T](str s) -> uint;
}

fn eq(&str a, &str b) -> bool {
  let uint i = byte_len(a);
  if (byte_len(b) != i) {
    ret false;
  }
  while (i > 0u) {
    i -= 1u;
    auto cha = a.(i);
    auto chb = b.(i);
    if (cha != chb) {
      ret false;
    }
  }
  ret true;
}

fn hash(&str s) -> uint {
  // djb hash.
  // FIXME: replace with murmur.
  let uint u = 5381u;
  for (u8 c in s) {
    u *= 33u;
    u += (c as uint);
  }
  ret u;
}

fn is_utf8(vec[u8] v) -> bool {
  fail; // FIXME
}

fn is_ascii(str s) -> bool {
  let uint i = byte_len(s);
  while (i > 0u) {
    i -= 1u;
    if ((s.(i) & 0x80u8) != 0u8) {
      ret false;
    }
  }
  ret true;
}

fn alloc(uint n_bytes) -> str {
  ret rustrt.str_alloc(n_bytes);
}

// Returns the number of bytes (a.k.a. UTF-8 code units) in s.
// Contrast with a function that would return the number of code
// points (char's), combining character sequences, words, etc.  See
// http://icu-project.org/apiref/icu4c/classBreakIterator.html for a
// way to implement those.
fn byte_len(str s) -> uint {
  ret rustrt.str_byte_len(s);
}

fn buf(str s) -> sbuf {
  ret rustrt.str_buf(s);
}

fn bytes(str s) -> vec[u8] {
  /* FIXME (issue #58):
   * Should be...
   *
   *  fn ith(str s, uint i) -> u8 {
   *      ret s.(i);
   *  }
   *  ret _vec.init_fn[u8](bind ith(s, _), byte_len(s));
   *
   * but we do not correctly decrement refcount of s when
   * the binding dies, so we have to do this manually.
   */
  let uint n = _str.byte_len(s);
  let vec[u8] v = _vec.alloc[u8](n);
  let uint i = 0u;
  while (i < n) {
    v += vec(s.(i));
    i += 1u;
  }
  ret v;
}

fn from_bytes(vec[u8] v) : is_utf8(v) -> str {
  ret rustrt.str_from_vec(v);
}

fn refcount(str s) -> uint {
  // -1 because calling this function incremented the refcount.
  ret rustrt.refcount[u8](s) - 1u;
}
<|endoftext|>


<commit_before>/*
Module: bitv

Bitvectors.
*/

export t;
export create;
export union;
export intersect;
export assign;
export clone;
export get;
export equal;
export clear;
export set_all;
export invert;
export difference;
export set;
export is_true;
export is_false;
export to_vec;
export to_str;
export eq_vec;

// FIXME: With recursive object types, we could implement binary methods like
//        union, intersection, and difference. At that point, we could write
//        an optimizing version of this module that produces a different obj
//        for the case where nbits <= 32.

/*
Type: t

The bitvector type.
*/
type t = @{storage: [mutable uint], nbits: uint};

// FIXME: this should be a constant once they work
fn uint_bits() -> uint { ret 32u + (1u << 32u >> 27u); }

/*
Function: create

Constructs a bitvector.

Parameters:
nbits - The number of bits in the bitvector
init - If true then the bits are initialized to 1, otherwise 0
*/
fn create(nbits: uint, init: bool) -> t {
    let elt = if init { !0u } else { 0u };
    let storage = vec::init_elt_mut::<uint>(elt, nbits / uint_bits() + 1u);
    ret @{storage: storage, nbits: nbits};
}

fn process(op: block(uint, uint) -> uint, v0: t, v1: t) -> bool {
    let len = vec::len(v1.storage);
    assert (vec::len(v0.storage) == len);
    assert (v0.nbits == v1.nbits);
    let changed = false;
    uint::range(0u, len) {|i|
        let w0 = v0.storage[i];
        let w1 = v1.storage[i];
        let w = op(w0, w1);
        if w0 != w { changed = true; v0.storage[i] = w; }
    };
    ret changed;
}

fn lor(w0: uint, w1: uint) -> uint { ret w0 | w1; }

fn union(v0: t, v1: t) -> bool { let sub = lor; ret process(sub, v0, v1); }

fn land(w0: uint, w1: uint) -> uint { ret w0 & w1; }

fn intersect(v0: t, v1: t) -> bool {
    let sub = land;
    ret process(sub, v0, v1);
}

fn right(_w0: uint, w1: uint) -> uint { ret w1; }

fn assign(v0: t, v1: t) -> bool { let sub = right; ret process(sub, v0, v1); }

fn clone(v: t) -> t {
    let storage = vec::init_elt_mut::<uint>(0u, v.nbits / uint_bits() + 1u);
    let len = vec::len(v.storage);
    uint::range(0u, len) {|i| storage[i] = v.storage[i]; };
    ret @{storage: storage, nbits: v.nbits};
}

fn get(v: t, i: uint) -> bool {
    assert (i < v.nbits);
    let bits = uint_bits();
    let w = i / bits;
    let b = i % bits;
    let x = 1u & v.storage[w] >> b;
    ret x == 1u;
}

fn equal(v0: t, v1: t) -> bool {
    // FIXME: when we can break or return from inside an iterator loop,
    //        we can eliminate this painful while-loop

    let len = vec::len(v1.storage);
    let i = 0u;
    while i < len {
        if v0.storage[i] != v1.storage[i] { ret false; }
        i = i + 1u;
    }
    ret true;
}

fn clear(v: t) {
    uint::range(0u, vec::len(v.storage)) {|i| v.storage[i] = 0u; };
}

fn set_all(v: t) {
    uint::range(0u, v.nbits) {|i| set(v, i, true); };
}

fn invert(v: t) {
    uint::range(0u, vec::len(v.storage)) {|i|
        v.storage[i] = !v.storage[i];
    };
}

/* v0 = v0 - v1 */
fn difference(v0: t, v1: t) -> bool {
    invert(v1);
    let b = intersect(v0, v1);
    invert(v1);
    ret b;
}

fn set(v: t, i: uint, x: bool) {
    assert (i < v.nbits);
    let bits = uint_bits();
    let w = i / bits;
    let b = i % bits;
    let flag = 1u << b;
    v.storage[w] = if x { v.storage[w] | flag } else { v.storage[w] & !flag };
}

/* true if all bits are 1 */
fn is_true(v: t) -> bool {
    for i: uint in to_vec(v) { if i != 1u { ret false; } }
    ret true;
}

/* true if all bits are non-1 */
fn is_false(v: t) -> bool {
    for i: uint in to_vec(v) { if i == 1u { ret false; } }
    ret true;
}

fn init_to_vec(v: t, i: uint) -> uint { ret if get(v, i) { 1u } else { 0u }; }

fn to_vec(v: t) -> [uint] {
    let sub = bind init_to_vec(v, _);
    ret vec::init_fn::<uint>(sub, v.nbits);
}

fn to_str(v: t) -> str {
    let rs = "";
    for i: uint in to_vec(v) { if i == 1u { rs += "1"; } else { rs += "0"; } }
    ret rs;
}

fn eq_vec(v0: t, v1: [uint]) -> bool {
    assert (v0.nbits == vec::len::<uint>(v1));
    let len = v0.nbits;
    let i = 0u;
    while i < len {
        let w0 = get(v0, i);
        let w1 = v1[i];
        if !w0 && w1 != 0u || w0 && w1 == 0u { ret false; }
        i = i + 1u;
    }
    ret true;
}

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

Bitvectors.
*/

export t;
export create;
export union;
export intersect;
export assign;
export clone;
export get;
export equal;
export clear;
export set_all;
export invert;
export difference;
export set;
export is_true;
export is_false;
export to_vec;
export to_str;
export eq_vec;

// FIXME: With recursive object types, we could implement binary methods like
//        union, intersection, and difference. At that point, we could write
//        an optimizing version of this module that produces a different obj
//        for the case where nbits <= 32.

/*
Type: t

The bitvector type.
*/
type t = @{storage: [mutable uint], nbits: uint};

// FIXME: this should be a constant once they work
fn uint_bits() -> uint { ret 32u + (1u << 32u >> 27u); }

/*
Function: create

Constructs a bitvector.

Parameters:
nbits - The number of bits in the bitvector
init - If true then the bits are initialized to 1, otherwise 0
*/
fn create(nbits: uint, init: bool) -> t {
    let elt = if init { !0u } else { 0u };
    let storage = vec::init_elt_mut::<uint>(elt, nbits / uint_bits() + 1u);
    ret @{storage: storage, nbits: nbits};
}

fn process(op: block(uint, uint) -> uint, v0: t, v1: t) -> bool {
    let len = vec::len(v1.storage);
    assert (vec::len(v0.storage) == len);
    assert (v0.nbits == v1.nbits);
    let changed = false;
    uint::range(0u, len) {|i|
        let w0 = v0.storage[i];
        let w1 = v1.storage[i];
        let w = op(w0, w1);
        if w0 != w { changed = true; v0.storage[i] = w; }
    };
    ret changed;
}

fn lor(w0: uint, w1: uint) -> uint { ret w0 | w1; }

fn union(v0: t, v1: t) -> bool { let sub = lor; ret process(sub, v0, v1); }

fn land(w0: uint, w1: uint) -> uint { ret w0 & w1; }

/*
Function: intersect

Calculates the intersection of two bitvectors

Sets `v0` to the intersection of `v0` and `v1`

Preconditions:

Both bitvectors must be the same length

Returns:

True if `v0` was changed
*/
fn intersect(v0: t, v1: t) -> bool {
    let sub = land;
    ret process(sub, v0, v1);
}

fn right(_w0: uint, w1: uint) -> uint { ret w1; }

/*
Function: assign

Assigns the value of `v1` to `v0`

Preconditions:

Both bitvectors must be the same length

Returns:

True if `v0` was changed
*/
fn assign(v0: t, v1: t) -> bool { let sub = right; ret process(sub, v0, v1); }

/*
Function: clone

Makes a copy of a bitvector
*/
fn clone(v: t) -> t {
    let storage = vec::init_elt_mut::<uint>(0u, v.nbits / uint_bits() + 1u);
    let len = vec::len(v.storage);
    uint::range(0u, len) {|i| storage[i] = v.storage[i]; };
    ret @{storage: storage, nbits: v.nbits};
}

/*
Function: get

Retreive the value at index `i`
*/
fn get(v: t, i: uint) -> bool {
    assert (i < v.nbits);
    let bits = uint_bits();
    let w = i / bits;
    let b = i % bits;
    let x = 1u & v.storage[w] >> b;
    ret x == 1u;
}

// FIXME: This doesn't account for the actual size of the vectors,
// so it could end up comparing garbage bits
/*
Function: equal

Compares two bitvectors

Preconditions:

Both bitvectors must be the same length

Returns:

True if both bitvectors contain identical elements
*/
fn equal(v0: t, v1: t) -> bool {
    // FIXME: when we can break or return from inside an iterator loop,
    //        we can eliminate this painful while-loop

    let len = vec::len(v1.storage);
    let i = 0u;
    while i < len {
        if v0.storage[i] != v1.storage[i] { ret false; }
        i = i + 1u;
    }
    ret true;
}

/*
Function: clear

Set all bits to 0
*/
fn clear(v: t) {
    uint::range(0u, vec::len(v.storage)) {|i| v.storage[i] = 0u; };
}

/*
Function: set_all

Set all bits to 1
*/
fn set_all(v: t) {
    uint::range(0u, v.nbits) {|i| set(v, i, true); };
}

/*
Function: invert

Invert all bits
*/
fn invert(v: t) {
    uint::range(0u, vec::len(v.storage)) {|i|
        v.storage[i] = !v.storage[i];
    };
}

/*
Function: difference

Calculate the difference between two bitvectors

Sets each element of `v0` to the value of that element minus the element
of `v1` at the same index.

Preconditions:

Both bitvectors must be the same length

Returns:

True if `v0` was changed
*/
fn difference(v0: t, v1: t) -> bool {
    invert(v1);
    let b = intersect(v0, v1);
    invert(v1);
    ret b;
}

/*
Function: set

Set the value of a bit at a given index

Preconditions:

`i` must be less than the length of the bitvector
*/
fn set(v: t, i: uint, x: bool) {
    assert (i < v.nbits);
    let bits = uint_bits();
    let w = i / bits;
    let b = i % bits;
    let flag = 1u << b;
    v.storage[w] = if x { v.storage[w] | flag } else { v.storage[w] & !flag };
}

/*
Function: is_true

Returns true if all bits are 1
*/
fn is_true(v: t) -> bool {
    for i: uint in to_vec(v) { if i != 1u { ret false; } }
    ret true;
}

/*
Function: is_false

Returns true if all bits are 0
*/
fn is_false(v: t) -> bool {
    for i: uint in to_vec(v) { if i == 1u { ret false; } }
    ret true;
}

fn init_to_vec(v: t, i: uint) -> uint { ret if get(v, i) { 1u } else { 0u }; }

/*
Function: to_vec

Converts the bitvector to a vector of uint with the same length. Each uint
in the resulting vector has either value 0u or 1u.
*/
fn to_vec(v: t) -> [uint] {
    let sub = bind init_to_vec(v, _);
    ret vec::init_fn::<uint>(sub, v.nbits);
}

/*
Function: to_str

Converts the bitvector to a string. The resulting string has the same
length as the bitvector, and each character is either '0' or '1'.
*/
fn to_str(v: t) -> str {
    let rs = "";
    for i: uint in to_vec(v) { if i == 1u { rs += "1"; } else { rs += "0"; } }
    ret rs;
}

/*
Function: eq_vec

Compare a bitvector to a vector of uint. The uint vector is expected to
only contain the values 0u and 1u.

Preconditions:

Both the bitvector and vector must have the same length
*/
fn eq_vec(v0: t, v1: [uint]) -> bool {
    assert (v0.nbits == vec::len::<uint>(v1));
    let len = v0.nbits;
    let i = 0u;
    while i < len {
        let w0 = get(v0, i);
        let w1 = v1[i];
        if !w0 && w1 != 0u || w0 && w1 == 0u { ret false; }
        i = i + 1u;
    }
    ret true;
}

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


<commit_before><commit_msg>Abstract shader compiler into ShaderProgram struct<commit_after><|endoftext|>


<commit_before><commit_msg>Add template file with parsed tree<commit_after>use std::path::{Path, PathBuf};
use super::{Name, Statement};

// A binding of template source file information and the parsed AST.
pub struct Template {
    pub tree: Statement,
    pub path: PathBuf,
    pub name: String,
    pub id: String,
}

impl Template {
    /// Creates a template from file name and root AST node.
    ///
    /// The file name is used as an identifier in compiled function names
    /// to ensure uniqueness when linked with other templates. It provides
    /// a stable name to be referenced as a partial in other templates.
    pub fn new(base: &PathBuf, path: PathBuf, tree: Statement) -> Self {
        let name = name(base, &path);
        let id = Name::new(&name).id();

        Template {
            tree: tree,
            path: path,
            name: name,
            id: id,
        }
    }
}

/// Creates a shortened path name for a template file name. The base directory
/// being compiled and the file extension is stripped off to create the short
/// name: `app/templates/include/header.mustache -> include/header`.
fn name(base: &Path, path: &Path) -> String {
    let base = path.strip_prefix(base).unwrap();
    let stem = base.file_stem().unwrap();
    let name = base.with_file_name(stem);
    String::from(name.to_str().unwrap())
}

#[cfg(test)]
mod tests {
    use super::Template;
    use super::super::Statement;
    use std::path::PathBuf;

    #[test]
    fn name() {
        let base = PathBuf::from("app/templates");
        let path = PathBuf::from("app/templates/include/header.mustache");
        let tree = Statement::Content(String::from("test"));

        let template = Template::new(&base, path, tree);
        assert_eq!("include/header", template.name);
        assert_eq!("include_header", template.id);
    }
}
<|endoftext|>


<commit_before><commit_msg>Close terminal when scene closes<commit_after><|endoftext|>


<commit_before>use common::debug::*;
use common::pci::*;

use programs::session::*;

pub struct XHCI {
    pub bus: usize,
    pub slot: usize,
    pub func: usize,
    pub base: usize,
    pub memory_mapped: bool,
    pub irq: u8
}

impl SessionDevice for XHCI {
    fn handle(&mut self, irq: u8){
        if irq == self.irq {
            d("XHCI handle");
        }
    }
}

impl XHCI {
    pub unsafe fn init(&self){
        d("XHCI on: ");
        dh(self.base);
        if self.memory_mapped {
            d(" memory mapped");
        }else{
            d(" port mapped");
        }
        d(" IRQ: ");
        dbh(self.irq);
        dl();

        pci_write(self.bus, self.slot, self.func, 0x04, pci_read(self.bus, self.slot, self.func, 0x04) | (1 << 2)); // Bus master

        let cap_base = self.base;
        let op_base = cap_base + *(cap_base as *mut u8) as usize;
        let db_base = cap_base + *((cap_base + 0x14) as *mut u32) as usize;
        let rt_base = cap_base + *((cap_base + 0x18) as *mut u32) as usize;

        d("CAP_BASE: ");
        dh(cap_base);

        d(" OP_BASE: ");
        dh(op_base);

        d(" DB_BASE: ");
        dh(db_base);

        d(" RT_BASE: ");
        dh(rt_base);
        dl();

        //Set FLADJ Frame Length Adjustment (optional?)
        //Set I/O memory maps (optional?)

        //Wait until the Controller Not Ready flag in USBSTS is 0
        let usbsts = (op_base + 0x04) as *mut u32;
        while *usbsts & (1 << 11) == (1 << 11) {
            d("Controller Not Ready\n");
        }
        d("Controller Ready ");
        dh(*usbsts as usize);
        dl();

        //Set Run/Stop to 0
        let usbcmd = op_base as *mut u32;
        *usbcmd = *usbcmd & 0xFFFFFFFE;

        while *usbsts & 1 == 0 {
            d("Command Not Ready\n");
        }
        d("Command Ready ");
        dh(*usbcmd as usize);
        dl();

        //Program the Max Device Slots Enabled in the CONFIG register
        let hcsparams1 = (cap_base + 0x04) as *const u32;

        d("Enabling Slots ");
        dd((*hcsparams1 & 0xFF) as usize);
        dl();

        let config = (op_base + 0x38) as *mut u32;
        dh(*config as usize);
        *config = *hcsparams1 & 0xFF;
        d(" ");
        dh(*config as usize);
        dl();

        //Program the Device Context Base Address Array Pointer with a pointer to the Device Context Base Address Array
        //Device the Command Ring Dequeue Pointer by programming the Command ring Control register with a pointer to the first TRB
        //Initialize interrupts (optional)
            //Allocate and initalize the MSI-X Message Table, setting the message address and message data, and enable the vectors. At least table vector entry 0 should be initialized
            //Allocate and initialize the MSI-X Pending Bit Array
            //Point the Table Offset and PBA Offsets in the MSI-X Capability Structure to the MSI-X Message Control Table and Pending Bit Array
            //Initialize the Message Control register in the MSI-X Capability Structure
            //Initialize each active interrupter by:
                //TODO: Pull from page 72
        //Write the USBCMD to turn on the host controller by setting Run/Stop to 1
    }
}
<commit_msg>WIP XHCI<commit_after>use common::debug::*;
use common::pci::*;

use programs::session::*;

pub struct XHCI {
    pub bus: usize,
    pub slot: usize,
    pub func: usize,
    pub base: usize,
    pub memory_mapped: bool,
    pub irq: u8
}

impl SessionDevice for XHCI {
    fn handle(&mut self, irq: u8){
        if irq == self.irq {
            d("XHCI handle");
        }
    }
}

impl XHCI {
    pub unsafe fn init(&self){
        d("XHCI on: ");
        dh(self.base);
        if self.memory_mapped {
            d(" memory mapped");
        }else{
            d(" port mapped");
        }
        d(" IRQ: ");
        dbh(self.irq);
        dl();

        pci_write(self.bus, self.slot, self.func, 0x04, pci_read(self.bus, self.slot, self.func, 0x04) | (1 << 2)); // Bus master

        let cap_base = self.base;
        let op_base = cap_base + *(cap_base as *mut u8) as usize;
        let db_base = cap_base + *((cap_base + 0x14) as *mut u32) as usize;
        let rt_base = cap_base + *((cap_base + 0x18) as *mut u32) as usize;

        d("CAP_BASE: ");
        dh(cap_base);

        d(" OP_BASE: ");
        dh(op_base);

        d(" DB_BASE: ");
        dh(db_base);

        d(" RT_BASE: ");
        dh(rt_base);
        dl();

        //Set FLADJ Frame Length Adjustment (optional?)
        //Set I/O memory maps (optional?)

        //Wait until the Controller Not Ready flag in USBSTS is 0
        let usbsts = (op_base + 0x04) as *mut u32;
        while *usbsts & (1 << 11) == (1 << 11) {
            d("Controller Not Ready\n");
        }
        d("Controller Ready ");
        dh(*usbsts as usize);
        dl();

        //Set Run/Stop to 0
        let usbcmd = op_base as *mut u32;
        *usbcmd = *usbcmd & 0xFFFFFFFE;

        while *usbsts & 1 == 0 {
            d("Command Not Ready\n");
        }
        d("Command Ready ");
        dh(*usbcmd as usize);
        dl();

        //Program the Max Device Slots Enabled in the CONFIG register
        let hcsparams1 = (cap_base + 0x04) as *const u32;

        d("Enabling Slots ");
        dd((*hcsparams1 & 0xFF) as usize);
        dl();

        let config = (op_base + 0x38) as *mut u32;
        dh(*config as usize);
        *config = (*config & 0xFFFFFF00) | (*hcsparams1 & 0xFF);
        d(" ");
        dh(*config as usize);
        dl();

        //Program the Device Context Base Address Array Pointer with a pointer to the Device Context Base Address Array
        //Device the Command Ring Dequeue Pointer by programming the Command ring Control register with a pointer to the first TRB
        //Initialize interrupts (optional)
            //Allocate and initalize the MSI-X Message Table, setting the message address and message data, and enable the vectors. At least table vector entry 0 should be initialized
            //Allocate and initialize the MSI-X Pending Bit Array
            //Point the Table Offset and PBA Offsets in the MSI-X Capability Structure to the MSI-X Message Control Table and Pending Bit Array
            //Initialize the Message Control register in the MSI-X Capability Structure
            //Initialize each active interrupter by:
                //TODO: Pull from page 72
        //Write the USBCMD to turn on the host controller by setting Run/Stop to 1
    }
}
<|endoftext|>


<commit_before>use std::cell::RefCell;
use std::io::{self, ErrorKind};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use std::sync::mpsc;

use mio;
use slab::Slab;
use futures::{Future, Tokens, Wake, PollResult};

pub type Waiter = Arc<Wake>;
pub type Source = Arc<mio::Evented + Send + Sync>;

static NEXT_LOOP_ID: AtomicUsize = ATOMIC_USIZE_INIT;
scoped_thread_local!(static CURRENT_LOOP: Loop);

const SLAB_CAPACITY: usize = 1024 * 64;

pub struct Loop {
    id: usize,
    io: RefCell<mio::Poll>,
    tx: mio::channel::Sender<Message>,
    rx: mio::channel::Receiver<Message>,
    dispatch: RefCell<Slab<Scheduled, usize>>,
}

#[derive(Clone)]
pub struct LoopHandle {
    id: usize,
    tx: mio::channel::Sender<Message>,
}

#[derive(Copy, Clone)]
pub enum Direction {
    Read,
    Write,
}

struct Scheduled {
    source: Source,
    reader: Option<Waiter>,
    writer: Option<Waiter>,
}

impl Scheduled {
    fn waiter_for(&mut self, dir: Direction) -> &mut Option<Waiter> {
        match dir {
            Direction::Read => &mut self.reader,
            Direction::Write => &mut self.writer,
        }
    }

    fn event_set(&self) -> mio::EventSet {
        let mut set = mio::EventSet::none();
        if self.reader.is_some() {
            set = set | mio::EventSet::readable()
        }
        if self.writer.is_some() {
            set = set | mio::EventSet::writable()
        }
        set
    }
}

enum Message {
    AddSource(Source, Arc<AtomicUsize>, Waiter),
    DropSource(usize),
    Schedule(usize, Direction, Waiter),
    Deschedule(usize, Direction),
    Shutdown,
}

fn register(poll: &mut mio::Poll, token: usize, sched: &Scheduled) {
    // TODO: handle error
    poll.register(&*sched.source,
                  mio::Token(token),
                  mio::EventSet::none(),
                  mio::PollOpt::level())
        .unwrap();
}

fn reregister(poll: &mut mio::Poll, token: usize, sched: &Scheduled) {
    // TODO: handle error
    poll.reregister(&*sched.source,
                    mio::Token(token),
                    sched.event_set(),
                    mio::PollOpt::edge() | mio::PollOpt::oneshot())
        .unwrap();
}

fn deregister(poll: &mut mio::Poll, sched: &Scheduled) {
    // TODO: handle error
    poll.deregister(&*sched.source).unwrap();
}

impl Loop {
    pub fn new() -> io::Result<Loop> {
        let (tx, rx) = mio::channel::from_std_channel(mpsc::channel());
        let io = try!(mio::Poll::new());
        try!(io.register(&rx,
                         mio::Token(0),
                         mio::EventSet::readable(),
                         mio::PollOpt::edge()));
        Ok(Loop {
            id: NEXT_LOOP_ID.fetch_add(1, Ordering::Relaxed),
            io: RefCell::new(io),
            tx: tx,
            rx: rx,
            dispatch: RefCell::new(Slab::new_starting_at(1, SLAB_CAPACITY)),
        })
    }

    pub fn handle(&self) -> LoopHandle {
        LoopHandle {
            id: self.id,
            tx: self.tx.clone(),
        }
    }

    pub fn run(&mut self) {
        loop {
            let amt;
            // On Linux, Poll::poll is epoll_wait, which may return EINTR if a
            // ptracer attaches. This retry loop prevents crashing when
            // attaching strace, or similar.
            loop {
                match self.io.borrow_mut().poll(None) {
                    Ok(a) => {
                        amt = a;
                        break;
                    }
                    Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
                    err @ Err(_) => {
                        err.unwrap();
                    }
                }
            }

            // TODO: coalesce token sets for a given Wake?
            for i in 0..amt {
                let event = self.io.borrow_mut().events().get(i).unwrap();
                let token = event.token().as_usize();
                if token == 0 {
                    while let Ok(msg) = self.rx.try_recv() {
                        self.notify(msg);
                    }
                } else {
                    let mut reader = None;
                    let mut writer = None;

                    if let Some(sched) = self.dispatch.borrow_mut().get_mut(token) {
                        if event.kind().is_readable() {
                            reader = sched.reader.take();
                        }

                        if event.kind().is_writable() {
                            writer = sched.writer.take();
                        }
                    }

                    CURRENT_LOOP.set(self, || {
                        if let Some(reader_wake) = reader.take() {
                            reader_wake.wake(&Tokens::from_usize(token));
                        }
                        if let Some(writer_wake) = writer.take() {
                            writer_wake.wake(&Tokens::from_usize(token));
                        }
                    });

                    // For now, always reregister, to deal with the fact that
                    // combined oneshot + read|write requires rearming even if
                    // only one side fired.
                    //
                    // TODO: optimize this
                    if let Some(sched) = self.dispatch.borrow().get(token) {
                        reregister(&mut self.io.borrow_mut(), token, &sched);
                    }
                }
            }
        }
    }

    fn add_source(&self, source: Source) -> usize {
        let sched = Scheduled {
            source: source,
            reader: None,
            writer: None,
        };
        let mut dispatch = self.dispatch.borrow_mut();
        // TODO: handle out of space
        let entry = dispatch.vacant_entry().unwrap();
        register(&mut self.io.borrow_mut(), entry.index(), &sched);
        entry.insert(sched).index()
    }

    fn drop_source(&self, token: usize) {
        let sched = self.dispatch.borrow_mut().remove(token).unwrap();
        deregister(&mut self.io.borrow_mut(), &sched);
    }

    fn schedule(&self, token: usize, dir: Direction, wake: Waiter) {
        let mut dispatch = self.dispatch.borrow_mut();
        let sched = dispatch.get_mut(token).unwrap();
        *sched.waiter_for(dir) = Some(wake);
        reregister(&mut self.io.borrow_mut(), token, sched);
    }

    fn deschedule(&self, token: usize, dir: Direction) {
        let mut dispatch = self.dispatch.borrow_mut();
        let sched = dispatch.get_mut(token).unwrap();
        *sched.waiter_for(dir) = None;
        reregister(&mut self.io.borrow_mut(), token, sched);
    }

    fn notify(&self, msg: Message) {
        match msg {
            Message::AddSource(source, id, wake) => {
                let tok = self.add_source(source);
                id.store(tok, Ordering::Relaxed);
                wake.wake(&Tokens::from_usize(ADD_SOURCE_TOKEN));
            }
            Message::DropSource(tok) => self.drop_source(tok),
            Message::Schedule(tok, dir, wake) => self.schedule(tok, dir, wake),
            Message::Deschedule(tok, dir) => self.deschedule(tok, dir),
            Message::Shutdown => unimplemented!(),
        }
    }
}

impl LoopHandle {
    fn send(&self, msg: Message) {
        let mut msg_dance = Some(msg);

        if CURRENT_LOOP.is_set() {
            CURRENT_LOOP.with(|lp| {
                if lp.id == self.id {
                    // TODO: we should probably clear the message queue first,
                    // to avoid out of order delivery? Currently these messages
                    // are "skipping the queue"
                    lp.notify(msg_dance.take().unwrap());
                }
            })
        }

        if let Some(msg) = msg_dance.take() {
            self.tx
                .send(msg)
                .map_err(|_| ())
                .expect("failed to send register message") // todo: handle failure
        }
    }

    pub fn add_source(&self, source: Source) -> AddSource {
        AddSource {
            loop_handle: self.clone(),
            source: Some(source),
            id: Arc::new(AtomicUsize::new(0)),
            scheduled: false,
        }
    }

    fn add_source_(&self, source: Source, id: Arc<AtomicUsize>, wake: Waiter) {
        self.send(Message::AddSource(source, id, wake));
    }

    pub fn drop_source(&self, tok: usize) {
        self.send(Message::DropSource(tok));
    }

    pub fn schedule(&self, tok: usize, dir: Direction, wake: Waiter) {
        self.send(Message::Schedule(tok, dir, wake));
    }

    pub fn deschedule(&self, tok: usize, dir: Direction) {
        self.send(Message::Deschedule(tok, dir));
    }
}

const ADD_SOURCE_TOKEN: usize = 0;

pub struct AddSource {
    loop_handle: LoopHandle,
    source: Option<Source>,
    id: Arc<AtomicUsize>,
    scheduled: bool,
}

impl Future for AddSource {
    type Item = usize;
    type Error = io::Error; // TODO: integrate channel error?

    fn poll(&mut self, tokens: &Tokens) -> Option<PollResult<usize, io::Error>> {
        if self.scheduled {
            if tokens.may_contain(&Tokens::from_usize(ADD_SOURCE_TOKEN)) {
                let id = self.id.load(Ordering::Relaxed);
                if id != 0 {
                    return Some(Ok(id))
                }
            }
        } else {
            if CURRENT_LOOP.is_set() {
                let res = CURRENT_LOOP.with(|lp| {
                    if lp.id == self.loop_handle.id {
                        Some(lp.add_source(self.source.take().unwrap()))
                    } else {
                        None
                    }
                });
                if let Some(id) = res {
                    return Some(Ok(id));
                }
            }
        }

        None
    }

    fn schedule(&mut self, wake: Arc<Wake>) {
        if self.scheduled { return; }
        self.scheduled = true;
        self.loop_handle.add_source_(self.source.take().unwrap(), self.id.clone(), wake);
    }
}
<commit_msg>Execute all channel messages prior to executing a TLS message<commit_after>use std::cell::RefCell;
use std::io::{self, ErrorKind};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use std::sync::mpsc;

use mio;
use slab::Slab;
use futures::{Future, Tokens, Wake, PollResult};

pub type Waiter = Arc<Wake>;
pub type Source = Arc<mio::Evented + Send + Sync>;

static NEXT_LOOP_ID: AtomicUsize = ATOMIC_USIZE_INIT;
scoped_thread_local!(static CURRENT_LOOP: Loop);

const SLAB_CAPACITY: usize = 1024 * 64;

pub struct Loop {
    id: usize,
    io: RefCell<mio::Poll>,
    tx: mio::channel::Sender<Message>,
    rx: mio::channel::Receiver<Message>,
    dispatch: RefCell<Slab<Scheduled, usize>>,
}

#[derive(Clone)]
pub struct LoopHandle {
    id: usize,
    tx: mio::channel::Sender<Message>,
}

#[derive(Copy, Clone)]
pub enum Direction {
    Read,
    Write,
}

struct Scheduled {
    source: Source,
    reader: Option<Waiter>,
    writer: Option<Waiter>,
}

impl Scheduled {
    fn waiter_for(&mut self, dir: Direction) -> &mut Option<Waiter> {
        match dir {
            Direction::Read => &mut self.reader,
            Direction::Write => &mut self.writer,
        }
    }

    fn event_set(&self) -> mio::EventSet {
        let mut set = mio::EventSet::none();
        if self.reader.is_some() {
            set = set | mio::EventSet::readable()
        }
        if self.writer.is_some() {
            set = set | mio::EventSet::writable()
        }
        set
    }
}

enum Message {
    AddSource(Source, Arc<AtomicUsize>, Waiter),
    DropSource(usize),
    Schedule(usize, Direction, Waiter),
    Deschedule(usize, Direction),
    Shutdown,
}

fn register(poll: &mut mio::Poll, token: usize, sched: &Scheduled) {
    // TODO: handle error
    poll.register(&*sched.source,
                  mio::Token(token),
                  mio::EventSet::none(),
                  mio::PollOpt::level())
        .unwrap();
}

fn reregister(poll: &mut mio::Poll, token: usize, sched: &Scheduled) {
    // TODO: handle error
    poll.reregister(&*sched.source,
                    mio::Token(token),
                    sched.event_set(),
                    mio::PollOpt::edge() | mio::PollOpt::oneshot())
        .unwrap();
}

fn deregister(poll: &mut mio::Poll, sched: &Scheduled) {
    // TODO: handle error
    poll.deregister(&*sched.source).unwrap();
}

impl Loop {
    pub fn new() -> io::Result<Loop> {
        let (tx, rx) = mio::channel::from_std_channel(mpsc::channel());
        let io = try!(mio::Poll::new());
        try!(io.register(&rx,
                         mio::Token(0),
                         mio::EventSet::readable(),
                         mio::PollOpt::edge()));
        Ok(Loop {
            id: NEXT_LOOP_ID.fetch_add(1, Ordering::Relaxed),
            io: RefCell::new(io),
            tx: tx,
            rx: rx,
            dispatch: RefCell::new(Slab::new_starting_at(1, SLAB_CAPACITY)),
        })
    }

    pub fn handle(&self) -> LoopHandle {
        LoopHandle {
            id: self.id,
            tx: self.tx.clone(),
        }
    }

    pub fn run(&mut self) {
        loop {
            let amt;
            // On Linux, Poll::poll is epoll_wait, which may return EINTR if a
            // ptracer attaches. This retry loop prevents crashing when
            // attaching strace, or similar.
            loop {
                match self.io.borrow_mut().poll(None) {
                    Ok(a) => {
                        amt = a;
                        break;
                    }
                    Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
                    err @ Err(_) => {
                        err.unwrap();
                    }
                }
            }

            // TODO: coalesce token sets for a given Wake?
            for i in 0..amt {
                let event = self.io.borrow_mut().events().get(i).unwrap();
                let token = event.token().as_usize();
                if token == 0 {
                    self.consume_queue();
                } else {
                    let mut reader = None;
                    let mut writer = None;

                    if let Some(sched) = self.dispatch.borrow_mut().get_mut(token) {
                        if event.kind().is_readable() {
                            reader = sched.reader.take();
                        }

                        if event.kind().is_writable() {
                            writer = sched.writer.take();
                        }
                    }

                    CURRENT_LOOP.set(self, || {
                        if let Some(reader_wake) = reader.take() {
                            reader_wake.wake(&Tokens::from_usize(token));
                        }
                        if let Some(writer_wake) = writer.take() {
                            writer_wake.wake(&Tokens::from_usize(token));
                        }
                    });

                    // For now, always reregister, to deal with the fact that
                    // combined oneshot + read|write requires rearming even if
                    // only one side fired.
                    //
                    // TODO: optimize this
                    if let Some(sched) = self.dispatch.borrow().get(token) {
                        reregister(&mut self.io.borrow_mut(), token, &sched);
                    }
                }
            }
        }
    }

    fn add_source(&self, source: Source) -> usize {
        let sched = Scheduled {
            source: source,
            reader: None,
            writer: None,
        };
        let mut dispatch = self.dispatch.borrow_mut();
        // TODO: handle out of space
        let entry = dispatch.vacant_entry().unwrap();
        register(&mut self.io.borrow_mut(), entry.index(), &sched);
        entry.insert(sched).index()
    }

    fn drop_source(&self, token: usize) {
        let sched = self.dispatch.borrow_mut().remove(token).unwrap();
        deregister(&mut self.io.borrow_mut(), &sched);
    }

    fn schedule(&self, token: usize, dir: Direction, wake: Waiter) {
        let mut dispatch = self.dispatch.borrow_mut();
        let sched = dispatch.get_mut(token).unwrap();
        *sched.waiter_for(dir) = Some(wake);
        reregister(&mut self.io.borrow_mut(), token, sched);
    }

    fn deschedule(&self, token: usize, dir: Direction) {
        let mut dispatch = self.dispatch.borrow_mut();
        let sched = dispatch.get_mut(token).unwrap();
        *sched.waiter_for(dir) = None;
        reregister(&mut self.io.borrow_mut(), token, sched);
    }

    fn consume_queue(&self) {
        while let Ok(msg) = self.rx.try_recv() {
            self.notify(msg);
        }
    }

    fn notify(&self, msg: Message) {
        match msg {
            Message::AddSource(source, id, wake) => {
                let tok = self.add_source(source);
                id.store(tok, Ordering::Relaxed);
                wake.wake(&Tokens::from_usize(ADD_SOURCE_TOKEN));
            }
            Message::DropSource(tok) => self.drop_source(tok),
            Message::Schedule(tok, dir, wake) => self.schedule(tok, dir, wake),
            Message::Deschedule(tok, dir) => self.deschedule(tok, dir),
            Message::Shutdown => unimplemented!(),
        }
    }
}

impl LoopHandle {
    fn send(&self, msg: Message) {
        let mut msg_dance = Some(msg);

        if CURRENT_LOOP.is_set() {
            CURRENT_LOOP.with(|lp| {
                if lp.id == self.id {
                    // Need to execute all existing requests first, to ensure
                    // that our message is processed "in order"
                    lp.consume_queue()
                    lp.notify(msg_dance.take().unwrap());
                }
            })
        }

        if let Some(msg) = msg_dance.take() {
            self.tx
                .send(msg)
                .map_err(|_| ())
                .expect("failed to send register message") // todo: handle failure
        }
    }

    pub fn add_source(&self, source: Source) -> AddSource {
        AddSource {
            loop_handle: self.clone(),
            source: Some(source),
            id: Arc::new(AtomicUsize::new(0)),
            scheduled: false,
        }
    }

    fn add_source_(&self, source: Source, id: Arc<AtomicUsize>, wake: Waiter) {
        self.send(Message::AddSource(source, id, wake));
    }

    pub fn drop_source(&self, tok: usize) {
        self.send(Message::DropSource(tok));
    }

    pub fn schedule(&self, tok: usize, dir: Direction, wake: Waiter) {
        self.send(Message::Schedule(tok, dir, wake));
    }

    pub fn deschedule(&self, tok: usize, dir: Direction) {
        self.send(Message::Deschedule(tok, dir));
    }
}

const ADD_SOURCE_TOKEN: usize = 0;

pub struct AddSource {
    loop_handle: LoopHandle,
    source: Option<Source>,
    id: Arc<AtomicUsize>,
    scheduled: bool,
}

impl Future for AddSource {
    type Item = usize;
    type Error = io::Error; // TODO: integrate channel error?

    fn poll(&mut self, tokens: &Tokens) -> Option<PollResult<usize, io::Error>> {
        if self.scheduled {
            if tokens.may_contain(&Tokens::from_usize(ADD_SOURCE_TOKEN)) {
                let id = self.id.load(Ordering::Relaxed);
                if id != 0 {
                    return Some(Ok(id))
                }
            }
        } else {
            if CURRENT_LOOP.is_set() {
                let res = CURRENT_LOOP.with(|lp| {
                    if lp.id == self.loop_handle.id {
                        Some(lp.add_source(self.source.take().unwrap()))
                    } else {
                        None
                    }
                });
                if let Some(id) = res {
                    return Some(Ok(id));
                }
            }
        }

        None
    }

    fn schedule(&mut self, wake: Arc<Wake>) {
        if self.scheduled { return; }
        self.scheduled = true;
        self.loop_handle.add_source_(self.source.take().unwrap(), self.id.clone(), wake);
    }
}
<|endoftext|>


<commit_before>use std::env;

fn main() {
    if env::var("CARGO_PKG_VERSION").unwrap() == "1.3.0" {
        panic!(
            "Did you remember to publish documentation on the config file? \
             If not go do it. And then delete this build script."
        );
    }
}
<commit_msg>`diesel.toml` has been documented<commit_after><|endoftext|>


<commit_before><commit_msg>add list benchmarks<commit_after>#![feature(test)]
extern crate test;

#[macro_use]
extern crate lambda_calculus as lambda;

use test::Bencher;
use lambda::church::lists::*;
use lambda::church::numerals::*;
use lambda::combinators::c;
use lambda::*;

fn list1() -> Term { Term::from(vec![1.into()]) }
fn list2() -> Term { Term::from(vec![2.into(), 3.into()]) }
fn list3() -> Term { Term::from(vec![1.into(), 2.into(), 3.into()]) }
fn   gt1() -> Term { app!(c(), gt(), 1.into()) }

#[bench]
fn list_null(b: &mut Bencher) {
    b.iter(|| { beta(app(null(), list3()), HAP, 0, false) } );
}

#[bench]
fn list_head(b: &mut Bencher) {
    b.iter(|| { beta(app(head(), list3()), HAP, 0, false) } );
}

#[bench]
fn list_tail(b: &mut Bencher) {
    b.iter(|| { beta(app(tail(), list3()), HAP, 0, false) } );
}

#[bench]
fn list_length(b: &mut Bencher) {
    b.iter(|| { beta(app(length(), list3()), HAP, 0, false) } );
}

#[bench]
fn list_building(b: &mut Bencher) {
    b.iter(|| { beta(app!(list(), 3.into(), 1.into(), 2.into(), 3.into()), HAP, 0, false) } );
}

#[bench]
fn reversing(b: &mut Bencher) {
    b.iter(|| { beta(app(reverse(), list3()), HAP, 0, false) } );
}

#[bench]
fn appending(b: &mut Bencher) {
    b.iter(|| { beta(app!(append(), list1(), list2()), HAP, 0, false) } );
}

#[bench]
fn indexing(b: &mut Bencher) {
    b.iter(|| { beta(app!(index(), 1.into(), list3()), HAP, 0, false) } );
}

#[bench]
fn mapping(b: &mut Bencher) {
    b.iter(|| { beta(app!(map(), gt1(), list3()), HAP, 0, false) } );
}

#[bench]
fn list_foldl(b: &mut Bencher) {
    b.iter(|| { beta(app!(foldl(), plus(), 0.into(), list3()), HAP, 0, false) } );
}

#[bench]
fn list_foldr(b: &mut Bencher) {
    b.iter(|| { beta(app!(foldr(), plus(), 0.into(), list3()), HAP, 0, false) } );
}

#[bench]
fn filtering(b: &mut Bencher) {
    b.iter(|| { beta(app!(filter(), gt1(), list3()), HAP, 0, false) } );
}

#[bench]
fn list_init(b: &mut Bencher) {
    b.iter(|| { beta(app(init(), list3()), HAP, 0, false) } );
}

#[bench]
fn list_last(b: &mut Bencher) {
    b.iter(|| { beta(app(last(), list3()), HAP, 0, false) } );
}
<|endoftext|>


<commit_before><commit_msg>:art: Add AttachmentBuilder<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing consts for Solaris/Illumos<commit_after><|endoftext|>