<commit_before>use std::convert::Into;
generate_error_imports!();

generate_custom_error_types!(HookError, HookErrorKind, CustomData,
    HookExecutionError  => "Hook exec error",
    AccessTypeViolation => "Hook access type violation"
);

#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)]
pub struct CustomData {
    aborting: bool,
}

impl HookError {

    pub fn is_aborting(&self) -> bool {
        match self.custom_data {
            Some(b) => b.aborting,
            None => true
        }
    }

}
<commit_msg>Add error kind for denied hooks<commit_after>use std::convert::Into;
generate_error_imports!();

generate_custom_error_types!(HookError, HookErrorKind, CustomData,
    HookExecutionError  => "Hook exec error",
    AccessTypeViolation => "Hook access type violation",
    MutableHooksNotAllowed => "Mutable Hooks are denied"
);

#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)]
pub struct CustomData {
    aborting: bool,
}

impl HookError {

    pub fn is_aborting(&self) -> bool {
        match self.custom_data {
            Some(b) => b.aborting,
            None => true
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #24863 - asajeffrey:gstplugin-resizing, r=ferjm<commit_after><|endoftext|>


<commit_before><commit_msg>test(safety): add safety issue test<commit_after>#[macro_use]
extern crate toml_edit;

use toml_edit::{Document, Key};
use std::mem;

macro_rules! parse_doc {
    ($toml:ident) => (
        {
            let doc = Document::parse($toml);
            assert!(doc.is_ok());
            doc.unwrap()
        }
    );
}

macro_rules! as_table {
    ($entry:ident) => (
        {
            assert!($entry.is_table());
            $entry.as_table_mut().unwrap()
        }
    );
}

#[test]
fn test_safety_issue() {

    let toml1 = r#"
[a]
b = 2
[a.c]
b = 3
"#;
    let toml2 = r#"
[b]
a = 2
[b.c]
a = 3
"#;
    let mut doc1 = parse_doc!(toml1);
    let mut doc2 = parse_doc!(toml2);

    {
        let mut r1 = doc1.root_mut();
        let mut r2 = doc2.root_mut();
        {
            let mut a = r1.entry("a");
            let mut a = as_table!(a);
            let mut ac = a.entry("c");
            let mut ac = as_table!(ac);
            ac.append_table(parse_key!("ac"));

            let mut b = r2.entry("b");
            let mut b = as_table!(b);
            let mut bc = b.entry("c");
            let mut bc = as_table!(bc);
            bc.append_table(parse_key!("bc"));

            mem::swap(ac, bc); // now both documents are invalid (duplicate keys) :(
        }

        // what's even worse,
        // `ac` is now pointing to `[b.c]`
        let mut a = r1.entry("a");
        let mut a = as_table!(a);
        let mut ac = a.entry("c");
        let mut ac = as_table!(ac);
        ac.append_table(parse_key!("'i am in [b.c]'"));

        // same for `bc`
        let mut b = r2.entry("b");
        let mut b = as_table!(b);
        let mut bc = b.entry("c");
        let mut bc = as_table!(bc);
        bc.append_table(parse_key!("'i am in [a.c]'"));
    }

    assert_eq!(
        doc1.to_string(),
        r#"
[a]
b = 2
[b.c]
a = 3

[b.c.bc]

[b.c.'i am in [b.c]']
"#
    );
    assert_eq!(
        doc2.to_string(),
        r#"
[b]
a = 2
[a.c]
b = 3

[a.c.ac]

[a.c.'i am in [a.c]']
"#
    );
}
<|endoftext|>


<commit_before><commit_msg>Check we can bind before we spawn a thread.<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/.

pub const DBUS_TIMEOUT: i32 = 20000; // millieconds

pub const STRATIS_VERSION: &'static str = "1";
pub const MANAGER_NAME: &'static str = "/Manager";
pub const STRATIS_BASE_PATH: &'static str = "/org/storage/stratis1";
pub const STRATIS_BASE_SERVICE: &'static str = "org.storage.stratis1";
pub const STRATIS_BASE_MANAGER: &'static str = "/org/storage/stratis1/Manager";
pub const STRATIS_MANAGER_INTERFACE: &'static str = "org.storage.stratis1.Manager";
pub const STRATIS_POOL_BASE_INTERFACE: &'static str = "org.storage.stratis1.pool";
pub const STRATIS_VOLUME_BASE_INTERFACE: &'static str = "org.storage.stratis1.volume";
pub const STRATIS_DEV_BASE_INTERFACE: &'static str = "org.storage.stratis1.dev";
pub const STRATIS_CACHE_BASE_INTERFACE: &'static str = "org.storage.stratis1.cache";
pub const STRATIS_POOL_BASE_PATH: &'static str = "/org/storage/stratis/pool";

pub const LIST_POOLS: &'static str = "ListPools";
pub const CREATE_POOL: &'static str = "CreatePool";
pub const DESTROY_POOL: &'static str = "DestroyPool";
pub const GET_POOL_OBJECT_PATH: &'static str = "GetPoolObjectPath";
pub const GET_VOLUME_OBJECT_PATH: &'static str = "GetVolumeObjectPath";
pub const GET_DEV_OBJECT_PATH: &'static str = "GetDevObjectPath";
pub const GET_CACHE_OBJECT_PATH: &'static str = "GetCacheObjectPath";
pub const GET_ERROR_CODES: &'static str = "GetErrorCodes";
pub const GET_RAID_LEVELS: &'static str = "GetRaidLevels";
pub const GET_DEV_TYPES: &'static str = "GetDevTypes";

pub trait HasCodes {
    /// Indicates that this enum can be converted to an int or described
    /// with a string.
    fn get_error_int(&self) -> u16;
    fn get_error_string(&self) -> &str;
}

custom_derive! {
    #[derive(Copy, Clone, EnumDisplay,
             IterVariants(StratisDBusErrorVariants),
             IterVariantNames(StratisDBusErrorVariantNames))]
    #[allow(non_camel_case_types)]
    pub enum StratisErrorEnum {
        STRATIS_OK,
        STRATIS_ERROR,
        STRATIS_NULL,
        STRATIS_NOTFOUND,
        STRATIS_POOL_NOTFOUND,
        STRATIS_VOLUME_NOTFOUND,
        STRATIS_DEV_NOTFOUND,
        STRATIS_CACHE_NOTFOUND,
        STRATIS_BAD_PARAM,
        STRATIS_ALREADY_EXISTS,
        STRATIS_NULL_NAME,
        STRATIS_NO_POOLS,
        STRATIS_LIST_FAILURE,
    }
}

impl HasCodes for StratisErrorEnum {
    fn get_error_int(&self) -> u16 {
        *self as u16
    }

    fn get_error_string(&self) -> &str {
        match *self {
            // TODO deal with internationalization/do this better
            StratisErrorEnum::STRATIS_OK => "Ok",
            StratisErrorEnum::STRATIS_ERROR => "A general error happened",
            StratisErrorEnum::STRATIS_NULL => "Null parameter was supplied",
            StratisErrorEnum::STRATIS_NOTFOUND => "Not found",
            StratisErrorEnum::STRATIS_POOL_NOTFOUND => "Pool not found",
            StratisErrorEnum::STRATIS_VOLUME_NOTFOUND => "Volume not found",
            StratisErrorEnum::STRATIS_CACHE_NOTFOUND => "Cache not found",
            StratisErrorEnum::STRATIS_BAD_PARAM => "Bad parameter",
            StratisErrorEnum::STRATIS_DEV_NOTFOUND => "Dev not found",
            StratisErrorEnum::STRATIS_ALREADY_EXISTS => "Already exists",
            StratisErrorEnum::STRATIS_NULL_NAME => "Null name supplied",
            StratisErrorEnum::STRATIS_NO_POOLS => "No pools",
            StratisErrorEnum::STRATIS_LIST_FAILURE => "List operation failure.",
        }
    }
}

custom_derive! {
    #[derive(Copy, Clone, EnumDisplay,
             IterVariants(StratisDBusRaidTypeVariants),
             IterVariantNames(StratisDBusRaidTypeVariantNames))]
    #[allow(non_camel_case_types)]
    pub enum StratisRaidType {
        STRATIS_RAID_TYPE_UNKNOWN,
        /** Single */
        STRATIS_RAID_TYPE_SINGLE,
        /** Mirror between two disks. For 4 disks or more, they are RAID10.*/
        STRATIS_RAID_TYPE_RAID1,
        /** Block-level striping with distributed parity */
        STRATIS_RAID_TYPE_RAID5,
        /** Block-level striping with two distributed parities, aka, RAID-DP */
        STRATIS_RAID_TYPE_RAID6,
    }
}

impl HasCodes for StratisRaidType {
    fn get_error_int(&self) -> u16 {
        *self as u16
    }

    fn get_error_string(&self) -> &str {
        match *self {
            StratisRaidType::STRATIS_RAID_TYPE_UNKNOWN => "Ok",
            StratisRaidType::STRATIS_RAID_TYPE_SINGLE => "Single",
            StratisRaidType::STRATIS_RAID_TYPE_RAID1 => "Mirrored",
            StratisRaidType::STRATIS_RAID_TYPE_RAID5 => {
                "Block-level striping with distributed parity"
            }
            StratisRaidType::STRATIS_RAID_TYPE_RAID6 => {
                "Block-level striping with two distributed parities"
            }
        }
    }
}
<commit_msg>Remove comments from RaidType enum<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/.

pub const DBUS_TIMEOUT: i32 = 20000; // millieconds

