<commit_before>extern crate serialize;

use serialize::{Decodable,json};
use std::io::Process;
use std::io::fs::File;
use std::io::process::ProcessOutput;
use std::io::{fs,IoResult,Truncate,UserRWX,Write};
use std::str;

#[deriving(Decodable,Show)]
struct Example {
    id: ~str,
    title: ~str,
}

fn read(file: &Path) -> IoResult<~str> {
    let mut file = try!(File::open(file));

    Ok(try!(file.read_to_str()))
}

fn write(file: &Path, contents: &str) -> IoResult<()> {
    let mut file = try!(File::open_mode(file, Truncate, Write));

    Ok(try!(file.write_str(contents)))
}

fn update(example: &Example) -> bool {
    print!("{}... ", example.id);

    let src_dir = Path::new(format!("src/{}", example.id));
    let out_dir = Path::new(format!("output/examples/{}", example.id));

    let sources: Vec<Path> = match fs::readdir(&src_dir) {
        Err(_) => {
            println!("couldn't read {}", src_dir.display());
            return false
        } Ok(contents) => contents.move_iter().filter(|path| match path.extension_str() {
            None => false,
            Some(extension) => extension == "rs",
        }).collect(),
    };

    let mut template = match read(&src_dir.join("input.md")) {
        Err(_) => {
            println!("couldn't read input.md");
            return false
        } Ok(contents) => format!("\\# {}\n\n{}", example.title, contents),
    };

    // insert source code in markdown
    for source in sources.iter() {
        let filename = source.filename_str().unwrap();
        let code = match read(source) {
            Err(_) => {
                println!("couldn't read {}", filename);
                return false;
            }, Ok(contents) => format!("``` rust\n// {}\n{}```", filename, contents),
        };

        template = template.replace(format!("\\{{}\\}", filename), code);
    }

    // insert program output in markdown
    for source in sources.iter() {
        let filename = source.filename_str().unwrap();
        let token = format!("\\{{}\\}", source.with_extension("out").filename_str().unwrap());

        if template.contains(token) {
            match compile_run(source) {
                Err(action) => {
                    println!("couldn't {} {}", action, filename);
                    return false;
                }, Ok(output) => {
                    let output = format!("```\n$ rustc {} && ./{}\n{}```",
                                         filename,
                                         filename.split('.').nth(0).unwrap(),
                                         output);

                    template = template.replace(token, output);
                }
            }
        }
    }

    if !out_dir.exists() {
        fs::mkdir(&out_dir, UserRWX).unwrap();
    }

    match write(&out_dir.join("README.md"), template) {
        Err(_) => {
            println!("couldn't write README.md");
            false
        } Ok(_) => {
            println!("DONE");
            true
        }
    }
}

fn compile_run(path: &Path) -> Result<~str, &'static str> {
    match Process::output("rustc", [path.as_str().unwrap().to_owned(),
                                    "-o".to_owned(),
                                    "executable".to_owned()]) {
        Err(_) => return Err("compile"),
        Ok(out) => {
            if !out.status.success() {
                return Ok(str::from_utf8_owned(out.error.as_slice().to_owned()).unwrap());
            }
        }
    }

    match Process::output("./executable", []) {
        Err(_) => Err("run"),
        Ok(out) => {
            fs::unlink(&Path::new("./executable")).unwrap();
            let ProcessOutput { status: _, output: out, error: err } = out;
            let stdout = str::from_utf8_owned(out.as_slice().to_owned()).unwrap();
            let stderr = str::from_utf8_owned(err.as_slice().to_owned()).unwrap();

            Ok(vec!(stdout, stderr).concat())
        }
    }
}

fn main() {
    let src_dir = Path::new("src");

    let examples: Vec<Example> = match read(&src_dir.join("order.json")) {
        Err(err) => fail!("couldn't read order.json: {}", err),
        Ok(string) => match json::from_str(string) {
            Err(err) => fail!("order.json is invalid json: {}", err),
            Ok(json) => match Decodable::decode(&mut json::Decoder::new(json)) {
                Err(err) => fail!("error decoding order.json: {}", err),
                Ok(data) => data,
            }
        }
    };

    let mut indent = false;
    let summary = examples.move_iter().map(|example| {
        if example.id.as_slice() == "staging" {
            indent = true;
        }

        let chapter = if update(&example) {
            format!("* [{}](examples/{}/README.md)", example.title, example.id)
        } else {
            format!("* {}", example.title)
        };

        if indent &&
            example.id.as_slice() != "staging" &&
            example.id.as_slice() != "todo" {
            format!("  {}", chapter)
        } else {
            chapter
        }
    }).collect::<Vec<~str>>().connect("\n");

    if write(&Path::new("output/SUMMARY.md"), summary).is_err() {
        fail!("failed to write SUMMARY.md");
    }
}
<commit_msg>update.rs: use new Command API, look for source files also in directories<commit_after>extern crate serialize;

use serialize::{Decodable,json};
use std::io::fs::File;
use std::io::process::{Command,ProcessOutput};
use std::io::{fs,IoResult,Truncate,UserRWX,Write};
use std::str;

#[deriving(Decodable,Show)]
struct Example {
    id: ~str,
    title: ~str,
}

fn read(file: &Path) -> IoResult<~str> {
    let mut file = try!(File::open(file));

    Ok(try!(file.read_to_str()))
}

fn write(file: &Path, contents: &str) -> IoResult<()> {
    let mut file = try!(File::open_mode(file, Truncate, Write));

    Ok(try!(file.write_str(contents)))
}

fn update(example: &Example) -> bool {
    print!("{}... ", example.id);

    let src_dir = Path::new(format!("src/{}", example.id));
    let out_dir = Path::new(format!("output/examples/{}", example.id));

    let sources: Vec<Path> = match fs::walk_dir(&src_dir) {
        Err(_) => {
            println!("couldn't read {}", src_dir.display());
            return false
        } Ok(contents) => contents.filter(|path| match path.extension_str() {
            None => false,
            Some(extension) => extension == "rs",
        }).collect(),
    };

    let mut template = match read(&src_dir.join("input.md")) {
        Err(_) => {
            println!("couldn't read input.md");
            return false
        } Ok(contents) => format!("\\# {}\n\n{}", example.title, contents),
    };

    // insert source code in markdown
    for source in sources.iter() {
        let path = source.as_str().unwrap().split('/').skip(2).collect::<Vec<&str>>().connect("/");
        let code = match read(source) {
            Err(_) => {
                println!("couldn't read {}", path);
                return false;
            }, Ok(contents) => format!("``` rust\n// {}\n{}```", path, contents),
        };

        template = template.replace(format!("\\{{}\\}", path), code);
    }

    // insert program output in markdown
    for source in sources.iter() {
        let filename = source.filename_str().unwrap();
        let token = format!("\\{{}\\}", source.with_extension("out").filename_str().unwrap());

        if template.contains(token) {
            match compile_run(source) {
                Err(action) => {
                    println!("couldn't {} {}", action, filename);
                    return false;
                }, Ok(output) => {
                    let output = format!("```\n$ rustc {} && ./{}\n{}```",
                                         filename,
                                         filename.split('.').nth(0).unwrap(),
                                         output);

                    template = template.replace(token, output);
                }
            }
        }
    }

    if !out_dir.exists() {
        fs::mkdir(&out_dir, UserRWX).unwrap();
    }

    match write(&out_dir.join("README.md"), template) {
        Err(_) => {
            println!("couldn't write README.md");
            false
        } Ok(_) => {
            println!("DONE");
            true
        }
    }
}

fn compile_run(path: &Path) -> Result<~str, &'static str> {
    match Command::new("rustc").args([path.as_str().unwrap(), "-o", "executable"]).output() {
        Err(_) => return Err("compile"),
        Ok(out) => {
            if !out.status.success() {
                return Ok(str::from_utf8_owned(out.error.as_slice().to_owned()).unwrap());
            }
        }
    }

    match Command::new("./executable").output() {
        Err(_) => Err("run"),
        Ok(out) => {
            fs::unlink(&Path::new("./executable")).unwrap();
            let ProcessOutput { status: _, output: out, error: err } = out;
            let stdout = str::from_utf8_owned(out.as_slice().to_owned()).unwrap();
            let stderr = str::from_utf8_owned(err.as_slice().to_owned()).unwrap();

            Ok(vec!(stdout, stderr).concat())
        }
    }
}

