<commit_before>use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::result::Result;
use std::path::{Path, PathBuf};
use std::convert::From;
use std::convert::Into;

#[derive(Debug)]
#[derive(Clone)]
// #[derive(Display)]
pub enum FileIDType {
    UUID,
}

#[derive(Clone)]
pub struct FileID {
    id: Option<String>,
    id_type: FileIDType,
}

impl FileID {

    pub fn new(id_type: FileIDType, id: String) -> FileID {
        FileID {
            id: Some(id),
            id_type: id_type,
        }
    }

    pub fn is_valid(&self) -> bool {
        self.id.is_some()
    }

}

impl Debug for FileID {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "FileID[{:?}]: {:?}",
               self.id_type,
               self.id);
        Ok(())
    }

}

impl Display for FileID {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "FileID[{:?}]: {:?}",
               self.id_type,
               self.id);
        Ok(())
    }

}

impl Into<String> for FileID {

    fn into(self) -> String {
        if let Some(id) = self.id {
            id.clone()
        } else {
            String::from("INVALID")
        }
    }

}

impl From<String> for FileID {

    fn from(s: String) -> FileID {
        unimplemented!()
    }

}

impl<'a> From<&'a String> for FileID {

    fn from(s: &'a String) -> FileID {
        unimplemented!()
    }

}

impl From<PathBuf> for FileID {

    fn from(s: PathBuf) -> FileID {
        unimplemented!()
    }

}

impl<'a> From<&'a PathBuf> for FileID {

    fn from(s: &'a PathBuf) -> FileID {
        unimplemented!()
    }

}

pub struct FileIDError {
    summary: String,
    descrip: String,
}

impl FileIDError {

    pub fn new(s: String, d: String) -> FileIDError {
        FileIDError {
            summary: s,
            descrip: d,
        }
    }

}

impl<'a> Error for FileIDError {

    fn description(&self) -> &str {
        &self.summary[..]
    }

    fn cause(&self) -> Option<&Error> {
        None
    }

}

impl<'a> Debug for FileIDError {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "FileIDError: '{}'\n{}", self.summary, self.descrip);
        Ok(())
    }

}

impl<'a> Display for FileIDError {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "FileIDError: '{}'", self.summary);
        Ok(())
    }

}

pub type FileIDResult = Result<FileID, FileIDError>;

<commit_msg>Add test: file_id_from_string()<commit_after>use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use std::result::Result;
use std::path::{Path, PathBuf};
use std::convert::From;
use std::convert::Into;

#[derive(Debug)]
#[derive(Clone)]
// #[derive(Display)]
pub enum FileIDType {
    UUID,
}

#[derive(Clone)]
pub struct FileID {
    id: Option<String>,
    id_type: FileIDType,
}

impl FileID {

    pub fn new(id_type: FileIDType, id: String) -> FileID {
        FileID {
            id: Some(id),
            id_type: id_type,
        }
    }

    pub fn is_valid(&self) -> bool {
        self.id.is_some()
    }

}

impl Debug for FileID {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "FileID[{:?}]: {:?}",
               self.id_type,
               self.id);
        Ok(())
    }

}

impl Display for FileID {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "FileID[{:?}]: {:?}",
               self.id_type,
               self.id);
        Ok(())
    }

}

impl Into<String> for FileID {

    fn into(self) -> String {
        if let Some(id) = self.id {
            id.clone()
        } else {
            String::from("INVALID")
        }
    }

}

impl From<String> for FileID {

    fn from(s: String) -> FileID {
        unimplemented!()
    }

}

impl<'a> From<&'a String> for FileID {

    fn from(s: &'a String) -> FileID {
        unimplemented!()
    }

}

impl From<PathBuf> for FileID {

    fn from(s: PathBuf) -> FileID {
        unimplemented!()
    }

}

impl<'a> From<&'a PathBuf> for FileID {

    fn from(s: &'a PathBuf) -> FileID {
        unimplemented!()
    }

}

pub struct FileIDError {
    summary: String,
    descrip: String,
}

impl FileIDError {

    pub fn new(s: String, d: String) -> FileIDError {
        FileIDError {
            summary: s,
            descrip: d,
        }
    }

}

impl<'a> Error for FileIDError {

    fn description(&self) -> &str {
        &self.summary[..]
    }

    fn cause(&self) -> Option<&Error> {
        None
    }

}

impl<'a> Debug for FileIDError {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "FileIDError: '{}'\n{}", self.summary, self.descrip);
        Ok(())
    }

}

impl<'a> Display for FileIDError {

    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        write!(fmt, "FileIDError: '{}'", self.summary);
        Ok(())
    }

}

pub type FileIDResult = Result<FileID, FileIDError>;

#[cfg(test)]
mod test {

    use super::{FileID, FileIDType};

    #[test]
    fn file_id_from_string() {
        setup_logger();

        let s1 = String::from("/home/user/testmodule-UUID-some-id.imag");
        let s2 = String::from("/home/user/testmodule-UUID-some-id.extension.imag");
        let s3 = String::from("/home/user/testmodule-NOHASH-some-id.imag");

        let id1 = FileID::from(s1);
        let id2 = FileID::from(s2);
        let id3 = FileID::from(s3);

        println!("Id 1 : {:?}", id1);
        println!("Id 2 : {:?}", id2);
        println!("Id 3 : {:?}", id3);

        assert_eq!(FileIDType::UUID, id1.get_type());
        assert_eq!(FileIDType::UUID, id2.get_type());
        assert_eq!(FileIDType::NONE, id3.get_type());

        let f1 : String = id1.into();
        let f2 : String = id2.into();
        let f3 : String = id3.into();

        assert_eq!(String::from("some-id"), f1);
        assert_eq!(String::from("some-id"), f2);
        assert_eq!(String::from("INVALID"), f3);
    }

    fn setup_logger() {
        extern crate log;
        use log::{LogLevelFilter, set_logger};
        use runtime::ImagLogger;

        log::set_logger(|max_log_lvl| {
            let lvl = LogLevelFilter::Debug;
            max_log_lvl.set(lvl);
            Box::new(ImagLogger::new(lvl.to_log_level().unwrap()))
        });
        debug!("Init logger for test");
    }

}

<|endoftext|>


<commit_before><commit_msg>Added audio_driver example<commit_after>extern crate emu;

use emu::audio_driver::{AudioDriver, RenderCallback};
use emu::audio_driver_factory::create_default;

use std::f64::consts::PI;

use std::thread;

struct TestUserResource {
    name: String,
    phase: f64
}

impl TestUserResource {
    fn new(name: String) -> TestUserResource {
        println!("Test user resource created ({})", name);
        TestUserResource { name: name, phase: 0.0 }
    }
}

impl Drop for TestUserResource {
    fn drop(&mut self) {
        println!("Test user resource destroyed ({})", self.name);
    }
}

fn main() {
    let mut driver = {
        let mut test_user_resource = TestUserResource::new(String::from("a"));
        let callback: Box<RenderCallback> = Box::new(move |buffer, num_frames| {
            for i in 0..num_frames {
                let value = (test_user_resource.phase * PI).sin() as f32;
                let buffer_index = i * 2;
                buffer[buffer_index + 0] = value;
                buffer[buffer_index + 1] = value;
                test_user_resource.phase += 440.0 / 44100.0;
            }
        });

        let mut ret = create_default();
        ret.set_render_callback(Some(callback));
        ret
    };

    println!("All systems are go.");

    println!("Starting render callback tests.");
    thread::sleep_ms(1000);

    println!("Swapping callback...");

    {
        let mut test_user_resource = TestUserResource::new(String::from("b"));
        let callback: Box<RenderCallback> = Box::new(move |buffer, num_frames| {
            for i in 0..num_frames {
                let value = (test_user_resource.phase * 2.0 * PI).sin() as f32;
                let buffer_index = i * 2;
                buffer[buffer_index + 0] = value;
                buffer[buffer_index + 1] = value;
                test_user_resource.phase += 440.0 / 44100.0;
            }
        });

        driver.set_render_callback(Some(callback));
    }

    println!("Callback swapped");
    thread::sleep_ms(1000);

    println!("Render callback tests completed.");

    println!("Starting is enabled tests.");

    println!("Driver is enabled: {}", driver.is_enabled());
    thread::sleep_ms(1000);

    driver.set_is_enabled(false);
    println!("Driver is enabled: {}", driver.is_enabled());
    thread::sleep_ms(1000);

    driver.set_is_enabled(true);
    println!("Driver is enabled: {}", driver.is_enabled());
    thread::sleep_ms(1000);

    println!("Is enabled tests completed.");

    println!("Starting sample rate tests.");

    println!("Driver sample rate: {}", driver.sample_rate());
    thread::sleep_ms(1000);

    driver.set_sample_rate(32000);
    println!("Driver sample rate: {}", driver.sample_rate());
    thread::sleep_ms(1000);

    driver.set_sample_rate(22050);
    println!("Driver sample rate: {}", driver.sample_rate());
    thread::sleep_ms(1000);

    driver.set_sample_rate(11025);
    println!("Driver sample rate: {}", driver.sample_rate());
    thread::sleep_ms(1000);

    driver.set_sample_rate(96000);
    println!("Driver sample rate: {}", driver.sample_rate());
    thread::sleep_ms(1000);

    driver.set_sample_rate(44100);
    println!("Driver sample rate: {}", driver.sample_rate());
    thread::sleep_ms(1000);

    println!("Sample rate tests completed.");

    //let mut derp = String::new();
    //io::stdin().read_line(&mut derp).ok();
}
<|endoftext|>


<commit_before>// Copyright 2012 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-test FIXME #2263
// xfail-fast
// This test had to do with an outdated version of the iterable trait.
// However, the condition it was testing seemed complex enough to
// warrant still having a test, so I inlined the old definitions.

trait iterable<A> {
    fn iter(blk: &fn(A));
}

impl<A> iterable<A> for @fn(&fn(A)) {
    fn iter(blk: &fn(A)) { self(blk); }
}

impl iterable<uint> for @fn(&fn(uint)) {
    fn iter(blk: &fn(&&v: uint)) { self( |i| blk(i) ) }
}

fn filter<A,IA:iterable<A>>(self: IA, prd: @fn(A) -> bool, blk: &fn(A)) {
    do self.iter |a| {
        if prd(a) { blk(a) }
    }
}

fn foldl<A,B,IA:iterable<A>>(self: IA, b0: B, blk: &fn(B, A) -> B) -> B {
    let mut b = b0;
    do self.iter |a| {
        b = blk(b, a);
    }
    b
}

