<commit_before>import dom::rcu;
import dom::rcu::methods;
import util::{tree, geom};
import geom::{size, rect, point, au};

enum box = @{
    tree: tree::fields<box>,
    node: node,
    mut bounds: geom::rect<au>
};

enum node_data = {
    tree: tree::fields<node>,
    kind: node_kind,

    // Points to the primary box.  Note that there may be multiple
    // boxes per DOM node.
    mut box: option<box>,
};

enum node_kind {
    nk_div,
    nk_img(size<au>)
}

type node = rcu::handle<node_data>;

impl of tree::tree for box {
    fn tree_fields() -> tree::fields<box> {
        ret self.tree;
    }
}

impl of tree::tree for node {
    fn tree_fields() -> tree::fields<node> {
        ret self.get().tree;
    }
}

fn new_node(+k: node_kind) -> node {
    rcu::handle(node_data({tree: tree::empty(),
                           kind: k,
                           mut box: none}))
}

fn new_box(n: node) -> box {
    box(@{tree: tree::empty(),
          node: n,
          mut bounds: geom::zero_rect_au()})
}

fn linked_box(n: node) -> box {
    let b = new_box(n);
    n.box = some(b);
    ret b;
}

fn reflow_block(root: box, available_width: au) {
    // Root here is the root of the reflow, not necessarily the doc as
    // a whole.

    alt root.node.get().kind {
      nk_img(size) {
        root.bounds.size = size;
        ret;
      }

      nk_div { /* fallthrough */ }
    }

    let mut current_height = 0;
    for tree::each_child(root) {|c|
        let mut blk_available_width = available_width;
        // FIXME subtract borders, margins, etc
        c.bounds.origin = {x: au(0), y: au(current_height)};
        reflow_block(c, blk_available_width);
        current_height += *c.bounds.size.height;
    }

    root.bounds.size = {width: available_width, // FIXME
                        height: au(current_height)};
}

#[cfg(test)]
mod test {

    /*
    use sdl;
    import sdl::video;

    fn with_screen(f: fn(*sdl::surface)) {
        let screen = video::set_video_mode(
            320, 200, 32,
            [video::hwsurface], [video::doublebuf]);
        assert screen != ptr::null();

        f(screen);

        video::free_surface(screen);
    }
    */

    fn flat_bounds(root: box) -> [geom::rect<au>] {
        let mut r = [];
        for tree::each_child(root) {|c|
            r += flat_bounds(c);
        }
        ret r + [root.bounds];
    }

    #[test]
    fn do_layout() {
        let n0 = new_node(nk_img(size(au(10),au(10))));
        let n1 = new_node(nk_img(size(au(10),au(10))));
        let n2 = new_node(nk_img(size(au(10),au(10))));
        let n3 = new_node(nk_div);

        tree::add_child(n3, n0);
        tree::add_child(n3, n1);
        tree::add_child(n3, n2);

        let b0 = linked_box(n0);
        let b1 = linked_box(n1);
        let b2 = linked_box(n2);
        let b3 = linked_box(n3);

        tree::add_child(b3, b0);
        tree::add_child(b3, b1);
        tree::add_child(b3, b2);

        reflow_block(b3, au(100));
        let fb = flat_bounds(b3);
        #debug["fb=%?", fb];
        assert fb == [geom::box(au(0), au(0), au(10), au(10)),
                      geom::box(au(0), au(10), au(10), au(10)),
                      geom::box(au(0), au(20), au(10), au(10)),
                      geom::box(au(0), au(0), au(100), au(30))];
    }
}<commit_msg>make the numbers a bit more interesting<commit_after>import dom::rcu;
import dom::rcu::methods;
import util::{tree, geom};
import geom::{size, rect, point, au};

enum box = @{
    tree: tree::fields<box>,
    node: node,
    mut bounds: geom::rect<au>
};

enum node_data = {
    tree: tree::fields<node>,
    kind: node_kind,

    // Points to the primary box.  Note that there may be multiple
    // boxes per DOM node.
    mut box: option<box>,
};

enum node_kind {
    nk_div,
    nk_img(size<au>)
}

type node = rcu::handle<node_data>;

impl of tree::tree for box {
    fn tree_fields() -> tree::fields<box> {
        ret self.tree;
    }
}

impl of tree::tree for node {
    fn tree_fields() -> tree::fields<node> {
        ret self.get().tree;
    }
}

fn new_node(+k: node_kind) -> node {
    rcu::handle(node_data({tree: tree::empty(),
                           kind: k,
                           mut box: none}))
}

fn new_box(n: node) -> box {
    box(@{tree: tree::empty(),
          node: n,
          mut bounds: geom::zero_rect_au()})
}

fn linked_box(n: node) -> box {
    let b = new_box(n);
    n.box = some(b);
    ret b;
}

fn reflow_block(root: box, available_width: au) {
    // Root here is the root of the reflow, not necessarily the doc as
    // a whole.

    alt root.node.get().kind {
      nk_img(size) {
        root.bounds.size = size;
        ret;
      }

      nk_div { /* fallthrough */ }
    }

    let mut current_height = 0;
    for tree::each_child(root) {|c|
        let mut blk_available_width = available_width;
        // FIXME subtract borders, margins, etc
        c.bounds.origin = {x: au(0), y: au(current_height)};
        reflow_block(c, blk_available_width);
        current_height += *c.bounds.size.height;
    }

    root.bounds.size = {width: available_width, // FIXME
                        height: au(current_height)};
}

#[cfg(test)]
mod test {

    /*
    use sdl;
    import sdl::video;

    fn with_screen(f: fn(*sdl::surface)) {
        let screen = video::set_video_mode(
            320, 200, 32,
            [video::hwsurface], [video::doublebuf]);
        assert screen != ptr::null();

        f(screen);

        video::free_surface(screen);
    }
    */

    fn flat_bounds(root: box) -> [geom::rect<au>] {
        let mut r = [];
        for tree::each_child(root) {|c|
            r += flat_bounds(c);
        }
        ret r + [root.bounds];
    }

    #[test]
    fn do_layout() {
        let n0 = new_node(nk_img(size(au(10),au(10))));
        let n1 = new_node(nk_img(size(au(10),au(15))));
        let n2 = new_node(nk_img(size(au(10),au(20))));
        let n3 = new_node(nk_div);

        tree::add_child(n3, n0);
        tree::add_child(n3, n1);
        tree::add_child(n3, n2);

        let b0 = linked_box(n0);
        let b1 = linked_box(n1);
        let b2 = linked_box(n2);
        let b3 = linked_box(n3);

        tree::add_child(b3, b0);
        tree::add_child(b3, b1);
        tree::add_child(b3, b2);

        reflow_block(b3, au(100));
        let fb = flat_bounds(b3);
        #debug["fb=%?", fb];
        assert fb == [geom::box(au(0), au(0), au(10), au(10)),   // n0
                      geom::box(au(0), au(10), au(10), au(15)),  // n1
                      geom::box(au(0), au(25), au(10), au(20)),  // n2
                      geom::box(au(0), au(0), au(100), au(45))]; // n3
    }
}<|endoftext|>


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

// this code used to cause an ICE

fn main() {
  let t = Err(0);
  match t {
    Some(k) => match k { //~ ERROR mismatched types
      a => println!("{}", a)
    },
    None => () //~ ERROR mismatched types
  }
}
<|endoftext|>


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

struct Foo<'a, 'b: 'a>(&'a &'b ());