fn main() {
    let src_dir = Path::new("src");

    let examples: Vec<Example> = match read(&src_dir.join("order.json")) {
        Err(err) => fail!("couldn't read order.json: {}", err),
        Ok(string) => match json::from_str(string) {
            Err(err) => fail!("order.json is invalid json: {}", err),
            Ok(json) => match Decodable::decode(&mut json::Decoder::new(json)) {
                Err(err) => fail!("error decoding order.json: {}", err),
                Ok(data) => data,
            }
        }
    };

    let mut indent = false;
    let summary = examples.move_iter().map(|example| {
        if example.id.as_slice() == "staging" {
            indent = true;
        }

        let chapter = if update(&example) {
            format!("* [{}](examples/{}/README.md)", example.title, example.id)
        } else {
            format!("* {}", example.title)
        };

        if indent &&
            example.id.as_slice() != "staging" &&
            example.id.as_slice() != "todo" {
            format!("  {}", chapter)
        } else {
            chapter
        }
    }).collect::<Vec<~str>>().connect("\n");

    if write(&Path::new("output/SUMMARY.md"), summary).is_err() {
        fail!("failed to write SUMMARY.md");
    }
}
<|endoftext|>


<commit_before><commit_msg>create & overwriting<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: We go to the next month, not to the current one<commit_after><|endoftext|>


<commit_before><commit_msg>ioreg::register: Fix span associated with struct<commit_after><|endoftext|>


<commit_before><commit_msg>pass by-ref to val_eq<commit_after><|endoftext|>


<commit_before><commit_msg>Swap current and next HashSets + drain next instead of creating new allocations<commit_after><|endoftext|>


<commit_before><commit_msg>Incorporated debugger into new arch<commit_after><|endoftext|>


<commit_before><commit_msg>added tournament selection<commit_after><|endoftext|>


<commit_before><commit_msg>Creating simple black image<commit_after><|endoftext|>


<commit_before><commit_msg>day 10<commit_after><|endoftext|>


<commit_before><commit_msg>Function renaming.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed string offsets<commit_after><|endoftext|>


<commit_before><commit_msg>Render a grid on Products.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove ncollide as extern crate<commit_after><|endoftext|>


<commit_before><commit_msg>Renamed status handler (hand -> statush)<commit_after><|endoftext|>


<commit_before><commit_msg>use a bit int parameter for lychrel test<commit_after><|endoftext|>


<commit_before>use redox::{Vec, String, ToString};
use redox::collections::{BTreeMap, VecDeque};

use super::dvaddr::DVAddr;
use super::zio;

// Our implementation of the Adaptive Replacement Cache (ARC) is set up to allocate
// its buffer on the heap rather than in a private pool thing. This makes it much
// simpler to implement, but defers the fragmentation problem to the heap allocator.
// We named the type `ArCache` to avoid confusion with Rust's `Arc` reference type.
pub struct ArCache {
    mru_map: BTreeMap<DVAddr, Vec<u8>>, // Most recently used cache
    mru_queue: VecDeque<DVAddr>, // Oldest paths are at the end
    mru_size: usize, // Max mru cache size in bytes
    mru_used: usize, // Used bytes in mru cache
}

impl ArCache {
    pub fn new() -> Self {
        ArCache {
            mru_map: BTreeMap::new(),
            mru_queue: VecDeque::new(),
            mru_size: 10,
            mru_used: 0,
        }
    }

    pub fn read(&mut self, reader: &mut zio::Reader, dva: &DVAddr) -> Result<Vec<u8>, String> {
        if let Some(block) = self.mru_map.get(dva) {
            // Block is cached
            return Ok(block.clone());
        }

        // Block isn't cached, have to read it from disk
        let block = reader.read(dva.sector() as usize, dva.asize() as usize);

        // If necessary, make room for the block in the cache
        while self.mru_used + block.len() > self.mru_size {
            let last_dva = match self.mru_queue.pop_back()
            {
                Some(dva) => dva,
                None => return Err("No more ARC MRU items to free".to_string()),
            };
            self.mru_map.remove(&last_dva);
            self.mru_used -= last_dva.asize() as usize;
        }

        // Add the block to the cache
        self.mru_used += block.len();
        self.mru_map.insert(*dva, block);
        self.mru_queue.push_front(*dva);
        Ok(self.mru_map.get(dva).unwrap().clone())
    }
}
<commit_msg>Added TODOs in ARC for stratact<commit_after>use redox::{Vec, String, ToString};
use redox::collections::{BTreeMap, VecDeque};

use super::dvaddr::DVAddr;
use super::zio;

// Our implementation of the Adaptive Replacement Cache (ARC) is set up to allocate
// its buffer on the heap rather than in a private pool thing. This makes it much
// simpler to implement, but defers the fragmentation problem to the heap allocator.
// We named the type `ArCache` to avoid confusion with Rust's `Arc` reference type.
pub struct ArCache {
    // MRU
    // TODO: keep track of use counts. So mru_map becomes (use_count: u64, Vec<u8>)
    mru_map: BTreeMap<DVAddr, Vec<u8>>, // Most recently used cache
    mru_queue: VecDeque<DVAddr>, // Oldest DVAddrs are at the end
    mru_size: usize, // Max mru cache size in bytes
    mru_used: usize, // Used bytes in mru cache

    // MFU
    // TODO: Keep track of use counts. So mfu_map becomes (use_count: u64, Vec<u8>). Reset the use
    // count every once in a while. For instance, every 1000 reads. This will probably end up being
    // a knob for the user.
    mfu_map: BTreeMap<DVAddr, Vec<u8>>, // Most frequently used cache
    // TODO: Keep track of minimum frequency.
    mfu_min_freq: u64,
    mfu_size: usize, // Max mfu cache size in bytes
    mfu_used: usize, // Used bytes in mfu cache
}

impl ArCache {
    pub fn new() -> Self {
        ArCache {
            mru_map: BTreeMap::new(),
            mru_queue: VecDeque::new(),
            mru_size: 10,
            mru_used: 0,

            mfu_map: BTreeMap::new(),
            mfu_size: 10,
            mfu_used: 0,
        }
    }

    pub fn read(&mut self, reader: &mut zio::Reader, dva: &DVAddr) -> Result<Vec<u8>, String> {
        if let Some(block) = self.mru_map.get(dva) {
            // TODO: Keep track of MRU DVA use count. If it gets used a second time, move the block into
            // the MFU cache.

            // Block is cached
            return Ok(block.clone());
        }
        if let Some(block) = self.mfu_map.get(dva) {
            // TODO: keep track of DVA use count
            // Block is cached
            return Ok(block.clone());
        }

        // Block isn't cached, have to read it from disk
        let block = reader.read(dva.sector() as usize, dva.asize() as usize);
        self.cache_block(block);
    }

    fn mru_cache_block(&mut self, block: Vec<u8>) {
        // If necessary, make room for the block in the cache
        while self.mru_used + block.len() > self.mru_size {
            let last_dva = match self.mru_queue.pop_back()
            {
                Some(dva) => dva,
                None => return Err("No more ARC MRU items to free".to_string()),
            };
            self.mru_map.remove(&last_dva);
            self.mru_used -= last_dva.asize() as usize;
        }

        // Add the block to the cache
        self.mru_used += block.len();
        self.mru_map.insert(*dva, block);
        self.mru_queue.push_front(*dva);
        Ok(self.mru_map.get(dva).unwrap().clone())
    }

    // TODO: mfu_cache_block
}
<|endoftext|>


<commit_before><commit_msg>Add cfail test for custom attribute gate<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.

#[foo] //~ ERROR The attribute `foo`
fn main() {

}<|endoftext|>


<commit_before><commit_msg>Add lib to examples.<commit_after>extern crate lcm;

pub mod exlcm;
<|endoftext|>


<commit_before><commit_msg>feat(examples): add an example for version negotiation<commit_after>// Copyright 2017 Dmitry Tantsur <divius.inside@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate env_logger;
extern crate hyper;
extern crate openstack;

const KILO: openstack::ApiVersion = openstack::ApiVersion(2, 3);
const LIBERTY: openstack::ApiVersion = openstack::ApiVersion(2, 12);
const MITAKA: openstack::ApiVersion = openstack::ApiVersion(2, 25);
const NEWTON: openstack::ApiVersion = openstack::ApiVersion(2, 38);
const OCATA: openstack::ApiVersion = openstack::ApiVersion(2, 42);

