<commit_before><commit_msg>Add a file that fails to compile with rustc (~0.5)<commit_after>extern mod std;

use std::*;
use io::{ReaderUtil,WriterUtil};

enum Result {
  Nil,
  Int(int),
  Data(~[u8]),
  List(~[Result]),
  Error(~str),
  Status(~str)
}

priv fn parse_data(len: uint, io: io::Reader) -> Result {
  let res =
    if (len > 0) {
      let bytes = io.read_bytes(len as uint);
      assert bytes.len() == len;
      Data(bytes)
    } else {
      Data(~[])
    };
  assert io.read_char() == '\r';
  assert io.read_char() == '\n';
  return res;
}

priv fn parse_list(len: uint, io: io::Reader) -> Result {
  let mut list: ~[Result] = ~[];
  for len.times {
    let v =
      match io.read_char() {
        '$' => parse_bulk(io),
        ':' => parse_int(io),
         _  => fail
      };
    list.push(v);
  }
  return List(list);
}

priv fn chop(s: ~str) -> ~str {
  s.slice(0, s.len() - 1)
}

priv fn parse_bulk(io: io::Reader) -> Result {
  match int::from_str(chop(io.read_line())) {
    None => fail,
    Some(-1) => Nil,
    Some(len) if len >= 0 => parse_data(len as uint, io),
    Some(_) => fail
  }
}

priv fn parse_multi(io: io::Reader) -> Result {
  match int::from_str(chop(io.read_line())) {
    None => fail,
    Some(-1) => Nil,
    Some(0) => List(~[]),
    Some(len) if len >= 0 => parse_list(len as uint, io),
    Some(_) => fail
  }
}

priv fn parse_int(io: io::Reader) -> Result {
  match int::from_str(chop(io.read_line())) {
    None => fail,
    Some(i) => Int(i)
  }
}

priv fn parse_response(io: io::Reader) -> Result {
  match io.read_char() {
    '$' => parse_bulk(io),
    '*' => parse_multi(io),
    '+' => Status(chop(io.read_line())),
    '-' => Error(chop(io.read_line())),
    ':' => parse_int(io),
    _   => fail
  }
}

priv fn cmd_to_str(cmd: ~[~str]) -> ~str {
  let mut res = ~"*";
  str::push_str(&mut res, cmd.len().to_str());
  str::push_str(&mut res, "\r\n");
  for cmd.each |s| {
    str::push_str(&mut res, str::concat(~[~"$", s.len().to_str(), ~"\r\n", *s, ~"\r\n"]));
  }
  res
}

fn query(cmd: ~[~str], sb: net::tcp::TcpSocketBuf) -> Result {
  let cmd = cmd_to_str(cmd);
  //io::println(cmd);
  sb.write_str(cmd);
  let res = parse_response(sb as io::Reader);
  //io::println(fmt!("%?", res));
  res
}

fn query2(cmd: ~[~str]) -> Result {
  let cmd = cmd_to_str(cmd);
  do io::with_str_reader(~"$3\r\nXXX\r\n") |sb| {
    let res = parse_response(sb as io::Reader);
    io::println(fmt!("%?", res));
    res
  }
}

fn main() {
  let server_ip_addr = net::ip::v4::parse_addr("127.0.0.1");
  let server_port = 6379;
  let iotask = uv::global_loop::get();
  let connect_result = net::tcp::connect(server_ip_addr, server_port, iotask);
  let sock = result::unwrap(connect_result);
  let sb = net::tcp::socket_buf(sock);

  query(~[~"SET", ~"abc", ~"XXX"], sb);

  for 10_000.times {
    query(~[~"GET", ~"abc"], sb);
  }

  /*query(~[~"MULTI"], sb);
  query(~[~"GET", ~"def"], sb);
  query(~[~"INCR", ~"def"], sb);
  query(~[~"INCR", ~"def"], sb);
  query(~[~"GET", ~"def"], sb);
  query(~[~"EXEC"], sb);

  query(~[~"SET", ~"abc", ~"XXX"], sb);
  query(~[~"SET", ~"def", ~"123"], sb);
  query(~[~"GET", ~"abc"], sb);
  query(~[~"MGET", ~"abc", ~"def", ~"non"], sb);
*/
}
<|endoftext|>


<commit_before><commit_msg>add integration tests (only one for now)<commit_after><|endoftext|>


<commit_before><commit_msg>Use structopt in pg-to-tar.<commit_after><|endoftext|>


<commit_before><commit_msg>it is interesting<commit_after>/// copy from ../cons
use std::sync::Arc;

#[derive(Debug)]
enum Value {
    Nil,
    Integer(i64),
    List(Cons),
}

#[derive(Debug)]
struct Cons {
    car: Arc<Value>,
    cdr: Arc<Value>,
}

fn cons(a: Value, b: Cons) -> Cons {
    Cons {
        car: Arc::new(a),
        cdr: Arc::new(Value::List(b)),
    }
}
/////////////

impl Cons {
    fn flatten(self) -> Vec<Value> {
        let mut result = vec![];
        match Arc::try_unwrap(self.car).unwrap() {
            Value::List(l) => result.append(&mut l.flatten()),
            Value::Integer(v) => result.push(Value::Integer(v)),
            _ => {}
        }
        result
    }
}

fn main() {
    let test0 = cons(
        Value::Integer(1),
        cons(
            cons(Value::Integer(3), cons(Value::Integer(2), Value::Nil)),
            cons(cons(Value::Integer(5), Value::Nil), Value::Nil),
        ),
    );

    dbg!(test0.flatten());
}
<|endoftext|>


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

const _FOO: fn() -> String = || "foo".into();

pub fn bar() -> fn() -> String {
    || "bar".into()
}

fn main(){}
<|endoftext|>


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


<commit_before><commit_msg>Added different resolutions<commit_after><|endoftext|>


<commit_before><commit_msg>add basic perf in main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Update the window title<commit_after><|endoftext|>


<commit_before><commit_msg>Rewrite scene0 to use builder pattern for easy modification<commit_after><|endoftext|>


<commit_before><commit_msg>Added exit statuses<commit_after><|endoftext|>


<commit_before><commit_msg>Improved versions<commit_after><|endoftext|>


<commit_before><commit_msg>Removed superfluous strings from program errors<commit_after><|endoftext|>


<commit_before><commit_msg>Drop unneeded .as_ref()<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unneeded mkdir and optimize a format!<commit_after><|endoftext|>


<commit_before><commit_msg>println! no longer needs empty string for empty line<commit_after><|endoftext|>


<commit_before><commit_msg>error on main thread wont close the program<commit_after><|endoftext|>


<commit_before><commit_msg>Return type of rustboy_core::init changed from Gameboy to Result<Gameboy, &str>.<commit_after><|endoftext|>


<commit_before><commit_msg>Add initial implementation of peer state<commit_after>use std::collections::VecDeque;
use secp256k1::key::PublicKey;

#[derive(Clone)]
struct Peer<'a> {
    ltvk: &'a PublicKey,
    kepks: VecDeque<PublicKey>,
}

impl<'a> Peer<'a> {
    pub fn new(ltvk: &'a PublicKey) -> Self {
        Peer {
            ltvk: ltvk,
            kepks: VecDeque::with_capacity(2),
        }
    }

    pub fn push_kepk(&mut self, kepk: PublicKey) {
        self.kepks.push_back(kepk);
        assert!(self.kepks.len() <= 2);
    }

    pub fn get_kepk(&self) -> &PublicKey {
        self.kepks.get(0).unwrap()
    }

    pub fn shift_keys(&mut self) {
        self.kepks.pop_front().unwrap();
    }
}
<|endoftext|>


<commit_before><commit_msg>more rustup<commit_after><|endoftext|>


<commit_before><commit_msg>add more tiles to view<commit_after><|endoftext|>


<commit_before><commit_msg>ch11 fin<commit_after><|endoftext|>


<commit_before><commit_msg>Reorder drawing logic<commit_after><|endoftext|>


<commit_before><commit_msg>Display info on GD54xxDriver load<commit_after><|endoftext|>


<commit_before><commit_msg>HTTP client is recreated for every request<commit_after><|endoftext|>


<commit_before><commit_msg>fixed windows bugs<commit_after><|endoftext|>


<commit_before><commit_msg>Moving Plugin trait to command.rs and renaming to command<commit_after>use objects::update;

pub trait Command {
    fn execute(&mut self, update::Update);
}
<|endoftext|>


<commit_before><commit_msg>SyncFile: minor cleanup<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed repeat save bug<commit_after><|endoftext|>


<commit_before><commit_msg>testing Chan and Port, need further info on process and task passing in stateful objects and/or &str.<commit_after><|endoftext|>


<commit_before><commit_msg>Only output frame if scanner sync signals are enabled<commit_after><|endoftext|>


<commit_before><commit_msg>Reduce visability of modules<commit_after><|endoftext|>


<commit_before>#[doc = "An atomically reference counted wrapper that can be used
hare immutable data between tasks."]

export arc, get, clone;

#[abi = "cdecl"]
native mod rustrt {
    #[rust_stack]
    fn rust_atomic_increment(p: &mut libc::intptr_t)
        -> libc::intptr_t;

    #[rust_stack]
    fn rust_atomic_decrement(p: &mut libc::intptr_t)
        -> libc::intptr_t;
}

type arc_data<T> = {
    mut count: libc::intptr_t,
    data: T
};

resource arc_destruct<T>(data: *arc_data<T>) {
    unsafe {
        let ptr = &mut (*data).count;

        let new_count = rustrt::rust_atomic_decrement(ptr);
        assert new_count >= 0;
        if new_count == 0 {
            let _ptr : ~arc_data<T> = unsafe::reinterpret_cast(data);
            // drop glue takes over.
        }
    }
}

type arc<T> = arc_destruct<T>;

fn arc<T>(-data: T) -> arc<T> {
    let data = ~{mut count: 1, data: data};
    unsafe {
        let ptr = unsafe::reinterpret_cast(data);
        unsafe::forget(data);
        arc_destruct(ptr)
    }
}

fn get<T>(rc: &a.arc<T>) -> &a.T {
    unsafe {
        &(***rc).data
    }
}

fn clone<T>(rc: &arc<T>) -> arc<T> {
    let data = **rc;
    unsafe {
        rustrt::rust_atomic_increment(&mut (*data).count);
    }
    arc_destruct(**rc)
}
<commit_msg>Some comments giving some idea how to use these things.<commit_after>#[doc = "An atomically reference counted wrapper that can be used to
share immutable data between tasks."]

export arc, get, clone;

#[abi = "cdecl"]
native mod rustrt {
    #[rust_stack]
    fn rust_atomic_increment(p: &mut libc::intptr_t)
        -> libc::intptr_t;

    #[rust_stack]
    fn rust_atomic_decrement(p: &mut libc::intptr_t)
        -> libc::intptr_t;
}

type arc_data<T> = {
    mut count: libc::intptr_t,
    data: T
};

resource arc_destruct<T>(data: *arc_data<T>) {
    unsafe {
        let ptr = &mut (*data).count;

        let new_count = rustrt::rust_atomic_decrement(ptr);
        assert new_count >= 0;
        if new_count == 0 {
            let _ptr : ~arc_data<T> = unsafe::reinterpret_cast(data);
            // drop glue takes over.
        }
    }
}

type arc<T> = arc_destruct<T>;

#[doc="Create an atomically reference counted wrapper."]
fn arc<T>(-data: T) -> arc<T> {
    let data = ~{mut count: 1, data: data};
    unsafe {
        let ptr = unsafe::reinterpret_cast(data);
        unsafe::forget(data);
        arc_destruct(ptr)
    }
}

#[doc="Access the underlying data in an atomically reference counted
 wrapper."]