impl<'a, 'b> Foo<'a, 'b> {
    fn xmute(a: &'b ()) -> &'a () {
        unreachable!()
    }
}

pub fn foo<'a, 'b>(u: &'b ()) -> &'a () {
    Foo::<'a, 'b>::xmute(u) //~ ERROR lifetime bound not satisfied
}

fn main() {}<|endoftext|>


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

// ignore-windows
// ignore-android
// ignore-emscripten

#![feature(libc)]

extern crate libc;

use std::env;
use std::fs::File;
use std::io;
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::os::unix::prelude::*;
use std::process::{Command, Stdio};
use std::thread;

fn main() {
    let args = env::args().collect::<Vec<_>>();
    if args.len() == 1 {
        parent()
    } else {
        child(&args)
    }
}

fn parent() {
    let file = File::open("Makefile").unwrap();
    let tcp1 = TcpListener::bind("127.0.0.1:0").unwrap();
    let tcp2 = tcp1.try_clone().unwrap();
    let addr = tcp1.local_addr().unwrap();
    let t = thread::spawn(move || TcpStream::connect(addr).unwrap());
    let tcp3 = tcp1.accept().unwrap().0;
    let tcp4 = t.join().unwrap();
    let tcp5 = tcp3.try_clone().unwrap();
    let tcp6 = tcp4.try_clone().unwrap();
    let udp1 = UdpSocket::bind("127.0.0.1:0").unwrap();
    let udp2 = udp1.try_clone().unwrap();

    let mut child = Command::new(env::args().next().unwrap())
                            .arg("100")
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn().unwrap();
    let pipe1 = child.stdin.take().unwrap();
    let pipe2 = child.stdout.take().unwrap();
    let pipe3 = child.stderr.take().unwrap();

    let status = Command::new(env::args().next().unwrap())
                        .arg(file.as_raw_fd().to_string())
                        .arg(tcp1.as_raw_fd().to_string())
                        .arg(tcp2.as_raw_fd().to_string())
                        .arg(tcp3.as_raw_fd().to_string())
                        .arg(tcp4.as_raw_fd().to_string())
                        .arg(tcp5.as_raw_fd().to_string())
                        .arg(tcp6.as_raw_fd().to_string())
                        .arg(udp1.as_raw_fd().to_string())
                        .arg(udp2.as_raw_fd().to_string())
                        .arg(pipe1.as_raw_fd().to_string())
                        .arg(pipe2.as_raw_fd().to_string())
                        .arg(pipe3.as_raw_fd().to_string())
                        .status()
                        .unwrap();
    assert!(status.success());
    child.wait().unwrap();
}

fn child(args: &[String]) {
    let mut b = [0u8; 2];
    for arg in &args[1..] {
        let fd: libc::c_int = arg.parse().unwrap();
        unsafe {
            assert_eq!(libc::read(fd, b.as_mut_ptr() as *mut _, 2), -1);
            assert_eq!(io::Error::last_os_error().raw_os_error(),
                       Some(libc::EBADF));
        }
    }
}
<commit_msg>Auto merge of #35885 - durka:gh35753, r=arielb1<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-windows
// ignore-android
// ignore-emscripten

#![feature(libc)]

extern crate libc;

use std::env;
use std::fs::File;
use std::io;
use std::net::{TcpListener, TcpStream, UdpSocket};
use std::os::unix::prelude::*;
use std::process::{Command, Stdio};
use std::thread;

fn main() {
    let args = env::args().collect::<Vec<_>>();
    if args.len() == 1 {
        parent()
    } else {
        child(&args)
    }
}

fn parent() {
    let file = File::open(file!()).unwrap();
    let tcp1 = TcpListener::bind("127.0.0.1:0").unwrap();
    let tcp2 = tcp1.try_clone().unwrap();
    let addr = tcp1.local_addr().unwrap();
    let t = thread::spawn(move || TcpStream::connect(addr).unwrap());
    let tcp3 = tcp1.accept().unwrap().0;
    let tcp4 = t.join().unwrap();
    let tcp5 = tcp3.try_clone().unwrap();
    let tcp6 = tcp4.try_clone().unwrap();
    let udp1 = UdpSocket::bind("127.0.0.1:0").unwrap();
    let udp2 = udp1.try_clone().unwrap();

    let mut child = Command::new(env::args().next().unwrap())
                            .arg("100")
                            .stdout(Stdio::piped())
                            .stdin(Stdio::piped())
                            .stderr(Stdio::piped())
                            .spawn().unwrap();
    let pipe1 = child.stdin.take().unwrap();
    let pipe2 = child.stdout.take().unwrap();
    let pipe3 = child.stderr.take().unwrap();

    let status = Command::new(env::args().next().unwrap())
                        .arg(file.as_raw_fd().to_string())
                        .arg(tcp1.as_raw_fd().to_string())
                        .arg(tcp2.as_raw_fd().to_string())
                        .arg(tcp3.as_raw_fd().to_string())
                        .arg(tcp4.as_raw_fd().to_string())
                        .arg(tcp5.as_raw_fd().to_string())
                        .arg(tcp6.as_raw_fd().to_string())
                        .arg(udp1.as_raw_fd().to_string())
                        .arg(udp2.as_raw_fd().to_string())
                        .arg(pipe1.as_raw_fd().to_string())
                        .arg(pipe2.as_raw_fd().to_string())
                        .arg(pipe3.as_raw_fd().to_string())
                        .status()
                        .unwrap();
    assert!(status.success());
    child.wait().unwrap();
}

fn child(args: &[String]) {
    let mut b = [0u8; 2];
    for arg in &args[1..] {
        let fd: libc::c_int = arg.parse().unwrap();
        unsafe {
            assert_eq!(libc::read(fd, b.as_mut_ptr() as *mut _, 2), -1);
            assert_eq!(io::Error::last_os_error().raw_os_error(),
                       Some(libc::EBADF));
        }
    }
}
<|endoftext|>


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

#![crate_name = "foo"]

// @has foo/struct.Foo0.html
pub struct Foo0;

impl Foo0 {
    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.1: fn_with_doc'
    // @has - 'fn_with_doc short'
    // @has - 'fn_with_doc full'
    /// fn_with_doc short
    ///
    /// fn_with_doc full
    #[deprecated(since = "1.0.1", note = "fn_with_doc")]
    pub fn fn_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.2: fn_without_doc'
    #[deprecated(since = "1.0.2", note = "fn_without_doc")]
    pub fn fn_without_doc() {}
}

pub trait Bar {
    /// fn_empty_with_doc short
    ///
    /// fn_empty_with_doc full
    #[deprecated(since = "1.0.3", note = "fn_empty_with_doc")]
    fn fn_empty_with_doc();

    #[deprecated(since = "1.0.4", note = "fn_empty_without_doc")]
    fn fn_empty_without_doc();

    /// fn_def_with_doc short
    ///
    /// fn_def_with_doc full
    #[deprecated(since = "1.0.5", note = "fn_def_with_doc")]
    fn fn_def_with_doc() {}

    #[deprecated(since = "1.0.6", note = "fn_def_without_doc")]
    fn fn_def_without_doc() {}

    /// fn_def_def_with_doc short
    ///
    /// fn_def_def_with_doc full
    #[deprecated(since = "1.0.7", note = "fn_def_def_with_doc")]
    fn fn_def_def_with_doc() {}

    #[deprecated(since = "1.0.8", note = "fn_def_def_without_doc")]
    fn fn_def_def_without_doc() {}
}

// @has foo/struct.Foo1.html
pub struct Foo1;

impl Bar for Foo1 {
    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.3: fn_empty_with_doc'
    // @has - 'fn_empty_with_doc_impl short'
    // @has - 'fn_empty_with_doc_impl full'
    /// fn_empty_with_doc_impl short
    ///
    /// fn_empty_with_doc_impl full
    fn fn_empty_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.4: fn_empty_without_doc'
    fn fn_empty_without_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.5: fn_def_with_doc'
    // @has - 'fn_def_with_doc_impl short'
    // @has - 'fn_def_with_doc_impl full'
    /// fn_def_with_doc_impl short
    ///
    /// fn_def_with_doc_impl full
    fn fn_def_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.6: fn_def_without_doc'
    fn fn_def_without_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.7: fn_def_def_with_doc'
    // @has - 'fn_def_def_with_doc short'
    // @!has - 'fn_def_def_with_doc full'

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.8: fn_def_def_without_doc'
}

// @has foo/struct.Foo2.html
pub struct Foo2;

impl Bar for Foo2 {
    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.3: fn_empty_with_doc'
    // @has - 'fn_empty_with_doc short'
    // @!has - 'fn_empty_with_doc full'
    fn fn_empty_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.4: fn_empty_without_doc'
    // @has - 'fn_empty_without_doc_impl short'
    // @has - 'fn_empty_without_doc_impl full'
    /// fn_empty_without_doc_impl short
    ///
    /// fn_empty_without_doc_impl full
    fn fn_empty_without_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.5: fn_def_with_doc'
    // @has - 'fn_def_with_doc short'
    // @!has - 'fn_def_with full'
    fn fn_def_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.6: fn_def_without_doc'
    // @has - 'fn_def_without_doc_impl short'
    // @has - 'fn_def_without_doc_impl full'
    /// fn_def_without_doc_impl short
    ///
    /// fn_def_without_doc_impl full
    fn fn_def_without_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.7: fn_def_def_with_doc'
    // @has - 'fn_def_def_with_doc short'
    // @!has - 'fn_def_def_with_doc full'

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.8: fn_def_def_without_doc'
}
<commit_msg>Fix typo in deprecated_impls<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![crate_name = "foo"]

// @has foo/struct.Foo0.html
pub struct Foo0;

impl Foo0 {
    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.1: fn_with_doc'
    // @has - 'fn_with_doc short'
    // @has - 'fn_with_doc full'
    /// fn_with_doc short
    ///
    /// fn_with_doc full
    #[deprecated(since = "1.0.1", note = "fn_with_doc")]
    pub fn fn_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.2: fn_without_doc'
    #[deprecated(since = "1.0.2", note = "fn_without_doc")]
    pub fn fn_without_doc() {}
}

pub trait Bar {
    /// fn_empty_with_doc short
    ///
    /// fn_empty_with_doc full
    #[deprecated(since = "1.0.3", note = "fn_empty_with_doc")]
    fn fn_empty_with_doc();

    #[deprecated(since = "1.0.4", note = "fn_empty_without_doc")]
    fn fn_empty_without_doc();

    /// fn_def_with_doc short
    ///
    /// fn_def_with_doc full
    #[deprecated(since = "1.0.5", note = "fn_def_with_doc")]
    fn fn_def_with_doc() {}

    #[deprecated(since = "1.0.6", note = "fn_def_without_doc")]
    fn fn_def_without_doc() {}

    /// fn_def_def_with_doc short
    ///
    /// fn_def_def_with_doc full
    #[deprecated(since = "1.0.7", note = "fn_def_def_with_doc")]
    fn fn_def_def_with_doc() {}

    #[deprecated(since = "1.0.8", note = "fn_def_def_without_doc")]
    fn fn_def_def_without_doc() {}
}

// @has foo/struct.Foo1.html
pub struct Foo1;

impl Bar for Foo1 {
    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.3: fn_empty_with_doc'
    // @has - 'fn_empty_with_doc_impl short'
    // @has - 'fn_empty_with_doc_impl full'
    /// fn_empty_with_doc_impl short
    ///
    /// fn_empty_with_doc_impl full
    fn fn_empty_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.4: fn_empty_without_doc'
    fn fn_empty_without_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.5: fn_def_with_doc'
    // @has - 'fn_def_with_doc_impl short'
    // @has - 'fn_def_with_doc_impl full'
    /// fn_def_with_doc_impl short
    ///
    /// fn_def_with_doc_impl full
    fn fn_def_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.6: fn_def_without_doc'
    fn fn_def_without_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.7: fn_def_def_with_doc'
    // @has - 'fn_def_def_with_doc short'
    // @!has - 'fn_def_def_with_doc full'

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.8: fn_def_def_without_doc'
}

// @has foo/struct.Foo2.html
pub struct Foo2;

impl Bar for Foo2 {
    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.3: fn_empty_with_doc'
    // @has - 'fn_empty_with_doc short'
    // @!has - 'fn_empty_with_doc full'
    fn fn_empty_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.4: fn_empty_without_doc'
    // @has - 'fn_empty_without_doc_impl short'
    // @has - 'fn_empty_without_doc_impl full'
    /// fn_empty_without_doc_impl short
    ///
    /// fn_empty_without_doc_impl full
    fn fn_empty_without_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.5: fn_def_with_doc'
    // @has - 'fn_def_with_doc short'
    // @!has - 'fn_def_with_doc full'
    fn fn_def_with_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.6: fn_def_without_doc'
    // @has - 'fn_def_without_doc_impl short'
    // @has - 'fn_def_without_doc_impl full'
    /// fn_def_without_doc_impl short
    ///
    /// fn_def_without_doc_impl full
    fn fn_def_without_doc() {}

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.7: fn_def_def_with_doc'
    // @has - 'fn_def_def_with_doc short'
    // @!has - 'fn_def_def_with_doc full'

    // @has - '//*[@class="stab deprecated"]' 'Deprecated since 1.0.8: fn_def_def_without_doc'
}
<|endoftext|>


<commit_before><commit_msg>add z<commit_after>//
// zhttpto.rs
//
// Reference solution for PS1
// Running on Rust 0.8
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// Special thanks to Kiet Tran for providing code we incorporated into this.
//
// University of Virginia - cs4414 Fall 2013
// Weilin Xu and David Evans
// Version 0.2

extern mod extra;

use std::rt::io::*;
use std::rt::io::net::ip::{SocketAddr, Ipv4Addr};
use std::io::println;
use std::cell::Cell;
use std::task;
use std::{os, str, io};

static PORT: int = 4414;
static IPV4_LOOPBACK: &'static str = "127.0.0.1";
static mut visitor_count: uint = 0;

fn main() {
    let socket = net::tcp::TcpListener::bind(SocketAddr {ip: Ipv4Addr(127,0,0,1), port: PORT as u16});

    println(fmt!("Listening on tcp port %d ...", PORT));
    let mut acceptor = socket.listen().unwrap();

    // we can limit the incoming connection count.
    //for stream in acceptor.incoming().take(10 as uint) {
    for stream in acceptor.incoming() {
        println!("Saw connection!");
        let stream = Cell::new(stream);
        // Start a task to handle the connection
        do task::spawn {
            unsafe {
                visitor_count += 1;
            }
            let mut stream = stream.take();
            let mut buf = [0, ..500];
            stream.read(buf);
            let request_str = str::from_utf8(buf);

            let req_group : ~[&str]= request_str.splitn_iter(' ', 3).collect();
            if req_group.len() > 2 {
                let path = req_group[1];
                println(fmt!("Request for path: \n%?", path));

                let file_path = &os::getcwd().push(path.replace("/../", ""));
                if !os::path_exists(file_path) || os::path_is_dir(file_path) {
                    println(fmt!("Request received:\n%s", request_str));
                    let response: ~str = fmt!(
                        "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
<doctype !html><title>Hello, Rust!</title>

Greetings, Krusty!

Visitor count: %u

\r\n", unsafe{visitor_count});

                    stream.write(response.as_bytes());
                }
                else {
                    println(fmt!("serve file: %?", file_path));
                    match io::read_whole_file(file_path) {
                        Ok(file_data) => {
                            stream.write(file_data);
                        }
                        Err(err) => {
                            println(err);
                        }
                    }
                }
            }
            println!("connection terminates")
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>autocommit 2015-05-19 00:16:16 CEST<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/.

//! Syscall wrappers

pub use lrs_syscall::{
    openat, close, lseek, fcntl_dupfd_cloexec, fcntl_getfl, fcntl_setfl, fcntl_getfd,
    fcntl_setfd, ftruncate, getpid, getppid, setresuid, setresgid, fsync, fdatasync, sync,
    syncfs, fadvise, fchmod, fallocate, timerfd_create, epoll_create, flock, readahead,
    read, write, pread, pwrite, readv, writev, preadv, pwritev, getresuid, getresgid,
    getgroups, setgroups, statfs, fstatfs, prlimit, getdents, fstatat, faccessat,
    truncate, linkat, utimensat, renameat2, mkdirat, unlinkat, symlinkat, readlinkat,
    fchownat, fchmodat, mknodat, setxattr, lsetxattr, fsetxattr, getxattr, lgetxattr,
    fgetxattr, removexattr, lremovexattr, fremovexattr, listxattr, llistxattr, flistxattr,
    clock_getres, clock_gettime, clock_settime, clock_nanosleep, timerfd_settime,
    timerfd_gettime, epoll_ctl, epoll_pwait, sched_getaffinity, uname, sysinfo, getrandom,
    acct, mount, umount, sethostname, setdomainname, socket, connect, accept4, recvfrom,
    recvmsg, recvmmsg, sendto, sendmsg, sendmmsg, shutdown, bind, listen, getsockname,
    getpeername, socketpair, setsockopt, getsockopt, futex_wait, futex_wake, exit,
    exit_group, execveat, mmap, munmap, mremap, waitid, getcwd, chdir, ioctl_siocgstampns,
    ioctl_siocinq, ioctl_siocoutq,
};
<|endoftext|>


<commit_before><commit_msg>boring rust version<commit_after>fn is_ugly(num: i64) -> String {
    if num == -1 {
        return "yes".to_string();
    }
    match num {
        1 | 2 | 3 | 5 => return is_ugly(-1),
        _ => {}
    }

    if num % 2 == 0 {
        is_ugly(num / 2)
    } else if num % 3 == 0 {
        is_ugly(num / 3)
    } else if num % 5 == 0 {
        is_ugly(num / 5)
    } else {
        "no".to_string()
    }
}

fn main() {
    dbg!(is_ugly(6));
    dbg!(is_ugly(8));
    dbg!(is_ugly(14));
}
<|endoftext|>


<commit_before><commit_msg>Update android specific bits for newer rust.<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing request body to create_media_conent<commit_after><|endoftext|>


<commit_before><commit_msg>Simplify.<commit_after><|endoftext|>


<commit_before><commit_msg>flirt: add skeleton for sig2pat tool<commit_after>use log::{error};
use fern;
use failure::{Error};
use better_panic;
extern crate log;
extern crate clap;
extern crate chrono;

fn run(sig_path: &str) -> Result<(), Error> {
    let buf = std::fs::read(sig_path)?;

    for sig in flirt::sig::parse(&buf)?.iter() {
        println!("{:}", sig);
    }

    Ok(())
}

fn main() {
    better_panic::install();

    // while the macro form of clap is more readable,
    // it doesn't seem to allow us to use dynamically-generated values,
    // such as the defaults pulled from env vars, etc.
    let matches = clap::App::new("sig2pat")
        .author("Willi Ballenthin <willi.ballenthin@gmail.com>")
        .about("translate a FLIRT .sig file into a .pat file")
        .arg(clap::Arg::with_name("verbose")
            .short("v")
            .long("verbose")
            .multiple(true)
            .help("log verbose messages")
        )
        .arg(clap::Arg::with_name("sig")
            .required(true)
            .index(1)
            .help("path to .sig file")
        ).get_matches();

    let log_level = match matches.occurrences_of("verbose") {
        0 => log::LevelFilter::Info,
        1 => log::LevelFilter::Debug,
        2 => log::LevelFilter::Trace,
        _ => log::LevelFilter::Trace,
    };

    fern::Dispatch::new()
        .format(move |out, message, record| {
            out.finish(format_args!(
                "{} [{:5}] {} {}",
                chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
                record.level(),
                if log_level == log::LevelFilter::Trace {record.target()} else {""},
                message
            ))
        })
        .level(log_level)
        .chain(std::io::stderr())
        .apply()
        .expect("failed to configure logging");

    if let Err(e) = run(matches.value_of("sig").unwrap()) {
        error!("{:?}", e)
    }
}
<|endoftext|>


<commit_before><commit_msg>add file deepening.rs<commit_after>use std::cmp::{min, max};
use std::thread;
use std::sync::Arc;
use std::sync::mpsc::{channel, Sender, Receiver};
use basetypes::*;
use moves::*;
use tt::*;
use position::Position;
use search::threading::{Command, Report, serve_simple};
use search::MAX_DEPTH;

/// The half-with of the initial aspiration window in centipawns.
const INITIAL_ASPIRATION_WINDOW: Value = 17; // 16;

/// The `SearchExecutor` trait is used to execute consecutive searches
/// in different starting positions.
pub trait SearchExecutor {
    /// Creates a new instance.
    fn new(tt: Arc<Tt>) -> Self;

    /// Starts a new search.
    ///
    /// * `search_id`: a number identifying the new search;
    ///
    /// * `position`: the root position;
    ///
    /// * `depth`: the requested search depth;
    ///
    /// * `lower_bound`: the lower bound for the new search;
    ///
    /// * `upper_bound`: the upper bound for the new search;
    ///
    /// * `value`: the evaluation of the root position so far, or
    ///   `VALUE_UNKNOWN` if not available.
    ///
    /// * `searchmoves`: restricts the analysis to the supplied list
    ///   of moves only (no restrictions if the suppied list is
    ///   empty);
    ///
    /// * `variation_count`: specifies how many best lines of play to
    ///   calculate (the first move in each line will be different).
    ///
    /// After calling `start_search`, `wait_for_report` must be called
    /// periodically until the returned report indicates that the
    /// search is done. A new search must not be started until the
    /// previous search is done.
    fn start_search(&mut self,
                    search_id: usize,
                    position: Position,
                    depth: u8,
                    lower_bound: Value,
                    upper_bound: Value,
                    value: Value,
                    searchmoves: Vec<Move>,
                    variation_count: usize);

    /// Blocks and waits for a search report.
    fn wait_for_report(&mut self) -> Report;

    /// Requests the termination of the current search.
    ///
    /// After calling `terminate`, `wait_for_report` must continue to
    /// be called periodically until the returned report indicates
    /// that the search is done.
    fn terminate_search(&mut self);
}

/// Executes searches to a fixed depth.
pub struct SimpleSearcher {
    thread: Option<thread::JoinHandle<()>>,
    thread_commands: Sender<Command>,
    thread_reports: Receiver<Report>,
}

impl SearchExecutor for SimpleSearcher {
    fn new(tt: Arc<Tt>) -> SimpleSearcher {
        let (commands_tx, commands_rx) = channel();
        let (reports_tx, reports_rx) = channel();
        SimpleSearcher {
            thread: Some(thread::spawn(move || {
                serve_simple(tt, commands_rx, reports_tx);
            })),
            thread_commands: commands_tx,
            thread_reports: reports_rx,
        }
    }

    #[allow(unused_variables)]
    fn start_search(&mut self,
                    search_id: usize,
                    position: Position,
                    depth: u8,
                    lower_bound: Value,
                    upper_bound: Value,
                    value: Value,
                    searchmoves: Vec<Move>,
                    variation_count: usize) {
        debug_assert!(depth <= MAX_DEPTH);
        debug_assert!(lower_bound < upper_bound);
        debug_assert!(lower_bound != VALUE_UNKNOWN);
        debug_assert!(searchmoves.is_empty());
        self.thread_commands
            .send(Command::Search {
                search_id: search_id,
                position: position,
                depth: depth,
                lower_bound: lower_bound,
                upper_bound: upper_bound,
            })
            .unwrap();
    }

    fn wait_for_report(&mut self) -> Report {
        self.thread_reports.recv().unwrap()
    }

    fn terminate_search(&mut self) {
        self.thread_commands.send(Command::Stop).unwrap();
    }
}

impl Drop for SimpleSearcher {
    fn drop(&mut self) {
        self.thread_commands.send(Command::Exit).unwrap();
        self.thread.take().unwrap().join().unwrap();
    }
}

/// Executes searches to a fixed depth with intelligently reduced
/// bounds (aspiration window).
///
/// Aspiration windows are a way to reduce the search space in the
/// search. The way it works is that we get the value from the last
/// search iteration (the `value` parameter to the `start_search`
/// method), calculate a window around it, and use this as alpha-beta
/// bounds for the search. Because the window is narrower, more beta
/// cutoffs are achieved, and the search takes a shorter time. The
/// drawback is that if the true score is outside this window, then a
/// costly re-search must be made. But then most probably the
/// re-search will be much faster, because many positions will be
/// remembered from the TT.
pub struct AspirationSearcher {
    search_id: usize,
    position: Position,
    depth: u8,
    lower_bound: Value,
    upper_bound: Value,
    value: Value,

    search_is_terminated: bool,

    /// The number of positions searched during previous searches.
    searched_nodes: NodeCount,

    /// The aspiration window will be widened by this value if the
    /// aspirated search fails. We use `isize` to avoid overflows.
    delta: isize,

    /// The lower bound of the aspiration window.
    alpha: Value,

    /// The upper bound of the aspiration window.
    beta: Value,

    /// `AspirationSearcher` will hand over the real work to
    /// `SimpleSearcher`.
    simple_searcher: SimpleSearcher,
}

impl AspirationSearcher {
    /// A helper mehtod. It commands the slave thread to run a new search.
    fn start_aspirated_search(&mut self) {
        self.simple_searcher.start_search(0,
                                          self.position.clone(),
                                          self.depth,
                                          self.alpha,
                                          self.beta,
                                          self.value,
                                          vec![],
                                          1);
    }

    /// A helper method. It increases `self.delta` exponentially.
    fn increase_delta(&mut self) {
        self.delta += 3 * self.delta / 8;
        if self.delta > 1500 {
            self.delta = 1_000_000;
        }
    }

    /// A helper method. It widens the aspiration window if necessary.
    fn widen_aspiration_window(&mut self) -> bool {
        let v = self.value as isize;
        if self.value <= self.alpha && self.lower_bound < self.alpha {
            // Set smaller `self.alpha`.
            self.alpha = max(v - self.delta, self.lower_bound as isize) as Value;
            self.increase_delta();
            return true;
        } else if self.value >= self.beta && self.upper_bound > self.beta {
            // Set bigger `self.beta`.
            self.beta = min(v + self.delta, self.upper_bound as isize) as Value;
            self.increase_delta();
            return true;
        }
        false
    }
}

impl SearchExecutor for AspirationSearcher {
    fn new(tt: Arc<Tt>) -> AspirationSearcher {
        AspirationSearcher {
            search_id: 0,
            position: Position::from_fen(::STARTING_POSITION).ok().unwrap(),
            depth: 0,
            lower_bound: VALUE_MIN,
            upper_bound: VALUE_MAX,
            value: VALUE_UNKNOWN,
            search_is_terminated: false,
            searched_nodes: 0,
            delta: INITIAL_ASPIRATION_WINDOW as isize,
            alpha: VALUE_MIN,
            beta: VALUE_MAX,
            simple_searcher: SimpleSearcher::new(tt),
        }
    }

    fn start_search(&mut self,
                    search_id: usize,
                    position: Position,
                    depth: u8,
                    lower_bound: Value,
                    upper_bound: Value,
                    value: Value,
                    searchmoves: Vec<Move>,
                    variation_count: usize) {
        debug_assert!(depth <= MAX_DEPTH);
        debug_assert!(lower_bound < upper_bound);
        debug_assert!(lower_bound != VALUE_UNKNOWN);
        debug_assert!(variation_count > 0);
        self.search_id = search_id;
        self.position = position;
        self.depth = depth;
        self.lower_bound = lower_bound;
        self.upper_bound = upper_bound;
        self.value = value;
        self.search_is_terminated = false;
        self.searched_nodes = 0;
        self.delta = INITIAL_ASPIRATION_WINDOW as isize;

        // Set the initial aspiration window (`self.alpha`, `self.beta`).
        let (a, b) = if value == VALUE_UNKNOWN || value < lower_bound || value > upper_bound {
            (lower_bound, upper_bound)
        } else {
            let v = value as isize;
            (max(v - self.delta, lower_bound as isize) as Value,
             min(v + self.delta, upper_bound as isize) as Value)
        };
        self.alpha = a;
        self.beta = b;

        self.start_aspirated_search();
    }

    fn wait_for_report(&mut self) -> Report {
        loop {
            let Report { searched_nodes, depth, value, done, .. } = self.simple_searcher
                                                                        .wait_for_report();
            let searched_nodes = self.searched_nodes + searched_nodes;
            let depth = if done && !self.search_is_terminated {
                self.searched_nodes = searched_nodes;
                self.value = value;
                if self.widen_aspiration_window() {
                    // `value` is outside the aspiration window and we
                    // must start another search.
                    self.start_aspirated_search();
                    continue;
                }
                depth
            } else {
                0
            };

            return Report {
                search_id: self.search_id,
                searched_nodes: searched_nodes,
                depth: depth,
                value: self.value,
                best_moves: vec![],
                done: done,
            };
        }
    }

    fn terminate_search(&mut self) {
        self.search_is_terminated = true;
        self.simple_searcher.terminate_search();
    }
}
<|endoftext|>


<commit_before>import libc::c_uint;
import base::*;
import common::*;
import type_of::*;
import build::*;
import driver::session::session;
import syntax::ast;
import syntax::ast_util::local_def;
import metadata::csearch;
import back::{link, abi};
import lib::llvm::llvm;
import lib::llvm::{ValueRef, TypeRef};
import lib::llvm::llvm::LLVMGetParam;
import ast_map::{path, path_mod, path_name};
import std::map::hashmap;

fn trans_impl(ccx: @crate_ctxt, path: path, name: ast::ident,
              methods: [@ast::method], tps: [ast::ty_param]) {
    if tps.len() > 0u { ret; }
    let sub_path = path + [path_name(name)];
    for m in methods {
        if m.tps.len() == 0u {
            let llfn = get_item_val(ccx, m.id);
            trans_fn(ccx, sub_path + [path_name(m.ident)], m.decl, m.body,
                     llfn, impl_self(ty::node_id_to_type(ccx.tcx, m.self_id)),
                     none, m.id, none);
        }
    }
}

fn trans_self_arg(bcx: block, base: @ast::expr) -> result {
    let basety = expr_ty(bcx, base);
    let m_by_ref = ast::expl(ast::by_ref);
    let temp_cleanups = [];
    let result = trans_arg_expr(bcx, {mode: m_by_ref, ty: basety},
                                T_ptr(type_of::type_of(bcx.ccx(), basety)),
                                base, temp_cleanups);

    // by-ref self argument should not require cleanup in the case of
    // other arguments failing:
    assert temp_cleanups == [];

    ret result;
}

fn trans_method_callee(bcx: block, callee_id: ast::node_id,
                       self: @ast::expr, origin: typeck::method_origin)
    -> lval_maybe_callee {
    alt origin {
      typeck::method_static(did) {
        let {bcx, val} = trans_self_arg(bcx, self);
        {env: self_env(val, node_id_type(bcx, self.id))
         with lval_static_fn(bcx, did, callee_id)}
      }
      typeck::method_param(iid, off, p, b) {
        alt check bcx.fcx.param_substs {
          some(substs) {
            trans_monomorphized_callee(bcx, callee_id, self,
                                       iid, off, p, b, substs)
          }
        }
      }
      typeck::method_iface(_, off) {
        trans_iface_callee(bcx, self, callee_id, off)
      }
    }
}

fn trans_vtable_callee(bcx: block, env: callee_env, vtable: ValueRef,
                       callee_id: ast::node_id, n_method: uint)
    -> lval_maybe_callee {
    let bcx = bcx, ccx = bcx.ccx();
    let fty = node_id_type(bcx, callee_id);
    let llfty = type_of::type_of_fn_from_ty(ccx, fty);
    let vtable = PointerCast(bcx, vtable,
                             T_ptr(T_array(T_ptr(llfty), n_method + 1u)));
    let mptr = Load(bcx, GEPi(bcx, vtable, [0, n_method as int]));
    {bcx: bcx, val: mptr, kind: owned, env: env, tds: none}
}

fn method_with_name(ccx: @crate_ctxt, impl_id: ast::def_id,
                    name: ast::ident) -> ast::def_id {
    if impl_id.crate == ast::local_crate {
        alt check ccx.tcx.items.get(impl_id.node) {
          ast_map::node_item(@{node: ast::item_impl(_, _, _, ms), _}, _) {
            local_def(option::get(vec::find(ms, {|m| m.ident == name})).id)
          }
        }
    } else {
        csearch::get_impl_method(ccx.sess.cstore, impl_id, name)
    }
}

fn method_ty_param_count(ccx: @crate_ctxt, m_id: ast::def_id) -> uint {
    if m_id.crate == ast::local_crate {
        alt check ccx.tcx.items.get(m_id.node) {
          ast_map::node_method(m, _, _) { vec::len(m.tps) }
        }
    } else {
        csearch::get_type_param_count(ccx.sess.cstore, m_id)
    }
}

fn trans_monomorphized_callee(bcx: block, callee_id: ast::node_id,
                              base: @ast::expr, iface_id: ast::def_id,
                              n_method: uint, n_param: uint, n_bound: uint,
                              substs: param_substs) -> lval_maybe_callee {
    alt find_vtable_in_fn_ctxt(substs, n_param, n_bound) {
      typeck::vtable_static(impl_did, impl_substs, sub_origins) {
        let ccx = bcx.ccx();
        let mname = ty::iface_methods(ccx.tcx, iface_id)[n_method].ident;
        let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
        let n_m_tps = method_ty_param_count(ccx, mth_id);
        let node_substs = node_id_type_params(bcx, callee_id);
        let ty_substs = impl_substs +
            vec::tailn(node_substs, node_substs.len() - n_m_tps);
        let {bcx, val} = trans_self_arg(bcx, base);
        {env: self_env(val, node_id_type(bcx, base.id))
         with lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs,
                                   some(sub_origins))}
      }
      typeck::vtable_iface(iid, tps) {
        trans_iface_callee(bcx, base, callee_id, n_method)
      }
      typeck::vtable_param(n_param, n_bound) {
        fail "vtable_param left in monomorphized function's vtable substs";
      }
    }
}

// Method callee where the vtable comes from a boxed iface
fn trans_iface_callee(bcx: block, base: @ast::expr,
                      callee_id: ast::node_id, n_method: uint)
    -> lval_maybe_callee {
    let {bcx, val} = trans_temp_expr(bcx, base);
    let vtable = Load(bcx, PointerCast(bcx, GEPi(bcx, val, [0, 0]),
                                     T_ptr(T_ptr(T_vtable()))));
    let box = Load(bcx, GEPi(bcx, val, [0, 1]));
    // FIXME[impl] I doubt this is alignment-safe
    let self = GEPi(bcx, box, [0, abi::box_field_body]);
    trans_vtable_callee(bcx, self_env(self, expr_ty(bcx, base)), vtable,
                        callee_id, n_method)
}

fn find_vtable_in_fn_ctxt(ps: param_substs, n_param: uint, n_bound: uint)
    -> typeck::vtable_origin {
    let vtable_off = n_bound, i = 0u;
    // Vtables are stored in a flat array, finding the right one is
    // somewhat awkward
    for bounds in *ps.bounds {
        if i >= n_param { break; }
        for bound in *bounds {
            alt bound { ty::bound_iface(_) { vtable_off += 1u; } _ {} }
        }
        i += 1u;
    }
    option::get(ps.vtables)[vtable_off]
}

fn resolve_vtables_in_fn_ctxt(fcx: fn_ctxt, vts: typeck::vtable_res)
    -> typeck::vtable_res {
    @vec::map(*vts, {|d| resolve_vtable_in_fn_ctxt(fcx, d)})
}

fn resolve_vtable_in_fn_ctxt(fcx: fn_ctxt, vt: typeck::vtable_origin)
    -> typeck::vtable_origin {
    alt vt {
      typeck::vtable_static(iid, tys, sub) {
        let tys = alt fcx.param_substs {
          some(substs) {
            vec::map(tys, {|t|
                ty::substitute_type_params(fcx.ccx.tcx, substs.tys, t)
            })
          }
          _ { tys }
        };
        typeck::vtable_static(iid, tys, resolve_vtables_in_fn_ctxt(fcx, sub))
      }
      typeck::vtable_param(n_param, n_bound) {
        alt check fcx.param_substs {
          some(substs) {
            find_vtable_in_fn_ctxt(substs, n_param, n_bound)
          }
        }
      }
      _ { vt }
    }
}

fn vtable_id(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> mono_id {
    alt check origin {
      typeck::vtable_static(impl_id, substs, sub_vtables) {
        make_mono_id(ccx, impl_id, substs,
                     if (*sub_vtables).len() == 0u { none }
                     else { some(sub_vtables) }, none)
      }
      typeck::vtable_iface(iface_id, substs) {
        @{def: iface_id,
          params: vec::map(substs, {|t| mono_precise(t, none)})}
      }
    }
}

fn get_vtable(ccx: @crate_ctxt, origin: typeck::vtable_origin)
    -> ValueRef {
    let hash_id = vtable_id(ccx, origin);
    alt ccx.vtables.find(hash_id) {
      some(val) { val }
      none {
        alt check origin {
          typeck::vtable_static(id, substs, sub_vtables) {
            make_impl_vtable(ccx, id, substs, sub_vtables)
          }
        }
      }
    }
}

fn make_vtable(ccx: @crate_ctxt, ptrs: [ValueRef]) -> ValueRef {
    let tbl = C_struct(ptrs);
    let vt_gvar = str::as_c_str(ccx.names("vtable"), {|buf|
        llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf)
    });
    llvm::LLVMSetInitializer(vt_gvar, tbl);
    llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True);
    lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage);
    vt_gvar
}

fn make_impl_vtable(ccx: @crate_ctxt, impl_id: ast::def_id, substs: [ty::t],
                    vtables: typeck::vtable_res) -> ValueRef {
    let tcx = ccx.tcx;
    let ifce_id = ty::ty_to_def_id(option::get(ty::impl_iface(tcx, impl_id)));
    make_vtable(ccx, vec::map(*ty::iface_methods(tcx, ifce_id), {|im|
        let fty = ty::substitute_type_params(tcx, substs,
                                             ty::mk_fn(tcx, im.fty));
        if (*im.tps).len() > 0u || ty::type_has_vars(fty) {
            C_null(type_of_fn_from_ty(ccx, fty))
        } else {
            let m_id = method_with_name(ccx, impl_id, im.ident);
            monomorphic_fn(ccx, m_id, substs, some(vtables)).val
        }
    }))
}

fn trans_cast(bcx: block, val: @ast::expr, id: ast::node_id, dest: dest)
    -> block {
    if dest == ignore { ret trans_expr(bcx, val, ignore); }
    let ccx = bcx.ccx();
    let v_ty = expr_ty(bcx, val);
    let {bcx, box, body} = trans_malloc_boxed(bcx, v_ty);
    add_clean_free(bcx, box, false);
    bcx = trans_expr_save_in(bcx, val, body);
    revoke_clean(bcx, box);
    let result = get_dest_addr(dest);
    Store(bcx, box, PointerCast(bcx, GEPi(bcx, result, [0, 1]),
                                T_ptr(val_ty(box))));
    let orig = ccx.maps.vtable_map.get(id)[0];
    let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, orig);
    let vtable = get_vtable(bcx.ccx(), orig);
    Store(bcx, vtable, PointerCast(bcx, GEPi(bcx, result, [0, 0]),
                                   T_ptr(val_ty(vtable))));
    bcx
}
<commit_msg>Fix bug in vtable builder<commit_after>import libc::c_uint;
import base::*;
import common::*;
import type_of::*;
import build::*;
import driver::session::session;
import syntax::ast;
import syntax::ast_util::local_def;
import metadata::csearch;
import back::{link, abi};
import lib::llvm::llvm;
import lib::llvm::{ValueRef, TypeRef};
import lib::llvm::llvm::LLVMGetParam;
import ast_map::{path, path_mod, path_name};
import std::map::hashmap;

fn trans_impl(ccx: @crate_ctxt, path: path, name: ast::ident,
              methods: [@ast::method], tps: [ast::ty_param]) {
    if tps.len() > 0u { ret; }
    let sub_path = path + [path_name(name)];
    for m in methods {
        if m.tps.len() == 0u {
            let llfn = get_item_val(ccx, m.id);
            trans_fn(ccx, sub_path + [path_name(m.ident)], m.decl, m.body,
                     llfn, impl_self(ty::node_id_to_type(ccx.tcx, m.self_id)),
                     none, m.id, none);
        }
    }
}

fn trans_self_arg(bcx: block, base: @ast::expr) -> result {
    let basety = expr_ty(bcx, base);
    let m_by_ref = ast::expl(ast::by_ref);
    let temp_cleanups = [];
    let result = trans_arg_expr(bcx, {mode: m_by_ref, ty: basety},
                                T_ptr(type_of::type_of(bcx.ccx(), basety)),
                                base, temp_cleanups);

    // by-ref self argument should not require cleanup in the case of
    // other arguments failing:
    assert temp_cleanups == [];

    ret result;
}

fn trans_method_callee(bcx: block, callee_id: ast::node_id,
                       self: @ast::expr, origin: typeck::method_origin)
    -> lval_maybe_callee {
    alt origin {
      typeck::method_static(did) {
        let {bcx, val} = trans_self_arg(bcx, self);
        {env: self_env(val, node_id_type(bcx, self.id))
         with lval_static_fn(bcx, did, callee_id)}
      }
      typeck::method_param(iid, off, p, b) {
        alt check bcx.fcx.param_substs {
          some(substs) {
            trans_monomorphized_callee(bcx, callee_id, self,
                                       iid, off, p, b, substs)
          }
        }
      }
      typeck::method_iface(_, off) {
        trans_iface_callee(bcx, self, callee_id, off)
      }
    }
}

fn trans_vtable_callee(bcx: block, env: callee_env, vtable: ValueRef,
                       callee_id: ast::node_id, n_method: uint)
    -> lval_maybe_callee {
    let bcx = bcx, ccx = bcx.ccx();
    let fty = node_id_type(bcx, callee_id);
    let llfty = type_of::type_of_fn_from_ty(ccx, fty);
    let vtable = PointerCast(bcx, vtable,
                             T_ptr(T_array(T_ptr(llfty), n_method + 1u)));
    let mptr = Load(bcx, GEPi(bcx, vtable, [0, n_method as int]));
    {bcx: bcx, val: mptr, kind: owned, env: env, tds: none}
}

fn method_with_name(ccx: @crate_ctxt, impl_id: ast::def_id,
                    name: ast::ident) -> ast::def_id {
    if impl_id.crate == ast::local_crate {
        alt check ccx.tcx.items.get(impl_id.node) {
          ast_map::node_item(@{node: ast::item_impl(_, _, _, ms), _}, _) {
            local_def(option::get(vec::find(ms, {|m| m.ident == name})).id)
          }
        }
    } else {
        csearch::get_impl_method(ccx.sess.cstore, impl_id, name)
    }
}

fn method_ty_param_count(ccx: @crate_ctxt, m_id: ast::def_id) -> uint {
    if m_id.crate == ast::local_crate {
        alt check ccx.tcx.items.get(m_id.node) {
          ast_map::node_method(m, _, _) { vec::len(m.tps) }
        }
    } else {
        csearch::get_type_param_count(ccx.sess.cstore, m_id)
    }
}

fn trans_monomorphized_callee(bcx: block, callee_id: ast::node_id,
                              base: @ast::expr, iface_id: ast::def_id,
                              n_method: uint, n_param: uint, n_bound: uint,
                              substs: param_substs) -> lval_maybe_callee {
    alt find_vtable_in_fn_ctxt(substs, n_param, n_bound) {
      typeck::vtable_static(impl_did, impl_substs, sub_origins) {
        let ccx = bcx.ccx();
        let mname = ty::iface_methods(ccx.tcx, iface_id)[n_method].ident;
        let mth_id = method_with_name(bcx.ccx(), impl_did, mname);
        let n_m_tps = method_ty_param_count(ccx, mth_id);
        let node_substs = node_id_type_params(bcx, callee_id);
        let ty_substs = impl_substs +
            vec::tailn(node_substs, node_substs.len() - n_m_tps);
        let {bcx, val} = trans_self_arg(bcx, base);
        {env: self_env(val, node_id_type(bcx, base.id))
         with lval_static_fn_inner(bcx, mth_id, callee_id, ty_substs,
                                   some(sub_origins))}
      }
      typeck::vtable_iface(iid, tps) {
        trans_iface_callee(bcx, base, callee_id, n_method)
      }
      typeck::vtable_param(n_param, n_bound) {
        fail "vtable_param left in monomorphized function's vtable substs";
      }
    }
}

// Method callee where the vtable comes from a boxed iface
fn trans_iface_callee(bcx: block, base: @ast::expr,
                      callee_id: ast::node_id, n_method: uint)
    -> lval_maybe_callee {
    let {bcx, val} = trans_temp_expr(bcx, base);
    let vtable = Load(bcx, PointerCast(bcx, GEPi(bcx, val, [0, 0]),
                                     T_ptr(T_ptr(T_vtable()))));
    let box = Load(bcx, GEPi(bcx, val, [0, 1]));
    // FIXME[impl] I doubt this is alignment-safe
    let self = GEPi(bcx, box, [0, abi::box_field_body]);
    trans_vtable_callee(bcx, self_env(self, expr_ty(bcx, base)), vtable,
                        callee_id, n_method)
}

fn find_vtable_in_fn_ctxt(ps: param_substs, n_param: uint, n_bound: uint)
    -> typeck::vtable_origin {
    let vtable_off = n_bound, i = 0u;
    // Vtables are stored in a flat array, finding the right one is
    // somewhat awkward
    for bounds in *ps.bounds {
        if i >= n_param { break; }
        for bound in *bounds {
            alt bound { ty::bound_iface(_) { vtable_off += 1u; } _ {} }
        }
        i += 1u;
    }
    option::get(ps.vtables)[vtable_off]
}

fn resolve_vtables_in_fn_ctxt(fcx: fn_ctxt, vts: typeck::vtable_res)
    -> typeck::vtable_res {
    @vec::map(*vts, {|d| resolve_vtable_in_fn_ctxt(fcx, d)})
}

fn resolve_vtable_in_fn_ctxt(fcx: fn_ctxt, vt: typeck::vtable_origin)
    -> typeck::vtable_origin {
    alt vt {
      typeck::vtable_static(iid, tys, sub) {
        let tys = alt fcx.param_substs {
          some(substs) {
            vec::map(tys, {|t|
                ty::substitute_type_params(fcx.ccx.tcx, substs.tys, t)
            })
          }
          _ { tys }
        };
        typeck::vtable_static(iid, tys, resolve_vtables_in_fn_ctxt(fcx, sub))
      }
      typeck::vtable_param(n_param, n_bound) {
        alt check fcx.param_substs {
          some(substs) {
            find_vtable_in_fn_ctxt(substs, n_param, n_bound)
          }
        }
      }
      _ { vt }
    }
}

fn vtable_id(ccx: @crate_ctxt, origin: typeck::vtable_origin) -> mono_id {
    alt check origin {
      typeck::vtable_static(impl_id, substs, sub_vtables) {
        make_mono_id(ccx, impl_id, substs,
                     if (*sub_vtables).len() == 0u { none }
                     else { some(sub_vtables) }, none)
      }
      typeck::vtable_iface(iface_id, substs) {
        @{def: iface_id,
          params: vec::map(substs, {|t| mono_precise(t, none)})}
      }
    }
}

fn get_vtable(ccx: @crate_ctxt, origin: typeck::vtable_origin)
    -> ValueRef {
    let hash_id = vtable_id(ccx, origin);
    alt ccx.vtables.find(hash_id) {
      some(val) { val }
      none {
        alt check origin {
          typeck::vtable_static(id, substs, sub_vtables) {
            make_impl_vtable(ccx, id, substs, sub_vtables)
          }
        }
      }
    }
}

fn make_vtable(ccx: @crate_ctxt, ptrs: [ValueRef]) -> ValueRef {
    let tbl = C_struct(ptrs);
    let vt_gvar = str::as_c_str(ccx.names("vtable"), {|buf|
        llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf)
    });
    llvm::LLVMSetInitializer(vt_gvar, tbl);
    llvm::LLVMSetGlobalConstant(vt_gvar, lib::llvm::True);
    lib::llvm::SetLinkage(vt_gvar, lib::llvm::InternalLinkage);
    vt_gvar
}

fn make_impl_vtable(ccx: @crate_ctxt, impl_id: ast::def_id, substs: [ty::t],
                    vtables: typeck::vtable_res) -> ValueRef {
    let tcx = ccx.tcx;
    let ifce_id = ty::ty_to_def_id(option::get(ty::impl_iface(tcx, impl_id)));
    let has_tps = (*ty::lookup_item_type(ccx.tcx, impl_id).bounds).len() > 0u;
    make_vtable(ccx, vec::map(*ty::iface_methods(tcx, ifce_id), {|im|
        let fty = ty::substitute_type_params(tcx, substs,
                                             ty::mk_fn(tcx, im.fty));
        if (*im.tps).len() > 0u || ty::type_has_vars(fty) {
            C_null(type_of_fn_from_ty(ccx, fty))
        } else {
            let m_id = method_with_name(ccx, impl_id, im.ident);
            if has_tps {
                monomorphic_fn(ccx, m_id, substs, some(vtables)).val
            } else if m_id.crate == ast::local_crate {
                get_item_val(ccx, m_id.node)
            } else {
                trans_external_path(ccx, m_id, fty)
            }
        }
    }))
}

fn trans_cast(bcx: block, val: @ast::expr, id: ast::node_id, dest: dest)
    -> block {
    if dest == ignore { ret trans_expr(bcx, val, ignore); }
    let ccx = bcx.ccx();
    let v_ty = expr_ty(bcx, val);
    let {bcx, box, body} = trans_malloc_boxed(bcx, v_ty);
    add_clean_free(bcx, box, false);
    bcx = trans_expr_save_in(bcx, val, body);
    revoke_clean(bcx, box);
    let result = get_dest_addr(dest);
    Store(bcx, box, PointerCast(bcx, GEPi(bcx, result, [0, 1]),
                                T_ptr(val_ty(box))));
    let orig = ccx.maps.vtable_map.get(id)[0];
    let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, orig);
    let vtable = get_vtable(bcx.ccx(), orig);
    Store(bcx, vtable, PointerCast(bcx, GEPi(bcx, result, [0, 0]),
                                   T_ptr(val_ty(vtable))));
    bcx
}
<|endoftext|>