#[cfg(feature = "compute")]
fn main() {
    env_logger::init().unwrap();

    let identity = openstack::auth::Identity::from_env()
        .expect("Failed to create an identity provider from the environment");
    let mut session = openstack::Session::new(identity);

    let version_choice = vec![KILO, LIBERTY, MITAKA, NEWTON, OCATA];
    let version = session.negotiate_api_version::<openstack::compute::V2>(
        openstack::ApiVersionRequest::Choice(version_choice)
    ).expect("Unable to negotiation any Compute API version");

    match version {
        KILO => println!("Kilo API detected"),
        LIBERTY => println!("Liberty API detected"),
        MITAKA => println!("Mitaka API detected"),
        NEWTON => println!("Newton API detected"),
        OCATA => println!("Ocata API detected"),
        _ => unreachable!()
    }
    openstack::compute::v2::servers(&session).list().fetch()
        .expect(&format!("Cannot list servers with API version {}", version));
}

#[cfg(not(feature = "compute"))]
fn main() {
    panic!("This example cannot run with 'compute' feature disabled");
}

<|endoftext|>


<commit_before><commit_msg>examples: add simple<commit_after>extern crate rand;
extern crate pbr;
use rand::Rng;
use pbr::ProgressBar;
use std::thread;
use std::time::Duration;

fn main() {
    let count = 500;
    let mut pb = ProgressBar::new(count);
    pb.format("╢▌▌░╟");
    for _ in 0..count {
        pb.inc();
        let n = rand::thread_rng().gen_range(0, 100);
        thread::sleep(Duration::from_millis(n));
    }
    pb.finish_println("done!");
}
<|endoftext|>


<commit_before><commit_msg>Add solution to problem 33<commit_after>#![feature(zero_one)]
#[macro_use] extern crate libeuler;

use std::collections::HashSet;
use std::num::One;
use std::ops::Mul;
/// The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to
/// simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by
/// cancelling the 9s.
///
/// We shall consider fractions like, 30/50 = 3/5, to be trivial examples.
///
/// There are exactly four non-trivial examples of this type of fraction, less than one in value,
/// and containing two digits in the numerator and denominator.
///
/// If the product of these four fractions is given in its lowest common terms, find the value of
/// the denominator.
fn main() {
    solutions! {
        sol naive {
            let mut prod = Fraction::one();

            for i in 10..99 {
                for j in (i+1)..99 {
                    let fr = Fraction::new(i, j);
                    if fr.is_curious() {
                        prod = prod * fr;
                    }
                }
            }

            prod
        }
    }
}

#[derive(Debug, Clone)]
struct Fraction {
    numer: i64,
    denom: i64
}

impl Fraction {
    fn new(n: i64, d: i64) -> Fraction {
        Fraction {
            numer: n,
            denom: d
        }
    }

    fn gcd(a: i64, b: i64) -> i64 {
        if a == 0 || b == 0 {
            0
        } else if a == b {
            a
        } else if a > b {
            Fraction::gcd(a - b, b)
        } else {
            Fraction::gcd(a, b - a)
        }
    }

    fn reduced(&self) -> Fraction {
        let gcd = Fraction::gcd(self.numer, self.denom);

        if gcd == 0 {
            Fraction::new(0, 0)
        } else {
            Fraction::new(
                self.numer / gcd,
                self.denom / gcd)
        }
    }

    fn digits(mut a: i64) -> HashSet<u8> {
        let mut r = HashSet::new();
        while a > 0 {
            r.insert((a % 10) as u8);
            a /= 10;
        }

        r
    }

    fn common_digits(&self) -> Vec<u8> {
        Fraction::digits(self.numer).intersection(&Fraction::digits(self.denom)).map(|&a| a).collect()
    }

    fn is_curious(&self) -> bool {
        for &digit in self.common_digits().iter() {
            if digit != 0 {
                if &Fraction::new(self.numer.remove_digit(digit), self.denom.remove_digit(digit)) == self {
                    return true;
                }
            }
        }

        false
    }
}

impl PartialEq for Fraction {
    fn eq(&self, other: &Fraction) -> bool {
        let a = self.reduced();
        let b = other.reduced();

        a.numer == b.numer && a.denom == b.denom
    }
}

impl One for Fraction {
    fn one() -> Fraction {
        Fraction::new(1, 1)
    }
}

impl Mul for Fraction {
    type Output = Fraction;

    fn mul(self, rhs: Fraction) -> Fraction {
        Fraction::new(self.numer * rhs.numer, self.denom * rhs.denom).reduced()
    }
}

trait RemoveDigit {
    fn remove_digit(&self, digit: u8) -> Self;
}

impl RemoveDigit for i64 {
    fn remove_digit(&self, digit: u8) -> i64 {
        format!("{}", self).chars()
            .filter(|c| format!("{}", c) != format!("{}", digit))
            .collect::<String>()
            .parse().ok().unwrap_or(0)
    }
}
<|endoftext|>


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

use libeuler::SieveOfAtkin;
use std::collections::HashSet;
use num::traits::PrimInt;

/// The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and
/// 719, are themselves prime.
///
/// There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
///
/// How many circular primes are there below one million?
fn main() {
    solutions! {
        sol naive {
            let sieve = SieveOfAtkin::new(10_000_000);
            let mut vals = HashSet::new();

            for i in 1..1_000_000 {
                if vals.contains(&i) {
                    continue
                }

                let rots = rotations(i);
                let valid = rots.iter().all(|&v| sieve.is_prime(v as u64));
                if valid {
                    for v in rots.iter() {
                        vals.insert(v.clone());
                    }
                }
            }

            vals.len()
        }
    }
}

fn rotations(i: i64) -> Vec<i64> {
    let digits = (i as f64).log10().floor() as u32 + 1;
    (0..digits).map(|d| (10.pow(d), 10.pow(digits - d))).map(|(d, dig)| {
        let chop = i % d;
        let bottom = i / d;
        bottom + chop * dig
    }).collect()
}
<|endoftext|>


<commit_before><commit_msg>Shift opcodes - Probably wrong<commit_after><|endoftext|>


<commit_before><commit_msg>More documentation, simplify API<commit_after><|endoftext|>


<commit_before><commit_msg>added count_substr<commit_after>// Implements http://rosettacode.org/wiki/Count_occurrences_of_a_substring
// Author : Rahul Sharma
// Github : github.com/creativcoder

fn count_sub_string(src:&str,target:&str) -> usize {
    let mut buff = src.to_string();
    if buff.contains(target) {
      buff = buff.replace(target,"");
    }

    (src.len() - buff.len())/target.len()
}

fn main() {
    let text = "this is three of the four";
    let sub_str = "th";
    println!("{:?}",count_sub_string(text,sub_str));
}
<|endoftext|>


<commit_before><commit_msg>Heavily modified string parsing funcion<commit_after><|endoftext|>


<commit_before><commit_msg>* just be treated as column * to simplify the query struct<commit_after><|endoftext|>


<commit_before><commit_msg>Refactored Endpoint objects away from relay..<commit_after><|endoftext|>


<commit_before><commit_msg>Mutate widgets inside a callback closure<commit_after><|endoftext|>


<commit_before><commit_msg>Start defining integration tests for trait impls.<commit_after>#[macro_use(owned_tree)]
extern crate entmut;

use ::entmut::Nav;
use ::entmut::owned::Tree;
use std::borrow::Borrow;

// This will define macros for generalized tests of Nav and Editor impls.
// #[cfg(test)]
// mod template;

#[test]
#[allow(unused_variables)]
fn nav_instantiation() {
    let t = owned_tree!["a"];
    let v = t.view();
}

#[test]
fn nav_preserves_leaf_topology() {
    let t = owned_tree!["a"];
    let v = t.view();
    assert![v.at_leaf()];
    assert![v.at_root()];
    assert_eq![0, v.child_count()];
}

// #[test]
// fn nav_preserves_leaf_data() {
//     let t = owned_tree!["a"];
//     let t_data_view = &t.data;
//     let v = t.view();
//     let data: &str = v.borrow();
//     assert_eq!["a", data];
//     assert_eq![t_data_view, data];
// }
<|endoftext|>


<commit_before><commit_msg>Added library tests.<commit_after>extern crate exempi;

use exempi::*;
use exempi::xmpstring::XmpString;
use exempi::xmp::Xmp;