fn get<T>(rc: &a.arc<T>) -> &a.T {
    unsafe {
        &(***rc).data
    }
}

#[doc="Duplicate an atomically reference counted wrapper.

The resulting two `arc` objects will point to the same underlying data
object. However, one of the `arc` objects can be sent to another task,
allowing them to share the underlying data."]
fn clone<T>(rc: &arc<T>) -> arc<T> {
    let data = **rc;
    unsafe {
        rustrt::rust_atomic_increment(&mut (*data).count);
    }
    arc_destruct(**rc)
}
<|endoftext|>


<commit_before><commit_msg>Git add macro-based example for state composition<commit_after><|endoftext|>


<commit_before><commit_msg>Problem 63<commit_after>enum BinaryTree<T> {
    Node(T, ~BinaryTree<T>, ~BinaryTree<T>),
    Empty
}

fn internals<T>(tree: BinaryTree<T>) -> ~[T] {
    match tree {
        Empty                   => ~[],
        Node(_, ~Empty, ~Empty) => ~[],
        Node(x, ~left, ~right)  =>  (~[x]).move_iter()
                                    .chain(internals(left).move_iter())
                                    .chain(internals(right).move_iter())
                                    .to_owned_vec()
    }
}

fn main() {
    let t1: BinaryTree<uint> = Empty;
    let t2 = Node('x', ~Node('y', ~Empty, ~Empty), ~Node('z', ~Node('t', ~Empty, ~Empty), ~Empty));
    assert_eq!(internals(t1), ~[]);
    assert_eq!(internals(t2), ~['x', 'z']);
}

<|endoftext|>


<commit_before><commit_msg>Change the ordering of some methods in vga_buffer.<commit_after><|endoftext|>


<commit_before><commit_msg>account.banUser method<commit_after><|endoftext|>


<commit_before><commit_msg>Test CACHEDIR.TAG is created in an existing registry<commit_after><|endoftext|>


<commit_before><commit_msg>Parse multiple files into one route.<commit_after><|endoftext|>


<commit_before><commit_msg>Slight change in log macro details<commit_after><|endoftext|>


<commit_before><commit_msg>islocalhead<commit_after><|endoftext|>


<commit_before><commit_msg>[Rust] file open example<commit_after>use std::fs::File;

fn main() {
    let path = "file_open.rs".to_string();
    let f = File::open(&path);
    println!("{:?}", f);
}
<|endoftext|>


<commit_before><commit_msg>equip armor and weapon<commit_after><|endoftext|>


<commit_before><commit_msg>Minor formatting change<commit_after><|endoftext|>


<commit_before>use self::Token::*;
use self::Element::*;
use self::ComparisonOperator::*;
use regex::Regex;
use error::{Error, Result};

#[derive(Clone, Debug, PartialEq)]
pub enum ComparisonOperator {
    Equals,
    NotEquals,
    LessThan,
    GreaterThan,
    LessThanEquals,
    GreaterThanEquals,
    Contains,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Token {
    Pipe,
    Dot,
    Colon,
    Comma,
    OpenSquare,
    CloseSquare,
    OpenRound,
    CloseRound,
    Question,
    Dash,

    Identifier(String),
    StringLiteral(String),
    NumberLiteral(f32),
    DotDot,
    Comparison(ComparisonOperator),
}

#[derive(Clone, Debug, PartialEq)]
pub enum Element {
    Expression(Vec<Token>, String),
    Tag(Vec<Token>, String),
    Raw(String),
}

fn split_blocks(text: &str) -> Vec<&str> {
    let markup = Regex::new("\\{%.*?%\\}|\\{\\{.*?\\}\\}").unwrap();
    let mut tokens = vec![];
    let mut current = 0;
    for (begin, end) in markup.find_iter(text) {
        match &text[current..begin] {
            "" => {}
            t => tokens.push(t),
        }
        tokens.push(&text[begin..end]);
        current = end;
    }
    match &text[current..text.len()] {
        "" => {}
        t => tokens.push(t),
    }
    tokens
}

pub fn tokenize(text: &str) -> Result<Vec<Element>> {
    let expression = Regex::new("\\{\\{(.*?)\\}\\}").unwrap();
    let tag = Regex::new("\\{%(.*?)%\\}").unwrap();

    let mut blocks = vec![];

    for block in split_blocks(text) {
        if let Some(caps) = tag.captures(block) {
            blocks.push(Tag(try!(granularize(caps.at(1).unwrap_or(""))),
                            block.to_string()));
        } else if let Some(caps) = expression.captures(block) {
            blocks.push(Expression(try!(granularize(caps.at(1).unwrap_or(""))),
                                   block.to_string()));
        } else {
            blocks.push(Raw(block.to_string()));
        }
    }

    Ok(blocks)
}

fn split_atom(block: &str) -> Vec<String> {

    let mut vec = vec![];
    let mut buff = String::new();
    for c in block.chars() {
        if c == ' ' {
            if !buff.is_empty() {
                vec.push(buff.clone());
                buff.clear();
            }
        } else if c == ',' || c == ':' {
            if !buff.is_empty() { vec.push(buff.clone()) };
            vec.push(c.to_string());
            buff.clear();
        } else {
            buff.push(c);
        }
    }
    vec.push(buff.clone());
    vec
}

fn granularize(block: &str) -> Result<Vec<Token>> {
    let identifier = Regex::new(r"[a-zA-Z_][\w-]*\??").unwrap();
    let single_string_literal = Regex::new(r"'[^']*'").unwrap();
    let double_string_literal = Regex::new("\"[^\"]*\"").unwrap();
    let number_literal = Regex::new(r"^-?\d+(\.\d+)?$").unwrap();
    let dotdot = Regex::new(r"\.\.").unwrap();

    let mut result = vec![];

    for el in split_atom(block) {
        if el == "" {
            continue;
        }
        result.push(match &*el {
            "|" => Pipe,
            "." => Dot,
            ":" => Colon,
            "," => Comma,
            "[" => OpenSquare,
            "]" => CloseSquare,
            "(" => OpenRound,
            ")" => CloseRound,
            "?" => Question,
            "-" => Dash,

            "==" => Comparison(Equals),
            "!=" => Comparison(NotEquals),
            "<=" => Comparison(LessThanEquals),
            ">=" => Comparison(GreaterThanEquals),
            "<" => Comparison(LessThan),
            ">" => Comparison(GreaterThan),
            "contains" => Comparison(Contains),

            x if dotdot.is_match(x) => DotDot,
            x if single_string_literal.is_match(x) => StringLiteral(x[1..x.len() - 1].to_string()),
            x if double_string_literal.is_match(x) => StringLiteral(x[1..x.len() - 1].to_string()),
            x if number_literal.is_match(x) => NumberLiteral(x.parse::<f32>().expect(&format!("Could not parse {:?} as float", x))),
            x if identifier.is_match(x) => Identifier(x.to_string()),
            x => return Err(Error::Lexer(format!("{} is not a valid identifier", x))),
        });
    }

    Ok(result)
}

#[test]
fn test_split_blocks() {
    assert_eq!(split_blocks("asdlkjfn\n{{askdljfbalkjsdbf}} asdjlfb"),
               vec!["asdlkjfn\n", "{{askdljfbalkjsdbf}}", " asdjlfb"]);
    assert_eq!(split_blocks("asdlkjfn\n{%askdljfbalkjsdbf%} asdjlfb"),
               vec!["asdlkjfn\n", "{%askdljfbalkjsdbf%}", " asdjlfb"]);
}

#[test]
fn test_split_atom() {
    assert_eq!(split_atom("truc | arg:val"), vec!["truc", "|", "arg", ":", "val"]);
    assert_eq!(split_atom("truc | filter:arg1,arg2"), vec!["truc", "|", "filter", ":", "arg1", ",", "arg2"]);
}

#[test]
fn test_tokenize() {
    assert_eq!(tokenize("{{hello 'world'}}").unwrap(),
               vec![Expression(vec![Identifier("hello".to_string()),
                                    StringLiteral("world".to_string())],
                               "{{hello 'world'}}".to_string())]);
    assert_eq!(tokenize("{{hello.world}}").unwrap(),
               vec![Expression(vec![Identifier("hello.world".to_string())],
                               "{{hello.world}}".to_string())]);
    assert_eq!(tokenize("{{ hello 'world' }}").unwrap(),
               vec![Expression(vec![Identifier("hello".to_string()),
                                    StringLiteral("world".to_string())],
                               "{{ hello 'world' }}".to_string())]);
    assert_eq!(tokenize("{{   hello   'world'    }}").unwrap(),
               vec![Expression(vec![Identifier("hello".to_string()),
                                    StringLiteral("world".to_string())],
                               "{{   hello   'world'    }}".to_string())]);
    assert_eq!(tokenize("wat\n{{hello 'world'}} test").unwrap(),
               vec![Raw("wat\n".to_string()),
                    Expression(vec![Identifier("hello".to_string()),
                                    StringLiteral("world".to_string())],
                               "{{hello 'world'}}".to_string()),
                    Raw(" test".to_string())]);
}

#[test]
fn test_granularize() {
    assert_eq!(granularize("test me").unwrap(),
               vec![Identifier("test".to_string()), Identifier("me".to_string())]);
    assert_eq!(granularize("test == me").unwrap(),
               vec![Identifier("test".to_string()),
                    Comparison(Equals),
                    Identifier("me".to_string())]);
    assert_eq!(granularize("'test' == \"me\"").unwrap(),
               vec![StringLiteral("test".to_string()),
                    Comparison(Equals),
                    StringLiteral("me".to_string())]);
    assert_eq!(granularize("test | me:arg").unwrap(),
               vec![Identifier("test".to_string()), Pipe,
               Identifier("me".to_string()), Colon, Identifier("arg".to_string())]);
    assert_eq!(granularize("test | me:arg1,arg2").unwrap(),
               vec![Identifier("test".to_string()), Pipe,
               Identifier("me".to_string()), Colon, Identifier("arg1".to_string()),
               Comma, Identifier("arg2".to_string())]);
    assert_eq!(granularize("test | me : arg1, arg2").unwrap(),
               vec![Identifier("test".to_string()), Pipe,
               Identifier("me".to_string()), Colon, Identifier("arg1".to_string()),
               Comma, Identifier("arg2".to_string())]);
}
<commit_msg>Implement fmt::Display for Tokens<commit_after>use self::Token::*;
use self::Element::*;
use self::ComparisonOperator::*;
use regex::Regex;
use error::{Error, Result};
use std::fmt;

#[derive(Clone, Debug, PartialEq)]
pub enum ComparisonOperator {
    Equals,
    NotEquals,
    LessThan,
    GreaterThan,
    LessThanEquals,
    GreaterThanEquals,
    Contains,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Token {
    Pipe,
    Dot,
    Colon,
    Comma,
    OpenSquare,
    CloseSquare,
    OpenRound,
    CloseRound,
    Question,
    Dash,

    Identifier(String),
    StringLiteral(String),
    NumberLiteral(f32),
    DotDot,
    Comparison(ComparisonOperator),
}

impl fmt::Display for Token {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let out = match *self {
            Pipe => "|".to_owned(),
            Dot => ".".to_owned(),
            Colon => ":".to_owned(),
            Comma => ",".to_owned(),
            OpenSquare => "[".to_owned(),
            CloseSquare => "]".to_owned(),
            OpenRound => "(".to_owned(),
            CloseRound => ")".to_owned(),
            Question => "?".to_owned(),
            Dash => "-".to_owned(),
            DotDot => "..".to_owned(),