<commit_before><commit_msg>Codeforces 740B<commit_after>use std::io::stdin;

fn main() {
    let mut input_line = String::new();
    stdin().read_line(&mut input_line).unwrap();
    let mut input_iter = input_line.
        split_whitespace().
        map(|x| x.parse::<usize>().unwrap());

    let flower_count = input_iter.next().unwrap();
    let subarray_count = input_iter.next().unwrap();

    let mut sum_range = [0; 101];
    let mut input_line = String::new();
    stdin().read_line(&mut input_line).unwrap();
    let mut input_iter = input_line.
        split_whitespace().
        map(|x| x.parse::<i32>().unwrap());

    for i in 1..(flower_count + 1) {
        sum_range[i] = sum_range[i - 1] + input_iter.next().unwrap();
    }

    let mut result = 0;

    for _ in 1..(subarray_count + 1) {
        let mut input_line = String::new();
        stdin().read_line(&mut input_line).unwrap();
        let mut input_iter = input_line.
            split_whitespace().
            map(|x| x.parse::<usize>().unwrap());
        let left = input_iter.next().unwrap();
        let right = input_iter.next().unwrap();
        let happiness = sum_range[right] - sum_range[left - 1];
        if happiness > 0 {
            result += happiness;
        }
    }

    println!("{}", result);
}<|endoftext|>