pub const STRATIS_VERSION: &'static str = "1";
pub const MANAGER_NAME: &'static str = "/Manager";
pub const STRATIS_BASE_PATH: &'static str = "/org/storage/stratis1";
pub const STRATIS_BASE_SERVICE: &'static str = "org.storage.stratis1";
pub const STRATIS_BASE_MANAGER: &'static str = "/org/storage/stratis1/Manager";
pub const STRATIS_MANAGER_INTERFACE: &'static str = "org.storage.stratis1.Manager";
pub const STRATIS_POOL_BASE_INTERFACE: &'static str = "org.storage.stratis1.pool";
pub const STRATIS_VOLUME_BASE_INTERFACE: &'static str = "org.storage.stratis1.volume";
pub const STRATIS_DEV_BASE_INTERFACE: &'static str = "org.storage.stratis1.dev";
pub const STRATIS_CACHE_BASE_INTERFACE: &'static str = "org.storage.stratis1.cache";
pub const STRATIS_POOL_BASE_PATH: &'static str = "/org/storage/stratis/pool";

pub const LIST_POOLS: &'static str = "ListPools";
pub const CREATE_POOL: &'static str = "CreatePool";
pub const DESTROY_POOL: &'static str = "DestroyPool";
pub const GET_POOL_OBJECT_PATH: &'static str = "GetPoolObjectPath";
pub const GET_VOLUME_OBJECT_PATH: &'static str = "GetVolumeObjectPath";
pub const GET_DEV_OBJECT_PATH: &'static str = "GetDevObjectPath";
pub const GET_CACHE_OBJECT_PATH: &'static str = "GetCacheObjectPath";
pub const GET_ERROR_CODES: &'static str = "GetErrorCodes";
pub const GET_RAID_LEVELS: &'static str = "GetRaidLevels";
pub const GET_DEV_TYPES: &'static str = "GetDevTypes";

pub trait HasCodes {
    /// Indicates that this enum can be converted to an int or described
    /// with a string.
    fn get_error_int(&self) -> u16;
    fn get_error_string(&self) -> &str;
}

custom_derive! {
    #[derive(Copy, Clone, EnumDisplay,
             IterVariants(StratisDBusErrorVariants),
             IterVariantNames(StratisDBusErrorVariantNames))]
    #[allow(non_camel_case_types)]
    pub enum StratisErrorEnum {
        STRATIS_OK,
        STRATIS_ERROR,
        STRATIS_NULL,
        STRATIS_NOTFOUND,
        STRATIS_POOL_NOTFOUND,
        STRATIS_VOLUME_NOTFOUND,
        STRATIS_DEV_NOTFOUND,
        STRATIS_CACHE_NOTFOUND,
        STRATIS_BAD_PARAM,
        STRATIS_ALREADY_EXISTS,
        STRATIS_NULL_NAME,
        STRATIS_NO_POOLS,
        STRATIS_LIST_FAILURE,
    }
}

impl HasCodes for StratisErrorEnum {
    fn get_error_int(&self) -> u16 {
        *self as u16
    }

    fn get_error_string(&self) -> &str {
        match *self {
            // TODO deal with internationalization/do this better
            StratisErrorEnum::STRATIS_OK => "Ok",
            StratisErrorEnum::STRATIS_ERROR => "A general error happened",
            StratisErrorEnum::STRATIS_NULL => "Null parameter was supplied",
            StratisErrorEnum::STRATIS_NOTFOUND => "Not found",
            StratisErrorEnum::STRATIS_POOL_NOTFOUND => "Pool not found",
            StratisErrorEnum::STRATIS_VOLUME_NOTFOUND => "Volume not found",
            StratisErrorEnum::STRATIS_CACHE_NOTFOUND => "Cache not found",
            StratisErrorEnum::STRATIS_BAD_PARAM => "Bad parameter",
            StratisErrorEnum::STRATIS_DEV_NOTFOUND => "Dev not found",
            StratisErrorEnum::STRATIS_ALREADY_EXISTS => "Already exists",
            StratisErrorEnum::STRATIS_NULL_NAME => "Null name supplied",
            StratisErrorEnum::STRATIS_NO_POOLS => "No pools",
            StratisErrorEnum::STRATIS_LIST_FAILURE => "List operation failure.",
        }
    }
}

custom_derive! {
    #[derive(Copy, Clone, EnumDisplay,
             IterVariants(StratisDBusRaidTypeVariants),
             IterVariantNames(StratisDBusRaidTypeVariantNames))]
    #[allow(non_camel_case_types)]
    pub enum StratisRaidType {
        STRATIS_RAID_TYPE_UNKNOWN,
        STRATIS_RAID_TYPE_SINGLE,
        STRATIS_RAID_TYPE_RAID1,
        STRATIS_RAID_TYPE_RAID5,
        STRATIS_RAID_TYPE_RAID6,
    }
}

impl HasCodes for StratisRaidType {
    fn get_error_int(&self) -> u16 {
        *self as u16
    }