            Comparison(Equals) => "==".to_owned(),
            Comparison(NotEquals) => "!=".to_owned(),
            Comparison(LessThanEquals) => "<=".to_owned(),
            Comparison(GreaterThanEquals) => ">=".to_owned(),
            Comparison(LessThan) => "<".to_owned(),
            Comparison(GreaterThan) => ">".to_owned(),
            Comparison(Contains) => "contains".to_owned(),
            Identifier(ref x) => x.clone(),
            StringLiteral(ref x) => x.clone(),
            NumberLiteral(ref x) => x.to_string(),
        };
        write!(f, "{}", out)
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum Element {
    Expression(Vec<Token>, String),
    Tag(Vec<Token>, String),
    Raw(String),
}

fn split_blocks(text: &str) -> Vec<&str> {
    let markup = Regex::new("\\{%.*?%\\}|\\{\\{.*?\\}\\}").unwrap();
    let mut tokens = vec![];
    let mut current = 0;
    for (begin, end) in markup.find_iter(text) {
        match &text[current..begin] {
            "" => {}
            t => tokens.push(t),
        }
        tokens.push(&text[begin..end]);
        current = end;
    }
    match &text[current..text.len()] {
        "" => {}
        t => tokens.push(t),
    }
    tokens
}

pub fn tokenize(text: &str) -> Result<Vec<Element>> {
    let expression = Regex::new("\\{\\{(.*?)\\}\\}").unwrap();
    let tag = Regex::new("\\{%(.*?)%\\}").unwrap();

    let mut blocks = vec![];

    for block in split_blocks(text) {
        if let Some(caps) = tag.captures(block) {
            blocks.push(Tag(try!(granularize(caps.at(1).unwrap_or(""))),
                            block.to_string()));
        } else if let Some(caps) = expression.captures(block) {
            blocks.push(Expression(try!(granularize(caps.at(1).unwrap_or(""))),
                                   block.to_string()));
        } else {
            blocks.push(Raw(block.to_string()));
        }
    }

    Ok(blocks)
}

fn split_atom(block: &str) -> Vec<String> {

    let mut vec = vec![];
    let mut buff = String::new();
    for c in block.chars() {
        if c == ' ' {
            if !buff.is_empty() {
                vec.push(buff.clone());
                buff.clear();
            }
        } else if c == ',' || c == ':' {
            if !buff.is_empty() { vec.push(buff.clone()) };
            vec.push(c.to_string());
            buff.clear();
        } else {
            buff.push(c);
        }
    }
    vec.push(buff.clone());
    vec
}

fn granularize(block: &str) -> Result<Vec<Token>> {
    let identifier = Regex::new(r"[a-zA-Z_][\w-]*\??").unwrap();
    let single_string_literal = Regex::new(r"'[^']*'").unwrap();
    let double_string_literal = Regex::new("\"[^\"]*\"").unwrap();
    let number_literal = Regex::new(r"^-?\d+(\.\d+)?$").unwrap();
    let dotdot = Regex::new(r"\.\.").unwrap();

    let mut result = vec![];

    for el in split_atom(block) {
        if el == "" {
            continue;
        }
        result.push(match &*el {
            "|" => Pipe,
            "." => Dot,
            ":" => Colon,
            "," => Comma,
            "[" => OpenSquare,
            "]" => CloseSquare,
            "(" => OpenRound,
            ")" => CloseRound,
            "?" => Question,
            "-" => Dash,

            "==" => Comparison(Equals),
            "!=" => Comparison(NotEquals),
            "<=" => Comparison(LessThanEquals),
            ">=" => Comparison(GreaterThanEquals),
            "<" => Comparison(LessThan),
            ">" => Comparison(GreaterThan),
            "contains" => Comparison(Contains),

            x if dotdot.is_match(x) => DotDot,
            x if single_string_literal.is_match(x) => StringLiteral(x[1..x.len() - 1].to_string()),
            x if double_string_literal.is_match(x) => StringLiteral(x[1..x.len() - 1].to_string()),
            x if number_literal.is_match(x) => NumberLiteral(x.parse::<f32>().expect(&format!("Could not parse {:?} as float", x))),
            x if identifier.is_match(x) => Identifier(x.to_string()),
            x => return Err(Error::Lexer(format!("{} is not a valid identifier", x))),
        });
    }

    Ok(result)
}

#[test]
fn test_split_blocks() {
    assert_eq!(split_blocks("asdlkjfn\n{{askdljfbalkjsdbf}} asdjlfb"),
               vec!["asdlkjfn\n", "{{askdljfbalkjsdbf}}", " asdjlfb"]);
    assert_eq!(split_blocks("asdlkjfn\n{%askdljfbalkjsdbf%} asdjlfb"),
               vec!["asdlkjfn\n", "{%askdljfbalkjsdbf%}", " asdjlfb"]);
}

#[test]
fn test_split_atom() {
    assert_eq!(split_atom("truc | arg:val"), vec!["truc", "|", "arg", ":", "val"]);
    assert_eq!(split_atom("truc | filter:arg1,arg2"), vec!["truc", "|", "filter", ":", "arg1", ",", "arg2"]);
}

#[test]
fn test_tokenize() {
    assert_eq!(tokenize("{{hello 'world'}}").unwrap(),
               vec![Expression(vec![Identifier("hello".to_string()),
                                    StringLiteral("world".to_string())],
                               "{{hello 'world'}}".to_string())]);
    assert_eq!(tokenize("{{hello.world}}").unwrap(),
               vec![Expression(vec![Identifier("hello.world".to_string())],
                               "{{hello.world}}".to_string())]);
    assert_eq!(tokenize("{{ hello 'world' }}").unwrap(),
               vec![Expression(vec![Identifier("hello".to_string()),
                                    StringLiteral("world".to_string())],
                               "{{ hello 'world' }}".to_string())]);
    assert_eq!(tokenize("{{   hello   'world'    }}").unwrap(),
               vec![Expression(vec![Identifier("hello".to_string()),
                                    StringLiteral("world".to_string())],
                               "{{   hello   'world'    }}".to_string())]);
    assert_eq!(tokenize("wat\n{{hello 'world'}} test").unwrap(),
               vec![Raw("wat\n".to_string()),
                    Expression(vec![Identifier("hello".to_string()),
                                    StringLiteral("world".to_string())],
                               "{{hello 'world'}}".to_string()),
                    Raw(" test".to_string())]);
}

#[test]
fn test_granularize() {
    assert_eq!(granularize("test me").unwrap(),
               vec![Identifier("test".to_string()), Identifier("me".to_string())]);
    assert_eq!(granularize("test == me").unwrap(),
               vec![Identifier("test".to_string()),
                    Comparison(Equals),
                    Identifier("me".to_string())]);
    assert_eq!(granularize("'test' == \"me\"").unwrap(),
               vec![StringLiteral("test".to_string()),
                    Comparison(Equals),
                    StringLiteral("me".to_string())]);
    assert_eq!(granularize("test | me:arg").unwrap(),
               vec![Identifier("test".to_string()), Pipe,
               Identifier("me".to_string()), Colon, Identifier("arg".to_string())]);
    assert_eq!(granularize("test | me:arg1,arg2").unwrap(),
               vec![Identifier("test".to_string()), Pipe,
               Identifier("me".to_string()), Colon, Identifier("arg1".to_string()),
               Comma, Identifier("arg2".to_string())]);
    assert_eq!(granularize("test | me : arg1, arg2").unwrap(),
               vec![Identifier("test".to_string()), Pipe,
               Identifier("me".to_string()), Colon, Identifier("arg1".to_string()),
               Comma, Identifier("arg2".to_string())]);
}
<|endoftext|>


<commit_before><commit_msg>Add integration test checking false positive rate and also includes a simple check for no false negatives.<commit_after>extern crate cuckoofilter;
use cuckoofilter::CuckooFilter;
use std::collections::hash_map::DefaultHasher;

// Modelled after
// https://github.com/efficient/cuckoofilter/blob/master/example/test.cc
// to make test setup and results comparable.

#[test]
fn false_positive_rate() {
    let total_items = 1_000_000;

    let mut filter = CuckooFilter::<DefaultHasher>::with_capacity(total_items);

    let mut num_inserted: u64 = 0;
    // We might not be able to get all items in, but still there should be enough
    // so we can just use what has fit in and continue with the test.
    for i in 0..total_items {
        if filter.add(&i) {
            num_inserted += 1;
        } else {
            break;
        }
    }

    // The range 0..num_inserted are all known to be in the filter.
    // The filter shouldn't return false negatives, and therefore they should all be contained.
    for i in 0..num_inserted {
        assert!(filter.contains(&i));
    }

    // The range total_items..(2 * total_items) are all known *not* to be in the filter.
    // Every element for which the filter claims that it is contained is therefore a false positive.
    let mut false_queries: u64 = 0;
    for i in total_items..(2 * total_items) {
        if filter.contains(&i) {
            false_queries += 1;
        }
    }
    let false_positive_rate = (false_queries as f64) / (total_items as f64);

    println!("elements inserted: {}", num_inserted);
    println!("memory usage: {:.2}KiB", (filter.memory_usage() as f64) / 1024.0);
    println!("false positive rate: {}%", 100.0 * false_positive_rate);
    // ratio should be around 0.024, round up to 0.03 to accomodate for random fluctuation
    assert!(false_positive_rate < 0.03);
}
<|endoftext|>


<commit_before><commit_msg>More s-expressions<commit_after><|endoftext|>


<commit_before><commit_msg>video.getCatalogSection method<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #74449 - tmiasko:cmpxchg-test, r=nikomatsakis<commit_after>// Code generation of atomic operations.
//
// compile-flags: -O
#![crate_type = "lib"]

use std::sync::atomic::{AtomicI32, Ordering::*};

// CHECK-LABEL: @compare_exchange
#[no_mangle]
pub fn compare_exchange(a: &AtomicI32) {
    // CHECK: cmpxchg i32* %{{.*}}, i32 0, i32 10 monotonic monotonic
    let _ = a.compare_exchange(0, 10, Relaxed, Relaxed);

    // CHECK: cmpxchg i32* %{{.*}}, i32 0, i32 20 release monotonic
    let _ = a.compare_exchange(0, 20, Release, Relaxed);

    // CHECK: cmpxchg i32* %{{.*}}, i32 0, i32 30 acquire monotonic
    // CHECK: cmpxchg i32* %{{.*}}, i32 0, i32 31 acquire acquire
    let _ = a.compare_exchange(0, 30, Acquire, Relaxed);
    let _ = a.compare_exchange(0, 31, Acquire, Acquire);

    // CHECK: cmpxchg i32* %{{.*}}, i32 0, i32 40 acq_rel monotonic
    // CHECK: cmpxchg i32* %{{.*}}, i32 0, i32 41 acq_rel acquire
    let _ = a.compare_exchange(0, 40, AcqRel, Relaxed);
    let _ = a.compare_exchange(0, 41, AcqRel, Acquire);

    // CHECK: cmpxchg i32* %{{.*}}, i32 0, i32 50 seq_cst monotonic
    // CHECK: cmpxchg i32* %{{.*}}, i32 0, i32 51 seq_cst acquire
    // CHECK: cmpxchg i32* %{{.*}}, i32 0, i32 52 seq_cst seq_cst
    let _ = a.compare_exchange(0, 50, SeqCst, Relaxed);
    let _ = a.compare_exchange(0, 51, SeqCst, Acquire);
    let _ = a.compare_exchange(0, 52, SeqCst, SeqCst);
}

// CHECK-LABEL: @compare_exchange_weak
#[no_mangle]
pub fn compare_exchange_weak(w: &AtomicI32) {
    // CHECK: cmpxchg weak i32* %{{.*}}, i32 1, i32 10 monotonic monotonic
    let _ = w.compare_exchange_weak(1, 10, Relaxed, Relaxed);

    // CHECK: cmpxchg weak i32* %{{.*}}, i32 1, i32 20 release monotonic
    let _ = w.compare_exchange_weak(1, 20, Release, Relaxed);

    // CHECK: cmpxchg weak i32* %{{.*}}, i32 1, i32 30 acquire monotonic
    // CHECK: cmpxchg weak i32* %{{.*}}, i32 1, i32 31 acquire acquire
    let _ = w.compare_exchange_weak(1, 30, Acquire, Relaxed);
    let _ = w.compare_exchange_weak(1, 31, Acquire, Acquire);

    // CHECK: cmpxchg weak i32* %{{.*}}, i32 1, i32 40 acq_rel monotonic
    // CHECK: cmpxchg weak i32* %{{.*}}, i32 1, i32 41 acq_rel acquire
    let _ = w.compare_exchange_weak(1, 40, AcqRel, Relaxed);
    let _ = w.compare_exchange_weak(1, 41, AcqRel, Acquire);

    // CHECK: cmpxchg weak i32* %{{.*}}, i32 1, i32 50 seq_cst monotonic
    // CHECK: cmpxchg weak i32* %{{.*}}, i32 1, i32 51 seq_cst acquire
    // CHECK: cmpxchg weak i32* %{{.*}}, i32 1, i32 52 seq_cst seq_cst
    let _ = w.compare_exchange_weak(1, 50, SeqCst, Relaxed);
    let _ = w.compare_exchange_weak(1, 51, SeqCst, Acquire);
    let _ = w.compare_exchange_weak(1, 52, SeqCst, SeqCst);
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue #23389<commit_after>macro_rules! invalid { //~ ERROR Invalid macro matcher
    _ => ();
}

fn main() {
}
<|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 flow::Flow;
use flow_ref::FlowRef;

use std::collections::{linked_list, LinkedList};

// This needs to be reworked now that we have dynamically-sized types in Rust.
// Until then, it's just a wrapper around LinkedList.

pub struct FlowList {
    flows: LinkedList<FlowRef>,
}

pub struct FlowListIterator<'a> {
    it: linked_list::Iter<'a, FlowRef>,
}

pub struct MutFlowListIterator<'a> {
    it: linked_list::IterMut<'a, FlowRef>,
}

impl FlowList {
    /// Provide a reference to the front element, or None if the list is empty
    #[inline]
    pub fn front<'a>(&'a self) -> Option<&'a Flow> {
        self.flows.front().map(|head| &**head)
    }

    /// Provide a mutable reference to the front element, or None if the list is empty
    #[inline]
    #[allow(unsafe_code)]
    pub unsafe fn front_mut<'a>(&'a mut self) -> Option<&'a mut Flow> {
        self.flows.front_mut().map(|head| &mut **head)
    }

    /// Provide a reference to the back element, or None if the list is empty
    #[inline]
    pub fn back<'a>(&'a self) -> Option<&'a Flow> {
        self.flows.back().map(|tail| &**tail)
    }

    /// Provide a mutable reference to the back element, or None if the list is empty
    #[inline]
    #[allow(unsafe_code)]
    pub unsafe fn back_mut<'a>(&'a mut self) -> Option<&'a mut Flow> {
        self.flows.back_mut().map(|tail| &mut **tail)
    }

    /// Add an element first in the list
    ///
    /// O(1)
    pub fn push_front(&mut self, new_head: FlowRef) {
        self.flows.push_front(new_head);
    }

    /// Remove the first element and return it, or None if the list is empty
    ///
    /// O(1)
    pub fn pop_front(&mut self) -> Option<FlowRef> {
        self.flows.pop_front()
    }

    /// Add an element last in the list
    ///
    /// O(1)
    pub fn push_back(&mut self, new_tail: FlowRef) {
        self.flows.push_back(new_tail);
    }

    /// Create an empty list
    #[inline]
    pub fn new() -> FlowList {
        FlowList {
            flows: LinkedList::new(),
        }
    }

    /// Provide a forward iterator
    #[inline]
    pub fn iter<'a>(&'a self) -> FlowListIterator<'a> {
        FlowListIterator {
            it: self.flows.iter(),
        }
    }

    /// Provide a forward iterator with mutable references
    #[inline]
    pub fn iter_mut<'a>(&'a mut self) -> MutFlowListIterator<'a> {
        MutFlowListIterator {
            it: self.flows.iter_mut(),
        }
    }

    /// O(1)
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.flows.is_empty()
    }

    /// O(1)
    #[inline]
    pub fn len(&self) -> uint {
        self.flows.len()
    }
}