<commit_before><commit_msg>BPF: add assembly test<commit_after>// min-llvm-version: 10.0.1
// assembly-output: emit-asm
// compile-flags: --target bpfel-unknown-none -C target_feature=+alu32
// needs-llvm-components: bpf

#![feature(no_core, lang_items, rustc_attrs, repr_simd)]
#![crate_type = "rlib"]
#![no_core]
#![allow(asm_sub_register, non_camel_case_types)]

#[rustc_builtin_macro]
macro_rules! asm {
    () => {};
}
#[rustc_builtin_macro]
macro_rules! concat {
    () => {};
}
#[rustc_builtin_macro]
macro_rules! stringify {
    () => {};
}

#[lang = "sized"]
trait Sized {}
#[lang = "copy"]
trait Copy {}

type ptr = *const u64;

impl Copy for i8 {}
impl Copy for i16 {}
impl Copy for i32 {}
impl Copy for i64 {}
impl Copy for ptr {}

macro_rules! check {
    ($func:ident $ty:ident $class:ident) => {
        #[no_mangle]
        pub unsafe fn $func(x: $ty) -> $ty {
            let y;
            asm!("{} = {}", out($class) y, in($class) x);
            y
        }
    };
}

macro_rules! check_reg {
    ($func:ident $ty:ident $reg:tt) => {
        #[no_mangle]
        pub unsafe fn $func(x: $ty) -> $ty {
            let y;
            asm!(concat!($reg, " = ", $reg), lateout($reg) y, in($reg) x);
            y
        }
    };
}