#[test]
fn libary_tests() {
    assert!(exempi::init());

    assert!(exempi::get_error() == 0);

    // namespace registration tests.
    let mut prefix = XmpString::new();
    assert!(!prefix.is_null());

    assert!(exempi::register_namespace("http://rust.figuiere.net/ns/rust/",
                                       "rust", &mut prefix));
    assert!(exempi::get_error() == 0);
    assert!(prefix.to_str() != "");
    let mut prefix2 = XmpString::new();
    assert!(exempi::namespace_prefix("http://rust.figuiere.net/ns/rust/",
                                     &mut prefix2));
    assert!(exempi::get_error() == 0);
    assert!(prefix2 == prefix);

    let mut ns = XmpString::new();
    assert!(exempi::prefix_namespace(prefix.to_str(), &mut ns));
    assert!(exempi::get_error() == 0);
    assert!(ns.to_str() == "http://rust.figuiere.net/ns/rust/");

    let mut xmpblock = Xmp::new();
    assert!(!xmpblock.is_null());

    assert!(!xmpblock.has_property("http://rust.figuiere.net/ns/rust/", "test"));
    assert!(xmpblock.set_property("http://rust.figuiere.net/ns/rust/", "test",
                                   "foobar", 0));
    assert!(xmpblock.has_property("http://rust.figuiere.net/ns/rust/", "test"));
    let mut value = XmpString::new();
    let mut optionbits: u32 = 0;
    assert!(xmpblock.get_property("http://rust.figuiere.net/ns/rust/", "test",
                                  &mut value, &mut optionbits));
    assert!(value.to_str() == "foobar");
    assert!(optionbits == 0);

    let mut buffer = XmpString::new();
    // XXX we should use the constants... that we need to define.
    assert!(xmpblock.serialize(&mut buffer, 0x50, 0));
    println!("{}", buffer.to_str());

    exempi::terminate();
}
<|endoftext|>


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

#![macro_escape]

extern crate libc;

#[macro_export]
macro_rules! show_error(
    ($($args:expr),+) => ({
        pipe_write!(&mut ::std::io::stderr(), "{}: error: ", ::NAME);
        pipe_writeln!(&mut ::std::io::stderr(), $($args),+);
    })
)

#[macro_export]
macro_rules! show_warning(
    ($($args:expr),+) => ({
        pipe_write!(&mut ::std::io::stderr(), "{}: warning: ", ::NAME);
        pipe_writeln!(&mut ::std::io::stderr(), $($args),+);
    })
)

#[macro_export]
macro_rules! show_info(
    ($($args:expr),+) => ({
        pipe_write!(&mut ::std::io::stderr(), "{}: ", ::NAME);
        pipe_writeln!(&mut ::std::io::stderr(), $($args),+);
    })
)

#[macro_export]
macro_rules! eprint(
    ($($args:expr),+) => (pipe_write!(&mut ::std::io::stderr(), $($args),+))
)

#[macro_export]
macro_rules! eprintln(
    ($($args:expr),+) => (pipe_writeln!(&mut ::std::io::stderr(), $($args),+))
)

#[macro_export]
macro_rules! crash(
    ($exitcode:expr, $($args:expr),+) => ({
        show_error!($($args),+);
        unsafe { ::util::libc::exit($exitcode as ::util::libc::c_int); }
    })
)

#[macro_export]
macro_rules! exit(
    ($exitcode:expr) => ({
        unsafe { ::util::libc::exit($exitcode); }
    })
)

#[macro_export]
macro_rules! crash_if_err(
    ($exitcode:expr, $exp:expr) => (
        match $exp {
            Ok(m) => m,
            Err(f) => crash!($exitcode, "{}", f.to_string())
        }
    )
)

#[macro_export]
macro_rules! return_if_err(
    ($exitcode:expr, $exp:expr) => (
        match $exp {
            Ok(m) => m,
            Err(f) => {
                show_error!("{}", f);
                return $exitcode;
            }
        }
    )
)

// XXX: should the pipe_* macros return an Err just to show the write failed?

#[macro_export]
macro_rules! pipe_print(
    ($($args:expr),+) => (
        match write!(&mut ::std::io::stdout() as &mut Writer, $($args),+) {
            Ok(_) => true,
            Err(f) => {
                if f.kind == ::std::io::BrokenPipe {
                    false
                } else {
                    fail!("{}", f)
                }
            }
        }
    )
)

#[macro_export]
macro_rules! pipe_println(
    ($($args:expr),+) => (
        match writeln!(&mut ::std::io::stdout() as &mut Writer, $($args),+) {
            Ok(_) => true,
            Err(f) => {
                if f.kind == ::std::io::BrokenPipe {
                    false
                } else {
                    fail!("{}", f)
                }
            }
        }
    )
)

#[macro_export]
macro_rules! pipe_write(
    ($fd:expr, $($args:expr),+) => (
        match write!($fd, $($args),+) {
            Ok(_) => true,
            Err(f) => {
                if f.kind == ::std::io::BrokenPipe {
                    false
                } else {
                    fail!("{}", f)
                }
            }
        }
    )
)

#[macro_export]
macro_rules! pipe_writeln(
    ($fd:expr, $($args:expr),+) => (
        match write!($fd, $($args),+) {
            Ok(_) => true,
            Err(f) => {
                if f.kind == ::std::io::BrokenPipe {
                    false
                } else {
                    fail!("{}", f)
                }
            }
        }
    )
)

#[macro_export]
macro_rules! safe_write(
    ($fd:expr, $($args:expr),+) => (
        match write!($fd, $($args),+) {
            Ok(_) => {}
            Err(f) => fail!(f.to_string())
        }
    )
)

#[macro_export]
macro_rules! safe_writeln(
    ($fd:expr, $($args:expr),+) => (
        match writeln!($fd, $($args),+) {
            Ok(_) => {}
            Err(f) => fail!(f.to_string())
        }
    )
)

#[macro_export]
macro_rules! safe_unwrap(
    ($exp:expr) => (
        match $exp {
            Ok(m) => m,
            Err(f) => crash!(1, "{}", f.to_string())
        }
    )
)
<commit_msg>common/util: make pipe_writeln! use writeln! instead of write!<commit_after>/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Arcterus <arcterus@mail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#![macro_escape]

extern crate libc;

#[macro_export]
macro_rules! show_error(
    ($($args:expr),+) => ({
        pipe_write!(&mut ::std::io::stderr(), "{}: error: ", ::NAME);
        pipe_writeln!(&mut ::std::io::stderr(), $($args),+);
    })
)

#[macro_export]
macro_rules! show_warning(
    ($($args:expr),+) => ({
        pipe_write!(&mut ::std::io::stderr(), "{}: warning: ", ::NAME);
        pipe_writeln!(&mut ::std::io::stderr(), $($args),+);
    })
)

#[macro_export]
macro_rules! show_info(
    ($($args:expr),+) => ({
        pipe_write!(&mut ::std::io::stderr(), "{}: ", ::NAME);
        pipe_writeln!(&mut ::std::io::stderr(), $($args),+);
    })
)

#[macro_export]
macro_rules! eprint(
    ($($args:expr),+) => (pipe_write!(&mut ::std::io::stderr(), $($args),+))
)

#[macro_export]
macro_rules! eprintln(
    ($($args:expr),+) => (pipe_writeln!(&mut ::std::io::stderr(), $($args),+))
)

#[macro_export]
macro_rules! crash(
    ($exitcode:expr, $($args:expr),+) => ({
        show_error!($($args),+);
        unsafe { ::util::libc::exit($exitcode as ::util::libc::c_int); }
    })
)

#[macro_export]
macro_rules! exit(
    ($exitcode:expr) => ({
        unsafe { ::util::libc::exit($exitcode); }
    })
)

#[macro_export]
macro_rules! crash_if_err(
    ($exitcode:expr, $exp:expr) => (
        match $exp {
            Ok(m) => m,
            Err(f) => crash!($exitcode, "{}", f.to_string())
        }
    )
)

#[macro_export]
macro_rules! return_if_err(
    ($exitcode:expr, $exp:expr) => (
        match $exp {
            Ok(m) => m,
            Err(f) => {
                show_error!("{}", f);
                return $exitcode;
            }
        }
    )
)

// XXX: should the pipe_* macros return an Err just to show the write failed?

#[macro_export]
macro_rules! pipe_print(
    ($($args:expr),+) => (
        match write!(&mut ::std::io::stdout() as &mut Writer, $($args),+) {
            Ok(_) => true,
            Err(f) => {
                if f.kind == ::std::io::BrokenPipe {
                    false
                } else {
                    fail!("{}", f)
                }
            }
        }
    )
)

#[macro_export]
macro_rules! pipe_println(
    ($($args:expr),+) => (
        match writeln!(&mut ::std::io::stdout() as &mut Writer, $($args),+) {
            Ok(_) => true,
            Err(f) => {
                if f.kind == ::std::io::BrokenPipe {
                    false
                } else {
                    fail!("{}", f)
                }
            }
        }
    )
)