impl<'a> Iterator for FlowListIterator<'a> {
    type Item = &'a (Flow + 'a);
    #[inline]
    fn next(&mut self) -> Option<&'a (Flow + 'a)> {
        self.it.next().map(|x| &**x)
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        self.it.size_hint()
    }
}

impl<'a> Iterator for MutFlowListIterator<'a> {
    type Item = &'a mut (Flow + 'a);
    #[inline]
    fn next(&mut self) -> Option<&'a mut (Flow + 'a)> {
        self.it.next().map(|x| &mut **x)
    }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) {
        self.it.size_hint()
    }
}
<commit_msg>Use usize in flow_list.<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 flow::Flow;
use flow_ref::FlowRef;

use std::collections::{linked_list, LinkedList};

// This needs to be reworked now that we have dynamically-sized types in Rust.
// Until then, it's just a wrapper around LinkedList.

pub struct FlowList {
    flows: LinkedList<FlowRef>,
}

pub struct FlowListIterator<'a> {
    it: linked_list::Iter<'a, FlowRef>,
}

pub struct MutFlowListIterator<'a> {
    it: linked_list::IterMut<'a, FlowRef>,
}

impl FlowList {
    /// Provide a reference to the front element, or None if the list is empty
    #[inline]
    pub fn front<'a>(&'a self) -> Option<&'a Flow> {
        self.flows.front().map(|head| &**head)
    }

    /// Provide a mutable reference to the front element, or None if the list is empty
    #[inline]
    #[allow(unsafe_code)]
    pub unsafe fn front_mut<'a>(&'a mut self) -> Option<&'a mut Flow> {
        self.flows.front_mut().map(|head| &mut **head)
    }

    /// Provide a reference to the back element, or None if the list is empty
    #[inline]
    pub fn back<'a>(&'a self) -> Option<&'a Flow> {
        self.flows.back().map(|tail| &**tail)
    }

    /// Provide a mutable reference to the back element, or None if the list is empty
    #[inline]
    #[allow(unsafe_code)]
    pub unsafe fn back_mut<'a>(&'a mut self) -> Option<&'a mut Flow> {
        self.flows.back_mut().map(|tail| &mut **tail)
    }

    /// Add an element first in the list
    ///
    /// O(1)
    pub fn push_front(&mut self, new_head: FlowRef) {
        self.flows.push_front(new_head);
    }

    /// Remove the first element and return it, or None if the list is empty
    ///
    /// O(1)
    pub fn pop_front(&mut self) -> Option<FlowRef> {
        self.flows.pop_front()
    }

    /// Add an element last in the list
    ///
    /// O(1)
    pub fn push_back(&mut self, new_tail: FlowRef) {
        self.flows.push_back(new_tail);
    }

    /// Create an empty list
    #[inline]
    pub fn new() -> FlowList {
        FlowList {
            flows: LinkedList::new(),
        }
    }

    /// Provide a forward iterator
    #[inline]
    pub fn iter<'a>(&'a self) -> FlowListIterator<'a> {
        FlowListIterator {
            it: self.flows.iter(),
        }
    }

    /// Provide a forward iterator with mutable references
    #[inline]
    pub fn iter_mut<'a>(&'a mut self) -> MutFlowListIterator<'a> {
        MutFlowListIterator {
            it: self.flows.iter_mut(),
        }
    }

    /// O(1)
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.flows.is_empty()
    }

    /// O(1)
    #[inline]
    pub fn len(&self) -> usize {
        self.flows.len()
    }
}

impl<'a> Iterator for FlowListIterator<'a> {
    type Item = &'a (Flow + 'a);
    #[inline]
    fn next(&mut self) -> Option<&'a (Flow + 'a)> {
        self.it.next().map(|x| &**x)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.it.size_hint()
    }
}

impl<'a> Iterator for MutFlowListIterator<'a> {
    type Item = &'a mut (Flow + 'a);
    #[inline]
    fn next(&mut self) -> Option<&'a mut (Flow + 'a)> {
        self.it.next().map(|x| &mut **x)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.it.size_hint()
    }
}
<|endoftext|>


<commit_before>/*
 * Abstract Factory Design Pattern
 * http://joshldavis.com/rust-design-patterns/abstract-factory/
 */

/*
 * Core Trait that defines a Phone
 */
trait Phone {
    fn call(&self);
}

/*
 * Core Trait that defines a Tablet
 */
trait Tablet {
    fn play_games(&self);
}

/*
 * Core Trait that defines a Factory
 */
trait Factory<P: Phone, T: Tablet> {
    fn new_phone(&self) -> P;
    fn new_tablet(&self) -> T;
}

/*
 * Define our Apple products. Normally these structs would contain a lot more
 * data.
 */
struct iPhone;

impl Phone for iPhone {
    fn call(&self) {
        println("Look! I'm calling on an iPhone!");
    }
}

struct iPad;

impl Tablet for iPad {
    fn play_games(&self) {
        println("Just playing some games on my iPad.");
    }
}

/*
 * This would contain all stuff required to make Apple devices.
 */
struct AppleFactory;

impl Factory<iPhone, iPad> for AppleFactory {
    fn new_phone(&self) -> iPhone {
        return iPhone;
    }

    fn new_tablet(&self) -> iPad {
        return iPad;
    }
}

/*
 * Define our Google products. Like with Apple's products, these are
 * simplified.
 */

struct Nexus4;

impl Phone for Nexus4 {
    fn call(&self) {
        println("Look! I'm calling on a Nexus 4!");
    }
}

struct Nexus10;

impl Tablet for Nexus10 {
    fn play_games(&self) {
        println("Just playing some games on my Nexus 10.");
    }
}

/*
 * This would contain all stuff required to make Google devices.
 */
struct GoogleFactory;

impl Factory<Nexus4, Nexus10> for GoogleFactory {
    fn new_phone(&self) -> Nexus4 {
        return Nexus4;
    }

    fn new_tablet(&self) -> Nexus10 {
        return Nexus10;
    }
}

fn main() {
    let google = AppleFactory;
    let apple = GoogleFactory;

    let phone = apple.new_phone();
    phone.call();

    let phone = google.new_phone();
    phone.call();

    let tablet = apple.new_tablet();
    tablet.play_games();

    let tablet = google.new_tablet();
    tablet.play_games();
}
<commit_msg>Document Abstract Factory better<commit_after>/*
 * Abstract Factory Design Pattern
 * http://joshldavis.com/rust-design-patterns/abstract-factory/
 */

/*
 * Core Trait that defines a Phone
 */
trait Phone {
    fn call(&self);
}

/*
 * Core Trait that defines a Tablet
 */
trait Tablet {
    fn play_games(&self);
}

/*
 * Core Trait that defines a Factory
 */
trait Factory<P: Phone, T: Tablet> {
    fn new_phone(&self) -> P;
    fn new_tablet(&self) -> T;
}

/*
 * Define our Apple products. Normally these structs would contain a lot more
 * data.
 */
struct iPhone;

impl Phone for iPhone {
    fn call(&self) {
        println("Look! I'm calling on an iPhone!");
    }
}

struct iPad;

impl Tablet for iPad {
    fn play_games(&self) {
        println("Just playing some games on my iPad.");
    }
}

/*
 * Create AppleFactory and implement it for our Apple devices
 */