extern "C" {
    fn extern_func();
}

// CHECK-LABEL: sym_fn
// CHECK: #APP
// CHECK: call extern_func
// CHECK: #NO_APP
#[no_mangle]
pub unsafe fn sym_fn() {
    asm!("call {}", sym extern_func);
}

// CHECK-LABEL: reg_i8:
// CHECK: #APP
// CHECK: r{{[0-9]+}} = r{{[0-9]+}}
// CHECK: #NO_APP
check!(reg_i8 i8 reg);

// CHECK-LABEL: reg_i16:
// CHECK: #APP
// CHECK: r{{[0-9]+}} = r{{[0-9]+}}
// CHECK: #NO_APP
check!(reg_i16 i16 reg);

// CHECK-LABEL: reg_i32:
// CHECK: #APP
// CHECK: r{{[0-9]+}} = r{{[0-9]+}}
// CHECK: #NO_APP
check!(reg_i32 i32 reg);

// CHECK-LABEL: reg_i64:
// CHECK: #APP
// CHECK: r{{[0-9]+}} = r{{[0-9]+}}
// CHECK: #NO_APP
check!(reg_i64 i64 reg);

// CHECK-LABEL: wreg_i8:
// CHECK: #APP
// CHECK: w{{[0-9]+}} = w{{[0-9]+}}
// CHECK: #NO_APP
check!(wreg_i8 i8 wreg);