#[macro_export]
macro_rules! pipe_write(
    ($fd:expr, $($args:expr),+) => (
        match write!($fd, $($args),+) {
            Ok(_) => true,
            Err(f) => {
                if f.kind == ::std::io::BrokenPipe {
                    false
                } else {
                    fail!("{}", f)
                }
            }
        }
    )
)

#[macro_export]
macro_rules! pipe_writeln(
    ($fd:expr, $($args:expr),+) => (
        match writeln!($fd, $($args),+) {
            Ok(_) => true,
            Err(f) => {
                if f.kind == ::std::io::BrokenPipe {
                    false
                } else {
                    fail!("{}", f)
                }
            }
        }
    )
)

#[macro_export]
macro_rules! safe_write(
    ($fd:expr, $($args:expr),+) => (
        match write!($fd, $($args),+) {
            Ok(_) => {}
            Err(f) => fail!(f.to_string())
        }
    )
)

#[macro_export]
macro_rules! safe_writeln(
    ($fd:expr, $($args:expr),+) => (
        match writeln!($fd, $($args),+) {
            Ok(_) => {}
            Err(f) => fail!(f.to_string())
        }
    )
)

#[macro_export]
macro_rules! safe_unwrap(
    ($exp:expr) => (
        match $exp {
            Ok(m) => m,
            Err(f) => crash!(1, "{}", f.to_string())
        }
    )
)
<|endoftext|>


<commit_before><commit_msg>added dataflow example<commit_after>extern crate rand;
extern crate time;
extern crate timely;
extern crate differential_dataflow;

use std::hash::Hash;

use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::progress::timestamp::RootTimestamp;

use rand::{Rng, SeedableRng, StdRng};

use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::operators::join::JoinUnsigned;
use differential_dataflow::operators::group::GroupUnsigned;
use differential_dataflow::collection::LeastUpperBound;

type Node = usize;
type Edge = (Node, Node);

fn main() {

    let users: usize = std::env::args().nth(1).unwrap().parse().unwrap();
    let topics: usize = std::env::args().nth(2).unwrap().parse().unwrap();
    let batch: usize = std::env::args().nth(3).unwrap().parse().unwrap();
    let inspect: bool = std::env::args().nth(4).unwrap() == "inspect";

    // define a new computational scope, in which to run BFS
    timely::execute_from_args(std::env::args().skip(5), move |computation| {
        let start = time::precise_time_s();

        // define BFS dataflow; return handles to roots and edges inputs
        let (mut tweets, mut queries, probe) = computation.scoped(|scope| {

            // entries corresponding to (@username, @mention, #topic), but a (u32, u32, u32) instead.
            let (tweet_input, tweets) = scope.new_input();
            let tweets = Collection::new(tweets);

            // determine connected components based on mentions.
            let labels = connected_components(&tweets.map(|(u,m,_)| (u,m)));

            // produce pairs (label, topic) for each topic.
            let label_topics = tweets.map(|(u,_,t)| (u,t))
                                     .join(&labels)
                                     .map(|(_,t,l)| (l,t));

            // group by (l,t) and emit a count for each.
            let counts = label_topics.map(|x| (x,()))
                                     .group(|_,s,t| {
                                         t.push((s.next().unwrap().1, 1))
                                     });

            let k = 5;
            // retain the k largest counts. negate first to exploit ordering.
            let topk = counts.map(|((l,t), c)| (l, (-c, t)))
                             .group(move |_,s,t| {
                                 t.extend(s.take(k).map(|(&(_,t),_)| (t,1)));
                             });

            // entries corresponding to a @username, but a u32 instead.
            let (query_input, queries) = scope.new_input();
            let queries = Collection::new(queries);

            let label_query = queries.map(|q| (q,()))
                                     .join(&labels)
                                     .map(|(q, _, l)| (l,q));

            let mut query_topics = label_query.join(&topk);

            if !inspect {
                query_topics = query_topics.filter(|_| false);
            }

            let probe = query_topics.consolidate_by(|&(_,q,_)| q)
                                    .inspect(|&((l,q,t),w)| println!("\t(query: {},\tlabel: {},\ttopic:{}\t(weight: {})", q, l, t, w))
                                    .probe();

            (tweet_input, query_input, probe.0)
        });

        let tweet_seed: &[_] = &[0, 1, 2, computation.index()];
        let mut tweet_rng1: StdRng = SeedableRng::from_seed(tweet_seed);    // rng for edge additions
        let mut tweet_rng2: StdRng = SeedableRng::from_seed(tweet_seed);    // rng for edge deletions

        let query_seed: &[_] = &[1, 2, 3, computation.index()];
        let mut query_rng1: StdRng = SeedableRng::from_seed(query_seed);    // rng for edge additions
        let mut query_rng2: StdRng = SeedableRng::from_seed(query_seed);    // rng for edge deletions

        println!("performing AppealingDataflow with {} users, {} topics:", users, topics);

        for _ in 0 .. users/computation.peers() {
            tweets.send(((tweet_rng1.gen_range(0, users),
                          tweet_rng1.gen_range(0, users),
                          tweet_rng1.gen_range(0, topics)),1));
        }

        if computation.index() == 0 {
            queries.send((query_rng1.gen_range(0, users),1));
        }

        println!("loaded; elapsed: {}s", time::precise_time_s() - start);

        tweets.advance_to(1);
        queries.advance_to(1);
        while probe.le(&RootTimestamp::new(0)) { computation.step(); }

        println!("stable; elapsed: {}s", time::precise_time_s() - start);

        if batch > 0 {
            let mut changes = Vec::new();
            for wave in 0.. {
                let mut batch = batch / computation.peers();
                if computation.index() < batch % computation.peers() {
                    batch += 1;
                }

                for _ in 0..batch {
                    changes.push(((tweet_rng1.gen_range(0, users),
                                   tweet_rng1.gen_range(0, users),
                                   tweet_rng1.gen_range(0, topics)), 1));
                    changes.push(((tweet_rng2.gen_range(0, users),
                                   tweet_rng2.gen_range(0, users),
                                   tweet_rng2.gen_range(0, topics)),-1));
                }

                let start = time::precise_time_s();
                let round = *tweets.epoch();
                for change in changes.drain(..) {
                    tweets.send(change);
                }
                if computation.index() == 0 {
                    queries.send((query_rng1.gen_range(0, users), 1));
                    queries.send((query_rng2.gen_range(0, users),-1));
                }

                tweets.advance_to(round + 1);
                queries.advance_to(round + 1);

                while probe.le(&RootTimestamp::new(round)) { computation.step(); }

                if computation.index() == 0 {
                    println!("wave {}: avg {}", wave, (time::precise_time_s() - start) / (batch as f64));
                }
            }
        }
    });
}

fn connected_components<G: Scope>(edges: &Collection<G, Edge>) -> Collection<G, (Node, Node)>
    where G::Timestamp: LeastUpperBound+Hash {

    // each edge (x,y) means that we need at least a label for the min of x and y.
    let nodes = edges.map_in_place(|pair| {
                        let min = std::cmp::min(pair.0, pair.1);
                        *pair = (min, min);
                     })
                     .consolidate_by(|x| x.0);

    // each edge should exist in both directions.
    let edges = edges.map_in_place(|x| ::std::mem::swap(&mut x.0, &mut x.1))
                     .concat(&edges);

    // don't actually use these labels, just grab the type
    nodes.filter(|_| false)
         .iterate(|inner| {
             let edges = edges.enter(&inner.scope());
             let nodes = nodes.enter_at(&inner.scope(), |r| 256 * (64 - (r.0).0.leading_zeros() as u64));

            inner.join_map_u(&edges, |_k,l,d| (*d,*l))
                 .concat(&nodes)
                 .group_u(|_, s, t| { t.push((*s.peek().unwrap().0, 1)); } )
         })
}
<|endoftext|>


<commit_before><commit_msg>Add die-hard example.<commit_after>extern crate suppositions;
use std::cmp::min;
use suppositions::*;
use suppositions::generators::*;

// Run this with:
// ```
// cargo run --example die-hard
// ```
// You should see output of the form:
// ```
// thread 'main' panicked at 'Predicate failed for argument
// Ok([FillBigJug, BigToSmall, EmptySmallJug, BigToSmall, FillBigJug, BigToSmall]);
// check returned Ok(Err(State { big: 4, small: 3 }))', src/properties.rs:56:24
// ```

#[derive(Debug, Clone)]
pub enum Op {
    FillSmallJug,
    FillBigJug,
    EmptySmallJug,
    EmptyBigJug,
    SmallToBig,
    BigToSmall,
}

#[derive(Debug, Default, Clone)]
pub struct State {
    big: usize,
    small: usize,
}