struct AppleFactory;

impl Factory<iPhone, iPad> for AppleFactory {
    fn new_phone(&self) -> iPhone {
        return iPhone;
    }

    fn new_tablet(&self) -> iPad {
        return iPad;
    }
}

/*
 * Define our Google products. Like with Apple's products, these are
 * simplified.
 */

struct Nexus4;

impl Phone for Nexus4 {
    fn call(&self) {
        println("Look! I'm calling on a Nexus 4!");
    }
}

struct Nexus10;

impl Tablet for Nexus10 {
    fn play_games(&self) {
        println("Just playing some games on my Nexus 10.");
    }
}

/*
 * Create GoogleFactory and implement it for our Google devices
 */
struct GoogleFactory;

impl Factory<Nexus4, Nexus10> for GoogleFactory {
    fn new_phone(&self) -> Nexus4 {
        return Nexus4;
    }

    fn new_tablet(&self) -> Nexus10 {
        return Nexus10;
    }
}

fn main() {
    // Create our two different factories
    let google = AppleFactory;
    let apple = GoogleFactory;

    // Both factories use the same interface, so let's just use them

    // Test out creating phones
    let phone = apple.new_phone();
    phone.call();

    let phone = google.new_phone();
    phone.call();

    // Test out creating tablets
    let tablet = apple.new_tablet();
    tablet.play_games();

    let tablet = google.new_tablet();
    tablet.play_games();
}
<|endoftext|>


<commit_before><commit_msg>Create try-rust.rs<commit_after>fn main() {
    greet_the_world();

    // * the following two declarations
    //   are the same - aside from identifiers.
    // * they are both immutable.
    // * therefore, they must be initialised
    //   immediately
    let x = 5i;
    let y:int = 5;

    // this declares a mutable variable:
    let mut z = 10i;
    z = 100i; // tada!

    if z >= 50i {
        println!("z is a big number");
    } else {
        println!("z isn't a big number");
    }

    // similar to a ternary operator:
    let a = if x > 1 { true } else { false };
    // (these need semicolons)

    describe_number(200i);
    describe_number(23i);
}

// argument types must be specified
// ... and so must return types
fn describe_number(number: int) -> int {
    println!("the number is {}", number);

    let big = if number > 50 { "is big" } else { "isn't big" };
    println!("the number {}", big);

    number // ruby-esque return statements
           // don't need a semicolon, or else rust
           // would look for another expression to return
           // (and there isn't one, thrfr. the return type
           // would be a lie)
}

// * what follows is a doc comment (notice the triple slash):
// * doc comments support markdown!
// * `rustdoc` will generate HTML documentation from doc comments.

/// `greet_the_world` is a useless function that prints a string
/// that can be used for greeting the world.
///
/// # Arguments
///
/// * there are no arguments
///
/// # Example
///
/// ```rust
/// fn main() {
///     greet_the_world(); // prints 'hello, world'
/// }
/// ```
fn greet_the_world() {
    println!("hello, world");
}

<|endoftext|>


<commit_before><commit_msg>Auto merge of #24741 - cgwalters:note-setenv-and-unsetenv-are-not-threadsafe, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>Implement sparklines<commit_after>/// Number of ticks.
const N: usize = 8;
/// Ticks used for the sparkline.
static TICKS: [char; N] = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];

/// Render a sparkline of `data` into `buffer`.
pub fn render_u64(data: &[u64], buffer: &mut String) {
    match data.len() {
        0 => {
            return;
        },
        1 => {
            if data[0] == 0 {
                buffer.push(TICKS[0]);
            } else {
                buffer.push(TICKS[N - 1]);
            }
            return;
        },
        _ => {},
    }
    let max = data.iter().max().unwrap();
    let min = data.iter().min().unwrap();
    let scale = ((N - 1) as f64) / ((max - min) as f64);
    for i in data {
        let tick = (((i - min) as f64) * scale) as usize;
        buffer.push(TICKS[tick]);
    }
}

/// Calculate the required capacity for the sparkline, given the length of the
/// input data.
pub fn required_capacity(len: usize) -> usize {
    len * TICKS[0].len_utf8()
}

/// Render a sparkline of `data` into a newly allocated string.
pub fn render_u64_as_string(data: &[u64]) -> String {
    let cap = required_capacity(data.len());
    let mut s = String::with_capacity(cap);
    render_u64(data, &mut s);
    debug_assert_eq!(s.capacity(), cap);
    s
}

/// Render a sparkline of `data` into `buffer`.
pub fn render_f64(data: &[f64], buffer: &mut String) {
    match data.len() {
        0 => {
            return;
        },
        1 => {
            if data[0] == 0. {
                buffer.push(TICKS[0]);
            } else {
                buffer.push(TICKS[N - 1]);
            }
            return;
        },
        _ => {},
    }
    for x in data {
        assert!(x.is_finite(), "can only render finite values");
    }
    let max = data.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));
    let min = data.iter().fold(f64::INFINITY, |a, &b| a.min(b));
    let scale = ((N - 1) as f64) / (max - min);
    for x in data {
        let tick = ((x - min) * scale) as usize;
        buffer.push(TICKS[tick]);
    }
}

/// Render a sparkline of `data` into a newly allocated string.
pub fn render_f64_as_string(data: &[f64]) -> String {
    let cap = required_capacity(data.len());
    let mut s = String::with_capacity(cap);
    render_f64(data, &mut s);
    debug_assert_eq!(s.capacity(), cap);
    s
}

#[cfg(test)]
mod tests {
    #[test]
    fn render_u64() {
        let data = [2, 250, 670, 890, 2, 430, 11, 908, 123, 57];
        let mut s = String::with_capacity(super::required_capacity(data.len()));
        super::render_u64(&data, &mut s);
        println!("{}", s);
        assert_eq!("▁▂▆▇▁▄▁█▁▁", &s);
    }

    #[test]
    fn render_u64_as_string() {
        let data = [2, 250, 670, 890, 2, 430, 11, 908, 123, 57];
        let s = super::render_u64_as_string(&data);
        println!("{}", s);
        assert_eq!("▁▂▆▇▁▄▁█▁▁", &s);
    }

    #[test]
    fn render_f64() {
        let data = [2., 250., 670., 890., 2., 430., 11., 908., 123., 57.];
        let mut s = String::with_capacity(super::required_capacity(data.len()));
        super::render_f64(&data, &mut s);
        println!("{}", s);
        assert_eq!("▁▂▆▇▁▄▁█▁▁", &s);
    }

    #[test]
    fn render_f64_as_string() {
        let data = [2., 250., 670., 890., 2., 430., 11., 908., 123., 57.];
        let s = super::render_f64_as_string(&data);
        println!("{}", s);
        assert_eq!("▁▂▆▇▁▄▁█▁▁", &s);
    }
}
<|endoftext|>


<commit_before>#![cfg(feature = "glutin")]
/*!

Backend implementation for the glutin library

# Features

Only available if the 'glutin' feature is enabled.

*/
extern crate glutin;

use libc;

use DisplayBuild;
use Frame;
use GliumCreationError;

use context;
use backend;
use backend::Context;
use backend::Backend;
use version::Version;

use std::cell::{RefCell, Ref};
use std::rc::Rc;
use std::ops::Deref;

/// Facade implementation for glutin. Wraps both glium and glutin.
#[derive(Clone)]
pub struct GlutinFacade {
    // contains everything related to the current context and its state
    context: Rc<context::Context>,

    // contains the window
    backend: Rc<Option<RefCell<Rc<GlutinWindowBackend>>>>,
}

impl backend::Facade for GlutinFacade {
    fn get_context(&self) -> &Rc<Context> {
        &self.context
    }
}

/// Iterator for all the events received by the window.
pub struct PollEventsIter<'a> {
    window: Option<&'a RefCell<Rc<GlutinWindowBackend>>>,
}

impl<'a> Iterator for PollEventsIter<'a> {
    type Item = glutin::Event;

    fn next(&mut self) -> Option<glutin::Event> {
        if let Some(window) = self.window.as_ref() {
            window.borrow().poll_events().next()
        } else {
            None
        }
    }
}

/// Blocking iterator over all the events received by the window.
///
/// This iterator polls for events, until the window associated with its context
/// is closed.
pub struct WaitEventsIter<'a> {
    window: Option<&'a RefCell<Rc<GlutinWindowBackend>>>,
}

impl<'a> Iterator for WaitEventsIter<'a> {
    type Item = glutin::Event;

    fn next(&mut self) -> Option<glutin::Event> {
        if let Some(window) = self.window.as_ref() {
            window.borrow().wait_events().next()
        } else {
            None
        }
    }
}

/// Borrow of the glutin window.
pub struct WinRef<'a>(Ref<'a, Rc<GlutinWindowBackend>>);

impl<'a> Deref for WinRef<'a> {
    type Target = glutin::Window;

    fn deref(&self) -> &glutin::Window {
        self.0.get_window()
    }
}

impl GlutinFacade {
    /// Reads all events received by the window.
    ///
    /// This iterator polls for events and can be exhausted.
    pub fn poll_events(&self) -> PollEventsIter {
        PollEventsIter {
            window: self.backend.as_ref(),
        }
    }

    /// Reads all events received by the window.
    pub fn wait_events(&self) -> WaitEventsIter {
        WaitEventsIter {
            window: self.backend.as_ref(),
        }
    }

    /// Returns true if the window has been closed.
    pub fn is_closed(&self) -> bool {
        self.backend.as_ref().map(|b| b.borrow().is_closed()).unwrap_or(false)
    }

    /// Returns the underlying window, or `None` if glium uses a headless context.
    pub fn get_window(&self) -> Option<WinRef> {
        self.backend.as_ref().map(|w| WinRef(w.borrow()))
    }

    /// Returns the OpenGL version of the current context.
    // TODO: change Context so that this function derefs from it as well
    pub fn get_opengl_version(&self) -> Version {
        *self.context.get_version()
    }

    /// Start drawing on the backbuffer.
    ///
    /// This function returns a `Frame`, which can be used to draw on it. When the `Frame` is
    /// destroyed, the buffers are swapped.
    ///
    /// Note that destroying a `Frame` is immediate, even if vsync is enabled.
    pub fn draw(&self) -> Frame {
        Frame::new(self.context.clone(), self.get_framebuffer_dimensions())
    }
}

impl Deref for GlutinFacade {
    type Target = Context;

    fn deref(&self) -> &Context {
        &self.context
    }
}

impl DisplayBuild for glutin::WindowBuilder<'static> {
    type Facade = GlutinFacade;
    type Err = GliumCreationError<glutin::CreationError>;

    fn build_glium(self) -> Result<GlutinFacade, GliumCreationError<glutin::CreationError>> {
        let backend = Rc::new(try!(backend::glutin_backend::GlutinWindowBackend::new(self)));
        let context = try!(unsafe { context::Context::new(backend.clone(), true) });

        let display = GlutinFacade {
            context: context,
            backend: Rc::new(Some(RefCell::new(backend))),
        };

        Ok(display)
    }

    unsafe fn build_glium_unchecked(self) -> Result<GlutinFacade, GliumCreationError<glutin::CreationError>> {
        let backend = Rc::new(try!(backend::glutin_backend::GlutinWindowBackend::new(self)));
        let context = try!(context::Context::new(backend.clone(), false));

        let display = GlutinFacade {
            context: context,
            backend: Rc::new(Some(RefCell::new(backend))),
        };

        Ok(display)
    }

    fn rebuild_glium(self, display: &GlutinFacade) -> Result<(), GliumCreationError<glutin::CreationError>> {
        let mut existing_window = display.backend.as_ref()
                                         .expect("can't rebuild a headless display").borrow_mut();
        let new_backend = Rc::new(try!(existing_window.rebuild(self)));
        try!(unsafe { display.context.rebuild(new_backend.clone()) });
        *existing_window = new_backend;
        Ok(())
    }
}