fn range(lo: uint, hi: uint, it: &fn(uint)) {
    let mut i = lo;
    while i < hi {
        it(i);
        i += 1u;
    }
}

pub fn main() {
    let range: @fn(&fn(uint)) = |a| range(0u, 1000u, a);
    let filt: @fn(&fn(v: uint)) = |a| filter(
        range,
        |&&n: uint| n % 3u != 0u && n % 5u != 0u,
        a);
    let sum = foldl(filt, 0u, |accum, &&n: uint| accum + n );

    io::println(fmt!("%u", sum));
}
<commit_msg>fixed up issue-2185, but now it has a trait failure<commit_after>// Copyright 2012 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.

// does the second one subsume the first?
// xfail-test
// xfail-fast

// notes on this test case:
// On Thu, Apr 18, 2013 at 6:30 PM, John Clements <clements@brinckerhoff.org> wrote:
// the "issue-2185.rs" test was xfailed with a ref to #2263. Issue #2263 is now fixed, so I tried it again, and after adding some &self parameters, I got this error:
//
// Running /usr/local/bin/rustc:
// issue-2185.rs:24:0: 26:1 error: conflicting implementations for a trait
// issue-2185.rs:24 impl iterable<uint> for @fn(&fn(uint)) {
// issue-2185.rs:25     fn iter(&self, blk: &fn(v: uint)) { self( |i| blk(i) ) }
// issue-2185.rs:26 }
// issue-2185.rs:20:0: 22:1 note: note conflicting implementation here
// issue-2185.rs:20 impl<A> iterable<A> for @fn(&fn(A)) {
// issue-2185.rs:21     fn iter(&self, blk: &fn(A)) { self(blk); }
// issue-2185.rs:22 }
//
// … so it looks like it's just not possible to implement both the generic iterable<uint> and iterable<A> for the type iterable<uint>. Is it okay if I just remove this test?
//
// but Niko responded:
// think it's fine to remove this test, just because it's old and cruft and not hard to reproduce. *However* it should eventually be possible to implement the same interface for the same type multiple times with different type parameters, it's just that our current trait implementation has accidental limitations.

// so I'm leaving it in.

// This test had to do with an outdated version of the iterable trait.
// However, the condition it was testing seemed complex enough to
// warrant still having a test, so I inlined the old definitions.

trait iterable<A> {
    fn iter(&self, blk: &fn(A));
}

impl<A> iterable<A> for @fn(&fn(A)) {
    fn iter(&self, blk: &fn(A)) { self(blk); }
}

impl iterable<uint> for @fn(&fn(uint)) {
    fn iter(&self, blk: &fn(v: uint)) { self( |i| blk(i) ) }
}

fn filter<A,IA:iterable<A>>(self: IA, prd: @fn(A) -> bool, blk: &fn(A)) {
    do self.iter |a| {
        if prd(a) { blk(a) }
    }
}

fn foldl<A,B,IA:iterable<A>>(self: IA, b0: B, blk: &fn(B, A) -> B) -> B {
    let mut b = b0;
    do self.iter |a| {
        b = blk(b, a);
    }
    b
}

fn range(lo: uint, hi: uint, it: &fn(uint)) {
    let mut i = lo;
    while i < hi {
        it(i);
        i += 1u;
    }
}

pub fn main() {
    let range: @fn(&fn(uint)) = |a| range(0u, 1000u, a);
    let filt: @fn(&fn(v: uint)) = |a| filter(
        range,
        |&&n: uint| n % 3u != 0u && n % 5u != 0u,
        a);
    let sum = foldl(filt, 0u, |accum, &&n: uint| accum + n );

    io::println(fmt!("%u", sum));
}
<|endoftext|>


<commit_before><commit_msg>want to do<commit_after><|endoftext|>


<commit_before><commit_msg>feat: add support for reverse binding between PUB and SUB<commit_after>mod async_helpers;
use std::error::Error;
use zeromq::prelude::*;

#[async_helpers::main]
async fn main() -> Result<(), Box<dyn Error>> {
    println!("Start forwarder");
    let mut frontend = zeromq::SubSocket::new();
    frontend.bind("tcp://127.0.0.1:30001").await?;

    let mut backend = zeromq::PubSocket::new();
    backend.bind("tcp://127.0.0.1:30002").await?;

    frontend.subscribe("").await?;

    let forward = async move {
	loop {
	    let message = frontend.recv().await.unwrap();
	    println!("passing message: {:?}", message);
	    backend.send(message).await.unwrap();
	}
    };

    forward.await;

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>style: Split collect_style_attribute_and_animation_rules.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove an unnecessary cast in the Rust code<commit_after><|endoftext|>


<commit_before><commit_msg>Cleaned up conditionals<commit_after><|endoftext|>


<commit_before><commit_msg>Removed depricated code<commit_after><|endoftext|>


<commit_before><commit_msg>Fixing main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Add more docstrings and fix SphinxNode new signature<commit_after><|endoftext|>


<commit_before><commit_msg>added file<commit_after>// Kevin Lang
// Cole Garner
//
// Concurrent Patricia trie with managed memory instead of
// garbage collection. Based off of the following paper:
// http://www.temple.edu/cis/icdcs2013/data/5000a216.pdf
// by Niloufar Shafiei

<|endoftext|>


<commit_before>use std::io::fs;
use std::io;
use std::os;

use colours::{Plain, Style, Black, Red, Green, Yellow, Blue, Purple, Cyan};
mod colours;

fn main() {
    match os::args().as_slice() {
        [] => unreachable!(),
        [_] => { list(Path::new(".")) },
        [_, ref p] => { list(Path::new(p.as_slice())) },
        _ => { fail!("args?") },
    }
}

fn list(path: Path) {
    let mut files = match fs::readdir(&path) {
        Ok(files) => files,
        Err(e) => fail!("readdir: {}", e),
    };
    files.sort_by(|a, b| a.filename_str().cmp(&b.filename_str()));
    for file in files.iter() {
        let filename: &str = file.filename_str().unwrap();

        // We have to use lstat here instad of file.stat(), as it
        // doesn't follow symbolic links. Otherwise, the stat() call
        // will fail if it encounters a link that's target is
        // non-existent.
        let stat: io::FileStat = match fs::lstat(file) {
            Ok(stat) => stat,
            Err(e) => fail!("Couldn't stat {}: {}", filename, e),
        };

        let colour = file_colour(&stat, filename);

        println!("{} {}", perm_str(&stat), colour.paint(filename.to_owned()));
    }
}

fn file_colour(stat: &io::FileStat, filename: &str) -> Style {
    if stat.kind == io::TypeDirectory {
        Blue.normal()
    } else if stat.perm & io::UserExecute == io::UserExecute {
        Green.normal()
    } else if filename.ends_with("~") {
        Black.bold()
    } else {
        Plain
    }
}

fn perm_str(stat: &io::FileStat) -> ~str {
    let bits = stat.perm;
    return format!("{}{}{}{}{}{}{}{}{}{}",
                   type_char(stat.kind),
                   bit(bits, io::UserRead, ~"r", Yellow.bold()),
                   bit(bits, io::UserWrite, ~"w", Red.bold()),
                   bit(bits, io::UserExecute, ~"x", Green.bold().underline()),
                   bit(bits, io::GroupRead, ~"r", Yellow.normal()),
                   bit(bits, io::GroupWrite, ~"w", Red.normal()),
                   bit(bits, io::GroupExecute, ~"x", Green.normal()),
                   bit(bits, io::OtherRead, ~"r", Yellow.normal()),
                   bit(bits, io::OtherWrite, ~"w", Red.normal()),
                   bit(bits, io::OtherExecute, ~"x", Green.normal()),
                   );
}

fn bit(bits: u32, bit: u32, other: ~str, style: Style) -> ~str {
    if bits & bit == bit {
        style.paint(other)
    } else {
        Black.bold().paint(~"-")
    }
}

fn type_char(t: io::FileType) -> ~str {
    return match t {
        io::TypeFile => ~".",
        io::TypeDirectory => Blue.paint("d"),
        io::TypeNamedPipe => Yellow.paint("|"),
        io::TypeBlockSpecial => Purple.paint("s"),
        io::TypeSymlink => Cyan.paint("l"),
        _ => ~"?",
    }
}
<commit_msg>Make columns more generic<commit_after>use std::io::fs;
use std::io;
use std::os;

use colours::{Plain, Style, Black, Red, Green, Yellow, Blue, Purple, Cyan};
mod colours;

fn main() {
    match os::args().as_slice() {
        [] => unreachable!(),
        [_] => { list(Path::new(".")) },
        [_, ref p] => { list(Path::new(p.as_slice())) },
        _ => { fail!("args?") },
    }
}

enum Permissions {
    Permissions,
}

enum FileName {
    FileName,
}

trait Column {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str;
}

impl Column for FileName {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        file_colour(stat, filename).paint(filename.to_owned())
    }
}

impl Column for Permissions {
    fn display(&self, stat: &io::FileStat, filename: &str) -> ~str {
        let bits = stat.perm;
        return format!("{}{}{}{}{}{}{}{}{}{}",
            type_char(stat.kind),
            bit(bits, io::UserRead, ~"r", Yellow.bold()),
            bit(bits, io::UserWrite, ~"w", Red.bold()),
            bit(bits, io::UserExecute, ~"x", Green.bold().underline()),
            bit(bits, io::GroupRead, ~"r", Yellow.normal()),
            bit(bits, io::GroupWrite, ~"w", Red.normal()),
            bit(bits, io::GroupExecute, ~"x", Green.normal()),
            bit(bits, io::OtherRead, ~"r", Yellow.normal()),
            bit(bits, io::OtherWrite, ~"w", Red.normal()),
            bit(bits, io::OtherExecute, ~"x", Green.normal()),
       );
    }
}

fn list(path: Path) {
    let mut files = match fs::readdir(&path) {
        Ok(files) => files,
        Err(e) => fail!("readdir: {}", e),
    };
    files.sort_by(|a, b| a.filename_str().cmp(&b.filename_str()));
    for file in files.iter() {
        let filename: &str = file.filename_str().unwrap();

        // We have to use lstat here instad of file.stat(), as it
        // doesn't follow symbolic links. Otherwise, the stat() call
        // will fail if it encounters a link that's target is
        // non-existent.
        let stat: io::FileStat = match fs::lstat(file) {
            Ok(stat) => stat,
            Err(e) => fail!("Couldn't stat {}: {}", filename, e),
        };

        let columns = ~[~Permissions as ~Column, ~FileName as ~Column];
        let mut cells = columns.iter().map(|c| c.display(&stat, filename));

        let mut first = true;
        for cell in cells {
            if first {
                first = false;
            } else {
                print!(" ");
            }
            print!("{}", cell);
        }
        print!("\n");
    }
}