// CHECK-LABEL: wreg_i16:
// CHECK: #APP
// CHECK: w{{[0-9]+}} = w{{[0-9]+}}
// CHECK: #NO_APP
check!(wreg_i16 i16 wreg);

// CHECK-LABEL: wreg_i32:
// CHECK: #APP
// CHECK: w{{[0-9]+}} = w{{[0-9]+}}
// CHECK: #NO_APP
check!(wreg_i32 i32 wreg);

// CHECK-LABEL: r0_i8:
// CHECK: #APP
// CHECK: r0 = r0
// CHECK: #NO_APP
check_reg!(r0_i8 i8 "r0");

// CHECK-LABEL: r0_i16:
// CHECK: #APP
// CHECK: r0 = r0
// CHECK: #NO_APP
check_reg!(r0_i16 i16 "r0");

// CHECK-LABEL: r0_i32:
// CHECK: #APP
// CHECK: r0 = r0
// CHECK: #NO_APP
check_reg!(r0_i32 i32 "r0");

// CHECK-LABEL: r0_i64:
// CHECK: #APP
// CHECK: r0 = r0
// CHECK: #NO_APP
check_reg!(r0_i64 i64 "r0");

// CHECK-LABEL: w0_i8:
// CHECK: #APP
// CHECK: w0 = w0
// CHECK: #NO_APP
check_reg!(w0_i8 i8 "w0");

// CHECK-LABEL: w0_i16:
// CHECK: #APP
// CHECK: w0 = w0
// CHECK: #NO_APP
check_reg!(w0_i16 i16 "w0");

// CHECK-LABEL: w0_i32:
// CHECK: #APP
// CHECK: w0 = w0
// CHECK: #NO_APP
check_reg!(w0_i32 i32 "w0");
<|endoftext|>


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

use core::prelude::*;

use config;
use config::Config;
use doc::ItemUtils;
use doc;
use pass::Pass;

use core::io::ReaderUtil;
use core::io;
use core::libc;
use core::oldcomm;
use core::os;
use core::pipes;
use core::result;
use core::run;
use core::str;
use core::task;
use std::future;
use syntax;

pub enum WriteInstr {
    Write(~str),
    Done
}

pub type Writer = fn~(v: WriteInstr);
pub type WriterFactory = fn~(page: doc::Page) -> Writer;

pub trait WriterUtils {
    fn write_str(&self, +str: ~str);
    fn write_line(&self, +str: ~str);
    fn write_done(&self);
}

impl Writer: WriterUtils {
    fn write_str(&self, str: ~str) {
        (*self)(Write(str));
    }

    fn write_line(&self, str: ~str) {
        self.write_str(str + ~"\n");
    }

    fn write_done(&self) {
        (*self)(Done)
    }
}

pub fn make_writer_factory(config: config::Config) -> WriterFactory {
    match config.output_format {
      config::Markdown => {
        markdown_writer_factory(config)
      }
      config::PandocHtml => {
        pandoc_writer_factory(config)
      }
    }
}

fn markdown_writer_factory(config: config::Config) -> WriterFactory {
    fn~(page: doc::Page) -> Writer {
        markdown_writer(copy config, page)
    }
}

fn pandoc_writer_factory(config: config::Config) -> WriterFactory {
    fn~(page: doc::Page) -> Writer {
        pandoc_writer(copy config, page)
    }
}

fn markdown_writer(
    config: config::Config,
    page: doc::Page
) -> Writer {
    let filename = make_local_filename(config, page);
    do generic_writer |markdown| {
        write_file(&filename, markdown);
    }
}