impl DisplayBuild for glutin::HeadlessRendererBuilder {
    type Facade = GlutinFacade;
    type Err = GliumCreationError<glutin::CreationError>;

    fn build_glium(self) -> Result<GlutinFacade, GliumCreationError<glutin::CreationError>> {
        let backend = Rc::new(try!(backend::glutin_backend::GlutinHeadlessBackend::new(self)));
        let context = try!(unsafe { context::Context::new(backend.clone(), true) });

        let display = GlutinFacade {
            context: context,
            backend: Rc::new(None),
        };

        Ok(display)
    }

    unsafe fn build_glium_unchecked(self) -> Result<GlutinFacade, GliumCreationError<glutin::CreationError>> {
        let backend = Rc::new(try!(backend::glutin_backend::GlutinHeadlessBackend::new(self)));
        let context = try!(context::Context::new(backend.clone(), true));

        let display = GlutinFacade {
            context: context,
            backend: Rc::new(None),
        };

        Ok(display)
    }

    fn rebuild_glium(self, _: &GlutinFacade) -> Result<(), GliumCreationError<glutin::CreationError>> {
        unimplemented!()
    }
}

/// An implementation of the `Backend` trait for a glutin window.
pub struct GlutinWindowBackend {
    window: glutin::Window,
}

unsafe impl Backend for GlutinWindowBackend {
    fn swap_buffers(&self) {
        self.window.swap_buffers();
    }

    unsafe fn get_proc_address(&self, symbol: &str) -> *const libc::c_void {
        self.window.get_proc_address(symbol)
    }

    fn get_framebuffer_dimensions(&self) -> (u32, u32) {
        let (width, height) = self.window.get_inner_size().unwrap_or((800, 600));      // TODO: 800x600 ?
        let scale = self.window.hidpi_factor();
        (width * scale as u32, height * scale as u32)
    }

    fn is_current(&self) -> bool {
        self.window.is_current()
    }

    unsafe fn make_current(&self) {
        self.window.make_current();
    }
}

#[allow(missing_docs)]
impl GlutinWindowBackend {
    /// Builds a new backend from the builder.
    pub fn new(builder: glutin::WindowBuilder)
               -> Result<GlutinWindowBackend, GliumCreationError<glutin::CreationError>>
    {
        let window = try!(builder.build());

        Ok(GlutinWindowBackend {
            window: window,
        })
    }

    pub fn get_window(&self) -> &glutin::Window {
        &self.window
    }

    pub fn is_closed(&self) -> bool {
        self.window.is_closed()
    }

    pub fn poll_events(&self) -> glutin::PollEventsIterator {
        self.window.poll_events()
    }

    pub fn wait_events(&self) -> glutin::WaitEventsIterator {
        self.window.wait_events()
    }

    pub fn rebuild(&self, builder: glutin::WindowBuilder)
                   -> Result<GlutinWindowBackend, GliumCreationError<glutin::CreationError>>
    {
        let window = try!(builder.with_shared_lists(&self.window).build());

        Ok(GlutinWindowBackend {
            window: window,
        })
    }
}

/// An implementation of the `Backend` trait for a glutin headless context.
pub struct GlutinHeadlessBackend {
    context: glutin::HeadlessContext,
}

unsafe impl Backend for GlutinHeadlessBackend {
    fn swap_buffers(&self) {
    }

    unsafe fn get_proc_address(&self, symbol: &str) -> *const libc::c_void {
        self.context.get_proc_address(symbol)
    }

    fn get_framebuffer_dimensions(&self) -> (u32, u32) {
        (800, 600)      // FIXME: these are random
    }

    fn is_current(&self) -> bool {
        self.context.is_current()
    }

    unsafe fn make_current(&self) {
        self.context.make_current();
    }
}

impl GlutinHeadlessBackend {
    /// Builds a new backend from the builder.
    pub fn new(builder: glutin::HeadlessRendererBuilder)
               -> Result<GlutinHeadlessBackend, GliumCreationError<glutin::CreationError>>
    {
        let context = try!(builder.build());

        Ok(GlutinHeadlessBackend {
            context: context,
        })
    }
}
<commit_msg>[fix] framebuffer dimensions for non int scales<commit_after>#![cfg(feature = "glutin")]
/*!

Backend implementation for the glutin library

# Features

Only available if the 'glutin' feature is enabled.

*/
extern crate glutin;

use libc;

use DisplayBuild;
use Frame;
use GliumCreationError;

use context;
use backend;
use backend::Context;
use backend::Backend;
use version::Version;

use std::cell::{RefCell, Ref};
use std::rc::Rc;
use std::ops::Deref;

/// Facade implementation for glutin. Wraps both glium and glutin.
#[derive(Clone)]
pub struct GlutinFacade {
    // contains everything related to the current context and its state
    context: Rc<context::Context>,

    // contains the window
    backend: Rc<Option<RefCell<Rc<GlutinWindowBackend>>>>,
}

impl backend::Facade for GlutinFacade {
    fn get_context(&self) -> &Rc<Context> {
        &self.context
    }
}

/// Iterator for all the events received by the window.
pub struct PollEventsIter<'a> {
    window: Option<&'a RefCell<Rc<GlutinWindowBackend>>>,
}

impl<'a> Iterator for PollEventsIter<'a> {
    type Item = glutin::Event;

    fn next(&mut self) -> Option<glutin::Event> {
        if let Some(window) = self.window.as_ref() {
            window.borrow().poll_events().next()
        } else {
            None
        }
    }
}

/// Blocking iterator over all the events received by the window.
///
/// This iterator polls for events, until the window associated with its context
/// is closed.
pub struct WaitEventsIter<'a> {
    window: Option<&'a RefCell<Rc<GlutinWindowBackend>>>,
}

impl<'a> Iterator for WaitEventsIter<'a> {
    type Item = glutin::Event;

    fn next(&mut self) -> Option<glutin::Event> {
        if let Some(window) = self.window.as_ref() {
            window.borrow().wait_events().next()
        } else {
            None
        }
    }
}

/// Borrow of the glutin window.
pub struct WinRef<'a>(Ref<'a, Rc<GlutinWindowBackend>>);

impl<'a> Deref for WinRef<'a> {
    type Target = glutin::Window;

    fn deref(&self) -> &glutin::Window {
        self.0.get_window()
    }
}

impl GlutinFacade {
    /// Reads all events received by the window.
    ///
    /// This iterator polls for events and can be exhausted.
    pub fn poll_events(&self) -> PollEventsIter {
        PollEventsIter {
            window: self.backend.as_ref(),
        }
    }

    /// Reads all events received by the window.
    pub fn wait_events(&self) -> WaitEventsIter {
        WaitEventsIter {
            window: self.backend.as_ref(),
        }
    }

    /// Returns true if the window has been closed.
    pub fn is_closed(&self) -> bool {
        self.backend.as_ref().map(|b| b.borrow().is_closed()).unwrap_or(false)
    }

    /// Returns the underlying window, or `None` if glium uses a headless context.
    pub fn get_window(&self) -> Option<WinRef> {
        self.backend.as_ref().map(|w| WinRef(w.borrow()))
    }

    /// Returns the OpenGL version of the current context.
    // TODO: change Context so that this function derefs from it as well
    pub fn get_opengl_version(&self) -> Version {
        *self.context.get_version()
    }

    /// Start drawing on the backbuffer.
    ///
    /// This function returns a `Frame`, which can be used to draw on it. When the `Frame` is
    /// destroyed, the buffers are swapped.
    ///
    /// Note that destroying a `Frame` is immediate, even if vsync is enabled.
    pub fn draw(&self) -> Frame {
        Frame::new(self.context.clone(), self.get_framebuffer_dimensions())
    }
}

impl Deref for GlutinFacade {
    type Target = Context;

    fn deref(&self) -> &Context {
        &self.context
    }
}

impl DisplayBuild for glutin::WindowBuilder<'static> {
    type Facade = GlutinFacade;
    type Err = GliumCreationError<glutin::CreationError>;

    fn build_glium(self) -> Result<GlutinFacade, GliumCreationError<glutin::CreationError>> {
        let backend = Rc::new(try!(backend::glutin_backend::GlutinWindowBackend::new(self)));
        let context = try!(unsafe { context::Context::new(backend.clone(), true) });

        let display = GlutinFacade {
            context: context,
            backend: Rc::new(Some(RefCell::new(backend))),
        };

        Ok(display)
    }

    unsafe fn build_glium_unchecked(self) -> Result<GlutinFacade, GliumCreationError<glutin::CreationError>> {
        let backend = Rc::new(try!(backend::glutin_backend::GlutinWindowBackend::new(self)));
        let context = try!(context::Context::new(backend.clone(), false));

        let display = GlutinFacade {
            context: context,
            backend: Rc::new(Some(RefCell::new(backend))),
        };

        Ok(display)
    }

    fn rebuild_glium(self, display: &GlutinFacade) -> Result<(), GliumCreationError<glutin::CreationError>> {
        let mut existing_window = display.backend.as_ref()
                                         .expect("can't rebuild a headless display").borrow_mut();
        let new_backend = Rc::new(try!(existing_window.rebuild(self)));
        try!(unsafe { display.context.rebuild(new_backend.clone()) });
        *existing_window = new_backend;
        Ok(())
    }
}

impl DisplayBuild for glutin::HeadlessRendererBuilder {
    type Facade = GlutinFacade;
    type Err = GliumCreationError<glutin::CreationError>;

    fn build_glium(self) -> Result<GlutinFacade, GliumCreationError<glutin::CreationError>> {
        let backend = Rc::new(try!(backend::glutin_backend::GlutinHeadlessBackend::new(self)));
        let context = try!(unsafe { context::Context::new(backend.clone(), true) });

        let display = GlutinFacade {
            context: context,
            backend: Rc::new(None),
        };

        Ok(display)
    }

    unsafe fn build_glium_unchecked(self) -> Result<GlutinFacade, GliumCreationError<glutin::CreationError>> {
        let backend = Rc::new(try!(backend::glutin_backend::GlutinHeadlessBackend::new(self)));
        let context = try!(context::Context::new(backend.clone(), true));

        let display = GlutinFacade {
            context: context,
            backend: Rc::new(None),
        };

        Ok(display)
    }

    fn rebuild_glium(self, _: &GlutinFacade) -> Result<(), GliumCreationError<glutin::CreationError>> {
        unimplemented!()
    }
}

/// An implementation of the `Backend` trait for a glutin window.
pub struct GlutinWindowBackend {
    window: glutin::Window,
}

unsafe impl Backend for GlutinWindowBackend {
    fn swap_buffers(&self) {
        self.window.swap_buffers();
    }

    unsafe fn get_proc_address(&self, symbol: &str) -> *const libc::c_void {
        self.window.get_proc_address(symbol)
    }

    fn get_framebuffer_dimensions(&self) -> (u32, u32) {
        let (width, height) = self.window.get_inner_size().unwrap_or((800, 600));      // TODO: 800x600 ?
        let scale = self.window.hidpi_factor();
        ((width as f32 * scale) as u32, (height as f32 * scale) as u32)
    }

    fn is_current(&self) -> bool {
        self.window.is_current()
    }

    unsafe fn make_current(&self) {
        self.window.make_current();
    }
}

#[allow(missing_docs)]
impl GlutinWindowBackend {
    /// Builds a new backend from the builder.
    pub fn new(builder: glutin::WindowBuilder)
               -> Result<GlutinWindowBackend, GliumCreationError<glutin::CreationError>>
    {
        let window = try!(builder.build());

        Ok(GlutinWindowBackend {
            window: window,
        })
    }