fn file_colour(stat: &io::FileStat, filename: &str) -> Style {
    if stat.kind == io::TypeDirectory {
        Blue.normal()
    } else if stat.perm & io::UserExecute == io::UserExecute {
        Green.normal()
    } else if filename.ends_with("~") {
        Black.bold()
    } else {
        Plain
    }
}

fn bit(bits: u32, bit: u32, other: ~str, style: Style) -> ~str {
    if bits & bit == bit {
        style.paint(other)
    } else {
        Black.bold().paint(~"-")
    }
}

fn type_char(t: io::FileType) -> ~str {
    return match t {
        io::TypeFile => ~".",
        io::TypeDirectory => Blue.paint("d"),
        io::TypeNamedPipe => Yellow.paint("|"),
        io::TypeBlockSpecial => Purple.paint("s"),
        io::TypeSymlink => Cyan.paint("l"),
        _ => ~"?",
    }
}
<|endoftext|>


<commit_before><commit_msg>Added examples<commit_after>extern crate tg_botapi;

use tg_botapi::args;
use tg_botapi::BotApi;

use std::sync::Arc;
use std::thread;
use std::env;

fn main() {
    let token = &env::var("TOKEN").expect("No bot token provided, please set the environment variable TOKEN");
    let bot_arc = Arc::new(BotApi::new(token));

    let mut update_args = args::GetUpdates {
        offset: Some(0),
        limit: None,
        timeout: Some(600),
        allowed_updates: None,
    };

    'update_loop: loop {
        let updates = bot_arc.get_updates(&update_args).unwrap();

        for update in updates {
            update_args.offset = Some(update.update_id + 1);

            if let Some(message) = update.message {
                let bot = bot_arc.clone();

                let chat_id = message.chat.id;
                let msg_id = message.message_id;

                let message_text = format("\"{}\"\n    - <i>You, CURRENT_YEAR</i>",
                                          message.text.unwrap_or(String::new()));

                thread::spawn(move || {
                    let _ = bot.send_message(&args::SendMessage {
                        chat_id: Some(chat_id),
                        chat_username: None,
                        text: ,
                        parse_mode: Some("HTML"),
                        disable_web_page_preview: None,
                        disable_notification: None,
                        reply_to_message_id: None,
                        reply_markup: None,
                    });
                });
            }
        }
    }
    update_args.limit = Some(0);
    update_args.timeout = Some(0);
    let _ = bot.get_updates(&update_args);
}<|endoftext|>


<commit_before><commit_msg>Add todo test<commit_after>#[macro_use]
extern crate rustful;
extern crate rustc_serialize;
extern crate unicase;

use std::sync::RwLock;
use std::collections::btree_map::{BTreeMap, Iter};

use rustc_serialize::json;
use unicase::UniCase;

use rustful::{
    Server,
    Context,
    Response,
    Handler,
    TreeRouter
};
use rustful::header::{
    AccessControlAllowOrigin,
    AccessControlAllowMethods,
    AccessControlAllowHeaders,
    Host
};
use rustful::StatusCode;
use rustful::context::ExtJsonBody;

//Helper for setting a status code and then returning from a function
macro_rules! or_abort {
    ($e: expr, $response: expr, $status: expr) => (
        if let Some(v) = $e {
            v
        } else {
            $response.set_status($status);
            return
        }
    )
}

fn main() {
    let mut router = insert_routes!{
        TreeRouter::new() => {
            Get: Api(Some(list_all)),
            Post: Api(Some(store)),
            Delete: Api(Some(clear)),
            Options: Api(None),
            ":id" => {
                Get: Api(Some(get_todo)),
                Patch: Api(Some(edit_todo)),
                Delete: Api(Some(delete_todo)),
                Options: Api(None)
            }
        }
    };

    //Enables hyperlink search, which will be used in CORS
    router.find_hyperlinks = true;

    //Our imitation of a database
    let database = RwLock::new(Table::new());

    let server_result = Server {
        handlers: router,
        host: 8080.into(),
        content_type: content_type!(Application / Json; Charset = Utf8),
        global: Box::new(database).into(),
        ..Server::default()
    }.run();

    if let Err(e) = server_result {
        println!("could not run the server: {}", e)
    }
}

//List all the to-dos in the database
fn list_all(database: &Database, context: Context, mut response: Response) {
    let host = or_abort!(context.headers.get(), response, StatusCode::BadRequest);

    let todos: Vec<_> = database.read().unwrap().iter().map(|(&id, todo)| {
        NetworkTodo::from_todo(todo, host, id)
    }).collect();

    response.send(json::encode(&todos).unwrap());
}

//Store a new to-do with data fro the request body
fn store(database: &Database, mut context: Context, mut response: Response) {
    let todo: NetworkTodo = or_abort!(
        context.body.decode_json_body().ok(),
        response,
        StatusCode::BadRequest
    );

    let host = or_abort!(context.headers.get(), response, StatusCode::BadRequest);

    let mut database = database.write().unwrap();
    database.insert(todo.into());

    let todo = database.last().map(|(id, todo)| {
        NetworkTodo::from_todo(todo, host, id)
    });

    response.send(json::encode(&todo).unwrap());
}

//Clear the database
fn clear(database: &Database, _context: Context, _response: Response) {
    database.write().unwrap().clear();
}

//Send one particular to-do, selected by its id
fn get_todo(database: &Database, context: Context, mut response: Response) {
    let host = or_abort!(context.headers.get(), response, StatusCode::BadRequest);

    let id = or_abort!(
        context.variables.get("id").and_then(|id| id.parse().ok()),
        response,
        StatusCode::BadRequest
    );

    let todo = database.read().unwrap().get(id).map(|todo| {
        NetworkTodo::from_todo(&todo, host, id)
    });

    response.send(json::encode(&todo).unwrap());
}

//Update a to-do, selected by its, id with data from the request body
fn edit_todo(database: &Database, mut context: Context, mut response: Response) {
    let edits = or_abort!(
        context.body.decode_json_body().ok(),
        response,
        StatusCode::BadRequest
    );

    let host = or_abort!(context.headers.get(), response, StatusCode::BadRequest);

    let id = or_abort!(
        context.variables.get("id").and_then(|id| id.parse().ok()),
        response,
        StatusCode::BadRequest
    );

    let mut database =  database.write().unwrap();
    let mut todo = database.get_mut(id);
    todo.as_mut().map(|mut todo| todo.update(edits));

    let todo = todo.map(|todo| {
        NetworkTodo::from_todo(&todo, host, id)
    });

    response.send(json::encode(&todo).unwrap());
}

//Delete a to-do, selected by its id
fn delete_todo(database: &Database, context: Context, mut response: Response) {
    let id = or_abort!(
        context.variables.get("id").and_then(|id| id.parse().ok()),
        response,
        StatusCode::BadRequest
    );

    database.write().unwrap().delete(id);
}

//An API endpoint with an optional action
struct Api(Option<fn(&Database, Context, Response)>);

impl Handler for Api {
    fn handle_request(&self, context: Context, mut response: Response) {
        //Collect the accepted methods from the provided hyperlinks
        let mut methods: Vec<_> = context.hypermedia.links.iter().filter_map(|l| l.method.clone()).collect();
        methods.push(context.method.clone());

        //Setup cross origin resource sharing
        response.headers_mut().set(AccessControlAllowOrigin::Any);
        response.headers_mut().set(AccessControlAllowMethods(methods));
        response.headers_mut().set(AccessControlAllowHeaders(vec![UniCase("content-type".into())]));

        //Get the database from the global storage
        let database = if let Some(database) = context.global.get() {
            database
        } else {
            context.log.error("expected a globally accessible Database");
            response.set_status(StatusCode::InternalServerError);
            return
        };

        if let Some(action) = self.0 {
            action(database, context, response);
        }
    }
}

//A read-write-locked Table will do as our database
type Database = RwLock<Table>;

//A simple imitation of a database table
struct Table {
    next_id: usize,
    items: BTreeMap<usize, Todo>
}

impl Table {
    fn new() -> Table {
        Table {
            next_id: 0,
            items: BTreeMap::new()
        }
    }

    fn insert(&mut self, item: Todo) {
        self.items.insert(self.next_id, item);
        self.next_id += 1;
    }

    fn delete(&mut self, id: usize) {
        self.items.remove(&id);
    }

    fn clear(&mut self) {
        self.items.clear();
    }

    fn last(&self) -> Option<(usize, &Todo)> {
        self.items.keys().next_back().cloned().and_then(|id| {
            self.items.get(&id).map(|item| (id, item))
        })
    }

    fn get(&self, id: usize) -> Option<&Todo> {
        self.items.get(&id)
    }

    fn get_mut(&mut self, id: usize) -> Option<&mut Todo> {
        self.items.get_mut(&id)
    }

    fn iter(&self) -> Iter<usize, Todo> {
        (&self.items).iter()
    }
}

//A structure for what will be sent and received over the network
#[derive(RustcDecodable, RustcEncodable)]
struct NetworkTodo {
    title: Option<String>,
    completed: Option<bool>,
    order: Option<u32>,
    url: Option<String>
}

impl NetworkTodo {
    fn from_todo(todo: &Todo, host: &Host, id: usize) -> NetworkTodo {
        let url = if let Some(port) = host.port {
            format!("http://{}:{}/{}", host.hostname, port, id)
        } else {
            format!("http://{}/{}", host.hostname, id)
        };

        NetworkTodo {
            title: Some(todo.title.clone()),
            completed: Some(todo.completed),
            order: Some(todo.order),
            url: Some(url)
        }
    }
}

//The stored to-do data
struct Todo {
    title: String,
    completed: bool,
    order: u32
}

impl Todo {
    fn update(&mut self, changes: NetworkTodo) {
        if let Some(title) = changes.title {
            self.title = title;
        }

        if let Some(completed) = changes.completed {
            self.completed = completed;
        }

        if let Some(order) = changes.order {
            self.order = order
        }
    }
}