impl State {
    fn apply(&mut self, op: &Op) {
        match op {
            &Op::FillSmallJug => {
                self.small = 3;
            }
            &Op::FillBigJug => self.big = 5,
            &Op::EmptySmallJug => self.small = 0,
            &Op::EmptyBigJug => self.big = 0,
            &Op::SmallToBig => {
                let old = self.clone();
                self.big = min(old.big + self.small, 5);
                self.small -= self.big - old.big
            }

            &Op::BigToSmall => {
                let old = self.clone();
                self.small = min(old.big + self.small, 3);
                self.big -= self.small - old.small
            }
        }
    }

    fn assert_invariants(&self) {
        assert!(self.big <= 5);
        assert!(self.small <= 3);
    }
    fn finished(&self) -> bool {
        self.big == 4
    }
}

fn ops() -> Box<Generator<Item = Op>> {
    let g = one_of(consts(Op::FillSmallJug))
        .or(consts(Op::FillBigJug))
        .or(consts(Op::EmptySmallJug))
        .or(consts(Op::EmptyBigJug))
        .or(consts(Op::SmallToBig))
        .or(consts(Op::BigToSmall));
    Box::new(g)
}

fn main() {
    property(vecs(ops()).mean_length(1000)).check(|xs| {
        let mut sts = Vec::new();
        let mut st = State::default();
        for o in xs.iter() {
            st.apply(o);
            sts.push((o.clone(), st.clone()));
            st.assert_invariants();
            if st.finished() {
                return Err(st);
            }
        }
        return Ok(());
    });

    panic!("No solution found")
}
<|endoftext|>


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

use foo.bar; //~ ERROR expected one of `::`, `;`, or `as`, found `.`
<|endoftext|>


<commit_before><commit_msg>Add test with implemented bits of issue #570.<commit_after>// Issue #570

const lsl : int = 1 << 2;
const add : int = 1 + 2;
const addf : float = 1.0f + 2.0f;
const not : int = !0;
const notb : bool = !true;
const neg : int = -(1);

fn main() {
    assert(lsl == 4);
    assert(add == 3);
    assert(addf == 3.0f);
    assert(not == -1);
    assert(notb == false);
    assert(neg == -1);
}
<|endoftext|>


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

//! Metrics

use std::sync::Arc;

mod counter;
mod gauge;
mod meter;

pub use self::counter::{Counter, CounterSnapshot, StdCounter};
pub use self::gauge::{Gauge, GaugeSnapshot, StdGauge};
pub use self::meter::{Meter, MeterSnapshot, StdMeter};

/// a Metric
use histogram::Histogram;

#[allow(missing_docs)]
pub enum Metric {
    Counter(Arc<Counter>),
    Gauge(Arc<Gauge>),
    Meter(Arc<Meter>),
    Histogram(Histogram),
}
<commit_msg>Derive Clone for Metric<commit_after>// 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.

//! Metrics

use std::sync::Arc;

mod counter;
mod gauge;
mod meter;

pub use self::counter::{Counter, CounterSnapshot, StdCounter};
pub use self::gauge::{Gauge, GaugeSnapshot, StdGauge};
pub use self::meter::{Meter, MeterSnapshot, StdMeter};

/// a Metric
use histogram::Histogram;

#[allow(missing_docs)]
#[derive(Clone)]
pub enum Metric {
    Counter(Arc<Counter>),
    Gauge(Arc<Gauge>),
    Meter(Arc<Meter>),
    Histogram(Histogram),
}
<|endoftext|>


<commit_before><commit_msg>generic float added<commit_after><|endoftext|>


<commit_before><commit_msg>Make generate_variants() more flexible<commit_after><|endoftext|>


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

use std::fs;
use std::path::{PathBuf, Path};
use std::process::Command;

use build_helper::output;

use build::{Build, Compiler};

pub fn linkcheck(build: &Build, stage: u32, host: &str) {
    println!("Linkcheck stage{} ({})", stage, host);
    let compiler = Compiler::new(stage, host);
    build.run(build.tool_cmd(&compiler, "linkchecker")
                   .arg(build.out.join(host).join("doc")));
}

pub fn cargotest(build: &Build, stage: u32, host: &str) {

    let ref compiler = Compiler::new(stage, host);

    // Configure PATH to find the right rustc. NB. we have to use PATH
    // and not RUSTC because the Cargo test suite has tests that will
    // fail if rustc is not spelled `rustc`.
    let path = build.sysroot(compiler).join("bin");
    let old_path = ::std::env::var("PATH").expect("");
    let sep = if cfg!(windows) { ";" } else {":" };
    let ref newpath = format!("{}{}{}", path.display(), sep, old_path);

    // Note that this is a short, cryptic, and not scoped directory name. This
    // is currently to minimize the length of path on Windows where we otherwise
    // quickly run into path name limit constraints.
    let out_dir = build.out.join("ct");
    t!(fs::create_dir_all(&out_dir));

    build.run(build.tool_cmd(compiler, "cargotest")
                   .env("PATH", newpath)
                   .arg(&build.cargo)
                   .arg(&out_dir));
}

pub fn tidy(build: &Build, stage: u32, host: &str) {
    println!("tidy check stage{} ({})", stage, host);
    let compiler = Compiler::new(stage, host);
    build.run(build.tool_cmd(&compiler, "tidy")
                   .arg(build.src.join("src")));
}

fn testdir(build: &Build, host: &str) -> PathBuf {
    build.out.join(host).join("test")
}

pub fn compiletest(build: &Build,
                   compiler: &Compiler,
                   target: &str,
                   mode: &str,
                   suite: &str) {
    let mut cmd = build.tool_cmd(compiler, "compiletest");

    cmd.arg("--compile-lib-path").arg(build.rustc_libdir(compiler));
    cmd.arg("--run-lib-path").arg(build.sysroot_libdir(compiler, target));
    cmd.arg("--rustc-path").arg(build.compiler_path(compiler));
    cmd.arg("--rustdoc-path").arg(build.rustdoc(compiler));
    cmd.arg("--src-base").arg(build.src.join("src/test").join(suite));
    cmd.arg("--aux-base").arg(build.src.join("src/test/auxiliary"));
    cmd.arg("--build-base").arg(testdir(build, compiler.host).join(suite));
    cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
    cmd.arg("--mode").arg(mode);
    cmd.arg("--target").arg(target);
    cmd.arg("--host").arg(compiler.host);
    cmd.arg("--llvm-filecheck").arg(build.llvm_filecheck(&build.config.build));

    let linkflag = format!("-Lnative={}", build.test_helpers_out(target).display());
    cmd.arg("--host-rustcflags").arg("-Crpath");
    cmd.arg("--target-rustcflags").arg(format!("-Crpath {}", linkflag));

    // FIXME: needs android support
    cmd.arg("--android-cross-path").arg("");

    // FIXME: CFG_PYTHON should probably be detected more robustly elsewhere
    let python_default = "python";
    cmd.arg("--docck-python").arg(python_default);

    if build.config.build.ends_with("apple-darwin") {
        // Force /usr/bin/python on OSX for LLDB tests because we're loading the
        // LLDB plugin's compiled module which only works with the system python
        // (namely not Homebrew-installed python)
        cmd.arg("--lldb-python").arg("/usr/bin/python");
    } else {
        cmd.arg("--lldb-python").arg(python_default);
    }

    if let Some(ref vers) = build.gdb_version {
        cmd.arg("--gdb-version").arg(vers);
    }
    if let Some(ref vers) = build.lldb_version {
        cmd.arg("--lldb-version").arg(vers);
    }
    if let Some(ref dir) = build.lldb_python_dir {
        cmd.arg("--lldb-python-dir").arg(dir);
    }

    cmd.args(&build.flags.args);

    if build.config.verbose || build.flags.verbose {
        cmd.arg("--verbose");
    }

    if suite == "run-make" {
        let llvm_config = build.llvm_config(target);
        let llvm_components = output(Command::new(&llvm_config).arg("--components"));
        let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
        cmd.arg("--cc").arg(build.cc(target))
           .arg("--cxx").arg(build.cxx(target))
           .arg("--cflags").arg(build.cflags(target).join(" "))
           .arg("--llvm-components").arg(llvm_components.trim())
           .arg("--llvm-cxxflags").arg(llvm_cxxflags.trim());
    } else {
        cmd.arg("--cc").arg("")
           .arg("--cxx").arg("")
           .arg("--cflags").arg("")
           .arg("--llvm-components").arg("")
           .arg("--llvm-cxxflags").arg("");
    }

    // Running a C compiler on MSVC requires a few env vars to be set, to be
    // sure to set them here.
    if target.contains("msvc") {
        for &(ref k, ref v) in build.cc[target].0.env() {
            if k != "PATH" {
                cmd.env(k, v);
            }
        }
    }

    build.run(&mut cmd);
}