    fn get_error_string(&self) -> &str {
        match *self {
            StratisRaidType::STRATIS_RAID_TYPE_UNKNOWN => "Ok",
            StratisRaidType::STRATIS_RAID_TYPE_SINGLE => "Single",
            StratisRaidType::STRATIS_RAID_TYPE_RAID1 => "Mirrored",
            StratisRaidType::STRATIS_RAID_TYPE_RAID5 => {
                "Block-level striping with distributed parity"
            }
            StratisRaidType::STRATIS_RAID_TYPE_RAID6 => {
                "Block-level striping with two distributed parities"
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fixed pipes. Before they could only pull one value before the started to return FinishedPipe. Now you can pull all the values out of the pipe. I'm not sure that this is the best solution, but it is the only one I could come up with in two days of trying.<commit_after><|endoftext|>


<commit_before><commit_msg>implement part of the interpreter<commit_after>use operations::Op;

pub struct Interpreter {
    memory: Vec<u8>,
    pointer: i64,
    ops: Vec<Op>,
}

impl Interpreter {
    pub fn new(ops: Vec<Op>) -> Interpreter {
        let m = (0 .. 30000).map(|_| 0).collect();
        Interpreter { memory: m, pointer: 0, ops: ops }
    }

    pub fn run(&mut self) {
        let mut program_counter = 0;
        while program_counter < self.ops.len() {
            match self.ops[program_counter] {
                Op::Increment => self.increment(),
                Op::Decrement => self.decrement(),
                Op::Output    => self.output(),
                Op::Right     => self.right(),
                Op::Left      => self.left(),
                Op::Jump      => self.jump(&mut program_counter),
                Op::JumpBack  => self.jump_back(&mut program_counter),
                _ => panic!("boom"),
            }
            program_counter += 1;
        }
        println!("");
    }

    fn left(&mut self) {
        self.pointer -= 1;
    }

    fn right(&mut self) {
        self.pointer += 1;
    }

    fn increment(&mut self) {
        self.memory[self.pointer as usize] += 1;
    }

    fn decrement(&mut self) {
        self.memory[self.pointer as usize] -= 1;
    }

    fn output(&self) {
        print!("{}", (self.memory[self.pointer as usize]) as char);
    }

    fn jump(&mut self, program_counter: &mut usize) {
        let mut bal = 1i32;
        if self.memory[self.pointer as usize] == 0u8 {
            loop {
                *program_counter += 1;
                if self.ops[*program_counter] == Op::Jump {
                    bal += 1;
                } else if self.ops[*program_counter] == Op::JumpBack {
                    bal -= 1;
                }
                if bal == 0 {
                    break;
                }
            }
        }
    }

    fn jump_back(&mut self, program_counter: &mut usize) {
        let mut bal = 0i32;
        loop {
            if self.ops[*program_counter] == Op::Jump {
                bal += 1;
            } else if self.ops[*program_counter] == Op::JumpBack {
                bal -= 1;
            }
            *program_counter -= 1;
            if bal == 0 {
                break;
            }
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Silence warnings about macro-generated dead code<commit_after><|endoftext|>


<commit_before><commit_msg>get_subscribed_presences::Response::presence_events should be public<commit_after><|endoftext|>


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

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

#![feature(macro_rules)]

extern crate getopts;
extern crate libc;

use std::io;
use std::num::Int;
use std::char;

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

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

pub fn uumain(args: Vec<String>) -> int {
    let opts = [
        getopts::optopt("a", "suffix-length", "use suffixes of length N (default 2)", "N"),
        getopts::optopt("b", "bytes", "put SIZE bytes per output file", "SIZE"),
        getopts::optopt("C", "line-bytes", "put at most SIZE bytes of lines per output file", "SIZE"),
        getopts::optflag("d", "numeric-suffixes", "use numeric suffixes instead of alphabetic"),
        getopts::optopt("l", "lines", "put NUMBER lines per output file", "NUMBER"),
        getopts::optflag("", "verbose", "print a diagnostic just before each output file is opened"),
        getopts::optflag("h", "help", "display help and exit"),
        getopts::optflag("V", "version", "output version information and exit"),
    ];

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

    if matches.opt_present("h") {
        println!("{} v{}", NAME, VERSION);
        println!("");
        println!("Usage:");
        println!("  {0} [OPTION]... [INPUT [PREFIX]]", NAME);
        println!("");
        io::print(getopts::usage("Output fixed-size pieces of INPUT to PREFIXaa, PREFIX ab, ...; default size is 1000, and default PREFIX is 'x'. With no INPUT, or when INPUT is -, read standard input." , &opts).as_slice());
        println!("");
        println!("SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.");
        return 0;
    }

    if matches.opt_present("V") {
        println!("{} v{}", NAME, VERSION);
        return 0;
    }

    let mut settings = Settings {
        prefix: "".to_string(),
        numeric_suffix: false,
        suffix_length: 0,
        input: "".to_string(),
        strategy: "".to_string(),
        strategy_param: "".to_string(),
        verbose: false,
    };

    settings.numeric_suffix = if matches.opt_present("d") { true } else { false };

    settings.suffix_length = match matches.opt_str("a") {
        Some(n) => match from_str(n.as_slice()) {
            Some(m) => m,
            None => crash!(1, "cannot parse num")
        },
        None => 2
    };

    settings.verbose = if matches.opt_present("verbose") { true } else { false };

    settings.strategy = "l".to_string();
    settings.strategy_param = "1000".to_string();
    let strategies = vec!["b", "C", "l"];
    for e in strategies.iter() {
        match matches.opt_str(*e) {
            Some(a) => {
                if settings.strategy.as_slice() == "l" {
                    settings.strategy = e.to_string();
                    settings.strategy_param = a;
                } else {
                    crash!(1, "{}: cannot split in more than one way", NAME)
                }
            },
            None => {}
        }
    }

    let mut v = matches.free.iter();
    let (input, prefix) = match (v.next(), v.next()) {
        (Some(a), None) => (a.to_string(), "x".to_string()),
        (Some(a), Some(b)) => (a.to_string(), b.to_string()),
        (None, _) => ("-".to_string(), "x".to_string()),
    };
    settings.input = input;
    settings.prefix = prefix;

    split(&settings)
}

struct Settings {
    prefix: String,
    numeric_suffix: bool,
    suffix_length: uint,
    input: String,
    strategy: String,
    strategy_param: String,
    verbose: bool,
}

struct SplitControl {
    current_line: String, // Don't touch
    request_new_file: bool, // Splitter implementation requests new file
}

trait Splitter {
    // Factory pattern
    fn new(_hint: Option<Self>, &Settings) -> Box<Splitter>;

    // Consume the current_line and return the consumed string
    fn consume(&mut self, &mut SplitControl) -> String;
}

struct LineSplitter {
    saved_lines_to_write: uint,
    lines_to_write: uint,
}

impl Splitter for LineSplitter {
    fn new(_: Option<LineSplitter>, settings: &Settings) -> Box<Splitter> {
        let n = match from_str(settings.strategy_param.as_slice()) {
            Some(a) => a,
            _ => crash!(1, "invalid number of lines")
        };
        box LineSplitter {
            saved_lines_to_write: n,
            lines_to_write: n,
        } as Box<Splitter>
    }

    fn consume(&mut self, control: &mut SplitControl) -> String {
        self.lines_to_write -= 1;
        if self.lines_to_write == 0 {
            self.lines_to_write = self.saved_lines_to_write;
            control.request_new_file = true;
        }
        control.current_line.clone()
    }
}

struct ByteSplitter {
    saved_bytes_to_write: uint,
    bytes_to_write: uint,
}

impl Splitter for ByteSplitter {
    fn new(_: Option<ByteSplitter>, settings: &Settings) -> Box<Splitter> {
        let mut strategy_param : Vec<char> = settings.strategy_param.chars().collect();
        let suffix = strategy_param.pop().unwrap();
        let multiplier = match suffix {
            '0'...'9' => 1u,
            'b' => 512u,
            'k' => 1024u,
            'm' => 1024u * 1024u,
            _ => crash!(1, "invalid number of bytes")
        };
        let n = if suffix.is_alphabetic() {
            match String::from_chars(strategy_param.as_slice()).as_slice().parse::<uint>() {
                Some(a) => a,
                _ => crash!(1, "invalid number of bytes")
            }
        } else {
            match settings.strategy_param.as_slice().parse::<uint>() {
                Some(a) => a,
                _ => crash!(1, "invalid number of bytes")
            }
        };
        box ByteSplitter {
            saved_bytes_to_write: n * multiplier,
            bytes_to_write: n * multiplier,
        } as Box<Splitter>
    }

    fn consume(&mut self, control: &mut SplitControl) -> String {
        let line = control.current_line.clone();
        let n = std::cmp::min(line.as_slice().chars().count(), self.bytes_to_write);
        self.bytes_to_write -= n;
        if n == 0 {
            self.bytes_to_write = self.saved_bytes_to_write;
            control.request_new_file = true;
        }
        line.as_slice().slice(0, n).to_string()
    }
}

// (1, 3) -> "aab"
fn str_prefix(i: uint, width: uint) -> String {
    let mut c = "".to_string();
    let mut n = i;
    let mut w = width;
    while w > 0 {
        w -= 1;
        let div = Int::pow(26 as uint, w);
        let r = n / div;
        n -= r * div;
        c.push(char::from_u32((r as u32) + 97).unwrap());
    }
    c
}

// (1, 3) -> "001"
fn num_prefix(i: uint, width: uint) -> String {
    let mut c = "".to_string();
    let mut n = i;
    let mut w = width;
    while w > 0 {
        w -= 1;
        let div = Int::pow(10 as uint, w);
        let r = n / div;
        n -= r * div;
        c.push(char::from_digit(r, 10).unwrap());
    }
    c
}

fn split(settings: &Settings) -> int {
    let mut reader = io::BufferedReader::new(
        if settings.input.as_slice() == "-" {
            box io::stdio::stdin_raw() as Box<Reader>
        } else {
            let r = match io::File::open(&Path::new(settings.input.clone())) {
                Ok(a) => a,
                Err(_) => crash!(1, "cannot open '{}' for reading: No such file or directory", settings.input)
            };
            box r as Box<Reader>
        }
    );

    let mut splitter: Box<Splitter> =
        match settings.strategy.as_slice() {
            "l" => Splitter::new(None::<LineSplitter>, settings),
            "b" => Splitter::new(None::<ByteSplitter>, settings),
            a @ _ => crash!(1, "strategy {} not supported", a)
        };

    let mut control = SplitControl {
        current_line: "".to_string(), // Request new line
        request_new_file: true, // Request new file
    };

    let mut writer = io::BufferedWriter::new(box io::stdio::stdout_raw() as Box<Writer>);
    let mut fileno = 0;
    loop {
        if control.current_line.as_slice().chars().count() == 0 {
            match reader.read_line() {
                Ok(a) => { control.current_line = a; }
                Err(_) =>  { break; }
            }
        }

        if control.request_new_file {
            let mut filename = settings.prefix.to_string();
            filename.push_str(if settings.numeric_suffix {
                num_prefix(fileno, settings.suffix_length)
            } else {
                str_prefix(fileno, settings.suffix_length)
            }.as_slice());

            if fileno != 0 {
                crash_if_err!(1, writer.flush());
            }
            fileno += 1;
            writer = io::BufferedWriter::new(box io::File::open_mode(&Path::new(filename.as_slice()), io::Open, io::Write) as Box<Writer>);
            control.request_new_file = false;
        }

        let consumed = splitter.consume(&mut control);
        crash_if_err!(1, writer.write_str(consumed.as_slice()));

        let advance = consumed.as_slice().chars().count();
        let clone = control.current_line.clone();
        let sl = clone.as_slice();
        control.current_line = sl.slice(advance, sl.chars().count()).to_string();
    }
    0
}
<commit_msg>Removed deprecated calls.<commit_after>#![crate_name = "split"]

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

#![feature(macro_rules)]

extern crate getopts;
extern crate libc;

use std::io;
use std::num::Int;
use std::char;

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

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

pub fn uumain(args: Vec<String>) -> int {
    let opts = [
        getopts::optopt("a", "suffix-length", "use suffixes of length N (default 2)", "N"),
        getopts::optopt("b", "bytes", "put SIZE bytes per output file", "SIZE"),
        getopts::optopt("C", "line-bytes", "put at most SIZE bytes of lines per output file", "SIZE"),
        getopts::optflag("d", "numeric-suffixes", "use numeric suffixes instead of alphabetic"),
        getopts::optopt("l", "lines", "put NUMBER lines per output file", "NUMBER"),
        getopts::optflag("", "verbose", "print a diagnostic just before each output file is opened"),
        getopts::optflag("h", "help", "display help and exit"),
        getopts::optflag("V", "version", "output version information and exit"),
    ];

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

    if matches.opt_present("h") {
        println!("{} v{}", NAME, VERSION);
        println!("");
        println!("Usage:");
        println!("  {0} [OPTION]... [INPUT [PREFIX]]", NAME);
        println!("");
        io::print(getopts::usage("Output fixed-size pieces of INPUT to PREFIXaa, PREFIX ab, ...; default size is 1000, and default PREFIX is 'x'. With no INPUT, or when INPUT is -, read standard input." , &opts).as_slice());
        println!("");
        println!("SIZE may have a multiplier suffix: b for 512, k for 1K, m for 1 Meg.");
        return 0;
    }

    if matches.opt_present("V") {
        println!("{} v{}", NAME, VERSION);
        return 0;
    }

    let mut settings = Settings {
        prefix: "".to_string(),
        numeric_suffix: false,
        suffix_length: 0,
        input: "".to_string(),
        strategy: "".to_string(),
        strategy_param: "".to_string(),
        verbose: false,
    };

    settings.numeric_suffix = if matches.opt_present("d") { true } else { false };

    settings.suffix_length = match matches.opt_str("a") {
        Some(n) => match n.as_slice().parse() {
            Some(m) => m,
            None => crash!(1, "cannot parse num")
        },
        None => 2
    };

    settings.verbose = if matches.opt_present("verbose") { true } else { false };

    settings.strategy = "l".to_string();
    settings.strategy_param = "1000".to_string();
    let strategies = vec!["b", "C", "l"];
    for e in strategies.iter() {
        match matches.opt_str(*e) {
            Some(a) => {
                if settings.strategy.as_slice() == "l" {
                    settings.strategy = e.to_string();
                    settings.strategy_param = a;
                } else {
                    crash!(1, "{}: cannot split in more than one way", NAME)
                }
            },
            None => {}
        }
    }

    let mut v = matches.free.iter();
    let (input, prefix) = match (v.next(), v.next()) {
        (Some(a), None) => (a.to_string(), "x".to_string()),
        (Some(a), Some(b)) => (a.to_string(), b.to_string()),
        (None, _) => ("-".to_string(), "x".to_string()),
    };
    settings.input = input;
    settings.prefix = prefix;

    split(&settings)
}

struct Settings {
    prefix: String,
    numeric_suffix: bool,
    suffix_length: uint,
    input: String,
    strategy: String,
    strategy_param: String,
    verbose: bool,
}

struct SplitControl {
    current_line: String, // Don't touch
    request_new_file: bool, // Splitter implementation requests new file
}

trait Splitter {
    // Factory pattern
    fn new(_hint: Option<Self>, &Settings) -> Box<Splitter>;

    // Consume the current_line and return the consumed string
    fn consume(&mut self, &mut SplitControl) -> String;
}

struct LineSplitter {
    saved_lines_to_write: uint,
    lines_to_write: uint,
}

impl Splitter for LineSplitter {
    fn new(_: Option<LineSplitter>, settings: &Settings) -> Box<Splitter> {
        let n = match settings.strategy_param.as_slice().parse() {
            Some(a) => a,
            _ => crash!(1, "invalid number of lines")
        };
        box LineSplitter {
            saved_lines_to_write: n,
            lines_to_write: n,
        } as Box<Splitter>
    }

    fn consume(&mut self, control: &mut SplitControl) -> String {
        self.lines_to_write -= 1;
        if self.lines_to_write == 0 {
            self.lines_to_write = self.saved_lines_to_write;
            control.request_new_file = true;
        }
        control.current_line.clone()
    }
}

struct ByteSplitter {
    saved_bytes_to_write: uint,
    bytes_to_write: uint,
}

impl Splitter for ByteSplitter {
    fn new(_: Option<ByteSplitter>, settings: &Settings) -> Box<Splitter> {
        let mut strategy_param : Vec<char> = settings.strategy_param.chars().collect();
        let suffix = strategy_param.pop().unwrap();
        let multiplier = match suffix {
            '0'...'9' => 1u,
            'b' => 512u,
            'k' => 1024u,
            'm' => 1024u * 1024u,
            _ => crash!(1, "invalid number of bytes")
        };
        let n = if suffix.is_alphabetic() {
            match String::from_chars(strategy_param.as_slice()).as_slice().parse::<uint>() {
                Some(a) => a,
                _ => crash!(1, "invalid number of bytes")
            }
        } else {
            match settings.strategy_param.as_slice().parse::<uint>() {
                Some(a) => a,
                _ => crash!(1, "invalid number of bytes")
            }
        };
        box ByteSplitter {
            saved_bytes_to_write: n * multiplier,
            bytes_to_write: n * multiplier,
        } as Box<Splitter>
    }

    fn consume(&mut self, control: &mut SplitControl) -> String {
        let line = control.current_line.clone();
        let n = std::cmp::min(line.as_slice().chars().count(), self.bytes_to_write);
        self.bytes_to_write -= n;
        if n == 0 {
            self.bytes_to_write = self.saved_bytes_to_write;
            control.request_new_file = true;
        }
        line.as_slice().slice(0, n).to_string()
    }
}

// (1, 3) -> "aab"
fn str_prefix(i: uint, width: uint) -> String {
    let mut c = "".to_string();
    let mut n = i;
    let mut w = width;
    while w > 0 {
        w -= 1;
        let div = Int::pow(26 as uint, w);
        let r = n / div;
        n -= r * div;
        c.push(char::from_u32((r as u32) + 97).unwrap());
    }
    c
}

// (1, 3) -> "001"
fn num_prefix(i: uint, width: uint) -> String {
    let mut c = "".to_string();
    let mut n = i;
    let mut w = width;
    while w > 0 {
        w -= 1;
        let div = Int::pow(10 as uint, w);
        let r = n / div;
        n -= r * div;
        c.push(char::from_digit(r, 10).unwrap());
    }
    c
}

fn split(settings: &Settings) -> int {
    let mut reader = io::BufferedReader::new(
        if settings.input.as_slice() == "-" {
            box io::stdio::stdin_raw() as Box<Reader>
        } else {
            let r = match io::File::open(&Path::new(settings.input.clone())) {
                Ok(a) => a,
                Err(_) => crash!(1, "cannot open '{}' for reading: No such file or directory", settings.input)
            };
            box r as Box<Reader>
        }
    );

    let mut splitter: Box<Splitter> =
        match settings.strategy.as_slice() {
            "l" => Splitter::new(None::<LineSplitter>, settings),
            "b" => Splitter::new(None::<ByteSplitter>, settings),
            a @ _ => crash!(1, "strategy {} not supported", a)
        };

    let mut control = SplitControl {
        current_line: "".to_string(), // Request new line
        request_new_file: true, // Request new file
    };

    let mut writer = io::BufferedWriter::new(box io::stdio::stdout_raw() as Box<Writer>);
    let mut fileno = 0;
    loop {
        if control.current_line.as_slice().chars().count() == 0 {
            match reader.read_line() {
                Ok(a) => { control.current_line = a; }
                Err(_) =>  { break; }
            }
        }

        if control.request_new_file {
            let mut filename = settings.prefix.to_string();
            filename.push_str(if settings.numeric_suffix {
                num_prefix(fileno, settings.suffix_length)
            } else {
                str_prefix(fileno, settings.suffix_length)
            }.as_slice());

            if fileno != 0 {
                crash_if_err!(1, writer.flush());
            }
            fileno += 1;
            writer = io::BufferedWriter::new(box io::File::open_mode(&Path::new(filename.as_slice()), io::Open, io::Write) as Box<Writer>);
            control.request_new_file = false;
        }

        let consumed = splitter.consume(&mut control);
        crash_if_err!(1, writer.write_str(consumed.as_slice()));

        let advance = consumed.as_slice().chars().count();
        let clone = control.current_line.clone();
        let sl = clone.as_slice();
        control.current_line = sl.slice(advance, sl.chars().count()).to_string();
    }
    0
}
<|endoftext|>


<commit_before><commit_msg>Test that binops consume their arguments<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 binary operators consume their arguments

fn add<A: Add<B, ()>, B>(lhs: A, rhs: B) {
    lhs + rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn sub<A: Sub<B, ()>, B>(lhs: A, rhs: B) {
    lhs - rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn mul<A: Mul<B, ()>, B>(lhs: A, rhs: B) {
    lhs * rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn div<A: Div<B, ()>, B>(lhs: A, rhs: B) {
    lhs / rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn rem<A: Rem<B, ()>, B>(lhs: A, rhs: B) {
    lhs % rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn bitand<A: BitAnd<B, ()>, B>(lhs: A, rhs: B) {
    lhs & rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn bitor<A: BitOr<B, ()>, B>(lhs: A, rhs: B) {
    lhs | rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn bitxor<A: BitXor<B, ()>, B>(lhs: A, rhs: B) {
    lhs ^ rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn shl<A: Shl<B, ()>, B>(lhs: A, rhs: B) {
    lhs << rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn shr<A: Shr<B, ()>, B>(lhs: A, rhs: B) {
    lhs >> rhs;
    drop(lhs);  //~ ERROR use of moved value: `lhs`
    drop(rhs);  //~ ERROR use of moved value: `rhs`
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>cubeb-rs: Add example usage of cubeb.<commit_after>// Copyright © 2011 Mozilla Foundation
//
// This program is made available under an ISC-style license.  See the
// accompanying file LICENSE for details.

//! libcubeb api/function test. Plays a simple tone.
extern crate cubeb;

use cubeb::SampleType;
use std::f32::consts::PI;
use std::thread;
use std::time::Duration;

const SAMPLE_FREQUENCY: u32 = 48000;
const STREAM_FORMAT: cubeb::SampleFormat = cubeb::SampleFormat::S16LE;

// store the phase of the generated waveform
struct Tone {
    position: isize
}

impl cubeb::StreamCallback for Tone {
    type Frame = cubeb::MonoFrame<i16>;

    fn data_callback(&mut self, _: &[cubeb::MonoFrame<i16>], output: &mut [cubeb::MonoFrame<i16>]) -> isize {

        // generate our test tone on the fly
        for f in output.iter_mut() {
            // North American dial tone
            let t1 = (2.0 * PI * 350.0 * self.position as f32 / SAMPLE_FREQUENCY as f32).sin();
            let t2 = (2.0 * PI * 440.0 * self.position as f32 / SAMPLE_FREQUENCY as f32).sin();

            f.m = i16::from_float(0.5 * (t1 + t2));

            self.position += 1;
        }

        output.len() as isize
    }

    fn state_callback(&mut self, state: cubeb::State) {
        println!("stream {:?}", state);
    }
}

fn main() {
    let ctx = cubeb::Context::init("Cubeb tone example", None).expect("Failed to create cubeb context");

    // std::unique_ptr<cb_user_data> user_data(new cb_user_data());
    // ASSERT_TRUE(!!user_data) << "Error allocating user data";

    // user_data->position = 0;

    let params = cubeb::StreamParamsBuilder::new()
        .format(STREAM_FORMAT)
        .rate(SAMPLE_FREQUENCY)
        .channels(1)
        .layout(cubeb::ChannelLayout::Mono)
        .take();

    let stream_init_opts = cubeb::StreamInitOptionsBuilder::new()
        .stream_name("Cubeb tone (mono)")
        .output_stream_param(&params)
        .latency(4096)
        .take();

    let stream = ctx.stream_init(
        &stream_init_opts,
        Tone {
            position: 0
        }
    ).expect("Failed to create cubeb stream");

    stream.start().unwrap();
    thread::sleep(Duration::from_millis(500));
    stream.stop().unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Add test case that checks that class members must be prefixed with "self"<commit_after>class cat {
  priv {
    let mut meows : uint;
    fn sleep() { loop{} }
    fn meow() {
      #error("Meow");
      meows += 1u; //! ERROR unresolved name
      sleep();     //! ERROR unresolved name
    }
  }

  new(in_x : uint) { self.meows = in_x; }
}

 fn main() { }<|endoftext|>


<commit_before>extern crate specs;
extern crate futures;
extern crate serde;
extern crate serde_json;
extern crate websocket_server;

use self::specs::{Join, ReadStorage, WriteStorage, System, Entities, EntitiesRes};
use self::futures::{Future, Sink};
use self::websocket_server::Message;
use self::serde::ser::Serialize;

use model::comp::{Pos, Vel, Connect, Disconnect, Player as PlayerComp, Actor};
use model::client::{Message as ClientMessage, OpCode};

use std::collections::HashMap;
use std::fmt::Debug;

pub struct Sending;
impl<'a> System<'a> for Sending {
    #[allow(type_complexity)]
    type SystemData = (ReadStorage<'a, Pos>,
     ReadStorage<'a, Vel>,
     ReadStorage<'a, PlayerComp>,
     ReadStorage<'a, Actor>,
     WriteStorage<'a, Connect>,
     ReadStorage<'a, Disconnect>,
     Entities<'a>);

    fn run(
        &mut self,
        (pos, vel, player, actor, mut connect, disconnect, entities): Self::SystemData,
    ) {

        handle_new_connections(&player, &*entities, &actor, &mut connect);
        handle_disconnects(&player, &actor, &disconnect);

        send_world_updates(&player, &actor, &pos, &vel);
    }
}

fn send<T>(player: &PlayerComp, msg: &ClientMessage<T>)
where
    T: Serialize + Debug,
{
    let msg = serde_json::to_string(&msg).expect(&format!("Failed to serialize object {:?}", msg));
    let send_channel = player.send_channel.clone();
    send_channel.send(Message::Text(msg)).wait().expect(
        "Failed to send message",
    );
}

fn handle_new_connections(
    player: &ReadStorage<PlayerComp>,
    entities: &EntitiesRes,
    actor: &ReadStorage<Actor>,
    connect: &mut WriteStorage<Connect>,
) {
    let mut new_connections = Vec::new();
    for (new_player, entity, new_actor, _) in (player, entities, actor, &mut *connect).join() {
        new_connections.push((entity.clone(), new_actor.clone()));
        let mut actors = Vec::new();
        for actor in (&actor).join() {
            actors.push(actor);
        }
        let msg = ClientMessage::new_greeting(&new_actor.id, &actors);
        send(new_player, &msg);
    }

    for new_connection in new_connections {
        let (new_entity, new_actor) = new_connection;
        connect.remove(new_entity);
        let msg = ClientMessage::new_connection(&new_actor);
        for (player, entity) in (player, entities).join() {
            if entity != new_entity {
                send(player, &msg);
            }
        }
    }
}

fn handle_disconnects(
    player: &ReadStorage<PlayerComp>,
    actor: &ReadStorage<Actor>,
    disconnect: &ReadStorage<Disconnect>,
) {
    for (actor, _) in (actor, disconnect).join() {
        let msg = ClientMessage::new_disconnect(&actor.id);
        for player in (player).join() {
            send(player, &msg);
        }
    }

}

fn send_world_updates(
    player: &ReadStorage<PlayerComp>,
    actor: &ReadStorage<Actor>,
    pos: &ReadStorage<Pos>,
    vel: &ReadStorage<Vel>
) {
    let mut serialized_actors = HashMap::new();
    for actor in (actor).join() {
        serialized_actors.insert(actor.id, HashMap::new());
    }

    for (pos, vel, actor) in (pos, vel, actor).join() {
        let mut actor = serialized_actors.get_mut(&actor.id).unwrap();
        actor.insert("pos", json!(pos));
        actor.insert("vel", json!(vel));
    }

    for (player, actor) in (player, actor).join() {
        let mut actor = serialized_actors.get_mut(&actor.id).unwrap();
        actor.insert("delay", json!(player.delay));
    }
    let json_actors = json!(serialized_actors);
    for player in (player).join() {
        let last_input = json!(player.last_input);
        let payload = hashmap!(
            "last_input" => &last_input,
            "actors" => &json_actors
        );
        let world_state = ClientMessage {
            opcode: OpCode::WorldUpdate,
            payload: &payload
        };
        send(player, &world_state);
    }
}
<commit_msg>Core: Run rustfmt<commit_after>extern crate specs;
extern crate futures;
extern crate serde;
extern crate serde_json;
extern crate websocket_server;

use self::specs::{Join, ReadStorage, WriteStorage, System, Entities, EntitiesRes};
use self::futures::{Future, Sink};
use self::websocket_server::Message;
use self::serde::ser::Serialize;

use model::comp::{Pos, Vel, Connect, Disconnect, Player as PlayerComp, Actor};
use model::client::{Message as ClientMessage, OpCode};

use std::collections::HashMap;
use std::fmt::Debug;

pub struct Sending;
impl<'a> System<'a> for Sending {
    #[allow(type_complexity)]
    type SystemData = (ReadStorage<'a, Pos>,
     ReadStorage<'a, Vel>,
     ReadStorage<'a, PlayerComp>,
     ReadStorage<'a, Actor>,
     WriteStorage<'a, Connect>,
     ReadStorage<'a, Disconnect>,
     Entities<'a>);

    fn run(
        &mut self,
        (pos, vel, player, actor, mut connect, disconnect, entities): Self::SystemData,
    ) {

        handle_new_connections(&player, &*entities, &actor, &mut connect);
        handle_disconnects(&player, &actor, &disconnect);

        send_world_updates(&player, &actor, &pos, &vel);
    }
}

fn send<T>(player: &PlayerComp, msg: &ClientMessage<T>)
where
    T: Serialize + Debug,
{
    let msg = serde_json::to_string(&msg).expect(&format!("Failed to serialize object {:?}", msg));
    let send_channel = player.send_channel.clone();
    send_channel.send(Message::Text(msg)).wait().expect(
        "Failed to send message",
    );
}

fn handle_new_connections(
    player: &ReadStorage<PlayerComp>,
    entities: &EntitiesRes,
    actor: &ReadStorage<Actor>,
    connect: &mut WriteStorage<Connect>,
) {
    let mut new_connections = Vec::new();
    for (new_player, entity, new_actor, _) in (player, entities, actor, &mut *connect).join() {
        new_connections.push((entity.clone(), new_actor.clone()));
        let mut actors = Vec::new();
        for actor in (&actor).join() {
            actors.push(actor);
        }
        let msg = ClientMessage::new_greeting(&new_actor.id, &actors);
        send(new_player, &msg);
    }

    for new_connection in new_connections {
        let (new_entity, new_actor) = new_connection;
        connect.remove(new_entity);
        let msg = ClientMessage::new_connection(&new_actor);
        for (player, entity) in (player, entities).join() {
            if entity != new_entity {
                send(player, &msg);
            }
        }
    }
}

fn handle_disconnects(
    player: &ReadStorage<PlayerComp>,
    actor: &ReadStorage<Actor>,
    disconnect: &ReadStorage<Disconnect>,
) {
    for (actor, _) in (actor, disconnect).join() {
        let msg = ClientMessage::new_disconnect(&actor.id);
        for player in (player).join() {
            send(player, &msg);
        }
    }

}

fn send_world_updates(
    player: &ReadStorage<PlayerComp>,
    actor: &ReadStorage<Actor>,
    pos: &ReadStorage<Pos>,
    vel: &ReadStorage<Vel>,
) {
    let mut serialized_actors = HashMap::new();
    for actor in (actor).join() {
        serialized_actors.insert(actor.id, HashMap::new());
    }

    for (pos, vel, actor) in (pos, vel, actor).join() {
        let mut actor = serialized_actors.get_mut(&actor.id).unwrap();
        actor.insert("pos", json!(pos));
        actor.insert("vel", json!(vel));
    }

    for (player, actor) in (player, actor).join() {
        let mut actor = serialized_actors.get_mut(&actor.id).unwrap();
        actor.insert("delay", json!(player.delay));
    }
    let json_actors = json!(serialized_actors);
    for player in (player).join() {
        let last_input = json!(player.last_input);
        let payload =
            hashmap!(
            "last_input" => &last_input,
            "actors" => &json_actors
        );
        let world_state = ClientMessage {
            opcode: OpCode::WorldUpdate,
            payload: &payload,
        };
        send(player, &world_state);
    }
}
<|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 font_context::FontContext;
use style::computed_values::border_style;
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 extra::arc::Arc;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use geom::side_offsets::SideOffsets2D;
use servo_net::image::base::Image;
use png::{RGBA8, K8, KA8};
use servo_util::geometry::Au;
use std::vec;
use std::libc::types::common::c99::uint16_t;
use std::libc::size_t;

pub struct RenderContext<'self> {
    draw_target: &'self DrawTarget,
    font_ctx: @mut FontContext,
    opts: &'self Opts,
    /// The rectangle that this context encompasses in page coordinates.
    page_rect: Rect<f32>,
    /// The rectangle that this context encompasses in screen coordinates (pixels).
    screen_rect: Rect<uint>,
}

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

    pub fn draw_solid_color(&self, bounds: &Rect<Au>, color: Color) {
        self.draw_target.make_current();
        self.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<border_style::T>) {
        let draw_opts = DrawOptions(1 as AzFloat, 0 as uint16_t);
        let rect = bounds.to_azure_rect();
        let border = border.to_float_px();

        self.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.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.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.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.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 pixel_width = match image.color_type {
            RGBA8 => 4,
            K8    => 1,
            KA8   => 2,
            _     => fail!(~"color type not supported"),
        };
        let stride = image.width * pixel_width;

        self.draw_target.make_current();
        let draw_target_ref = &self.draw_target;
        let azure_surface = draw_target_ref.create_source_surface_from_data(image.pixels, 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.0f64 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.page_rect.origin.x as AzFloat,
                                self.page_rect.origin.y as AzFloat),
                        Size2D(self.screen_rect.size.width as AzFloat,
                               self.screen_rect.size.height as AzFloat));
        self.draw_target.make_current();
        self.draw_target.fill_rect(&rect, &pattern);
    }

    fn apply_border_style(style: border_style::T, border_width: AzFloat, dash: &mut [AzFloat], stroke_opts: &mut StrokeOptions){
        match style{
            border_style::none => {
            }
            border_style::hidden => {
            }
            //FIXME(sammykim): This doesn't work with dash_pattern and cap_style well. I referred firefox code.
            border_style::dotted => {
                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;
            }
            border_style::dashed => {
                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.
            border_style::solid => {
                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.
            //double, groove, ridge, inset, outset
        }
    }
}

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

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

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>push/pop clip<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 font_context::FontContext;
use style::computed_values::border_style;
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 extra::arc::Arc;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use geom::side_offsets::SideOffsets2D;
use servo_net::image::base::Image;
use png::{RGBA8, K8, KA8};
use servo_util::geometry::Au;
use std::vec;
use std::libc::types::common::c99::uint16_t;
use std::libc::size_t;

pub struct RenderContext<'self> {
    draw_target: &'self DrawTarget,
    font_ctx: @mut FontContext,
    opts: &'self Opts,
    /// The rectangle that this context encompasses in page coordinates.
    page_rect: Rect<f32>,
    /// The rectangle that this context encompasses in screen coordinates (pixels).
    screen_rect: Rect<uint>,
}

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

    pub fn draw_solid_color(&self, bounds: &Rect<Au>, color: Color) {
        self.draw_target.make_current();
        self.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<border_style::T>) {
        let draw_opts = DrawOptions(1 as AzFloat, 0 as uint16_t);
        let rect = bounds.to_azure_rect();
        let border = border.to_float_px();

        self.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.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.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.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.draw_target.stroke_line(start,
                                     end,
                                     &ColorPattern(color.left),
                                     &stroke_opts,
                                     &draw_opts);
    }

    pub fn draw_push_clip(&self,
                       bounds: &Rect<Au>,
                       border: SideOffsets2D<f32>
                       ){

        let rect = bounds.to_azure_rect();
        let path_builder = self.draw_target.create_path_builder();

        let left_top = Point2D(rect.origin.x, rect.origin.y);
        let right_top = Point2D(rect.origin.x + rect.size.width, rect.origin.y);
        let left_bottom = Point2D(rect.origin.x, rect.origin.y + rect.size.height);
        let right_bottom = Point2D(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);

        path_builder.move_to(left_top);
        path_builder.line_to(right_top);
        path_builder.line_to(right_bottom);
        path_builder.line_to(left_bottom);

        let path = path_builder.finish();
        self.draw_target.push_clip(&path);
    }

    pub fn draw_pop_clip(&self){
        self.draw_target.pop_clip();
    }

    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 pixel_width = match image.color_type {
            RGBA8 => 4,
            K8    => 1,
            KA8   => 2,
            _     => fail!(~"color type not supported"),
        };
        let stride = image.width * pixel_width;

        self.draw_target.make_current();
        let draw_target_ref = &self.draw_target;
        let azure_surface = draw_target_ref.create_source_surface_from_data(image.pixels, 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.0f64 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.page_rect.origin.x as AzFloat,
                                self.page_rect.origin.y as AzFloat),
                        Size2D(self.screen_rect.size.width as AzFloat,
                               self.screen_rect.size.height as AzFloat));
        self.draw_target.make_current();
        self.draw_target.fill_rect(&rect, &pattern);
    }

    fn apply_border_style(style: border_style::T, border_width: AzFloat, dash: &mut [AzFloat], stroke_opts: &mut StrokeOptions){
        match style{
            border_style::none => {
            }
            border_style::hidden => {
            }
            //FIXME(sammykim): This doesn't work with dash_pattern and cap_style well. I referred firefox code.
            border_style::dotted => {
                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;
            }
            border_style::dashed => {
                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.
            border_style::solid => {
                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.
            //double, groove, ridge, inset, outset
        }
    }
}

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

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

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>use core::fmt::{self, Write};
use core::result;

use system::syscall::{sys_write, sys_exit};

pub struct DebugStream;

impl Write for DebugStream {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let _ = sys_write(2, s.as_bytes());

        result::Result::Ok(())
    }
}

#[lang="panic_fmt"]
#[allow(unused_must_use)]
pub extern "C" fn panic_impl(args: &fmt::Arguments, file: &'static str, line: u32) -> ! {
    let mut stream = DebugStream;
    stream.write_str(file);
    stream.write_fmt(format_args!(":{}: ", line));
    stream.write_fmt(*args);
    stream.write_str("\n");

    loop {
        let _ = sys_exit(128);
    }
}
<commit_msg>Error checking in panic<commit_after>use core::fmt::{self, Write};
use core::result;

use system::syscall::{sys_write, sys_exit};

pub struct DebugStream;

impl Write for DebugStream {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        if let Err(_err) = sys_write(2, s.as_bytes()) {
            result::Result::Err(fmt::Error)
        } else {
            result::Result::Ok(())
        }
    }
}

#[lang="panic_fmt"]
#[allow(unused_must_use)]
pub extern "C" fn panic_impl(args: &fmt::Arguments, file: &'static str, line: u32) -> ! {
    let mut stream = DebugStream;
    stream.write_fmt(format_args!("Panic in {}:{}: {}\n", file, line, *args));

    loop {
        let _ = sys_exit(128);
    }
}
<|endoftext|>


<commit_before><commit_msg>Ingest in a thread pool sharded by railway id.<commit_after><|endoftext|>


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

use LinkerFlavor;
use target::{Target, TargetOptions, TargetResult};

// See https://developer.android.com/ndk/guides/abis.html#v7a
// for target ABI requirements.

pub fn target() -> TargetResult {
    let mut base = super::android_base::opts();
    base.features = "+v7,+thumb2,+vfp3,+d16,-neon".to_string();
    base.max_atomic_width = Some(64);

    Ok(Target {
        llvm_target: "armv7-none-linux-android".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
        arch: "arm".to_string(),
        target_os: "android".to_string(),
        target_env: "".to_string(),
        target_vendor: "unknown".to_string(),
        linker_flavor: LinkerFlavor::Gcc,
        options: TargetOptions {
            abi_blacklist: super::arm_base::abi_blacklist(),
            .. base
        },
    })
}
<commit_msg>Rollup merge of #41657 - malbarbo:android-armv7-linker, r=alexcrichton<commit_after>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use LinkerFlavor;
use target::{Target, TargetOptions, TargetResult};

// See https://developer.android.com/ndk/guides/abis.html#v7a
// for target ABI requirements.

pub fn target() -> TargetResult {
    let mut base = super::android_base::opts();
    base.features = "+v7,+thumb2,+vfp3,+d16,-neon".to_string();
    base.max_atomic_width = Some(64);
    base.pre_link_args
        .get_mut(&LinkerFlavor::Gcc).unwrap().push("-march=armv7-a".to_string());

    Ok(Target {
        llvm_target: "armv7-none-linux-android".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
        arch: "arm".to_string(),
        target_os: "android".to_string(),
        target_env: "".to_string(),
        target_vendor: "unknown".to_string(),
        linker_flavor: LinkerFlavor::Gcc,
        options: TargetOptions {
            abi_blacklist: super::arm_base::abi_blacklist(),
            .. base
        },
    })
}
<|endoftext|>


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

#[macro_use]
extern crate log;
#[macro_use]
extern crate objc;
extern crate objc_foundation;
extern crate cocoa;
extern crate gfx_core as core;
extern crate metal_rs as metal;
extern crate bit_set;

// use cocoa::base::{selector, class};
// use cocoa::foundation::{NSUInteger};

use metal::*;

use core::{handle, texture as tex};
use core::SubmissionResult;
use core::memory::{self, Usage, Bind};
use core::command::{AccessInfo, AccessGuard};

use std::cell::RefCell;
use std::sync::Arc;
// use std::{mem, ptr};

mod factory;
mod encoder;
mod command;
mod mirror;
mod map;

pub use self::command::CommandBuffer;
pub use self::factory::Factory;
pub use self::map::*;

// Grabbed from https://developer.apple.com/metal/limits/
const MTL_MAX_TEXTURE_BINDINGS: usize = 128;
const MTL_MAX_BUFFER_BINDINGS: usize = 31;
const MTL_MAX_SAMPLER_BINDINGS: usize = 16;

/// Internal struct of shared data between the device and its factories.
#[doc(hidden)]
pub struct Share {
    capabilities: core::Capabilities,
    handles: RefCell<handle::Manager<Resources>>,
}

pub mod native {
    use metal::*;

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Buffer(pub *mut MTLBuffer);
    unsafe impl Send for Buffer {}
    unsafe impl Sync for Buffer {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Texture(pub *mut MTLTexture);
    unsafe impl Send for Texture {}
    unsafe impl Sync for Texture {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Sampler(pub MTLSamplerState);
    unsafe impl Send for Sampler {}
    unsafe impl Sync for Sampler {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Rtv(pub *mut MTLTexture);
    unsafe impl Send for Rtv {}
    unsafe impl Sync for Rtv {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Dsv(pub *mut MTLTexture, pub Option<u16>);
    unsafe impl Send for Dsv {}
    unsafe impl Sync for Dsv {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Srv(pub *mut MTLTexture);
    unsafe impl Send for Srv {}
    unsafe impl Sync for Srv {}
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct InputLayout(pub MTLVertexDescriptor);
unsafe impl Send for InputLayout {}
unsafe impl Sync for InputLayout {}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct Shader {
    func: MTLFunction,
}
unsafe impl Send for Shader {}
unsafe impl Sync for Shader {}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct Program {
    vs: MTLFunction,
    ps: MTLFunction,
}
unsafe impl Send for Program {}
unsafe impl Sync for Program {}

pub struct ShaderLibrary {
    lib: MTLLibrary,
}
unsafe impl Send for ShaderLibrary {}
unsafe impl Sync for ShaderLibrary {}

// ShaderLibrary isn't handled via Device.cleanup(). Not really an issue since it will usually
// live for the entire application lifetime and be cloned rarely.
impl Drop for ShaderLibrary {
    fn drop(&mut self) {
        unsafe { self.lib.release() };
    }
}

impl Clone for ShaderLibrary {
    fn clone(&self) -> Self {
        unsafe { self.lib.retain() };
        ShaderLibrary { lib: self.lib }
    }
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct Pipeline {
    pipeline: MTLRenderPipelineState,
    depth_stencil: Option<MTLDepthStencilState>,
    winding: MTLWinding,
    cull: MTLCullMode,
    fill: MTLTriangleFillMode,
    alpha_to_one: bool,
    alpha_to_coverage: bool,
    depth_bias: i32,
    slope_scaled_depth_bias: i32,
    depth_clip: bool,
}
unsafe impl Send for Pipeline {}
unsafe impl Sync for Pipeline {}

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Buffer(native::Buffer, Usage, Bind);

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Texture(native::Texture, Usage);

pub struct Device {
    pub device: MTLDevice,
    pub drawable: *mut CAMetalDrawable,
    pub backbuffer: *mut MTLTexture,
    feature_set: MTLFeatureSet,
    share: Arc<Share>,
    frame_handles: handle::Manager<Resources>,
    max_resource_count: Option<usize>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Fence;

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Resources {}

impl core::Resources for Resources {
    type Buffer = Buffer;
    type Shader = Shader;
    type Program = Program;
    type PipelineStateObject = Pipeline;
    type Texture = Texture;
    type RenderTargetView = native::Rtv;
    type DepthStencilView = native::Dsv;
    type ShaderResourceView = native::Srv;
    type UnorderedAccessView = ();
    type Sampler = native::Sampler;
    type Fence = Fence;
    type Mapping = factory::RawMapping;
}

pub type ShaderModel = u16;

impl Device {
    pub fn get_shader_model(&self) -> ShaderModel {
        use metal::MTLFeatureSet::*;

        match self.feature_set {
            iOS_GPUFamily1_v1 |
            iOS_GPUFamily1_v2 => 10,
            iOS_GPUFamily2_v1 |
            iOS_GPUFamily2_v2 |
            iOS_GPUFamily3_v1 |
            OSX_GPUFamily1_v1 => 11,
        }
    }
}

impl core::Device for Device {
    type Resources = Resources;
    type CommandBuffer = command::CommandBuffer;

    fn get_capabilities(&self) -> &core::Capabilities {
        &self.share.capabilities
    }

    fn pin_submitted_resources(&mut self, man: &handle::Manager<Resources>) {
        self.frame_handles.extend(man);
        match self.max_resource_count {
            Some(c) if self.frame_handles.count() > c => {
                error!("Way too many resources in the current frame. Did you call \
                        Device::cleanup()?");
                self.max_resource_count = None;
            }
            _ => (),
        }
    }

    fn submit(&mut self,
              cb: &mut command::CommandBuffer,
              access: &AccessInfo<Resources>) -> SubmissionResult<()> {
        let _guard = try!(access.take_accesses());
        cb.commit(unsafe { *self.drawable });
        Ok(())
    }

    fn fenced_submit(&mut self,
                     _: &mut Self::CommandBuffer,
                     _: &AccessInfo<Resources>,
                     _after: Option<handle::Fence<Resources>>)
                     -> SubmissionResult<handle::Fence<Resources>> {
        unimplemented!()
    }

    fn wait_fence(&mut self, fence: &handle::Fence<Self::Resources>) {
        unimplemented!()
    }

    fn cleanup(&mut self) {
        use core::handle::Producer;
        self.frame_handles.clear();
        self.share.handles.borrow_mut().clean_with(&mut (),
                                                   |_, _v| {
                                                       // v.0.release();
                                                   }, // buffer
                                                   |_, _s| { //shader
                /*(*s.object).Release();
                (*s.reflection).Release();*/
            },
                                                   |_, _p| {
                                                       // if !p.vs.is_null() { p.vs.release(); }
                                                       // if !p.ps.is_null() { p.ps.release(); }
                                                   }, // program
                                                   |_, _v| { //PSO
                /*type Child = *mut winapi::ID3D11DeviceChild;
                (*v.layout).Release();
                (*(v.rasterizer as Child)).Release();
                (*(v.depth_stencil as Child)).Release();
                (*(v.blend as Child)).Release();*/
            },
                                                   |_, _v| {
                                                       // (*(v.0).0).release();
                                                   }, // texture
                                                   |_, _v| {
                                                       // (*v.0).Release();
                                                   }, // SRV
                                                   |_, _| {}, // UAV
                                                   |_, _v| {
                                                       // (*v.0).Release();
                                                   }, // RTV
                                                   |_, _v| {
                                                       // (*v.0).Release();
                                                   }, // DSV
                                                   |_, _v| {
                                                       // v.sampler.release();
                                                   }, // sampler
                                                   |_, _| {
                                                       // fence
                                                   });
    }
}

#[derive(Clone, Debug)]
pub enum InitError {
    FeatureSet,
}

pub fn create(format: core::format::Format,
              width: u32,
              height: u32)
              -> Result<(Device,
                         Factory,
                         handle::RawRenderTargetView<Resources>,
                         *mut CAMetalDrawable,
                         *mut MTLTexture),
                        InitError> {
    use core::handle::Producer;

    let share = Share {
        capabilities: core::Capabilities {
            max_vertex_count: 0,
            max_index_count: 0,
            max_texture_size: 0,
            max_patch_size: 0,
            instance_base_supported: false,
            instance_call_supported: false,
            instance_rate_supported: false,
            vertex_base_supported: false,
            srgb_color_supported: false,
            constant_buffer_supported: true,
            unordered_access_view_supported: false,
            separate_blending_slots_supported: false,
            copy_buffer_supported: true,
        },
        handles: RefCell::new(handle::Manager::new()),
    };

    let mtl_device = create_system_default_device();
    let feature_sets = {
        use metal::MTLFeatureSet::*;
        [OSX_GPUFamily1_v1,
         //OSX_GPUFamily1_v2,
         iOS_GPUFamily3_v1,
         iOS_GPUFamily2_v2,
         iOS_GPUFamily2_v1,
         iOS_GPUFamily1_v2,
         iOS_GPUFamily1_v1]
    };
    let selected_set = feature_sets.into_iter()
                                   .find(|&&f| mtl_device.supports_feature_set(f));

    let bb = Box::into_raw(Box::new(MTLTexture::nil()));
    let d = Box::into_raw(Box::new(CAMetalDrawable::nil()));

    let device = Device {
        device: mtl_device,
        feature_set: match selected_set {
            Some(&set) => set,
            None => return Err(InitError::FeatureSet),
        },
        share: Arc::new(share),
        frame_handles: handle::Manager::new(),
        max_resource_count: None,

        drawable: d,
        backbuffer: bb,
    };

    // let raw_addr: *mut MTLTexture = ptr::null_mut();//&mut MTLTexture::nil();//unsafe { mem::transmute(&(raw_tex.0).0) };
    let raw_tex = Texture(native::Texture(bb), Usage::Data);

    let color_info = tex::Info {
        kind: tex::Kind::D2(width as tex::Size,
                            height as tex::Size,
                            tex::AaMode::Single),
        levels: 1,
        format: format.0,
        bind: memory::RENDER_TARGET,
        usage: raw_tex.1,
    };
    let color_tex = device.share.handles.borrow_mut().make_texture(raw_tex, color_info);

    let mut factory = Factory::new(mtl_device, device.share.clone());

    let color_target = {
        use core::Factory;

        let desc = tex::RenderDesc {
            channel: format.1,
            level: 0,
            layer: None,
        };

        factory.view_texture_as_render_target_raw(&color_tex, desc).unwrap()
    };

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

#[macro_use]
extern crate log;
#[macro_use]
extern crate objc;
extern crate objc_foundation;
extern crate cocoa;
extern crate gfx_core as core;
extern crate metal_rs as metal;
extern crate bit_set;

// use cocoa::base::{selector, class};
// use cocoa::foundation::{NSUInteger};

use metal::*;

use core::{handle, texture as tex};
use core::SubmissionResult;
use core::memory::{self, Usage, Bind};
use core::command::{AccessInfo, AccessGuard};

use std::cell::RefCell;
use std::sync::Arc;
// use std::{mem, ptr};

mod factory;
mod encoder;
mod command;
mod mirror;
mod map;

pub use self::command::CommandBuffer;
pub use self::factory::Factory;
pub use self::map::*;

// Grabbed from https://developer.apple.com/metal/limits/
const MTL_MAX_TEXTURE_BINDINGS: usize = 128;
const MTL_MAX_BUFFER_BINDINGS: usize = 31;
const MTL_MAX_SAMPLER_BINDINGS: usize = 16;

/// Internal struct of shared data between the device and its factories.
#[doc(hidden)]
pub struct Share {
    capabilities: core::Capabilities,
    handles: RefCell<handle::Manager<Resources>>,
}

pub mod native {
    use metal::*;

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Buffer(pub *mut MTLBuffer);
    unsafe impl Send for Buffer {}
    unsafe impl Sync for Buffer {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Texture(pub *mut MTLTexture);
    unsafe impl Send for Texture {}
    unsafe impl Sync for Texture {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Sampler(pub MTLSamplerState);
    unsafe impl Send for Sampler {}
    unsafe impl Sync for Sampler {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Rtv(pub *mut MTLTexture);
    unsafe impl Send for Rtv {}
    unsafe impl Sync for Rtv {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Dsv(pub *mut MTLTexture, pub Option<u16>);
    unsafe impl Send for Dsv {}
    unsafe impl Sync for Dsv {}

    #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
    pub struct Srv(pub *mut MTLTexture);
    unsafe impl Send for Srv {}
    unsafe impl Sync for Srv {}
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct InputLayout(pub MTLVertexDescriptor);
unsafe impl Send for InputLayout {}
unsafe impl Sync for InputLayout {}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct Shader {
    func: MTLFunction,
}
unsafe impl Send for Shader {}
unsafe impl Sync for Shader {}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct Program {
    vs: MTLFunction,
    ps: MTLFunction,
}
unsafe impl Send for Program {}
unsafe impl Sync for Program {}

pub struct ShaderLibrary {
    lib: MTLLibrary,
}
unsafe impl Send for ShaderLibrary {}
unsafe impl Sync for ShaderLibrary {}

// ShaderLibrary isn't handled via Device.cleanup(). Not really an issue since it will usually
// live for the entire application lifetime and be cloned rarely.
impl Drop for ShaderLibrary {
    fn drop(&mut self) {
        unsafe { self.lib.release() };
    }
}

impl Clone for ShaderLibrary {
    fn clone(&self) -> Self {
        unsafe { self.lib.retain() };
        ShaderLibrary { lib: self.lib }
    }
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct Pipeline {
    pipeline: MTLRenderPipelineState,
    depth_stencil: Option<MTLDepthStencilState>,
    winding: MTLWinding,
    cull: MTLCullMode,
    fill: MTLTriangleFillMode,
    alpha_to_one: bool,
    alpha_to_coverage: bool,
    depth_bias: i32,
    slope_scaled_depth_bias: i32,
    depth_clip: bool,
}
unsafe impl Send for Pipeline {}
unsafe impl Sync for Pipeline {}

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Buffer(native::Buffer, Usage, Bind);

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Texture(native::Texture, Usage);

pub struct Device {
    pub device: MTLDevice,
    pub drawable: *mut CAMetalDrawable,
    pub backbuffer: *mut MTLTexture,
    feature_set: MTLFeatureSet,
    share: Arc<Share>,
    frame_handles: handle::Manager<Resources>,
    max_resource_count: Option<usize>,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Fence;

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Resources {}

impl core::Resources for Resources {
    type Buffer = Buffer;
    type Shader = Shader;
    type Program = Program;
    type PipelineStateObject = Pipeline;
    type Texture = Texture;
    type RenderTargetView = native::Rtv;
    type DepthStencilView = native::Dsv;
    type ShaderResourceView = native::Srv;
    type UnorderedAccessView = ();
    type Sampler = native::Sampler;
    type Fence = Fence;
    type Mapping = factory::RawMapping;
}

pub type ShaderModel = u16;

impl Device {
    pub fn get_shader_model(&self) -> ShaderModel {
        use metal::MTLFeatureSet::*;

        match self.feature_set {
            iOS_GPUFamily1_v1 |
            iOS_GPUFamily1_v2 => 10,
            iOS_GPUFamily2_v1 |
            iOS_GPUFamily2_v2 |
            iOS_GPUFamily3_v1 |
            macOS_GPUFamily1_v1 => 11,
            _ => unimplemented!()
        }
    }
}

impl core::Device for Device {
    type Resources = Resources;
    type CommandBuffer = command::CommandBuffer;

    fn get_capabilities(&self) -> &core::Capabilities {
        &self.share.capabilities
    }

    fn pin_submitted_resources(&mut self, man: &handle::Manager<Resources>) {
        self.frame_handles.extend(man);
        match self.max_resource_count {
            Some(c) if self.frame_handles.count() > c => {
                error!("Way too many resources in the current frame. Did you call \
                        Device::cleanup()?");
                self.max_resource_count = None;
            }
            _ => (),
        }
    }

    fn submit(&mut self,
              cb: &mut command::CommandBuffer,
              access: &AccessInfo<Resources>) -> SubmissionResult<()> {
        let _guard = try!(access.take_accesses());
        cb.commit(unsafe { *self.drawable });
        Ok(())
    }

    fn fenced_submit(&mut self,
                     _: &mut Self::CommandBuffer,
                     _: &AccessInfo<Resources>,
                     _after: Option<handle::Fence<Resources>>)
                     -> SubmissionResult<handle::Fence<Resources>> {
        unimplemented!()
    }

    fn wait_fence(&mut self, fence: &handle::Fence<Self::Resources>) {
        unimplemented!()
    }

    fn cleanup(&mut self) {
        use core::handle::Producer;
        self.frame_handles.clear();
        self.share.handles.borrow_mut().clean_with(&mut (),
                                                   |_, _v| {
                                                       // v.0.release();
                                                   }, // buffer
                                                   |_, _s| { //shader
                /*(*s.object).Release();
                (*s.reflection).Release();*/
            },
                                                   |_, _p| {
                                                       // if !p.vs.is_null() { p.vs.release(); }
                                                       // if !p.ps.is_null() { p.ps.release(); }
                                                   }, // program
                                                   |_, _v| { //PSO
                /*type Child = *mut winapi::ID3D11DeviceChild;
                (*v.layout).Release();
                (*(v.rasterizer as Child)).Release();
                (*(v.depth_stencil as Child)).Release();
                (*(v.blend as Child)).Release();*/
            },
                                                   |_, _v| {
                                                       // (*(v.0).0).release();
                                                   }, // texture
                                                   |_, _v| {
                                                       // (*v.0).Release();
                                                   }, // SRV
                                                   |_, _| {}, // UAV
                                                   |_, _v| {
                                                       // (*v.0).Release();
                                                   }, // RTV
                                                   |_, _v| {
                                                       // (*v.0).Release();
                                                   }, // DSV
                                                   |_, _v| {
                                                       // v.sampler.release();
                                                   }, // sampler
                                                   |_, _| {
                                                       // fence
                                                   });
    }
}

#[derive(Clone, Debug)]
pub enum InitError {
    FeatureSet,
}

pub fn create(format: core::format::Format,
              width: u32,
              height: u32)
              -> Result<(Device,
                         Factory,
                         handle::RawRenderTargetView<Resources>,
                         *mut CAMetalDrawable,
                         *mut MTLTexture),
                        InitError> {
    use core::handle::Producer;

    let share = Share {
        capabilities: core::Capabilities {
            max_vertex_count: 0,
            max_index_count: 0,
            max_texture_size: 0,
            max_patch_size: 0,
            instance_base_supported: false,
            instance_call_supported: false,
            instance_rate_supported: false,
            vertex_base_supported: false,
            srgb_color_supported: false,
            constant_buffer_supported: true,
            unordered_access_view_supported: false,
            separate_blending_slots_supported: false,
            copy_buffer_supported: true,
        },
        handles: RefCell::new(handle::Manager::new()),
    };

    let mtl_device = create_system_default_device();
    let feature_sets = {
        use metal::MTLFeatureSet::*;
        [macOS_GPUFamily1_v1,
         macOS_GPUFamily1_v2,
         iOS_GPUFamily3_v1,
         iOS_GPUFamily2_v2,
         iOS_GPUFamily2_v1,
         iOS_GPUFamily1_v2,
         iOS_GPUFamily1_v1]
    };
    let selected_set = feature_sets.into_iter()
                                   .find(|&&f| mtl_device.supports_feature_set(f));

    let bb = Box::into_raw(Box::new(MTLTexture::nil()));
    let d = Box::into_raw(Box::new(CAMetalDrawable::nil()));

    let device = Device {
        device: mtl_device,
        feature_set: match selected_set {
            Some(&set) => set,
            None => return Err(InitError::FeatureSet),
        },
        share: Arc::new(share),
        frame_handles: handle::Manager::new(),
        max_resource_count: None,

        drawable: d,
        backbuffer: bb,
    };

    // let raw_addr: *mut MTLTexture = ptr::null_mut();//&mut MTLTexture::nil();//unsafe { mem::transmute(&(raw_tex.0).0) };
    let raw_tex = Texture(native::Texture(bb), Usage::Data);

    let color_info = tex::Info {
        kind: tex::Kind::D2(width as tex::Size,
                            height as tex::Size,
                            tex::AaMode::Single),
        levels: 1,
        format: format.0,
        bind: memory::RENDER_TARGET,
        usage: raw_tex.1,
    };
    let color_tex = device.share.handles.borrow_mut().make_texture(raw_tex, color_info);

    let mut factory = Factory::new(mtl_device, device.share.clone());

    let color_target = {
        use core::Factory;

        let desc = tex::RenderDesc {
            channel: format.1,
            level: 0,
            layer: None,
        };

        factory.view_texture_as_render_target_raw(&color_tex, desc).unwrap()
    };

    Ok((device, factory, color_target, d, bb))
}
<|endoftext|>


<commit_before><commit_msg>Allow transaction inputs to be validated individually<commit_after><|endoftext|>