impl From<NetworkTodo> for Todo {
    fn from(todo: NetworkTodo) -> Todo {
        Todo {
            title: todo.title.unwrap_or(String::new()),
            completed: todo.completed.unwrap_or(false),
            order: todo.order.unwrap_or(0)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


<commit_before><commit_msg>blank message<commit_after><|endoftext|>


<commit_before><commit_msg>testando push<commit_after>Coded by 4code.rs
<|endoftext|>


<commit_before><commit_msg>split off computations<commit_after><|endoftext|>


<commit_before><commit_msg>Re-export libtest<commit_after>//! Support code for rustc's built in unit-test and micro-benchmarking
//! framework.
//!
//! Almost all user code will only be interested in `Bencher` and
//! `black_box`. All other interactions (such as writing tests and
//! benchmarks themselves) should be done via the `#[test]` and
//! `#[bench]` attributes.
//!
//! See the [Testing Chapter](../book/ch11-00-testing.html) of the book for more details.

#![crate_name = "test"]
#![unstable(feature = "test", issue = "27812")]
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/",
       test(attr(deny(warnings))))]

extern crate libtest;
pub use libtest::*;
<|endoftext|>


<commit_before><commit_msg>print kernel_paddr and kernel_vaddr<commit_after><|endoftext|>


<commit_before><commit_msg>Add rust code for robot-simulator case<commit_after>// The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.

#[derive(PartialEq, Debug)]
pub enum Direction {
    North,
    East,
    South,
    West,
}

impl Direction {
    fn turn_right(self) -> Self {
        match self {
            Direction::North => Direction::East,
            Direction::East => Direction::South,
            Direction::South => Direction::West,
            Direction::West => Direction::North,
        }
    }

    fn turn_left(self) -> Self {
        match self {
            Direction::North => Direction::West,
            Direction::East => Direction::North,
            Direction::South => Direction::East,
            Direction::West => Direction::South,
        }
    }
}

pub struct Robot {
    rx: isize,
    ry: isize,
    rd: Direction,
}

impl Robot {
    #[allow(unused_variables)]
    pub fn new(x: isize, y: isize, d: Direction) -> Self {
        Robot {
            rx: x,
            ry: y,
            rd: d,
        }
    }

    pub fn turn_right(self) -> Self {
        Robot {
            rx: self.rx,
            ry: self.ry,
            rd: self.rd.turn_right(),
        }
    }

    pub fn turn_left(self) -> Self {
        Robot {
            rx: self.rx,
            ry: self.ry,
            rd: self.rd.turn_left(),
        }
    }

    pub fn advance(self) -> Self {
        let (x, y) = match self.rd {
            Direction::North => (self.rx, self.ry + 1),
            Direction::East => (self.rx + 1, self.ry),
            Direction::South => (self.rx, self.ry - 1),
            Direction::West => (self.rx - 1, self.ry),
        };

        Robot {
            rx: x,
            ry: y,
            rd: self.rd,
        }
    }

    #[allow(unused_variables)]
    pub fn instructions(self, instructions: &str) -> Self {
        let mut r = self;
        for c in instructions.chars() {
            r = match c {
                'L' => r.turn_left(),
                'R' => r.turn_right(),
                'A' => r.advance(),
                _ => r,
            };
        }

        r
    }

    pub fn position(&self) -> (isize, isize) {
        (self.rx, self.ry)
    }

    pub fn direction(&self) -> &Direction {
        &self.rd
    }
}
<|endoftext|>


<commit_before><commit_msg>start new<commit_after>fn complex_number_multiply<'a>(x: &'a str, y: &'a str) -> String {}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>rust-errno, first commit.<commit_after>/*
 * Copyright (c) 2012, Ben Noordhuis <info@bnoordhuis.nl>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#[license = "ISC"];

#[link(name = "errno",
       vers = "1.0",
       author = "Ben Noordhuis <info@bnoordhuis.nl>")];

import size_t = ctypes::size_t;
import c_int = ctypes::c_int;
import sbuf = str::sbuf;

#[nolink]
native mod __glibc {
  fn __xpg_strerror_r(errnum: c_int, buf: *mutable u8, len: size_t) -> c_int;
  fn __errno_location() -> *c_int;
}

fn errno() -> int {
  unsafe { *__glibc::__errno_location() as int }
}

fn strerror(errnum: int) -> str {
  let bufv = vec::init_elt_mut(1024u, 0u8);
  let buf = ptr::mut_addr_of(bufv[0]);
  let len = vec::len(bufv);

  unsafe {
    let r = __glibc::__xpg_strerror_r(errnum as c_int, buf, len as size_t);

    if (r as bool) {
      fail #fmt("__glibc::__xpg_strerror_r() failed [errno=%d]", errno());
    }

    ret str::from_cstr(buf as sbuf);
  }
}

#[test]
fn test() {
  // FIXME chokes on localized messages
  assert errno::strerror(22) == "Invalid argument";
  assert errno::strerror(0) == "Success";
}

#[should_fail]
#[test]
fn test2() {
  errno::strerror(-1);
}
<|endoftext|>


<commit_before><commit_msg>add `pop_timeout`/`push_timeout` to bounded queues<commit_after><|endoftext|>


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

// This test case tests the incremental compilation hash (ICH) implementation
// for if expressions.

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

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

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