pub fn docs(build: &Build, compiler: &Compiler) {
    let mut stack = vec![build.src.join("src/doc")];

    while let Some(p) = stack.pop() {
        if p.is_dir() {
            stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
            continue
        }

        if p.extension().and_then(|s| s.to_str()) != Some("md") {
            continue
        }

        println!("doc tests for: {}", p.display());
        markdown_test(build, compiler, &p);
    }
}

pub fn error_index(build: &Build, compiler: &Compiler) {
    println!("Testing error-index stage{}", compiler.stage);

    let output = testdir(build, compiler.host).join("error-index.md");
    build.run(build.tool_cmd(compiler, "error_index_generator")
                   .arg("markdown")
                   .arg(&output)
                   .env("CFG_BUILD", &build.config.build));

    markdown_test(build, compiler, &output);
}

fn markdown_test(build: &Build, compiler: &Compiler, markdown: &Path) {
    let mut cmd = Command::new(build.rustdoc(compiler));
    build.add_rustc_lib_path(compiler, &mut cmd);
    cmd.arg("--test");
    cmd.arg(markdown);
    cmd.arg("--test-args").arg(build.flags.args.join(" "));
    build.run(&mut cmd);
}
<commit_msg>remove unused aux-base argument<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::fs;
use std::path::{PathBuf, Path};
use std::process::Command;

use build_helper::output;

use build::{Build, Compiler};

pub fn linkcheck(build: &Build, stage: u32, host: &str) {
    println!("Linkcheck stage{} ({})", stage, host);
    let compiler = Compiler::new(stage, host);
    build.run(build.tool_cmd(&compiler, "linkchecker")
                   .arg(build.out.join(host).join("doc")));
}

pub fn cargotest(build: &Build, stage: u32, host: &str) {

    let ref compiler = Compiler::new(stage, host);

    // Configure PATH to find the right rustc. NB. we have to use PATH
    // and not RUSTC because the Cargo test suite has tests that will
    // fail if rustc is not spelled `rustc`.
    let path = build.sysroot(compiler).join("bin");
    let old_path = ::std::env::var("PATH").expect("");
    let sep = if cfg!(windows) { ";" } else {":" };
    let ref newpath = format!("{}{}{}", path.display(), sep, old_path);

    // Note that this is a short, cryptic, and not scoped directory name. This
    // is currently to minimize the length of path on Windows where we otherwise
    // quickly run into path name limit constraints.
    let out_dir = build.out.join("ct");
    t!(fs::create_dir_all(&out_dir));

    build.run(build.tool_cmd(compiler, "cargotest")
                   .env("PATH", newpath)
                   .arg(&build.cargo)
                   .arg(&out_dir));
}

pub fn tidy(build: &Build, stage: u32, host: &str) {
    println!("tidy check stage{} ({})", stage, host);
    let compiler = Compiler::new(stage, host);
    build.run(build.tool_cmd(&compiler, "tidy")
                   .arg(build.src.join("src")));
}

fn testdir(build: &Build, host: &str) -> PathBuf {
    build.out.join(host).join("test")
}

pub fn compiletest(build: &Build,
                   compiler: &Compiler,
                   target: &str,
                   mode: &str,
                   suite: &str) {
    let mut cmd = build.tool_cmd(compiler, "compiletest");

    cmd.arg("--compile-lib-path").arg(build.rustc_libdir(compiler));
    cmd.arg("--run-lib-path").arg(build.sysroot_libdir(compiler, target));
    cmd.arg("--rustc-path").arg(build.compiler_path(compiler));
    cmd.arg("--rustdoc-path").arg(build.rustdoc(compiler));
    cmd.arg("--src-base").arg(build.src.join("src/test").join(suite));
    cmd.arg("--build-base").arg(testdir(build, compiler.host).join(suite));
    cmd.arg("--stage-id").arg(format!("stage{}-{}", compiler.stage, target));
    cmd.arg("--mode").arg(mode);
    cmd.arg("--target").arg(target);
    cmd.arg("--host").arg(compiler.host);
    cmd.arg("--llvm-filecheck").arg(build.llvm_filecheck(&build.config.build));

    let linkflag = format!("-Lnative={}", build.test_helpers_out(target).display());
    cmd.arg("--host-rustcflags").arg("-Crpath");
    cmd.arg("--target-rustcflags").arg(format!("-Crpath {}", linkflag));

    // FIXME: needs android support
    cmd.arg("--android-cross-path").arg("");

    // FIXME: CFG_PYTHON should probably be detected more robustly elsewhere
    let python_default = "python";
    cmd.arg("--docck-python").arg(python_default);

    if build.config.build.ends_with("apple-darwin") {
        // Force /usr/bin/python on OSX for LLDB tests because we're loading the
        // LLDB plugin's compiled module which only works with the system python
        // (namely not Homebrew-installed python)
        cmd.arg("--lldb-python").arg("/usr/bin/python");
    } else {
        cmd.arg("--lldb-python").arg(python_default);
    }

    if let Some(ref vers) = build.gdb_version {
        cmd.arg("--gdb-version").arg(vers);
    }
    if let Some(ref vers) = build.lldb_version {
        cmd.arg("--lldb-version").arg(vers);
    }
    if let Some(ref dir) = build.lldb_python_dir {
        cmd.arg("--lldb-python-dir").arg(dir);
    }

    cmd.args(&build.flags.args);

    if build.config.verbose || build.flags.verbose {
        cmd.arg("--verbose");
    }

    if suite == "run-make" {
        let llvm_config = build.llvm_config(target);
        let llvm_components = output(Command::new(&llvm_config).arg("--components"));
        let llvm_cxxflags = output(Command::new(&llvm_config).arg("--cxxflags"));
        cmd.arg("--cc").arg(build.cc(target))
           .arg("--cxx").arg(build.cxx(target))
           .arg("--cflags").arg(build.cflags(target).join(" "))
           .arg("--llvm-components").arg(llvm_components.trim())
           .arg("--llvm-cxxflags").arg(llvm_cxxflags.trim());
    } else {
        cmd.arg("--cc").arg("")
           .arg("--cxx").arg("")
           .arg("--cflags").arg("")
           .arg("--llvm-components").arg("")
           .arg("--llvm-cxxflags").arg("");
    }

    // Running a C compiler on MSVC requires a few env vars to be set, to be
    // sure to set them here.
    if target.contains("msvc") {
        for &(ref k, ref v) in build.cc[target].0.env() {
            if k != "PATH" {
                cmd.env(k, v);
            }
        }
    }

    build.run(&mut cmd);
}

pub fn docs(build: &Build, compiler: &Compiler) {
    let mut stack = vec![build.src.join("src/doc")];

    while let Some(p) = stack.pop() {
        if p.is_dir() {
            stack.extend(t!(p.read_dir()).map(|p| t!(p).path()));
            continue
        }

        if p.extension().and_then(|s| s.to_str()) != Some("md") {
            continue
        }

        println!("doc tests for: {}", p.display());
        markdown_test(build, compiler, &p);
    }
}

pub fn error_index(build: &Build, compiler: &Compiler) {
    println!("Testing error-index stage{}", compiler.stage);

    let output = testdir(build, compiler.host).join("error-index.md");
    build.run(build.tool_cmd(compiler, "error_index_generator")
                   .arg("markdown")
                   .arg(&output)
                   .env("CFG_BUILD", &build.config.build));

    markdown_test(build, compiler, &output);
}

fn markdown_test(build: &Build, compiler: &Compiler, markdown: &Path) {
    let mut cmd = Command::new(build.rustdoc(compiler));
    build.add_rustc_lib_path(compiler, &mut cmd);
    cmd.arg("--test");
    cmd.arg(markdown);
    cmd.arg("--test-args").arg(build.flags.args.join(" "));
    build.run(&mut cmd);
}
<|endoftext|>


<commit_before><commit_msg>Scheduler API changed allowing to peek next action<commit_after><|endoftext|>


<commit_before><commit_msg>:art: Refactor the return value for the method of fetch_completed_tasks<commit_after><|endoftext|>


<commit_before>// Copyright 2017 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Graphics pipeline descriptor.

use {state as s};
use super::EntryPoint;
use super::input_assembler::{AttributeDesc, InputAssemblerDesc, VertexBufferDesc};
use super::output_merger::{ColorInfo, DepthStencilDesc};