fn pandoc_writer(
    config: config::Config,
    page: doc::Page
) -> Writer {
    assert config.pandoc_cmd.is_some();
    let pandoc_cmd = (&config.pandoc_cmd).get();
    let filename = make_local_filename(config, page);

    let pandoc_args = ~[
        ~"--standalone",
        ~"--section-divs",
        ~"--from=markdown",
        ~"--to=html",
        ~"--css=rust.css",
        ~"--output=" + filename.to_str()
    ];

    do generic_writer |markdown| {
        use io::WriterUtil;

        debug!("pandoc cmd: %s", pandoc_cmd);
        debug!("pandoc args: %s", str::connect(pandoc_args, ~" "));

        let pipe_in = os::pipe();
        let pipe_out = os::pipe();
        let pipe_err = os::pipe();
        let pid = run::spawn_process(
            pandoc_cmd, pandoc_args, &None, &None,
            pipe_in.in, pipe_out.out, pipe_err.out);

        let writer = io::fd_writer(pipe_in.out, false);
        writer.write_str(markdown);

        os::close(pipe_in.in);
        os::close(pipe_out.out);
        os::close(pipe_err.out);
        os::close(pipe_in.out);

        let (stdout_po, stdout_ch) = pipes::stream();
        do task::spawn_sched(task::SingleThreaded) |move stdout_ch| {
            stdout_ch.send(readclose(pipe_out.in));
        }

        let (stderr_po, stderr_ch) = pipes::stream();
        do task::spawn_sched(task::SingleThreaded) |move stderr_ch| {
            stderr_ch.send(readclose(pipe_err.in));
        }
        let stdout = stdout_po.recv();
        let stderr = stderr_po.recv();

        let status = run::waitpid(pid);
        debug!("pandoc result: %i", status);
        if status != 0 {
            error!("pandoc-out: %s", stdout);
            error!("pandoc-err: %s", stderr);
            die!(~"pandoc failed");
        }
    }
}

fn readclose(fd: libc::c_int) -> ~str {
    // Copied from run::program_output
    unsafe {
        let file = os::fdopen(fd);
        let reader = io::FILE_reader(file, false);
        let buf = io::with_bytes_writer(|writer| {
            let mut bytes = [mut 0, ..4096];
            while !reader.eof() {
                let nread = reader.read(bytes, bytes.len());
                writer.write(bytes.view(0, nread));
            }
        });
        os::fclose(file);
        str::from_bytes(buf)
    }
}

fn generic_writer(process: fn~(markdown: ~str)) -> Writer {
    let (setup_po, setup_ch) = pipes::stream();
    do task::spawn |move process, move setup_ch| {
        let po: oldcomm::Port<WriteInstr> = oldcomm::Port();
        let ch = oldcomm::Chan(&po);
        setup_ch.send(ch);

        let mut markdown = ~"";
        let mut keep_going = true;
        while keep_going {
            match po.recv() {
              Write(s) => markdown += s,
              Done => keep_going = false
            }
        }
        process(move markdown);
    };
    let ch = setup_po.recv();

    fn~(instr: WriteInstr) {
        oldcomm::send(ch, instr);
    }
}

fn make_local_filename(
    config: config::Config,
    page: doc::Page
) -> Path {
    let filename = make_filename(copy config, page);
    config.output_dir.push_rel(&filename)
}

pub fn make_filename(
    config: config::Config,
    page: doc::Page
) -> Path {
    let filename = {
        match page {
          doc::CratePage(doc) => {
            if config.output_format == config::PandocHtml &&
                config.output_style == config::DocPerMod {
                ~"index"
            } else {
                assert doc.topmod.name() != ~"";
                doc.topmod.name()
            }
          }
          doc::ItemPage(doc) => {
            str::connect(doc.path() + ~[doc.name()], ~"_")
          }
        }
    };
    let ext = match config.output_format {
      config::Markdown => ~"md",
      config::PandocHtml => ~"html"
    };

    Path(filename).with_filetype(ext)
}

#[test]
fn should_use_markdown_file_name_based_off_crate() {
    let config = Config {
        output_dir: Path("output/dir"),
        output_format: config::Markdown,
        output_style: config::DocPerCrate,
        .. config::default_config(&Path("input/test.rc"))
    };
    let doc = test::mk_doc(~"test", ~"");
    let page = doc::CratePage(doc.CrateDoc());
    let filename = make_local_filename(config, page);
    assert filename.to_str() == ~"output/dir/test.md";
}

#[test]
fn should_name_html_crate_file_name_index_html_when_doc_per_mod() {
    let config = Config {
        output_dir: Path("output/dir"),
        output_format: config::PandocHtml,
        output_style: config::DocPerMod,
        .. config::default_config(&Path("input/test.rc"))
    };
    let doc = test::mk_doc(~"", ~"");
    let page = doc::CratePage(doc.CrateDoc());
    let filename = make_local_filename(config, page);
    assert filename.to_str() == ~"output/dir/index.html";
}

#[test]
fn should_name_mod_file_names_by_path() {
    let config = Config {
        output_dir: Path("output/dir"),
        output_format: config::PandocHtml,
        output_style: config::DocPerMod,
        .. config::default_config(&Path("input/test.rc"))
    };
    let doc = test::mk_doc(~"", ~"mod a { mod b { } }");
    let modb = copy doc.cratemod().mods()[0].mods()[0];
    let page = doc::ItemPage(doc::ModTag(modb));
    let filename = make_local_filename(config, page);
    assert  filename == Path("output/dir/a_b.html");
}

#[cfg(test)]
mod test {
    use astsrv;
    use doc;
    use extract;
    use path_pass;

    pub fn mk_doc(name: ~str, source: ~str) -> doc::Doc {
        do astsrv::from_str(source) |srv| {
            let doc = extract::from_srv(srv.clone(), copy name);
            let doc = (path_pass::mk_pass().f)(srv.clone(), doc);
            doc
        }
    }
}

fn write_file(path: &Path, s: ~str) {
    use io::WriterUtil;

    match io::file_writer(path, ~[io::Create, io::Truncate]) {
      result::Ok(writer) => {
        writer.write_str(s);
      }
      result::Err(e) => die!(e)
    }
}

pub fn future_writer_factory(
) -> (WriterFactory, oldcomm::Port<(doc::Page, ~str)>) {
    let markdown_po = oldcomm::Port();
    let markdown_ch = oldcomm::Chan(&markdown_po);
    let writer_factory = fn~(page: doc::Page) -> Writer {
        let (writer_po, writer_ch) = pipes::stream();
        do task::spawn |move writer_ch| {
            let (writer, future) = future_writer();
            writer_ch.send(move writer);
            let s = future.get();
            oldcomm::send(markdown_ch, (copy page, s));
        }
        writer_po.recv()
    };

    (move writer_factory, markdown_po)
}

fn future_writer() -> (Writer, future::Future<~str>) {
    let (port, chan) = pipes::stream();
    let writer = fn~(move chan, instr: WriteInstr) {
        chan.send(copy instr);
    };
    let future = do future::from_fn |move port| {
        let mut res = ~"";
        loop {
            match port.recv() {
              Write(s) => res += s,
              Done => break
            }
        }
        res
    };
    (move writer, move future)
}
<commit_msg>rustdoc: Remove another use of oldcomm<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::prelude::*;

use config;
use config::Config;
use doc::ItemUtils;
use doc;
use pass::Pass;

use core::io::ReaderUtil;
use core::io;
use core::libc;
use core::oldcomm;
use core::os;
use core::pipes;
use core::result;
use core::run;
use core::str;
use core::task;
use core::pipes::*;
use std::future;
use syntax;

pub enum WriteInstr {
    Write(~str),
    Done
}

pub type Writer = fn~(v: WriteInstr);
pub type WriterFactory = fn~(page: doc::Page) -> Writer;

pub trait WriterUtils {
    fn write_str(&self, +str: ~str);
    fn write_line(&self, +str: ~str);
    fn write_done(&self);
}

impl Writer: WriterUtils {
    fn write_str(&self, str: ~str) {
        (*self)(Write(str));
    }

    fn write_line(&self, str: ~str) {
        self.write_str(str + ~"\n");
    }

    fn write_done(&self) {
        (*self)(Done)
    }
}

pub fn make_writer_factory(config: config::Config) -> WriterFactory {
    match config.output_format {
      config::Markdown => {
        markdown_writer_factory(config)
      }
      config::PandocHtml => {
        pandoc_writer_factory(config)
      }
    }
}

fn markdown_writer_factory(config: config::Config) -> WriterFactory {
    fn~(page: doc::Page) -> Writer {
        markdown_writer(copy config, page)
    }
}

fn pandoc_writer_factory(config: config::Config) -> WriterFactory {
    fn~(page: doc::Page) -> Writer {
        pandoc_writer(copy config, page)
    }
}

fn markdown_writer(
    config: config::Config,
    page: doc::Page
) -> Writer {
    let filename = make_local_filename(config, page);
    do generic_writer |markdown| {
        write_file(&filename, markdown);
    }
}

fn pandoc_writer(
    config: config::Config,
    page: doc::Page
) -> Writer {
    assert config.pandoc_cmd.is_some();
    let pandoc_cmd = (&config.pandoc_cmd).get();
    let filename = make_local_filename(config, page);

    let pandoc_args = ~[
        ~"--standalone",
        ~"--section-divs",
        ~"--from=markdown",
        ~"--to=html",
        ~"--css=rust.css",
        ~"--output=" + filename.to_str()
    ];

    do generic_writer |markdown| {
        use io::WriterUtil;

        debug!("pandoc cmd: %s", pandoc_cmd);
        debug!("pandoc args: %s", str::connect(pandoc_args, ~" "));

        let pipe_in = os::pipe();
        let pipe_out = os::pipe();
        let pipe_err = os::pipe();
        let pid = run::spawn_process(
            pandoc_cmd, pandoc_args, &None, &None,
            pipe_in.in, pipe_out.out, pipe_err.out);

        let writer = io::fd_writer(pipe_in.out, false);
        writer.write_str(markdown);

        os::close(pipe_in.in);
        os::close(pipe_out.out);
        os::close(pipe_err.out);
        os::close(pipe_in.out);

        let (stdout_po, stdout_ch) = pipes::stream();
        do task::spawn_sched(task::SingleThreaded) |move stdout_ch| {
            stdout_ch.send(readclose(pipe_out.in));
        }

        let (stderr_po, stderr_ch) = pipes::stream();
        do task::spawn_sched(task::SingleThreaded) |move stderr_ch| {
            stderr_ch.send(readclose(pipe_err.in));
        }
        let stdout = stdout_po.recv();
        let stderr = stderr_po.recv();

        let status = run::waitpid(pid);
        debug!("pandoc result: %i", status);
        if status != 0 {
            error!("pandoc-out: %s", stdout);
            error!("pandoc-err: %s", stderr);
            die!(~"pandoc failed");
        }
    }
}

fn readclose(fd: libc::c_int) -> ~str {
    // Copied from run::program_output
    unsafe {
        let file = os::fdopen(fd);
        let reader = io::FILE_reader(file, false);
        let buf = io::with_bytes_writer(|writer| {
            let mut bytes = [mut 0, ..4096];
            while !reader.eof() {
                let nread = reader.read(bytes, bytes.len());
                writer.write(bytes.view(0, nread));
            }
        });
        os::fclose(file);
        str::from_bytes(buf)
    }
}