// Change condition (if) -------------------------------------------------------
#[cfg(cfail1)]
pub fn change_condition(x: bool) -> u32 {
    if x {
        return 1
    }

    return 0
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_condition(x: bool) -> u32 {
    if !x {
        return 1
    }

    return 0
}

// Change then branch (if) -----------------------------------------------------
#[cfg(cfail1)]
pub fn change_then_branch(x: bool) -> u32 {
    if x {
        return 1
    }

    return 0
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_then_branch(x: bool) -> u32 {
    if x {
        return 2
    }

    return 0
}

// Change else branch (if) -----------------------------------------------------
#[cfg(cfail1)]
pub fn change_else_branch(x: bool) -> u32 {
    if x {
        1
    } else {
        2
    }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_else_branch(x: bool) -> u32 {
    if x {
        1
    } else {
        3
    }
}

// Add else branch (if) --------------------------------------------------------
#[cfg(cfail1)]
pub fn add_else_branch(x: bool) -> u32 {
    let mut ret = 1;

    if x {
        ret += 1;
    }

    ret
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_else_branch(x: bool) -> u32 {
    let mut ret = 1;

    if x {
        ret += 1;
    } else {
    }

    ret
}

// Change condition (if let) ---------------------------------------------------
#[cfg(cfail1)]
pub fn change_condition_if_let(x: Option<u32>) -> u32 {
    if let Some(_x) = x {
        return 1
    }

    0
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_condition_if_let(x: Option<u32>) -> u32 {
    if let Some(_) = x {
        return 1
    }

    0
}

// Change then branch (if let) -------------------------------------------------
#[cfg(cfail1)]
pub fn change_then_branch_if_let(x: Option<u32>) -> u32 {
    if let Some(x) = x {
        return x
    }

    0
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_then_branch_if_let(x: Option<u32>) -> u32 {
    if let Some(x) = x {
        return x + 1
    }

    0
}

// Change else branch (if let) -------------------------------------------------
#[cfg(cfail1)]
pub fn change_else_branch_if_let(x: Option<u32>) -> u32 {
    if let Some(x) = x {
        x
    } else {
        1
    }
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn change_else_branch_if_let(x: Option<u32>) -> u32 {
    if let Some(x) = x {
        x
    } else {
        2
    }
}

// Add else branch (if let) ----------------------------------------------------
#[cfg(cfail1)]
pub fn add_else_branch_if_let(x: Option<u32>) -> u32 {
    let mut ret = 1;

    if let Some(x) = x {
        ret += x;
    }

    ret
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn add_else_branch_if_let(x: Option<u32>) -> u32 {
    let mut ret = 1;

    if let Some(x) = x {
        ret += x;
    } else {
    }

    ret
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for issue #17403<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.

// Test that closures cannot subvert aliasing restrictions

#![feature(overloaded_calls, unboxed_closures)]

fn main() {
    // Unboxed closure case
    {
        let mut x = 0u;
        let mut f = |&mut:| &mut x; //~ ERROR cannot infer
        let x = f();
        let y = f();
    }
    // Boxed closure case
    {
        let mut x = 0u;
        let f = || &mut x; //~ ERROR cannot infer
        let x = f();
        let y = f();
    }
}
<|endoftext|>


<commit_before><commit_msg>Invalid source code formating Fixed<commit_after><|endoftext|>


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

use servo_msg::compositor_msg::LayerBuffer;
use font_context::FontContext;
use geometry::Au;
use opts::Opts;

use azure::azure_hl::{B8G8R8A8, Color, ColorPattern, DrawOptions};
use azure::azure_hl::{DrawSurfaceOptions, DrawTarget, Linear, StrokeOptions};
use azure::AzFloat;
use std::libc::types::common::c99::uint16_t;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use geom::side_offsets::SideOffsets2D;
use servo_net::image::base::Image;
use extra::arc::Arc;

pub struct RenderContext<'self> {
    canvas: &'self ~LayerBuffer,
    font_ctx: @mut FontContext,
    opts: &'self Opts
}

impl<'self> RenderContext<'self>  {
    pub fn get_draw_target(&self) -> &'self DrawTarget {
        &self.canvas.draw_target
    }

    pub fn draw_solid_color(&self, bounds: &Rect<Au>, color: Color) {
        self.canvas.draw_target.make_current();
        self.canvas.draw_target.fill_rect(&bounds.to_azure_rect(), &ColorPattern(color));
    }

    pub fn draw_border(&self,
                       bounds: &Rect<Au>,
                       border: SideOffsets2D<Au>,
                       color: SideOffsets2D<Color>) {
        let draw_opts = DrawOptions(1 as AzFloat, 0 as uint16_t);
        let stroke_fields = 2; // CAP_SQUARE
        let mut stroke_opts = StrokeOptions(0 as AzFloat, 10 as AzFloat, stroke_fields);

        let rect = bounds.to_azure_rect();
        let border = border.to_float_px();

        self.canvas.draw_target.make_current();

        // draw top border
        stroke_opts.line_width = border.top;
        let y = rect.origin.y + border.top * 0.5;
        let start = Point2D(rect.origin.x, y);
        let end = Point2D(rect.origin.x + rect.size.width, y);
        self.canvas.draw_target.stroke_line(start, end, &ColorPattern(color.top), &stroke_opts, &draw_opts);

        // draw right border
        stroke_opts.line_width = border.right;
        let x = rect.origin.x + rect.size.width - border.right * 0.5;
        let start = Point2D(x, rect.origin.y);
        let end = Point2D(x, rect.origin.y + rect.size.height);
        self.canvas.draw_target.stroke_line(start, end, &ColorPattern(color.right), &stroke_opts, &draw_opts);

        // draw bottom border
        stroke_opts.line_width = border.bottom;
        let y = rect.origin.y + rect.size.height - border.bottom * 0.5;
        let start = Point2D(rect.origin.x, y);
        let end = Point2D(rect.origin.x + rect.size.width, y);
        self.canvas.draw_target.stroke_line(start, end, &ColorPattern(color.bottom), &stroke_opts, &draw_opts);

        // draw left border
        stroke_opts.line_width = border.left;
        let x = rect.origin.x + border.left * 0.5;
        let start = Point2D(x, rect.origin.y);
        let end = Point2D(x, rect.origin.y + rect.size.height);
        self.canvas.draw_target.stroke_line(start, end, &ColorPattern(color.left), &stroke_opts, &draw_opts);
    }

    pub fn draw_image(&self, bounds: Rect<Au>, image: Arc<~Image>) {
        let image = image.get();
        let size = Size2D(image.width as i32, image.height as i32);
        let stride = image.width * 4;

        self.canvas.draw_target.make_current();
        let draw_target_ref = &self.canvas.draw_target;
        let azure_surface = draw_target_ref.create_source_surface_from_data(image.data, size,
                                                                            stride as i32, B8G8R8A8);
        let source_rect = Rect(Point2D(0 as AzFloat, 0 as AzFloat),
                               Size2D(image.width as AzFloat, image.height as AzFloat));
        let dest_rect = bounds.to_azure_rect();
        let draw_surface_options = DrawSurfaceOptions(Linear, true);
        let draw_options = DrawOptions(1.0f as AzFloat, 0);
        draw_target_ref.draw_surface(azure_surface,
                                     dest_rect,
                                     source_rect,
                                     draw_surface_options,
                                     draw_options);
    }

    pub fn clear(&self) {
        let pattern = ColorPattern(Color(1.0, 1.0, 1.0, 1.0));
        let rect = Rect(Point2D(self.canvas.rect.origin.x as AzFloat,
                                self.canvas.rect.origin.y as AzFloat),
                        Size2D(self.canvas.screen_pos.size.width as AzFloat,
                               self.canvas.screen_pos.size.height as AzFloat));
        self.canvas.draw_target.make_current();
        self.canvas.draw_target.fill_rect(&rect, &pattern);
    }
}

trait to_float {
    fn to_float(&self) -> float;
}

impl to_float for u8 {
    fn to_float(&self) -> float {
        (*self as float) / 255f
    }
}

trait ToAzureRect {
    fn to_azure_rect(&self) -> Rect<AzFloat>;
}

impl ToAzureRect for Rect<Au> {
    fn to_azure_rect(&self) -> Rect<AzFloat> {
        Rect(Point2D(self.origin.x.to_nearest_px() as AzFloat,
                     self.origin.y.to_nearest_px() as AzFloat),
             Size2D(self.size.width.to_nearest_px() as AzFloat,
                    self.size.height.to_nearest_px() as AzFloat))
    }
}

trait ToSideOffsetsPx {
    fn to_float_px(&self) -> SideOffsets2D<AzFloat>;
}

impl ToSideOffsetsPx for SideOffsets2D<Au> {
    fn to_float_px(&self) -> SideOffsets2D<AzFloat> {
        SideOffsets2D::new(self.top.to_nearest_px() as AzFloat,
                           self.right.to_nearest_px() as AzFloat,
                           self.bottom.to_nearest_px() as AzFloat,
                           self.left.to_nearest_px() as AzFloat)
    }
}
<commit_msg>Add apply_border_style to apply each CSSBorderStyle<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use servo_msg::compositor_msg::LayerBuffer;
use font_context::FontContext;
use geometry::Au;
use newcss::values::CSSBorderStyle;
use newcss::values::{CSSBorderStyleNone, CSSBorderStyleHidden, CSSBorderStyleDotted, CSSBorderStyleDashed, CSSBorderStyleSolid, CSSBorderStyleDouble, CSSBorderStyleGroove, CSSBorderStyleRidge, CSSBorderStyleInset, CSSBorderStyleOutset};
use opts::Opts;

use azure::azure_hl::{B8G8R8A8, Color, ColorPattern, DrawOptions};
use azure::azure_hl::{DrawSurfaceOptions, DrawTarget, Linear, StrokeOptions};
use azure::{AZ_CAP_BUTT, AZ_CAP_ROUND};
use azure::AZ_JOIN_BEVEL;
use azure::AzFloat;
use std::vec;
use std::libc::types::common::c99::uint16_t;
use std::libc::size_t;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use geom::side_offsets::SideOffsets2D;
use servo_net::image::base::Image;
use extra::arc::Arc;

pub struct RenderContext<'self> {
    canvas: &'self ~LayerBuffer,
    font_ctx: @mut FontContext,
    opts: &'self Opts
}

impl<'self> RenderContext<'self>  {
    pub fn get_draw_target(&self) -> &'self DrawTarget {
        &self.canvas.draw_target
    }

    pub fn draw_solid_color(&self, bounds: &Rect<Au>, color: Color) {
        self.canvas.draw_target.make_current();
        self.canvas.draw_target.fill_rect(&bounds.to_azure_rect(), &ColorPattern(color));
    }

    pub fn draw_border(&self,
                       bounds: &Rect<Au>,
                       border: SideOffsets2D<Au>,
                       color: SideOffsets2D<Color>,
                       style: SideOffsets2D<CSSBorderStyle>) {
        let draw_opts = DrawOptions(1 as AzFloat, 0 as uint16_t);
        let rect = bounds.to_azure_rect();
        let border = border.to_float_px();

        self.canvas.draw_target.make_current();
        let mut dash: [AzFloat, ..2] = [0 as AzFloat, 0 as AzFloat];
        let mut stroke_opts = StrokeOptions(0 as AzFloat, 10 as AzFloat);

        // draw top border
        RenderContext::apply_border_style(style.top, border.top, dash, &mut stroke_opts);
        let y = rect.origin.y + border.top * 0.5;
        let start = Point2D(rect.origin.x, y);
        let end = Point2D(rect.origin.x + rect.size.width, y);
        self.canvas.draw_target.stroke_line(start, end, &ColorPattern(color.top), &stroke_opts, &draw_opts);

        // draw right border
        RenderContext::apply_border_style(style.right, border.right, dash,  &mut stroke_opts);
        let x = rect.origin.x + rect.size.width - border.right * 0.5;
        let start = Point2D(x, rect.origin.y);
        let end = Point2D(x, rect.origin.y + rect.size.height);
        self.canvas.draw_target.stroke_line(start, end, &ColorPattern(color.right), &stroke_opts, &draw_opts);

        // draw bottom border
        RenderContext::apply_border_style(style.bottom, border.bottom, dash, &mut stroke_opts);
        let y = rect.origin.y + rect.size.height - border.bottom * 0.5;
        let start = Point2D(rect.origin.x, y);
        let end = Point2D(rect.origin.x + rect.size.width, y);
        self.canvas.draw_target.stroke_line(start, end, &ColorPattern(color.bottom), &stroke_opts, &draw_opts);

        // draw left border
        RenderContext::apply_border_style(style.left, border.left, dash,  &mut stroke_opts);
        let x = rect.origin.x + border.left * 0.5;
        let start = Point2D(x, rect.origin.y);
        let end = Point2D(x, rect.origin.y + rect.size.height);
        self.canvas.draw_target.stroke_line(start, end, &ColorPattern(color.left), &stroke_opts, &draw_opts);
    }

    pub fn draw_image(&self, bounds: Rect<Au>, image: Arc<~Image>) {
        let image = image.get();
        let size = Size2D(image.width as i32, image.height as i32);
        let stride = image.width * 4;

        self.canvas.draw_target.make_current();
        let draw_target_ref = &self.canvas.draw_target;
        let azure_surface = draw_target_ref.create_source_surface_from_data(image.data, size,
                                                                            stride as i32, B8G8R8A8);
        let source_rect = Rect(Point2D(0 as AzFloat, 0 as AzFloat),
                               Size2D(image.width as AzFloat, image.height as AzFloat));
        let dest_rect = bounds.to_azure_rect();
        let draw_surface_options = DrawSurfaceOptions(Linear, true);
        let draw_options = DrawOptions(1.0f as AzFloat, 0);
        draw_target_ref.draw_surface(azure_surface,
                                     dest_rect,
                                     source_rect,
                                     draw_surface_options,
                                     draw_options);
    }

    pub fn clear(&self) {
        let pattern = ColorPattern(Color(1.0, 1.0, 1.0, 1.0));
        let rect = Rect(Point2D(self.canvas.rect.origin.x as AzFloat,
                                self.canvas.rect.origin.y as AzFloat),
                        Size2D(self.canvas.screen_pos.size.width as AzFloat,
                               self.canvas.screen_pos.size.height as AzFloat));
        self.canvas.draw_target.make_current();
        self.canvas.draw_target.fill_rect(&rect, &pattern);
    }

    fn apply_border_style(style: CSSBorderStyle, border_width: AzFloat, dash: &mut [AzFloat], stroke_opts: &mut StrokeOptions){
        match style{
            CSSBorderStyleNone => {
            }
            CSSBorderStyleHidden => {
            }
            //FIXME(sammykim): This doesn't work with dash_pattern and cap_style well. I referred firefox code.
            CSSBorderStyleDotted => {
                stroke_opts.line_width = border_width;

                if border_width > 2.0 {
                    dash[0] = 0 as AzFloat;
                    dash[1] = border_width * 2.0;

                    stroke_opts.set_cap_style(AZ_CAP_ROUND as u8);
                } else {
                    dash[0] = border_width;
                    dash[1] = border_width;
                }
                stroke_opts.mDashPattern = vec::raw::to_ptr(dash);
                stroke_opts.mDashLength = dash.len() as size_t;
            }
            CSSBorderStyleDashed => {
                stroke_opts.set_cap_style(AZ_CAP_BUTT as u8);
                stroke_opts.line_width = border_width;
                dash[0] = border_width*3 as AzFloat;
                dash[1] = border_width*3 as AzFloat;
                stroke_opts.mDashPattern = vec::raw::to_ptr(dash);
                stroke_opts.mDashLength = dash.len() as size_t;
            }
            //FIXME(sammykim): BorderStyleSolid doesn't show proper join-style with comparing firefox.
            CSSBorderStyleSolid => {
                stroke_opts.set_cap_style(AZ_CAP_BUTT as u8);
                stroke_opts.set_join_style(AZ_JOIN_BEVEL as u8);
                stroke_opts.line_width = border_width;
                stroke_opts.mDashLength = 0 as size_t;
            }
            //FIXME(sammykim): Five more styles should be implemented.
            CSSBorderStyleDouble => {

            }
            CSSBorderStyleGroove => {

            }
            CSSBorderStyleRidge => {

            }
            CSSBorderStyleInset => {

            }
            CSSBorderStyleOutset => {

            }
        }
    }
}

trait to_float {
    fn to_float(&self) -> float;
}

impl to_float for u8 {
    fn to_float(&self) -> float {
        (*self as float) / 255f
    }
}

trait ToAzureRect {
    fn to_azure_rect(&self) -> Rect<AzFloat>;
}

impl ToAzureRect for Rect<Au> {
    fn to_azure_rect(&self) -> Rect<AzFloat> {
        Rect(Point2D(self.origin.x.to_nearest_px() as AzFloat,
                     self.origin.y.to_nearest_px() as AzFloat),
             Size2D(self.size.width.to_nearest_px() as AzFloat,
                    self.size.height.to_nearest_px() as AzFloat))
    }
}

trait ToSideOffsetsPx {
    fn to_float_px(&self) -> SideOffsets2D<AzFloat>;
}

impl ToSideOffsetsPx for SideOffsets2D<Au> {
    fn to_float_px(&self) -> SideOffsets2D<AzFloat> {
        SideOffsets2D::new(self.top.to_nearest_px() as AzFloat,
                           self.right.to_nearest_px() as AzFloat,
                           self.bottom.to_nearest_px() as AzFloat,
                           self.left.to_nearest_px() as AzFloat)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add build.rs<commit_after>use std::process::{Command, Stdio};
use std::str;
fn is_python2() -> bool {
    let script = r"
import sys
print(sys.version_info[0])
";
    let out = Command::new("python")
        .args(&["-c", script])
        .stderr(Stdio::inherit())
        .output()
        .expect("Failed to run the python interpreter");
    let version = str::from_utf8(&out.stdout).unwrap();
    version.starts_with("2")
}

fn cfg(python2: bool) {
    if python2 {
        println!("cargo:rustc-cfg=Py_2");
    } else {
        println!("cargo:rustc-cfg=Py_3");
    }
}

fn main() {
    if cfg!(feature = "python3") {
        cfg(false);
    } else if cfg!(feature = "python2") {
        cfg(true);
    } else {
        cfg(is_python2());
    }
}
<|endoftext|>


<commit_before><commit_msg>Update about-text in imag-ids<commit_after><|endoftext|>


<commit_before><commit_msg>Updates<commit_after><|endoftext|>


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

// The crate store - a central repo for information collected about external
// crates and libraries

use core::prelude::*;

use metadata::cstore;
use metadata::decoder;

use core::vec;
use std::oldmap;
use std;
use syntax::{ast, attr};
use syntax::parse::token::ident_interner;

// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = oldmap::HashMap<ast::crate_num, ast::crate_num>;

pub struct crate_metadata {
    name: @~str,
    data: @~[u8],
    cnum_map: cnum_map,
    cnum: ast::crate_num
}

pub struct CStore {
    priv metas: oldmap::HashMap<ast::crate_num, @crate_metadata>,
    priv extern_mod_crate_map: extern_mod_crate_map,
    priv used_crate_files: ~[Path],
    priv used_libraries: ~[~str],
    priv used_link_args: ~[~str],
    intr: @ident_interner
}

// Map from node_id's of local extern mod statements to crate numbers
type extern_mod_crate_map = oldmap::HashMap<ast::node_id, ast::crate_num>;

pub fn mk_cstore(intr: @ident_interner) -> CStore {
    let meta_cache = oldmap::HashMap();
    let crate_map = oldmap::HashMap();
    return CStore {
        metas: meta_cache,
        extern_mod_crate_map: crate_map,
        used_crate_files: ~[],
        used_libraries: ~[],
        used_link_args: ~[],
        intr: intr
    };
}

pub fn get_crate_data(cstore: @mut CStore, cnum: ast::crate_num)
                   -> @crate_metadata {
    return cstore.metas.get(&cnum);
}

pub fn get_crate_hash(cstore: @mut CStore, cnum: ast::crate_num) -> @~str {
    let cdata = get_crate_data(cstore, cnum);
    decoder::get_crate_hash(cdata.data)
}

pub fn get_crate_vers(cstore: @mut CStore, cnum: ast::crate_num) -> @~str {
    let cdata = get_crate_data(cstore, cnum);
    decoder::get_crate_vers(cdata.data)
}

pub fn set_crate_data(cstore: @mut CStore,
                      cnum: ast::crate_num,
                      data: @crate_metadata) {
    let metas = cstore.metas;
    metas.insert(cnum, data);
}

pub fn have_crate_data(cstore: @mut CStore, cnum: ast::crate_num) -> bool {
    cstore.metas.contains_key(&cnum)
}

pub fn iter_crate_data(cstore: @mut CStore,
                       i: &fn(ast::crate_num, @crate_metadata)) {
    let metas = cstore.metas;
    for metas.each |&k, &v| {
        i(k, v);
    }
}

pub fn add_used_crate_file(cstore: @mut CStore, lib: &Path) {
    let cstore = &mut *cstore;
    if !vec::contains(cstore.used_crate_files, lib) {
        cstore.used_crate_files.push(copy *lib);
    }
}

pub fn get_used_crate_files(cstore: @mut CStore) -> ~[Path] {
    return /*bad*/copy cstore.used_crate_files;
}

pub fn add_used_library(cstore: @mut CStore, lib: @~str) -> bool {
    fail_unless!(*lib != ~"");

    let cstore = &mut *cstore;
    if cstore.used_libraries.contains(&*lib) { return false; }
    cstore.used_libraries.push(/*bad*/ copy *lib);
    true
}

pub fn get_used_libraries(cstore: @mut CStore) -> ~[~str] {
    /*bad*/copy cstore.used_libraries
}

pub fn add_used_link_args(cstore: @mut CStore, args: &str) {
    cstore.used_link_args.push_all(args.split_char(' '));
}

pub fn get_used_link_args(cstore: @mut CStore) -> ~[~str] {
    /*bad*/copy cstore.used_link_args
}

pub fn add_extern_mod_stmt_cnum(cstore: @mut CStore,
                                emod_id: ast::node_id,
                                cnum: ast::crate_num) {
    let extern_mod_crate_map = cstore.extern_mod_crate_map;
    extern_mod_crate_map.insert(emod_id, cnum);
}

pub fn find_extern_mod_stmt_cnum(cstore: @mut CStore,
                                 emod_id: ast::node_id)
                       -> Option<ast::crate_num> {
    let extern_mod_crate_map = cstore.extern_mod_crate_map;
    extern_mod_crate_map.find(&emod_id)
}

// returns hashes of crates directly used by this crate. Hashes are
// sorted by crate name.
pub fn get_dep_hashes(cstore: @mut CStore) -> ~[~str] {
    struct crate_hash { name: @~str, hash: @~str }
    let mut result = ~[];

    let extern_mod_crate_map = cstore.extern_mod_crate_map;
    for extern_mod_crate_map.each_value |&cnum| {
        let cdata = cstore::get_crate_data(cstore, cnum);
        let hash = decoder::get_crate_hash(cdata.data);
        debug!("Add hash[%s]: %s", *cdata.name, *hash);
        result.push(crate_hash {
            name: cdata.name,
            hash: hash
        });
    }

    let sorted = std::sort::merge_sort(result, |a, b| a.name <= b.name);

    debug!("sorted:");
    for sorted.each |x| {
        debug!("  hash[%s]: %s", *x.name, *x.hash);
    }

    sorted.map(|ch| /*bad*/copy *ch.hash)
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>make crates with the same name sort consistently<commit_after>// Copyright 2012 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.

// The crate store - a central repo for information collected about external
// crates and libraries

use core::prelude::*;

use metadata::cstore;
use metadata::decoder;

use core::vec;
use std::oldmap;
use std;
use syntax::{ast, attr};
use syntax::parse::token::ident_interner;

// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = oldmap::HashMap<ast::crate_num, ast::crate_num>;

pub struct crate_metadata {
    name: @~str,
    data: @~[u8],
    cnum_map: cnum_map,
    cnum: ast::crate_num
}

pub struct CStore {
    priv metas: oldmap::HashMap<ast::crate_num, @crate_metadata>,
    priv extern_mod_crate_map: extern_mod_crate_map,
    priv used_crate_files: ~[Path],
    priv used_libraries: ~[~str],
    priv used_link_args: ~[~str],
    intr: @ident_interner
}

// Map from node_id's of local extern mod statements to crate numbers
type extern_mod_crate_map = oldmap::HashMap<ast::node_id, ast::crate_num>;

pub fn mk_cstore(intr: @ident_interner) -> CStore {
    let meta_cache = oldmap::HashMap();
    let crate_map = oldmap::HashMap();
    return CStore {
        metas: meta_cache,
        extern_mod_crate_map: crate_map,
        used_crate_files: ~[],
        used_libraries: ~[],
        used_link_args: ~[],
        intr: intr
    };
}

pub fn get_crate_data(cstore: @mut CStore, cnum: ast::crate_num)
                   -> @crate_metadata {
    return cstore.metas.get(&cnum);
}

pub fn get_crate_hash(cstore: @mut CStore, cnum: ast::crate_num) -> @~str {
    let cdata = get_crate_data(cstore, cnum);
    decoder::get_crate_hash(cdata.data)
}

pub fn get_crate_vers(cstore: @mut CStore, cnum: ast::crate_num) -> @~str {
    let cdata = get_crate_data(cstore, cnum);
    decoder::get_crate_vers(cdata.data)
}

pub fn set_crate_data(cstore: @mut CStore,
                      cnum: ast::crate_num,
                      data: @crate_metadata) {
    let metas = cstore.metas;
    metas.insert(cnum, data);
}

pub fn have_crate_data(cstore: @mut CStore, cnum: ast::crate_num) -> bool {
    cstore.metas.contains_key(&cnum)
}

pub fn iter_crate_data(cstore: @mut CStore,
                       i: &fn(ast::crate_num, @crate_metadata)) {
    let metas = cstore.metas;
    for metas.each |&k, &v| {
        i(k, v);
    }
}

pub fn add_used_crate_file(cstore: @mut CStore, lib: &Path) {
    let cstore = &mut *cstore;
    if !vec::contains(cstore.used_crate_files, lib) {
        cstore.used_crate_files.push(copy *lib);
    }
}

pub fn get_used_crate_files(cstore: @mut CStore) -> ~[Path] {
    return /*bad*/copy cstore.used_crate_files;
}

pub fn add_used_library(cstore: @mut CStore, lib: @~str) -> bool {
    fail_unless!(*lib != ~"");

    let cstore = &mut *cstore;
    if cstore.used_libraries.contains(&*lib) { return false; }
    cstore.used_libraries.push(/*bad*/ copy *lib);
    true
}

pub fn get_used_libraries(cstore: @mut CStore) -> ~[~str] {
    /*bad*/copy cstore.used_libraries
}

pub fn add_used_link_args(cstore: @mut CStore, args: &str) {
    cstore.used_link_args.push_all(args.split_char(' '));
}

pub fn get_used_link_args(cstore: @mut CStore) -> ~[~str] {
    /*bad*/copy cstore.used_link_args
}

pub fn add_extern_mod_stmt_cnum(cstore: @mut CStore,
                                emod_id: ast::node_id,
                                cnum: ast::crate_num) {
    let extern_mod_crate_map = cstore.extern_mod_crate_map;
    extern_mod_crate_map.insert(emod_id, cnum);
}

pub fn find_extern_mod_stmt_cnum(cstore: @mut CStore,
                                 emod_id: ast::node_id)
                       -> Option<ast::crate_num> {
    let extern_mod_crate_map = cstore.extern_mod_crate_map;
    extern_mod_crate_map.find(&emod_id)
}

// returns hashes of crates directly used by this crate. Hashes are sorted by
// (crate name, crate version, crate hash) in lexicographic order (not semver)
pub fn get_dep_hashes(cstore: @mut CStore) -> ~[~str] {
    struct crate_hash { name: @~str, vers: @~str, hash: @~str }
    let mut result = ~[];

    let extern_mod_crate_map = cstore.extern_mod_crate_map;
    for extern_mod_crate_map.each_value |&cnum| {
        let cdata = cstore::get_crate_data(cstore, cnum);
        let hash = decoder::get_crate_hash(cdata.data);
        let vers = decoder::get_crate_vers(cdata.data);
        debug!("Add hash[%s]: %s %s", *cdata.name, *vers, *hash);
        result.push(crate_hash {
            name: cdata.name,
            vers: vers,
            hash: hash
        });
    }

    let sorted = do std::sort::merge_sort(result) |a, b| {
        (a.name, a.vers, a.hash) <= (b.name, b.vers, b.hash)
    };

    debug!("sorted:");
    for sorted.each |x| {
        debug!("  hash[%s]: %s", *x.name, *x.hash);
    }

    sorted.map(|ch| /*bad*/copy *ch.hash)
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>


<commit_before><commit_msg>Refactor libimagwiki to fit new store iterator interface<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.

#![feature(rustc_attrs)]

macro_rules! foo { () => {
    let x = 1;
    macro_rules! bar { () => {x} }
    let _ = bar!();
}}

#[rustc_error]
fn main() { foo! {}; } //~ ERROR compilation successful
<commit_msg>Add test for issue #31856<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.

#![feature(rustc_attrs)]
#![allow(warnings)]

macro_rules! foo { () => {
    let x = 1;
    macro_rules! bar { () => {x} }
    let _ = bar!();
}}

macro_rules! bar { // test issue #31856
    ($n:ident) => (
        let a = 1;
        let $n = a;
    )
}

#[rustc_error]
fn main() { //~ ERROR compilation successful
    foo! {};
    bar! {};
}
<|endoftext|>


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

fn main() {
    let thing = ();
    let other: typeof(thing) = thing; //~ ERROR attempt to use a non-constant value in a constant
    //~^ ERROR `typeof` is a reserved keyword but unimplemented [E0516]
}

fn f(){
    let q = 1;
    <typeof(q)>::N //~ ERROR attempt to use a non-constant value in a constant
    //~^ ERROR `typeof` is a reserved keyword but unimplemented [E0516]
}

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

// Check we do the correct privacy checks when we import a name and there is an
// item with that name in both the value and type namespaces.

#![allow(dead_code)]
#![allow(unused_imports)]

// public type, private value
pub mod foo1 {
    pub trait Bar {
    }
    pub struct Baz;

    fn Bar() { }
}

fn test_single1() {
    use foo1::Bar;  //~ ERROR function `Bar` is private

    Bar();
}

fn test_list1() {
    use foo1::{Bar,Baz};  //~ ERROR `Bar` is private

    Bar();
}

// private type, public value
pub mod foo2 {
    trait Bar {
    }
    pub struct Baz;

    pub fn Bar() { }
}

fn test_single2() {
    use foo2::Bar;  //~ ERROR trait `Bar` is private

    let _x : Box<Bar>;
}

fn test_list2() {
    use foo2::{Bar,Baz};  //~ ERROR `Bar` is private

    let _x: Box<Bar>;
}

// neither public
pub mod foo3 {
    trait Bar {
    }
    pub struct Baz;

    fn Bar() { }
}

fn test_unused3() {
    use foo3::Bar;  //~ ERROR `Bar` is private
}

fn test_single3() {
    use foo3::Bar;  //~ ERROR `Bar` is private

    Bar();
    let _x: Box<Bar>;
}

fn test_list3() {
    use foo3::{Bar,Baz};  //~ ERROR `Bar` is private

    Bar();
    let _x: Box<Bar>;
}

fn main() {
}
<commit_msg>Fix fallout in tests.<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.

// Check we do the correct privacy checks when we import a name and there is an
// item with that name in both the value and type namespaces.

#![allow(dead_code)]
#![allow(unused_imports)]

// public type, private value
pub mod foo1 {
    pub trait Bar {
    }
    pub struct Baz;

    fn Bar() { }
}

fn test_single1() {
    use foo1::Bar;

    Bar(); //~ ERROR unresolved name `Bar`
}

fn test_list1() {
    use foo1::{Bar,Baz};

    Bar(); //~ ERROR unresolved name `Bar`
}

// private type, public value
pub mod foo2 {
    trait Bar {
    }
    pub struct Baz;

    pub fn Bar() { }
}

fn test_single2() {
    use foo2::Bar;

    let _x : Box<Bar>; //~ ERROR type name `Bar` is undefined
}

fn test_list2() {
    use foo2::{Bar,Baz};

    let _x: Box<Bar>; //~ ERROR type name `Bar` is undefined
}

// neither public
pub mod foo3 {
    trait Bar {
    }
    pub struct Baz;

    fn Bar() { }
}

fn test_unused3() {
    use foo3::Bar;  //~ ERROR `Bar` is private
}

fn test_single3() {
    use foo3::Bar;  //~ ERROR `Bar` is private

    Bar();
    let _x: Box<Bar>;
}

fn test_list3() {
    use foo3::{Bar,Baz};  //~ ERROR `Bar` is private

    Bar();
    let _x: Box<Bar>;
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #49731 - japaric:std-thumb-for-real, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>Get glassful bin compiling by moving to new_io.<commit_after><|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.

// no-prefer-dynamic
// ignore-cross-compile

#![feature(rustc_private)]

extern crate rustc_back;

use std::env;
use std::fs;
use std::process;
use std::str;
use rustc_back::tempdir::TempDir;

fn main() {
    // If we're the child, make sure we were invoked correctly
    let args: Vec<String> = env::args().collect();
    if args.len() > 1 && args[1] == "child" {
        // FIXME: This should check the whole `args[0]` instead of just
        // checking that it ends_with the executable name. This
        // is needed because of Windows, which has a different behavior.
        // See #15149 for more info.
        return assert!(args[0].ends_with(&format!("mytest{}",
                                                  env::consts::EXE_SUFFIX)));
    }

    test();
}

fn test() {
    // If we're the parent, copy our own binary to a new directory.
    let my_path = env::current_exe().unwrap();
    let my_dir  = my_path.parent().unwrap();

    let child_dir = TempDir::new_in(&my_dir, "issue-15140-child").unwrap();
    let child_dir = child_dir.path();

    let child_path = child_dir.join(&format!("mytest{}",
                                             env::consts::EXE_SUFFIX));
    fs::copy(&my_path, &child_path).unwrap();

    // Append the new directory to our own PATH.
    let path = {
        let mut paths: Vec<_> = env::split_paths(&env::var_os("PATH").unwrap()).collect();
        paths.push(child_dir.to_path_buf());
        env::join_paths(paths.iter()).unwrap()
    };

    let child_output = process::Command::new("mytest").env("PATH", &path)
                                                      .arg("child")
                                                      .output().unwrap();

    assert!(child_output.status.success(),
            format!("child assertion failed\n child stdout:\n {}\n child stderr:\n {}",
                    str::from_utf8(&child_output.stdout).unwrap(),
                    str::from_utf8(&child_output.stderr).unwrap()));

    fs::remove_dir_all(&child_dir).unwrap();

}
<commit_msg>Auto merge of #25615 - petrochenkov:issue25542, 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.

// no-prefer-dynamic
// ignore-cross-compile

#![feature(rustc_private)]

extern crate rustc_back;

use std::env;
use std::fs;
use std::process;
use std::str;
use rustc_back::tempdir::TempDir;

fn main() {
    // If we're the child, make sure we were invoked correctly
    let args: Vec<String> = env::args().collect();
    if args.len() > 1 && args[1] == "child" {
        // FIXME: This should check the whole `args[0]` instead of just
        // checking that it ends_with the executable name. This
        // is needed because of Windows, which has a different behavior.
        // See #15149 for more info.
        return assert!(args[0].ends_with(&format!("mytest{}",
                                                  env::consts::EXE_SUFFIX)));
    }

    test();
}

fn test() {
    // If we're the parent, copy our own binary to a new directory.
    let my_path = env::current_exe().unwrap();
    let my_dir  = my_path.parent().unwrap();

    let child_dir = TempDir::new_in(&my_dir, "issue-15140-child").unwrap();
    let child_dir = child_dir.path();

    let child_path = child_dir.join(&format!("mytest{}",
                                             env::consts::EXE_SUFFIX));
    fs::copy(&my_path, &child_path).unwrap();

    // Append the new directory to our own PATH.
    let path = {
        let mut paths: Vec<_> = env::split_paths(&env::var_os("PATH").unwrap()).collect();
        paths.push(child_dir.to_path_buf());
        env::join_paths(paths.iter()).unwrap()
    };

    let child_output = process::Command::new("mytest").env("PATH", &path)
                                                      .arg("child")
                                                      .output().unwrap();

    assert!(child_output.status.success(),
            format!("child assertion failed\n child stdout:\n {}\n child stderr:\n {}",
                    str::from_utf8(&child_output.stdout).unwrap(),
                    str::from_utf8(&child_output.stderr).unwrap()));

    let res = fs::remove_dir_all(&child_dir);
    if res.is_err() {
        // On Windows deleting just executed mytest.exe can fail because it's still locked
        std::thread::sleep_ms(1000);
        fs::remove_dir_all(&child_dir).unwrap();
    }
}
<|endoftext|>


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

#![deny(warnings)]

extern crate build_helper;

use std::env;
use std::process::Command;
use build_helper::{run, native_lib_boilerplate};

fn main() {
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    if cfg!(feature = "backtrace") &&
        !target.contains("msvc") &&
        !target.contains("emscripten") &&
        !target.contains("fuchsia") &&
        !target.contains("wasm32")
    {
        let _ = build_libbacktrace(&host, &target);
    }

    if target.contains("linux") {
        if target.contains("android") {
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=log");
            println!("cargo:rustc-link-lib=gcc");
        } else if !target.contains("musl") {
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=rt");
            println!("cargo:rustc-link-lib=pthread");
        }
    } else if target.contains("freebsd") {
        println!("cargo:rustc-link-lib=execinfo");
        println!("cargo:rustc-link-lib=pthread");
    } else if target.contains("dragonfly") || target.contains("bitrig") ||
              target.contains("netbsd") || target.contains("openbsd") {
        println!("cargo:rustc-link-lib=pthread");
    } else if target.contains("solaris") {
        println!("cargo:rustc-link-lib=socket");
        println!("cargo:rustc-link-lib=posix4");
        println!("cargo:rustc-link-lib=pthread");
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("apple-darwin") {
        println!("cargo:rustc-link-lib=System");

        // res_init and friends require -lresolv on macOS/iOS.
        // See #41582 and http://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("apple-ios") {
        println!("cargo:rustc-link-lib=System");
        println!("cargo:rustc-link-lib=objc");
        println!("cargo:rustc-link-lib=framework=Security");
        println!("cargo:rustc-link-lib=framework=Foundation");
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("windows") {
        println!("cargo:rustc-link-lib=advapi32");
        println!("cargo:rustc-link-lib=ws2_32");
        println!("cargo:rustc-link-lib=userenv");
        println!("cargo:rustc-link-lib=shell32");
    } else if target.contains("fuchsia") {
        // use system-provided libbacktrace
        if cfg!(feature = "backtrace") {
            println!("cargo:rustc-link-lib=backtrace");
        }
        println!("cargo:rustc-link-lib=zircon");
        println!("cargo:rustc-link-lib=fdio");
        println!("cargo:rustc-link-lib=launchpad"); // for std::process
    }
}

fn build_libbacktrace(host: &str, target: &str) -> Result<(), ()> {
    let native = native_lib_boilerplate("libbacktrace", "libbacktrace", "backtrace", ".libs")?;

    run(Command::new("sh")
                .current_dir(&native.out_dir)
                .arg(native.src_dir.join("configure").to_str().unwrap()
                                   .replace("C:\\", "/c/")
                                   .replace("\\", "/"))
                .arg("--with-pic")
                .arg("--disable-multilib")
                .arg("--disable-shared")
                .arg("--disable-host-shared")
                .arg(format!("--host={}", build_helper::gnu_target(target)))
                .arg(format!("--build={}", build_helper::gnu_target(host)))
                .env("CFLAGS", env::var("CFLAGS").unwrap_or_default() + " -fvisibility=hidden"));

    run(Command::new(build_helper::make(host))
                .current_dir(&native.out_dir)
                .arg(format!("INCDIR={}", native.src_dir.display()))
                .arg("-j").arg(env::var("NUM_JOBS").expect("NUM_JOBS was not set")));
    Ok(())
}
<commit_msg>Add proper library dependencies for libstd on CloudABI.<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![deny(warnings)]

extern crate build_helper;

use std::env;
use std::process::Command;
use build_helper::{run, native_lib_boilerplate};

fn main() {
    let target = env::var("TARGET").expect("TARGET was not set");
    let host = env::var("HOST").expect("HOST was not set");
    if cfg!(feature = "backtrace") &&
        !target.contains("cloudabi") &&
        !target.contains("emscripten") &&
        !target.contains("fuchsia") &&
        !target.contains("msvc") &&
        !target.contains("wasm32")
    {
        let _ = build_libbacktrace(&host, &target);
    }

    if target.contains("linux") {
        if target.contains("android") {
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=log");
            println!("cargo:rustc-link-lib=gcc");
        } else if !target.contains("musl") {
            println!("cargo:rustc-link-lib=dl");
            println!("cargo:rustc-link-lib=rt");
            println!("cargo:rustc-link-lib=pthread");
        }
    } else if target.contains("freebsd") {
        println!("cargo:rustc-link-lib=execinfo");
        println!("cargo:rustc-link-lib=pthread");
    } else if target.contains("dragonfly") || target.contains("bitrig") ||
              target.contains("netbsd") || target.contains("openbsd") {
        println!("cargo:rustc-link-lib=pthread");
    } else if target.contains("solaris") {
        println!("cargo:rustc-link-lib=socket");
        println!("cargo:rustc-link-lib=posix4");
        println!("cargo:rustc-link-lib=pthread");
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("apple-darwin") {
        println!("cargo:rustc-link-lib=System");

        // res_init and friends require -lresolv on macOS/iOS.
        // See #41582 and http://blog.achernya.com/2013/03/os-x-has-silly-libsystem.html
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("apple-ios") {
        println!("cargo:rustc-link-lib=System");
        println!("cargo:rustc-link-lib=objc");
        println!("cargo:rustc-link-lib=framework=Security");
        println!("cargo:rustc-link-lib=framework=Foundation");
        println!("cargo:rustc-link-lib=resolv");
    } else if target.contains("windows") {
        println!("cargo:rustc-link-lib=advapi32");
        println!("cargo:rustc-link-lib=ws2_32");
        println!("cargo:rustc-link-lib=userenv");
        println!("cargo:rustc-link-lib=shell32");
    } else if target.contains("fuchsia") {
        // use system-provided libbacktrace
        if cfg!(feature = "backtrace") {
            println!("cargo:rustc-link-lib=backtrace");
        }
        println!("cargo:rustc-link-lib=zircon");
        println!("cargo:rustc-link-lib=fdio");
        println!("cargo:rustc-link-lib=launchpad"); // for std::process
    } else if target.contains("cloudabi") {
        if cfg!(feature = "backtrace") {
            println!("cargo:rustc-link-lib=unwind");
        }
        println!("cargo:rustc-link-lib=c");
        println!("cargo:rustc-link-lib=compiler_rt");
    }
}

fn build_libbacktrace(host: &str, target: &str) -> Result<(), ()> {
    let native = native_lib_boilerplate("libbacktrace", "libbacktrace", "backtrace", ".libs")?;

    run(Command::new("sh")
                .current_dir(&native.out_dir)
                .arg(native.src_dir.join("configure").to_str().unwrap()
                                   .replace("C:\\", "/c/")
                                   .replace("\\", "/"))
                .arg("--with-pic")
                .arg("--disable-multilib")
                .arg("--disable-shared")
                .arg("--disable-host-shared")
                .arg(format!("--host={}", build_helper::gnu_target(target)))
                .arg(format!("--build={}", build_helper::gnu_target(host)))
                .env("CFLAGS", env::var("CFLAGS").unwrap_or_default() + " -fvisibility=hidden"));

    run(Command::new(build_helper::make(host))
                .current_dir(&native.out_dir)
                .arg(format!("INCDIR={}", native.src_dir.display()))
                .arg("-j").arg(env::var("NUM_JOBS").expect("NUM_JOBS was not set")));
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Add GetHandler for the getters.<commit_after><|endoftext|>


<commit_before><commit_msg>Implement From<T> for ObjectStream<commit_after><|endoftext|>


<commit_before><commit_msg>Split subprocesses into functions.<commit_after><|endoftext|>


<commit_before><commit_msg>Add another discriminant-size-related test, this time with fields.<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.

#[feature(macro_rules)];

use std::mem::size_of;

macro_rules! check {
    ($t:ty, $sz:expr, $($e:expr, $s:expr),*) => {{
        assert_eq!(size_of::<$t>(), $sz);
        $({
            static S: $t = $e;
            let v: $t = $e;
            assert_eq!(S, v);
            assert_eq!(format!("{:?}", v), ~$s);
            assert_eq!(format!("{:?}", S), ~$s);
        });*
    }}
}

pub fn main() {
    check!(Option<u8>, 2,
           None, "None",
           Some(129u8), "Some(129u8)");
    check!(Option<i16>, 4,
           None, "None",
           Some(-20000i16), "Some(-20000i16)");
    check!(Either<u8, i8>, 2,
           Left(132u8), "Left(132u8)",
           Right(-32i8), "Right(-32i8)");
    check!(Either<u8, i16>, 4,
           Left(132u8), "Left(132u8)",
           Right(-20000i16), "Right(-20000i16)");
}
<|endoftext|>


<commit_before><commit_msg>heap: fix free function<commit_after><|endoftext|>


<commit_before><commit_msg>very out of scope part 9<commit_after>fn main() {
	let result = hash(515);
	for i in range(-99,99) {
		print!("{}, ", hash(i));
	}
}

//convert a number to a relatively uniform
fn hash(num: int) -> int {
	if num == 0 {
		return 0;
	}

	let mut sum = 0;
	let mut currentNum = num;

	if currentNum < 0 {
		currentNum = -currentNum;
	}

	loop {
		let digit = currentNum % 10;
		sum += digit;
		if currentNum < 10 {
			break;
		}
		currentNum /= 10;
	}

	if sum >= 10 {
		return hash(sum);
	}
	sum
}
<|endoftext|>


<commit_before><commit_msg>Flush for Redox stdin_of<commit_after><|endoftext|>


<commit_before><commit_msg>chat: Implements `Encodable` for `ChatJson` manually.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for issue-54239<commit_after>// Regression test for #54239, shouldn't trigger lint.
// check-pass
// edition:2018

#![deny(missing_debug_implementations)]

struct DontLookAtMe(i32);

async fn secret() -> DontLookAtMe {
    DontLookAtMe(41)
}

pub async fn looking() -> i32 { // Shouldn't trigger lint here.
    secret().await.0
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>[algo] fibonacci with Binet (N1)<commit_after>// Fibbonacci with Binet's formula
// bad take, it does not work
fn main() {
    (0..100).for_each(|number: u32| {
        let value = binet(number);

        println!("For {} Value is {}", number, value);
    })
}

fn binet(number: u32) -> i32 {
    let sr_5 = (5 as f32).sqrt() + 1.;
    let result = (1. + sr_5 / 2.).powf(number as f32) / sr_5;
    result as i32
}
<|endoftext|>


<commit_before><commit_msg>Test case for checks on pattern-bound vars<commit_after>use std;
import std::option::*;

pure fn p(x:int) -> bool { true }

fn f(x:int) : p(x) { }

fn main() {
    alt some(5) {
      some(y) {
        check p(y);
        f(y);
      }
      _ { fail "yuck"; }
    }
}
<|endoftext|>