// Vulkan:
//  - SpecializationInfo not provided per shader
//  - TODO: infer rasterization discard from shaders?
//
// D3D12:
//  - rootSignature specified outside
//  - logicOp can be set for each RTV
//  - streamOutput not included
//  - IA: semantic name and index extracted from shader reflection

/// A complete set of shaders to build a graphics pipeline.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct GraphicsShaderSet {
    ///
    pub vertex_shader: EntryPoint,
    ///
    pub hull_shader: Option<EntryPoint>,
    ///
    pub domain_shader: Option<EntryPoint>,
    ///
    pub geometry_shader: Option<EntryPoint>,
    ///
    pub pixel_shader: Option<EntryPoint>,
}

///
pub struct GraphicsPipelineDesc {
    /// Rasterizer setup
    pub rasterizer: Rasterizer,
    /// Shader entry points
    pub shader_entries: GraphicsShaderSet,

    /// Vertex buffers (IA)
    pub vertex_buffers: Vec<VertexBufferDesc>,
    /// Vertex attributes (IA)
    pub attributes: Vec<AttributeDesc>,
    ///
    pub input_assembler: InputAssemblerDesc,

    ///
    pub blending: Vec<BlendDesc>,
    /// Depth stencil (DSV)
    pub depth_stencil: Option<DepthStencilDesc>,
}

///
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature="serialize", derive(Serialize, Deserialize))]
pub struct DepthBias {
    ///
    pub const_factor: f32,
    ///
    pub clamp: f32,
    ///
    pub slope_factor: f32,
}

/// Rasterization state.
#[derive(Clone, Debug)]
#[cfg_attr(feature="serialize", derive(Serialize, Deserialize))]
pub struct Rasterizer {
    /// How to rasterize this primitive.
    pub polgyon_mode: s::RasterMethod,
    /// Which face should be culled.
    pub cull_mode: s::CullFace,
    /// Which vertex winding is considered to be the front face for culling.
    pub front_face: s::FrontFace,
    ///
    pub depth_clamping: bool,
    ///
    pub depth_bias: Option<DepthBias>,
    ///
    pub conservative_rasterization: bool,
}

///
pub enum BlendTargets {
    ///
    Single(ColorInfo),
    ///
    Independent(Vec<ColorInfo>),
}

///
pub struct BlendDesc {
    ///
    pub alpha_coverage: bool,
    ///
    pub logic_op: Option<LogicOp>,
    ///
    pub blend_targets: BlendTargets,
}

///
pub enum LogicOp {
    ///
    Clear,
    ///
    And,
    ///
    AndReverse,
    ///
    AndInverted,
    ///
    Copy,
    ///
    CopyInverted,
    ///
    NoOp,
    ///
    Xor,
    ///
    Nor,
    ///
    Or,
    ///
    OrReverse,
    ///
    OrInverted,
    ///
    Equivalent,
    ///
    Invert,
    ///
    Nand,
    ///
    Set,
}
<commit_msg>[ll] core: Add feature flag to discard primitives before the rasterizer stage (pso)<commit_after>// Copyright 2017 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Graphics pipeline descriptor.

use {state as s};
use super::EntryPoint;
use super::input_assembler::{AttributeDesc, InputAssemblerDesc, VertexBufferDesc};
use super::output_merger::{ColorInfo, DepthStencilDesc};

// Vulkan:
//  - SpecializationInfo not provided per shader
//
// D3D12:
//  - rootSignature specified outside
//  - logicOp can be set for each RTV
//  - streamOutput not included
//  - IA: semantic name and index extracted from shader reflection

/// A complete set of shaders to build a graphics pipeline.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct GraphicsShaderSet {
    ///
    pub vertex_shader: EntryPoint,
    ///
    pub hull_shader: Option<EntryPoint>,
    ///
    pub domain_shader: Option<EntryPoint>,
    ///
    pub geometry_shader: Option<EntryPoint>,
    ///
    pub pixel_shader: Option<EntryPoint>,
}

///
pub struct GraphicsPipelineDesc {
    /// Rasterizer setup
    pub rasterizer: Rasterizer,
    /// Shader entry points
    pub shader_entries: GraphicsShaderSet,

    /// Vertex buffers (IA)
    pub vertex_buffers: Vec<VertexBufferDesc>,
    /// Vertex attributes (IA)
    pub attributes: Vec<AttributeDesc>,
    ///
    pub input_assembler: InputAssemblerDesc,

    ///
    pub blending: Vec<BlendDesc>,
    /// Depth stencil (DSV)
    pub depth_stencil: Option<DepthStencilDesc>,
}

///
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature="serialize", derive(Serialize, Deserialize))]
pub struct DepthBias {
    ///
    pub const_factor: f32,
    ///
    pub clamp: f32,
    ///
    pub slope_factor: f32,
}

/// Rasterization state.
#[derive(Clone, Debug)]
#[cfg_attr(feature="serialize", derive(Serialize, Deserialize))]
pub struct Rasterizer {
    /// How to rasterize this primitive.
    pub polgyon_mode: s::RasterMethod,
    /// Which face should be culled.
    pub cull_mode: s::CullFace,
    /// Which vertex winding is considered to be the front face for culling.
    pub front_face: s::FrontFace,
    ///
    pub depth_clamping: bool,
    ///
    pub depth_bias: Option<DepthBias>,
    ///
    pub conservative_rasterization: bool,
    /// Discard primitives before the rasterizer.
    pub rasterizer_discard: bool,
}

///
pub enum BlendTargets {
    /// All attachments share the same blend state.
    Single(ColorInfo),
    /// All attachments have independt blend states.
    Independent(Vec<ColorInfo>),
}

///
pub struct BlendDesc {
    ///
    pub alpha_coverage: bool,
    ///
    pub logic_op: Option<LogicOp>,
    ///
    pub blend_targets: BlendTargets,
}

///
pub enum LogicOp {
    ///
    Clear,
    ///
    And,
    ///
    AndReverse,
    ///
    AndInverted,
    ///
    Copy,
    ///
    CopyInverted,
    ///
    NoOp,
    ///
    Xor,
    ///
    Nor,
    ///
    Or,
    ///
    OrReverse,
    ///
    OrInverted,
    ///
    Equivalent,
    ///
    Invert,
    ///
    Nand,
    ///
    Set,
}
<|endoftext|>


<commit_before><commit_msg>start hacking together a backtrace hack module.<commit_after>use libc::{c_char, c_int, c_void};
use std::mem;
use std::ptr;

extern {
    fn backtrace(buffer: *mut *mut c_void, size: c_int) -> c_int;
    fn backtrace_symbols(buffer: *mut *const c_void, size: c_int) -> *mut *mut c_char;
    fn backtrace_symbols_fd(buffer: *mut *const c_void, size: c_int, fd: c_int);
}

pub fn stack_height() -> usize {
    let local: u32 = 0;
    let height = &local as *const _ as usize;
    super::main_height() - height
}

pub fn backtrace_return_addresses() -> Vec<*const c_void> {
    let height = stack_height();
    let word_size = mem::size_of::<usize>();
    let rounded_height = (height + (word_size - 1)) / word_size;
    assert!(rounded_height >= 0);
    assert!(rounded_height <= ::std::i32::MAX as usize);
    let mut buffer = vec![ptr::null(); rounded_height];
    let rounded_height = rounded_height as i32;
    unsafe {
        let filled_size = backtrace(buffer.as_mut_ptr() as *mut *mut c_void,
                                    rounded_height);
        assert!(filled_size >= 0);
        buffer.set_len(filled_size as usize);
    }
    buffer
}
<|endoftext|>


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

// FIXME - This test gives different results on different machines.
fn invoke<'a, F>(x: &'a i32, f: F) -> &'a i32
where F: FnOnce(&'a i32, &i32) -> &'a i32
{
    let y = 22;
    f(x, &y)
}

fn foo<'a>(x: &'a i32) { //~ ERROR E0495
    invoke(&x, |a, b| if a > b { a } else { b });
}

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

// Test that we give the generic E0495 when one of the free regions is
// bound in a closure (rather than suggesting a change to the signature
// of the closure, which is not specified in `foo` but rather in `invoke`).

// FIXME - This might be better as a UI test, but the finer details
// of the error seem to vary on different machines.
fn invoke<'a, F>(x: &'a i32, f: F) -> &'a i32
where F: FnOnce(&'a i32, &i32) -> &'a i32
{
    let y = 22;
    f(x, &y)
}

fn foo<'a>(x: &'a i32) { //~ ERROR E0495
    invoke(&x, |a, b| if a > b { a } else { b });
}

fn main() {}
<|endoftext|>