    pub fn get_window(&self) -> &glutin::Window {
        &self.window
    }

    pub fn is_closed(&self) -> bool {
        self.window.is_closed()
    }

    pub fn poll_events(&self) -> glutin::PollEventsIterator {
        self.window.poll_events()
    }

    pub fn wait_events(&self) -> glutin::WaitEventsIterator {
        self.window.wait_events()
    }

    pub fn rebuild(&self, builder: glutin::WindowBuilder)
                   -> Result<GlutinWindowBackend, GliumCreationError<glutin::CreationError>>
    {
        let window = try!(builder.with_shared_lists(&self.window).build());

        Ok(GlutinWindowBackend {
            window: window,
        })
    }
}

/// An implementation of the `Backend` trait for a glutin headless context.
pub struct GlutinHeadlessBackend {
    context: glutin::HeadlessContext,
}

unsafe impl Backend for GlutinHeadlessBackend {
    fn swap_buffers(&self) {
    }

    unsafe fn get_proc_address(&self, symbol: &str) -> *const libc::c_void {
        self.context.get_proc_address(symbol)
    }

    fn get_framebuffer_dimensions(&self) -> (u32, u32) {
        (800, 600)      // FIXME: these are random
    }

    fn is_current(&self) -> bool {
        self.context.is_current()
    }

    unsafe fn make_current(&self) {
        self.context.make_current();
    }
}