fn generic_writer(process: fn~(markdown: ~str)) -> Writer {
    let (po, ch) = stream::<WriteInstr>();
    do task::spawn |move process, move setup_ch| {
        let mut markdown = ~"";
        let mut keep_going = true;
        while keep_going {
            match po.recv() {
              Write(s) => markdown += s,
              Done => keep_going = false
            }
        }
        process(move markdown);
    };
    fn~(instr: WriteInstr) {
        ch.send(instr);
    }
}

fn make_local_filename(
    config: config::Config,
    page: doc::Page
) -> Path {
    let filename = make_filename(copy config, page);
    config.output_dir.push_rel(&filename)
}

pub fn make_filename(
    config: config::Config,
    page: doc::Page
) -> Path {
    let filename = {
        match page {
          doc::CratePage(doc) => {
            if config.output_format == config::PandocHtml &&
                config.output_style == config::DocPerMod {
                ~"index"
            } else {
                assert doc.topmod.name() != ~"";
                doc.topmod.name()
            }
          }
          doc::ItemPage(doc) => {
            str::connect(doc.path() + ~[doc.name()], ~"_")
          }
        }
    };
    let ext = match config.output_format {
      config::Markdown => ~"md",
      config::PandocHtml => ~"html"
    };

    Path(filename).with_filetype(ext)
}

#[test]
fn should_use_markdown_file_name_based_off_crate() {
    let config = Config {
        output_dir: Path("output/dir"),
        output_format: config::Markdown,
        output_style: config::DocPerCrate,
        .. config::default_config(&Path("input/test.rc"))
    };
    let doc = test::mk_doc(~"test", ~"");
    let page = doc::CratePage(doc.CrateDoc());
    let filename = make_local_filename(config, page);
    assert filename.to_str() == ~"output/dir/test.md";
}

#[test]
fn should_name_html_crate_file_name_index_html_when_doc_per_mod() {
    let config = Config {
        output_dir: Path("output/dir"),
        output_format: config::PandocHtml,
        output_style: config::DocPerMod,
        .. config::default_config(&Path("input/test.rc"))
    };
    let doc = test::mk_doc(~"", ~"");
    let page = doc::CratePage(doc.CrateDoc());
    let filename = make_local_filename(config, page);
    assert filename.to_str() == ~"output/dir/index.html";
}

#[test]
fn should_name_mod_file_names_by_path() {
    let config = Config {
        output_dir: Path("output/dir"),
        output_format: config::PandocHtml,
        output_style: config::DocPerMod,
        .. config::default_config(&Path("input/test.rc"))
    };
    let doc = test::mk_doc(~"", ~"mod a { mod b { } }");
    let modb = copy doc.cratemod().mods()[0].mods()[0];
    let page = doc::ItemPage(doc::ModTag(modb));
    let filename = make_local_filename(config, page);
    assert  filename == Path("output/dir/a_b.html");
}

#[cfg(test)]
mod test {
    use astsrv;
    use doc;
    use extract;
    use path_pass;

    pub fn mk_doc(name: ~str, source: ~str) -> doc::Doc {
        do astsrv::from_str(source) |srv| {
            let doc = extract::from_srv(srv.clone(), copy name);
            let doc = (path_pass::mk_pass().f)(srv.clone(), doc);
            doc
        }
    }
}

fn write_file(path: &Path, s: ~str) {
    use io::WriterUtil;

    match io::file_writer(path, ~[io::Create, io::Truncate]) {
      result::Ok(writer) => {
        writer.write_str(s);
      }
      result::Err(e) => die!(e)
    }
}

pub fn future_writer_factory(
) -> (WriterFactory, oldcomm::Port<(doc::Page, ~str)>) {
    let markdown_po = oldcomm::Port();
    let markdown_ch = oldcomm::Chan(&markdown_po);
    let writer_factory = fn~(page: doc::Page) -> Writer {
        let (writer_po, writer_ch) = pipes::stream();
        do task::spawn |move writer_ch| {
            let (writer, future) = future_writer();
            writer_ch.send(move writer);
            let s = future.get();
            oldcomm::send(markdown_ch, (copy page, s));
        }
        writer_po.recv()
    };

    (move writer_factory, markdown_po)
}

fn future_writer() -> (Writer, future::Future<~str>) {
    let (port, chan) = pipes::stream();
    let writer = fn~(move chan, instr: WriteInstr) {
        chan.send(copy instr);
    };
    let future = do future::from_fn |move port| {
        let mut res = ~"";
        loop {
            match port.recv() {
              Write(s) => res += s,
              Done => break
            }
        }
        res
    };
    (move writer, move future)
}
<|endoftext|>


<commit_before><commit_msg>Create an idiomatic fibonacci function<commit_after>fn fib(n: i64) -> i64 {
    match n {
        0 => 0,
        1 => 1,
        _ => fib(n - 1) + fib(n - 2)
    }
}

fn main() {
    let n = 10;

    println!("fib({}) = {}", n, fib(n));
}
<|endoftext|>


<commit_before><commit_msg>Removed in_processed from Document<commit_after><|endoftext|>


<commit_before><commit_msg>Add simple benchmarks<commit_after>#![feature(test)]

extern crate test;
extern crate uuid;

use test::Bencher;
use uuid::Uuid;

#[bench]
fn bench_parse(b: &mut Bencher) {
    b.iter(|| {
        let _ = Uuid::parse_str("");
        let _ = Uuid::parse_str("!");
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E45");
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa-BBF-329BF39FA1E4");
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa-BGBF-329BF39FA1E4");
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa-B6BFF329BF39FA1E4");
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa");
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faaXB6BFF329BF39FA1E4");
        let _ = Uuid::parse_str("F9168C5E-CEB-24fa-eB6BFF32-BF39FA1E4");
        let _ = Uuid::parse_str("01020304-1112-2122-3132-41424344");
        let _ = Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c88");
        let _ = Uuid::parse_str("67e5504410b1426f9247bb680e5fe0cg8");
        let _ = Uuid::parse_str("67e5504410b1426%9247bb680e5fe0c8");

        // Valid
        let _ = Uuid::parse_str("00000000000000000000000000000000");
        let _ = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8");
        let _ = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8");
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4");
        let _ = Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c8");
        let _ = Uuid::parse_str("01020304-1112-2122-3132-414243444546");
        let _ = Uuid::parse_str("urn:uuid:67e55044-10b1-426f-9247-bb680e5fe0c8");

        // Nil
        let _ = Uuid::parse_str("00000000000000000000000000000000");
        let _ = Uuid::parse_str("00000000-0000-0000-0000-000000000000");

        // Test error reporting
        let _ = Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c");
        let _ = Uuid::parse_str("67e550X410b1426f9247bb680e5fe0cd");
        let _ = Uuid::parse_str("67e550-4105b1426f9247bb680e5fe0c");
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa-B6BF1-02BF39FA1E4");
    });
}

#[bench]
fn bench_parse_invalid_len(b: &mut Bencher) {
    b.iter(|| {
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa-BBF-329BF39FA1E4");
    })
}

#[bench]
fn bench_parse_invalid_character(b: &mut Bencher) {
    b.iter(|| {
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa-BGBF-329BF39FA1E4");
    })
}

#[bench]
fn bench_parse_invalid_group_len(b: &mut Bencher) {
    b.iter(|| {
        let _ = Uuid::parse_str("01020304-1112-2122-3132-41424344");
    });
}

#[bench]
fn bench_parse_invalid_groups(b: &mut Bencher) {
    b.iter(|| {
        let _ = Uuid::parse_str("F9168C5E-CEB2-4faa-B6BFF329BF39FA1E4");
    });
}

#[bench]
fn bench_valid_hyphenated(b: &mut Bencher) {
    b.iter(|| {
        let _ = Uuid::parse_str("67e55044-10b1-426f-9247-bb680e5fe0c8");
    });
}

#[bench]
fn bench_valid_short(b: &mut Bencher) {
    b.iter(|| {
        let _ = Uuid::parse_str("67e5504410b1426f9247bb680e5fe0c8");
    });
}
<|endoftext|>


<commit_before><commit_msg>Do not list entries which are not "log" entries<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #8937 - alexcrichton:optimize-vendor-a-bit, r=Eh2406<commit_after><|endoftext|>


<commit_before><commit_msg>Add a simple group example (#120)<commit_after>#[macro_use]
extern crate structopt;

use structopt::StructOpt;

#[derive(StructOpt, Debug)]
struct Opt {
    /// Set a custom HTTP verb
    #[structopt(long = "method", group = "verb")]
    method: Option<String>,
    /// HTTP GET; default if no other HTTP verb is selected
    #[structopt(long = "get", group = "verb")]
    get: bool,
    /// HTTP HEAD
    #[structopt(long = "head", group = "verb")]
    head: bool,
    /// HTTP POST
    #[structopt(long = "post", group = "verb")]
    post: bool,
    /// HTTP PUT
    #[structopt(long = "put", group = "verb")]
    put: bool,
    /// HTTP DELETE
    #[structopt(long = "delete", group = "verb")]
    delete: bool,
}

fn main() {
    let opt = Opt::from_args();
    println!("{:?}", opt);
}
<|endoftext|>


<commit_before><commit_msg>Example from lkuper's intern talk, but now with static methods!<commit_after>// Example from lkuper's intern talk, August 2012 -- now with static
// methods!

trait Equal {
    static fn isEq(a: self, b: self) -> bool;
}

enum Color { cyan, magenta, yellow, black }

impl Color : Equal {
    static fn isEq(a: Color, b: Color) -> bool {
        match (a, b) {
          (cyan, cyan)       => { true  }
          (magenta, magenta) => { true  }
          (yellow, yellow)   => { true  }
          (black, black)     => { true  }
          _                  => { false }
        }
    }
}

enum ColorTree {
    leaf(Color),
    branch(@ColorTree, @ColorTree)
}

impl ColorTree : Equal {
    static fn isEq(a: ColorTree, b: ColorTree) -> bool {
        match (a, b) {
          (leaf(x), leaf(y)) => { isEq(x, y) }
          (branch(l1, r1), branch(l2, r2)) => {
            isEq(*l1, *l2) && isEq(*r1, *r2)
          }
          _ => { false }
        }
    }
}

fn main() {
    assert isEq(cyan, cyan);
    assert isEq(magenta, magenta);
    assert !isEq(cyan, yellow);
    assert !isEq(magenta, cyan);

    assert isEq(leaf(cyan), leaf(cyan));
    assert !isEq(leaf(cyan), leaf(yellow));

    assert isEq(branch(@leaf(magenta), @leaf(cyan)),
                branch(@leaf(magenta), @leaf(cyan)));

    assert !isEq(branch(@leaf(magenta), @leaf(cyan)),
                 branch(@leaf(magenta), @leaf(magenta)));

    log(error, "Assertions all succeeded!");
}<|endoftext|>