impl GlutinHeadlessBackend {
    /// Builds a new backend from the builder.
    pub fn new(builder: glutin::HeadlessRendererBuilder)
               -> Result<GlutinHeadlessBackend, GliumCreationError<glutin::CreationError>>
    {
        let context = try!(builder.build());

        Ok(GlutinHeadlessBackend {
            context: context,
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>Enumerate queue families and choose one<commit_after><|endoftext|>


<commit_before><commit_msg>Reordered a couple of tests, to make it look prettier.<commit_after><|endoftext|>


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

use core::prelude::*;

use boxed::Box;
use cmp;
use mem;
use ptr;
use libc::consts::os::posix01::{PTHREAD_CREATE_JOINABLE, PTHREAD_STACK_MIN};
use libc;
use thunk::Thunk;

use sys_common::stack::RED_ZONE;
use sys_common::thread::*;

pub type rust_thread = libc::pthread_t;
pub type rust_thread_return = *mut u8;
pub type StartFn = extern "C" fn(*mut libc::c_void) -> rust_thread_return;

#[no_stack_check]
pub extern fn thread_start(main: *mut libc::c_void) -> rust_thread_return {
    return start_thread(main);
}

#[cfg(all(not(target_os = "linux"), not(target_os = "macos")))]
pub mod guard {
    pub unsafe fn current() -> uint {
        0
    }

    pub unsafe fn main() -> uint {
        0
    }

    pub unsafe fn init() {
    }
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub mod guard {
    use super::*;
    #[cfg(any(target_os = "linux", target_os = "android"))]
    use mem;
    #[cfg(any(target_os = "linux", target_os = "android"))]
    use ptr;
    use libc;
    use libc::funcs::posix88::mman::{mmap};
    use libc::consts::os::posix88::{PROT_NONE,
                                    MAP_PRIVATE,
                                    MAP_ANON,
                                    MAP_FAILED,
                                    MAP_FIXED};

    // These are initialized in init() and only read from after
    static mut PAGE_SIZE: uint = 0;
    static mut GUARD_PAGE: uint = 0;

    #[cfg(target_os = "macos")]
    unsafe fn get_stack_start() -> *mut libc::c_void {
        current() as *mut libc::c_void
    }

    #[cfg(any(target_os = "linux", target_os = "android"))]
    unsafe fn get_stack_start() -> *mut libc::c_void {
        let mut attr: libc::pthread_attr_t = mem::zeroed();
        if pthread_getattr_np(pthread_self(), &mut attr) != 0 {
            panic!("failed to get thread attributes");
        }
        let mut stackaddr = ptr::null_mut();
        let mut stacksize = 0;
        if pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize) != 0 {
            panic!("failed to get stack information");
        }
        if pthread_attr_destroy(&mut attr) != 0 {
            panic!("failed to destroy thread attributes");
        }
        stackaddr
    }

    pub unsafe fn init() {
        let psize = libc::sysconf(libc::consts::os::sysconf::_SC_PAGESIZE);
        if psize == -1 {
            panic!("failed to get page size");
        }

        PAGE_SIZE = psize as uint;

        let stackaddr = get_stack_start();

        // Rellocate the last page of the stack.
        // This ensures SIGBUS will be raised on
        // stack overflow.
        let result = mmap(stackaddr,
                          PAGE_SIZE as libc::size_t,
                          PROT_NONE,
                          MAP_PRIVATE | MAP_ANON | MAP_FIXED,
                          -1,
                          0);

        if result != stackaddr || result == MAP_FAILED {
            panic!("failed to allocate a guard page");
        }

        let offset = if cfg!(target_os = "linux") {
            2
        } else {
            1
        };

        GUARD_PAGE = stackaddr as uint + offset * PAGE_SIZE;
    }

    pub unsafe fn main() -> uint {
        GUARD_PAGE
    }

    #[cfg(target_os = "macos")]
    pub unsafe fn current() -> uint {
        (pthread_get_stackaddr_np(pthread_self()) as libc::size_t -
         pthread_get_stacksize_np(pthread_self())) as uint
    }

    #[cfg(any(target_os = "linux", target_os = "android"))]
    pub unsafe fn current() -> uint {
        let mut attr: libc::pthread_attr_t = mem::zeroed();
        if pthread_getattr_np(pthread_self(), &mut attr) != 0 {
            panic!("failed to get thread attributes");
        }
        let mut guardsize = 0;
        if pthread_attr_getguardsize(&attr, &mut guardsize) != 0 {
            panic!("failed to get stack guard page");
        }
        if guardsize == 0 {
            panic!("there is no guard page");
        }
        let mut stackaddr = ptr::null_mut();
        let mut stacksize = 0;
        if pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize) != 0 {
            panic!("failed to get stack information");
        }
        if pthread_attr_destroy(&mut attr) != 0 {
            panic!("failed to destroy thread attributes");
        }

        stackaddr as uint + guardsize as uint
    }
}

pub unsafe fn create(stack: uint, p: Thunk) -> rust_thread {
    let mut native: libc::pthread_t = mem::zeroed();
    let mut attr: libc::pthread_attr_t = mem::zeroed();
    assert_eq!(pthread_attr_init(&mut attr), 0);
    assert_eq!(pthread_attr_setdetachstate(&mut attr,
                                           PTHREAD_CREATE_JOINABLE), 0);

    // Reserve room for the red zone, the runtime's stack of last resort.
    let stack_size = cmp::max(stack, RED_ZONE + min_stack_size(&attr) as uint);
    match pthread_attr_setstacksize(&mut attr, stack_size as libc::size_t) {
        0 => {
        },
        libc::EINVAL => {
            // EINVAL means |stack_size| is either too small or not a
            // multiple of the system page size.  Because it's definitely
            // >= PTHREAD_STACK_MIN, it must be an alignment issue.
            // Round up to the nearest page and try again.
            let page_size = libc::sysconf(libc::_SC_PAGESIZE) as uint;
            let stack_size = (stack_size + page_size - 1) &
                             (-(page_size as int - 1) as uint - 1);
            assert_eq!(pthread_attr_setstacksize(&mut attr, stack_size as libc::size_t), 0);
        },
        errno => {
            // This cannot really happen.
            panic!("pthread_attr_setstacksize() error: {}", errno);
        },
    };

    let arg: *mut libc::c_void = mem::transmute(box p); // must box since sizeof(p)=2*uint
    let ret = pthread_create(&mut native, &attr, thread_start, arg);
    assert_eq!(pthread_attr_destroy(&mut attr), 0);

    if ret != 0 {
        // be sure to not leak the closure
        let _p: Box<Box<FnOnce()+Send>> = mem::transmute(arg);
        panic!("failed to spawn native thread: {}", ret);
    }
    native
}

pub unsafe fn join(native: rust_thread) {
    assert_eq!(pthread_join(native, ptr::null_mut()), 0);
}

pub unsafe fn detach(native: rust_thread) {
    assert_eq!(pthread_detach(native), 0);
}

pub unsafe fn yield_now() { assert_eq!(sched_yield(), 0); }
// glibc >= 2.15 has a __pthread_get_minstack() function that returns
// PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
// storage.  We need that information to avoid blowing up when a small stack
// is created in an application with big thread-local storage requirements.
// See #6233 for rationale and details.
//
// Link weakly to the symbol for compatibility with older versions of glibc.
// Assumes that we've been dynamically linked to libpthread but that is
// currently always the case.  Note that you need to check that the symbol
// is non-null before calling it!
#[cfg(target_os = "linux")]
fn min_stack_size(attr: *const libc::pthread_attr_t) -> libc::size_t {
    type F = unsafe extern "C" fn(*const libc::pthread_attr_t) -> libc::size_t;
    extern {
        #[linkage = "extern_weak"]
        static __pthread_get_minstack: *const ();
    }
    if __pthread_get_minstack.is_null() {
        PTHREAD_STACK_MIN
    } else {
        unsafe { mem::transmute::<*const (), F>(__pthread_get_minstack)(attr) }
    }
}

// __pthread_get_minstack() is marked as weak but extern_weak linkage is
// not supported on OS X, hence this kludge...
#[cfg(not(target_os = "linux"))]
fn min_stack_size(_: *const libc::pthread_attr_t) -> libc::size_t {
    PTHREAD_STACK_MIN
}

#[cfg(any(target_os = "linux"))]
extern {
    pub fn pthread_self() -> libc::pthread_t;
    pub fn pthread_getattr_np(native: libc::pthread_t,
                              attr: *mut libc::pthread_attr_t) -> libc::c_int;
    pub fn pthread_attr_getguardsize(attr: *const libc::pthread_attr_t,
                                     guardsize: *mut libc::size_t) -> libc::c_int;
    pub fn pthread_attr_getstack(attr: *const libc::pthread_attr_t,
                                 stackaddr: *mut *mut libc::c_void,
                                 stacksize: *mut libc::size_t) -> libc::c_int;
}

#[cfg(target_os = "macos")]
extern {
    pub fn pthread_self() -> libc::pthread_t;
    pub fn pthread_get_stackaddr_np(thread: libc::pthread_t) -> *mut libc::c_void;
    pub fn pthread_get_stacksize_np(thread: libc::pthread_t) -> libc::size_t;
}

extern {
    fn pthread_create(native: *mut libc::pthread_t,
                      attr: *const libc::pthread_attr_t,
                      f: StartFn,
                      value: *mut libc::c_void) -> libc::c_int;
    fn pthread_join(native: libc::pthread_t,
                    value: *mut *mut libc::c_void) -> libc::c_int;
    fn pthread_attr_init(attr: *mut libc::pthread_attr_t) -> libc::c_int;
    pub fn pthread_attr_destroy(attr: *mut libc::pthread_attr_t) -> libc::c_int;
    fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t,
                                 stack_size: libc::size_t) -> libc::c_int;
    fn pthread_attr_setdetachstate(attr: *mut libc::pthread_attr_t,
                                   state: libc::c_int) -> libc::c_int;
    fn pthread_detach(thread: libc::pthread_t) -> libc::c_int;
    fn sched_yield() -> libc::c_int;
}
<commit_msg>Give mmap a page-aligned stack start address<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.

use core::prelude::*;

use boxed::Box;
use cmp;
use mem;
use ptr;
use libc::consts::os::posix01::{PTHREAD_CREATE_JOINABLE, PTHREAD_STACK_MIN};
use libc;
use thunk::Thunk;

use sys_common::stack::RED_ZONE;
use sys_common::thread::*;

pub type rust_thread = libc::pthread_t;
pub type rust_thread_return = *mut u8;
pub type StartFn = extern "C" fn(*mut libc::c_void) -> rust_thread_return;

#[no_stack_check]
pub extern fn thread_start(main: *mut libc::c_void) -> rust_thread_return {
    return start_thread(main);
}

#[cfg(all(not(target_os = "linux"), not(target_os = "macos")))]
pub mod guard {
    pub unsafe fn current() -> uint {
        0
    }

    pub unsafe fn main() -> uint {
        0
    }

    pub unsafe fn init() {
    }
}

#[cfg(any(target_os = "linux", target_os = "macos"))]
pub mod guard {
    use super::*;
    #[cfg(any(target_os = "linux", target_os = "android"))]
    use mem;
    #[cfg(any(target_os = "linux", target_os = "android"))]
    use ptr;
    use libc;
    use libc::funcs::posix88::mman::{mmap};
    use libc::consts::os::posix88::{PROT_NONE,
                                    MAP_PRIVATE,
                                    MAP_ANON,
                                    MAP_FAILED,
                                    MAP_FIXED};

    // These are initialized in init() and only read from after
    static mut PAGE_SIZE: uint = 0;
    static mut GUARD_PAGE: uint = 0;

    #[cfg(target_os = "macos")]
    unsafe fn get_stack_start() -> *mut libc::c_void {
        current() as *mut libc::c_void
    }

    #[cfg(any(target_os = "linux", target_os = "android"))]
    unsafe fn get_stack_start() -> *mut libc::c_void {
        let mut attr: libc::pthread_attr_t = mem::zeroed();
        if pthread_getattr_np(pthread_self(), &mut attr) != 0 {
            panic!("failed to get thread attributes");
        }
        let mut stackaddr = ptr::null_mut();
        let mut stacksize = 0;
        if pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize) != 0 {
            panic!("failed to get stack information");
        }
        if pthread_attr_destroy(&mut attr) != 0 {
            panic!("failed to destroy thread attributes");
        }
        stackaddr
    }

    pub unsafe fn init() {
        let psize = libc::sysconf(libc::consts::os::sysconf::_SC_PAGESIZE);
        if psize == -1 {
            panic!("failed to get page size");
        }

        PAGE_SIZE = psize as uint;

        let mut stackaddr = get_stack_start();

        // Ensure stackaddr is page aligned! A parent process might
        // have reset RLIMIT_STACK to be non-page aligned. The
        // pthread_attr_getstack() reports the usable stack area
        // stackaddr < stackaddr + stacksize, so if stackaddr is not
        // page-aligned, calculate the fix such that stackaddr <
        // new_page_aligned_stackaddr < stackaddr + stacksize
        let remainder = (stackaddr as usize) % (PAGE_SIZE as usize);
        if remainder != 0 {
            stackaddr = ((stackaddr as usize) + (PAGE_SIZE as usize) - remainder)
                as *mut libc::c_void;
        }

        // Rellocate the last page of the stack.
        // This ensures SIGBUS will be raised on
        // stack overflow.
        let result = mmap(stackaddr,
                          PAGE_SIZE as libc::size_t,
                          PROT_NONE,
                          MAP_PRIVATE | MAP_ANON | MAP_FIXED,
                          -1,
                          0);

        if result != stackaddr || result == MAP_FAILED {
            panic!("failed to allocate a guard page");
        }

        let offset = if cfg!(target_os = "linux") {
            2
        } else {
            1
        };

        GUARD_PAGE = stackaddr as uint + offset * PAGE_SIZE;
    }

    pub unsafe fn main() -> uint {
        GUARD_PAGE
    }

    #[cfg(target_os = "macos")]
    pub unsafe fn current() -> uint {
        (pthread_get_stackaddr_np(pthread_self()) as libc::size_t -
         pthread_get_stacksize_np(pthread_self())) as uint
    }

    #[cfg(any(target_os = "linux", target_os = "android"))]
    pub unsafe fn current() -> uint {
        let mut attr: libc::pthread_attr_t = mem::zeroed();
        if pthread_getattr_np(pthread_self(), &mut attr) != 0 {
            panic!("failed to get thread attributes");
        }
        let mut guardsize = 0;
        if pthread_attr_getguardsize(&attr, &mut guardsize) != 0 {
            panic!("failed to get stack guard page");
        }
        if guardsize == 0 {
            panic!("there is no guard page");
        }
        let mut stackaddr = ptr::null_mut();
        let mut stacksize = 0;
        if pthread_attr_getstack(&attr, &mut stackaddr, &mut stacksize) != 0 {
            panic!("failed to get stack information");
        }
        if pthread_attr_destroy(&mut attr) != 0 {
            panic!("failed to destroy thread attributes");
        }

        stackaddr as uint + guardsize as uint
    }
}

pub unsafe fn create(stack: uint, p: Thunk) -> rust_thread {
    let mut native: libc::pthread_t = mem::zeroed();
    let mut attr: libc::pthread_attr_t = mem::zeroed();
    assert_eq!(pthread_attr_init(&mut attr), 0);
    assert_eq!(pthread_attr_setdetachstate(&mut attr,
                                           PTHREAD_CREATE_JOINABLE), 0);

    // Reserve room for the red zone, the runtime's stack of last resort.
    let stack_size = cmp::max(stack, RED_ZONE + min_stack_size(&attr) as uint);
    match pthread_attr_setstacksize(&mut attr, stack_size as libc::size_t) {
        0 => {
        },
        libc::EINVAL => {
            // EINVAL means |stack_size| is either too small or not a
            // multiple of the system page size.  Because it's definitely
            // >= PTHREAD_STACK_MIN, it must be an alignment issue.
            // Round up to the nearest page and try again.
            let page_size = libc::sysconf(libc::_SC_PAGESIZE) as uint;
            let stack_size = (stack_size + page_size - 1) &
                             (-(page_size as int - 1) as uint - 1);
            assert_eq!(pthread_attr_setstacksize(&mut attr, stack_size as libc::size_t), 0);
        },
        errno => {
            // This cannot really happen.
            panic!("pthread_attr_setstacksize() error: {}", errno);
        },
    };

    let arg: *mut libc::c_void = mem::transmute(box p); // must box since sizeof(p)=2*uint
    let ret = pthread_create(&mut native, &attr, thread_start, arg);
    assert_eq!(pthread_attr_destroy(&mut attr), 0);

    if ret != 0 {
        // be sure to not leak the closure
        let _p: Box<Box<FnOnce()+Send>> = mem::transmute(arg);
        panic!("failed to spawn native thread: {}", ret);
    }
    native
}

pub unsafe fn join(native: rust_thread) {
    assert_eq!(pthread_join(native, ptr::null_mut()), 0);
}

pub unsafe fn detach(native: rust_thread) {
    assert_eq!(pthread_detach(native), 0);
}

pub unsafe fn yield_now() { assert_eq!(sched_yield(), 0); }
// glibc >= 2.15 has a __pthread_get_minstack() function that returns
// PTHREAD_STACK_MIN plus however many bytes are needed for thread-local
// storage.  We need that information to avoid blowing up when a small stack
// is created in an application with big thread-local storage requirements.
// See #6233 for rationale and details.
//
// Link weakly to the symbol for compatibility with older versions of glibc.
// Assumes that we've been dynamically linked to libpthread but that is
// currently always the case.  Note that you need to check that the symbol
// is non-null before calling it!
#[cfg(target_os = "linux")]
fn min_stack_size(attr: *const libc::pthread_attr_t) -> libc::size_t {
    type F = unsafe extern "C" fn(*const libc::pthread_attr_t) -> libc::size_t;
    extern {
        #[linkage = "extern_weak"]
        static __pthread_get_minstack: *const ();
    }
    if __pthread_get_minstack.is_null() {
        PTHREAD_STACK_MIN
    } else {
        unsafe { mem::transmute::<*const (), F>(__pthread_get_minstack)(attr) }
    }
}

// __pthread_get_minstack() is marked as weak but extern_weak linkage is
// not supported on OS X, hence this kludge...
#[cfg(not(target_os = "linux"))]
fn min_stack_size(_: *const libc::pthread_attr_t) -> libc::size_t {
    PTHREAD_STACK_MIN
}

#[cfg(any(target_os = "linux"))]
extern {
    pub fn pthread_self() -> libc::pthread_t;
    pub fn pthread_getattr_np(native: libc::pthread_t,
                              attr: *mut libc::pthread_attr_t) -> libc::c_int;
    pub fn pthread_attr_getguardsize(attr: *const libc::pthread_attr_t,
                                     guardsize: *mut libc::size_t) -> libc::c_int;
    pub fn pthread_attr_getstack(attr: *const libc::pthread_attr_t,
                                 stackaddr: *mut *mut libc::c_void,
                                 stacksize: *mut libc::size_t) -> libc::c_int;
}

#[cfg(target_os = "macos")]
extern {
    pub fn pthread_self() -> libc::pthread_t;
    pub fn pthread_get_stackaddr_np(thread: libc::pthread_t) -> *mut libc::c_void;
    pub fn pthread_get_stacksize_np(thread: libc::pthread_t) -> libc::size_t;
}

extern {
    fn pthread_create(native: *mut libc::pthread_t,
                      attr: *const libc::pthread_attr_t,
                      f: StartFn,
                      value: *mut libc::c_void) -> libc::c_int;
    fn pthread_join(native: libc::pthread_t,
                    value: *mut *mut libc::c_void) -> libc::c_int;
    fn pthread_attr_init(attr: *mut libc::pthread_attr_t) -> libc::c_int;
    pub fn pthread_attr_destroy(attr: *mut libc::pthread_attr_t) -> libc::c_int;
    fn pthread_attr_setstacksize(attr: *mut libc::pthread_attr_t,
                                 stack_size: libc::size_t) -> libc::c_int;
    fn pthread_attr_setdetachstate(attr: *mut libc::pthread_attr_t,
                                   state: libc::c_int) -> libc::c_int;
    fn pthread_detach(thread: libc::pthread_t) -> libc::c_int;
    fn sched_yield() -> libc::c_int;
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #86352 - yerke:add-test-for-issue-37508, r=Mark-Simulacrum<commit_after>// only-x86_64
// compile-flags: -Ccode-model=large --crate-type lib
// build-pass
//
// Regression test for issue #37508

#![no_main]
#![no_std]
#![feature(thread_local, lang_items)]

#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

use core::panic::PanicInfo;

#[panic_handler]
fn panic(_panic: &PanicInfo<'_>) -> ! {
    loop {}
}

pub struct BB;

#[thread_local]
static mut KEY: Key = Key { inner: BB, dtor_running: false };

pub unsafe fn set() -> Option<&'static BB> {
    if KEY.dtor_running {
        return None;
    }
    Some(&KEY.inner)
}

pub struct Key {
    inner: BB,
    dtor_running: bool,
}
<|endoftext|>


<commit_before><commit_msg>Add additional regression test<commit_after>// check-pass
// compile-flags: --emit=mir,link
// Checks that we don't ICE due to attempting to run const prop
// on a function with unsatisifable 'where' clauses

#![allow(unused)]

trait A {
    fn foo(&self) -> Self where Self: Copy;
}

impl A for [fn(&())] {
    fn foo(&self) -> Self where Self: Copy { *(&[] as &[_]) }
}

impl A for i32 {
    fn foo(&self) -> Self { 3 }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Undo accidental test deletion in previous commit.<commit_after><|endoftext|>