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

#![deny(warnings)]

extern crate filetime;

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

use filetime::FileTime;

/// A helper macro to `unwrap` a result except also print out details like:
///
/// * The file/line of the panic
/// * The expression that failed
/// * The error itself
///
/// This is currently used judiciously throughout the build system rather than
/// using a `Result` with `try!`, but this may change one day...
#[macro_export]
macro_rules! t {
    ($e:expr) => (match $e {
        Ok(e) => e,
        Err(e) => panic!("{} failed with {}", stringify!($e), e),
    })
}

pub fn run(cmd: &mut Command) {
    println!("running: {:?}", cmd);
    run_silent(cmd);
}

pub fn run_silent(cmd: &mut Command) {
    let status = match cmd.status() {
        Ok(status) => status,
        Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}",
                                cmd, e)),
    };
    if !status.success() {
        fail(&format!("command did not execute successfully: {:?}\n\
                       expected success, got: {}",
                      cmd,
                      status));
    }
}

pub fn run_suppressed(cmd: &mut Command) {
    let output = match cmd.output() {
        Ok(status) => status,
        Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}",
                                cmd, e)),
    };
    if !output.status.success() {
        fail(&format!("command did not execute successfully: {:?}\n\
                       expected success, got: {}\n\n\
                       stdout ----\n{}\n\
                       stderr ----\n{}\n",
                      cmd,
                      output.status,
                      String::from_utf8_lossy(&output.stdout),
                      String::from_utf8_lossy(&output.stderr)));
    }
}

pub fn gnu_target(target: &str) -> String {
    match target {
        "i686-pc-windows-msvc" => "i686-pc-win32".to_string(),
        "x86_64-pc-windows-msvc" => "x86_64-pc-win32".to_string(),
        "i686-pc-windows-gnu" => "i686-w64-mingw32".to_string(),
        "x86_64-pc-windows-gnu" => "x86_64-w64-mingw32".to_string(),
        s => s.to_string(),
    }
}

pub fn cc2ar(cc: &Path, target: &str) -> Option<PathBuf> {
    if target.contains("msvc") {
        None
    } else if target.contains("musl") {
        Some(PathBuf::from("ar"))
    } else if target.contains("openbsd") {
        Some(PathBuf::from("ar"))
    } else {
        let parent = cc.parent().unwrap();
        let file = cc.file_name().unwrap().to_str().unwrap();
        for suffix in &["gcc", "cc", "clang"] {
            if let Some(idx) = file.rfind(suffix) {
                let mut file = file[..idx].to_owned();
                file.push_str("ar");
                return Some(parent.join(&file));
            }
        }
        Some(parent.join(file))
    }
}

pub fn make(host: &str) -> PathBuf {
    if host.contains("bitrig") || host.contains("dragonfly") ||
        host.contains("freebsd") || host.contains("netbsd") ||
        host.contains("openbsd") {
        PathBuf::from("gmake")
    } else {
        PathBuf::from("make")
    }
}

pub fn output(cmd: &mut Command) -> String {
    let output = match cmd.stderr(Stdio::inherit()).output() {
        Ok(status) => status,
        Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}",
                                cmd, e)),
    };
    if !output.status.success() {
        panic!("command did not execute successfully: {:?}\n\
                expected success, got: {}",
               cmd,
               output.status);
    }
    String::from_utf8(output.stdout).unwrap()
}

pub fn rerun_if_changed_anything_in_dir(dir: &Path) {
    let mut stack = dir.read_dir().unwrap()
                       .map(|e| e.unwrap())
                       .filter(|e| &*e.file_name() != ".git")
                       .collect::<Vec<_>>();
    while let Some(entry) = stack.pop() {
        let path = entry.path();
        if entry.file_type().unwrap().is_dir() {
            stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
        } else {
            println!("cargo:rerun-if-changed={}", path.display());
        }
    }
}

/// Returns the last-modified time for `path`, or zero if it doesn't exist.
pub fn mtime(path: &Path) -> FileTime {
    fs::metadata(path).map(|f| {
        FileTime::from_last_modification_time(&f)
    }).unwrap_or(FileTime::zero())
}

/// Returns whether `dst` is up to date given that the file or files in `src`
/// are used to generate it.
///
/// Uses last-modified time checks to verify this.
pub fn up_to_date(src: &Path, dst: &Path) -> bool {
    let threshold = mtime(dst);
    let meta = match fs::metadata(src) {
        Ok(meta) => meta,
        Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
    };
    if meta.is_dir() {
        dir_up_to_date(src, &threshold)
    } else {
        FileTime::from_last_modification_time(&meta) <= threshold
    }
}

#[must_use]
pub struct NativeLibBoilerplate {
    pub src_dir: PathBuf,
    pub out_dir: PathBuf,
}

impl Drop for NativeLibBoilerplate {
    fn drop(&mut self) {
        t!(File::create(self.out_dir.join("rustbuild.timestamp")));
    }
}

// Perform standard preparations for native libraries that are build only once for all stages.
// Emit rerun-if-changed and linking attributes for Cargo, check if any source files are
// updated, calculate paths used later in actual build with CMake/make or C/C++ compiler.
// If Err is returned, then everything is up-to-date and further build actions can be skipped.
// Timestamps are created automatically when the result of `native_lib_boilerplate` goes out
// of scope, so all the build actions should be completed until then.
pub fn native_lib_boilerplate(src_name: &str,
                              out_name: &str,
                              link_name: &str,
                              search_subdir: &str)
                              -> Result<NativeLibBoilerplate, ()> {
    let current_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
    let src_dir = current_dir.join("..").join(src_name);
    rerun_if_changed_anything_in_dir(&src_dir);

    let out_dir = env::var_os("RUSTBUILD_NATIVE_DIR").unwrap_or(env::var_os("OUT_DIR").unwrap());
    let out_dir = PathBuf::from(out_dir).join(out_name);
    let _ = fs::create_dir_all(&out_dir);
    println!("cargo:rustc-link-lib=static={}", link_name);
    println!("cargo:rustc-link-search=native={}", out_dir.join(search_subdir).display());

    let timestamp = out_dir.join("rustbuild.timestamp");
    if !up_to_date(Path::new("build.rs"), &timestamp) || !up_to_date(&src_dir, &timestamp) {
        Ok(NativeLibBoilerplate { src_dir: src_dir, out_dir: out_dir })
    } else {
        Err(())
    }
}

fn dir_up_to_date(src: &Path, threshold: &FileTime) -> bool {
    t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
        let meta = t!(e.metadata());
        if meta.is_dir() {
            dir_up_to_date(&e.path(), threshold)
        } else {
            FileTime::from_last_modification_time(&meta) < *threshold
        }
    })
}

fn fail(s: &str) -> ! {
    println!("\n\n{}\n\n", s);
    std::process::exit(1);
}
<commit_msg>Auto merge of #40337 - alexcrichton:racy-dirs, r=brson<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![deny(warnings)]

extern crate filetime;

use std::fs::File;
use std::io;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::{fs, env};

use filetime::FileTime;

/// A helper macro to `unwrap` a result except also print out details like:
///
/// * The file/line of the panic
/// * The expression that failed
/// * The error itself
///
/// This is currently used judiciously throughout the build system rather than
/// using a `Result` with `try!`, but this may change one day...
#[macro_export]
macro_rules! t {
    ($e:expr) => (match $e {
        Ok(e) => e,
        Err(e) => panic!("{} failed with {}", stringify!($e), e),
    })
}

pub fn run(cmd: &mut Command) {
    println!("running: {:?}", cmd);
    run_silent(cmd);
}

pub fn run_silent(cmd: &mut Command) {
    let status = match cmd.status() {
        Ok(status) => status,
        Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}",
                                cmd, e)),
    };
    if !status.success() {
        fail(&format!("command did not execute successfully: {:?}\n\
                       expected success, got: {}",
                      cmd,
                      status));
    }
}

pub fn run_suppressed(cmd: &mut Command) {
    let output = match cmd.output() {
        Ok(status) => status,
        Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}",
                                cmd, e)),
    };
    if !output.status.success() {
        fail(&format!("command did not execute successfully: {:?}\n\
                       expected success, got: {}\n\n\
                       stdout ----\n{}\n\
                       stderr ----\n{}\n",
                      cmd,
                      output.status,
                      String::from_utf8_lossy(&output.stdout),
                      String::from_utf8_lossy(&output.stderr)));
    }
}

pub fn gnu_target(target: &str) -> String {
    match target {
        "i686-pc-windows-msvc" => "i686-pc-win32".to_string(),
        "x86_64-pc-windows-msvc" => "x86_64-pc-win32".to_string(),
        "i686-pc-windows-gnu" => "i686-w64-mingw32".to_string(),
        "x86_64-pc-windows-gnu" => "x86_64-w64-mingw32".to_string(),
        s => s.to_string(),
    }
}

pub fn cc2ar(cc: &Path, target: &str) -> Option<PathBuf> {
    if target.contains("msvc") {
        None
    } else if target.contains("musl") {
        Some(PathBuf::from("ar"))
    } else if target.contains("openbsd") {
        Some(PathBuf::from("ar"))
    } else {
        let parent = cc.parent().unwrap();
        let file = cc.file_name().unwrap().to_str().unwrap();
        for suffix in &["gcc", "cc", "clang"] {
            if let Some(idx) = file.rfind(suffix) {
                let mut file = file[..idx].to_owned();
                file.push_str("ar");
                return Some(parent.join(&file));
            }
        }
        Some(parent.join(file))
    }
}

pub fn make(host: &str) -> PathBuf {
    if host.contains("bitrig") || host.contains("dragonfly") ||
        host.contains("freebsd") || host.contains("netbsd") ||
        host.contains("openbsd") {
        PathBuf::from("gmake")
    } else {
        PathBuf::from("make")
    }
}

pub fn output(cmd: &mut Command) -> String {
    let output = match cmd.stderr(Stdio::inherit()).output() {
        Ok(status) => status,
        Err(e) => fail(&format!("failed to execute command: {:?}\nerror: {}",
                                cmd, e)),
    };
    if !output.status.success() {
        panic!("command did not execute successfully: {:?}\n\
                expected success, got: {}",
               cmd,
               output.status);
    }
    String::from_utf8(output.stdout).unwrap()
}

pub fn rerun_if_changed_anything_in_dir(dir: &Path) {
    let mut stack = dir.read_dir().unwrap()
                       .map(|e| e.unwrap())
                       .filter(|e| &*e.file_name() != ".git")
                       .collect::<Vec<_>>();
    while let Some(entry) = stack.pop() {
        let path = entry.path();
        if entry.file_type().unwrap().is_dir() {
            stack.extend(path.read_dir().unwrap().map(|e| e.unwrap()));
        } else {
            println!("cargo:rerun-if-changed={}", path.display());
        }
    }
}

/// Returns the last-modified time for `path`, or zero if it doesn't exist.
pub fn mtime(path: &Path) -> FileTime {
    fs::metadata(path).map(|f| {
        FileTime::from_last_modification_time(&f)
    }).unwrap_or(FileTime::zero())
}

/// Returns whether `dst` is up to date given that the file or files in `src`
/// are used to generate it.
///
/// Uses last-modified time checks to verify this.
pub fn up_to_date(src: &Path, dst: &Path) -> bool {
    let threshold = mtime(dst);
    let meta = match fs::metadata(src) {
        Ok(meta) => meta,
        Err(e) => panic!("source {:?} failed to get metadata: {}", src, e),
    };
    if meta.is_dir() {
        dir_up_to_date(src, &threshold)
    } else {
        FileTime::from_last_modification_time(&meta) <= threshold
    }
}

#[must_use]
pub struct NativeLibBoilerplate {
    pub src_dir: PathBuf,
    pub out_dir: PathBuf,
}

impl Drop for NativeLibBoilerplate {
    fn drop(&mut self) {
        t!(File::create(self.out_dir.join("rustbuild.timestamp")));
    }
}

// Perform standard preparations for native libraries that are build only once for all stages.
// Emit rerun-if-changed and linking attributes for Cargo, check if any source files are
// updated, calculate paths used later in actual build with CMake/make or C/C++ compiler.
// If Err is returned, then everything is up-to-date and further build actions can be skipped.
// Timestamps are created automatically when the result of `native_lib_boilerplate` goes out
// of scope, so all the build actions should be completed until then.
pub fn native_lib_boilerplate(src_name: &str,
                              out_name: &str,
                              link_name: &str,
                              search_subdir: &str)
                              -> Result<NativeLibBoilerplate, ()> {
    let current_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
    let src_dir = current_dir.join("..").join(src_name);
    rerun_if_changed_anything_in_dir(&src_dir);

    let out_dir = env::var_os("RUSTBUILD_NATIVE_DIR").unwrap_or(env::var_os("OUT_DIR").unwrap());
    let out_dir = PathBuf::from(out_dir).join(out_name);
    t!(create_dir_racy(&out_dir));
    println!("cargo:rustc-link-lib=static={}", link_name);
    println!("cargo:rustc-link-search=native={}", out_dir.join(search_subdir).display());

    let timestamp = out_dir.join("rustbuild.timestamp");
    if !up_to_date(Path::new("build.rs"), &timestamp) || !up_to_date(&src_dir, &timestamp) {
        Ok(NativeLibBoilerplate { src_dir: src_dir, out_dir: out_dir })
    } else {
        Err(())
    }
}

fn dir_up_to_date(src: &Path, threshold: &FileTime) -> bool {
    t!(fs::read_dir(src)).map(|e| t!(e)).all(|e| {
        let meta = t!(e.metadata());
        if meta.is_dir() {
            dir_up_to_date(&e.path(), threshold)
        } else {
            FileTime::from_last_modification_time(&meta) < *threshold
        }
    })
}

fn fail(s: &str) -> ! {
    println!("\n\n{}\n\n", s);
    std::process::exit(1);
}

fn create_dir_racy(path: &Path) -> io::Result<()> {
    match fs::create_dir(path) {
        Ok(()) => return Ok(()),
        Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => return Ok(()),
        Err(ref e) if e.kind() == io::ErrorKind::NotFound => {}
        Err(e) => return Err(e),
    }
    match path.parent() {
        Some(p) => try!(create_dir_racy(p)),
        None => return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")),
    }
    match fs::create_dir(path) {
        Ok(()) => Ok(()),
        Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
        Err(e) => Err(e),
    }
}
<|endoftext|>


<commit_before><commit_msg>remove insert sentinel code<commit_after><|endoftext|>


<commit_before><commit_msg>beginnings of a bulk classifier<commit_after>extern crate classifier;
use classifier::Classifier;
use diesel::pg::PgConnection;
use dotenv::dotenv;
use self::models::Ad;

// For now we grab all the ads in the database and classify and resave them not
// ideal in the future, but we're launching next week.
fn main() {
    dotenv().ok();
    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let conn = PgConnection::establish(&database_url).expect("could not connect to the databas");
    let ads: Vec<Ad> = diesel::select
}
<|endoftext|>


<commit_before><commit_msg>#24468 call update_entry API from process_response_eof<commit_after><|endoftext|>


<commit_before><commit_msg>Add additional test case for superregion<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.

// Test that when a `..` impl applies, we also check that any
// supertrait conditions are met.

#![feature(optin_builtin_traits)]

use std::marker::MarkerTrait;

trait MyTrait : 'static {}

impl MyTrait for .. {}

fn foo<T:MyTrait>() { }

fn bar<'a>() {
    foo::<&'a ()>(); //~ ERROR does not fulfill the required lifetime
}

fn main() {
}
<|endoftext|>


<commit_before>use expression::Expression;
use query_builder::AsQuery;
use query_source::QuerySource;

/// Sets the order clause of a query. If there was already a order clause, it
/// will be overridden. The expression passed to `order` must actually be valid
/// for the query. See also:
/// [`.desc()`](../expression/expression_methods/global_expression_methods/trait.ExpressionMethods.html#method.desc)
/// and [`.asc()`](../expression/expression_methods/global_expression_methods/trait.ExpressionMethods.html#method.asc)
///
/// This is automatically implemented for the various query builder types.
pub trait OrderDsl<Expr: Expression>: AsQuery {
    type Output: AsQuery<SqlType=Self::SqlType>;

    fn order(self, expr: Expr) -> Self::Output;
}

impl<T, Expr, ST> OrderDsl<Expr> for T where
    Expr: Expression,
    T: QuerySource + AsQuery<SqlType=ST>,
    T::Query: OrderDsl<Expr, SqlType=ST>,
{
    type Output = <T::Query as OrderDsl<Expr>>::Output;

    fn order(self, expr: Expr) -> Self::Output {
        self.as_query().order(expr)
    }
}
<commit_msg>fix broken doc links<commit_after>use expression::Expression;
use query_builder::AsQuery;
use query_source::QuerySource;

/// Sets the order clause of a query. If there was already a order clause, it
/// will be overridden. The expression passed to `order` must actually be valid
/// for the query. See also:
/// [`.desc()`](../../expression/expression_methods/global_expression_methods/trait.ExpressionMethods.html#method.desc)
/// and [`.asc()`](../../expression/expression_methods/global_expression_methods/trait.ExpressionMethods.html#method.asc)
///
/// This is automatically implemented for the various query builder types.
pub trait OrderDsl<Expr: Expression>: AsQuery {
    type Output: AsQuery<SqlType=Self::SqlType>;

    fn order(self, expr: Expr) -> Self::Output;
}

impl<T, Expr, ST> OrderDsl<Expr> for T where
    Expr: Expression,
    T: QuerySource + AsQuery<SqlType=ST>,
    T::Query: OrderDsl<Expr, SqlType=ST>,
{
    type Output = <T::Query as OrderDsl<Expr>>::Output;

    fn order(self, expr: Expr) -> Self::Output {
        self.as_query().order(expr)
    }
}
<|endoftext|>


<commit_before><commit_msg>added another example of reversing a singleton vector<commit_after>extern crate quickcheck;

use quickcheck::{TestResult, quickcheck};

fn reverse<T: Clone>(xs: &[T]) -> ~[T] {
    let mut rev = ~[];
    for x in xs.iter() {
        rev.unshift(x.clone())
    }
    rev
}

fn main() {
    fn prop(xs: ~[int]) -> ~TestResult {
        if xs.len() != 1 {
            return TestResult::discard()
        }
        TestResult::from_bool(xs == reverse(xs))
    }
    quickcheck(prop);
}
<|endoftext|>


<commit_before>use redox::Vec;

pub struct AvlNode<T> {
    value: T,
    left: Option<AvlNodeId>, // ID for left node
    right: Option<AvlNodeId>, // ID for right node
}

#[derive(Copy, Clone)]
pub struct AvlNodeId {
    index: usize,
    time_stamp: u64,
}

impl AvlNodeId {
    pub fn get<'a, T: PartialOrd>(&self, avl: &'a AvlTree<T>) -> &'a AvlNode<T> {
        let ref slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_ref().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get<'a, T: PartialOrd>(&self, avl: &'a AvlTree<T>) -> Option<&'a AvlNode<T>> {
        avl.nodes
           .get(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_ref()
               } else {
                   None
               }
           })
    }

    pub fn get_mut<'a, T: PartialOrd>(&self, avl: &'a mut AvlTree<T>) -> &'a mut AvlNode<T> {
        let ref mut slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_mut().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get_mut<'a, T: PartialOrd>(&self, avl: &'a mut AvlTree<T>) -> Option<&'a mut AvlNode<T>> {
        avl.nodes
           .get_mut(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_mut()
               } else {
                   None
               }
           })
    }
}

pub struct AvlTree<T: PartialOrd> {
    root: Option<AvlNodeId>, // Index of the root node
    nodes: Vec<AvlSlot<T>>,
    free_list: Vec<usize>,
}

impl<T: PartialOrd> AvlTree<T> {
    pub fn new() -> Self {
        AvlTree {
            root: None,
            nodes: Vec::new(),
            free_list: Vec::new(),
        }
    }

    // Inserts a value into the tree, keeping it balanced. Lesser values will be stored on
    // the left, while greater values will be stored on the right. No duplicates are allowed.
    pub fn insert(&mut self, value: T) {
        let root = self.root;
        self.root = Some(self._insert(value, root));
    }

    pub fn in_order<F: Fn(&AvlNode<T>)>(&self, f: &F) {
        if let Some(root) = self.root {
            self._in_order(f, root);
        }
    }

    // Implementation of insert
    fn _insert(&mut self, value: T, node_index: Option<AvlNodeId>) -> AvlNodeId {
        let node =
            match node_index {
                Some(node) => {
                    // Node exists, check which way to branch.
                    if value == node.get(self).value {
                        return node;
                    } else if value < node.get(self).value {
                        let l = node.get(self).left;
                        node.get_mut(self).left = Some(self._insert(value, l));
                    } else if value > node.get(self).value {
                        let r = node.get(self).right;
                        node.get_mut(self).right = Some(self._insert(value, r));
                    }

                    node
                },
                None => {
                    // The node doesn't exist, create it here.
                    self.allocate_node(value)
                },
            };

        self.rebalance(node)
    }

    pub fn _in_order<F: Fn(&AvlNode<T>)>(&self, f: &F, node: AvlNodeId) {
        if let Some(l) = node.get(self).left {
            self._in_order(f, l);
        }
        f(node.get(self));
        if let Some(r) = node.get(self).right {
            self._in_order(f, r);
        }
    }

    // Performs a left rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_left(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate left, the right child node must exist
        let r = node.get(self).right.unwrap();
        let rl = r.get(self).left;

        let ret = r;
        node.get_mut(self).right = rl;
        ret.get_mut(self).left = Some(node);

        ret
    }

    // Performs a right rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_right(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate right, the left child node must exist
        let l = node.get(self).left.unwrap();
        let lr = l.get(self).right;

        let ret = l;
        node.get_mut(self).left = lr;
        ret.get_mut(self).right = Some(node);

        ret
    }

    // performs a left-right double rotation on a tree/subtree.
    fn rotate_leftright(&mut self, node: AvlNodeId) -> AvlNodeId {
        let l = node.get(self).left.unwrap();
        let new_l = self.rotate_left(l); // Left node needs to exist
        node.get_mut(self).left = Some(new_l);
        self.rotate_right(node)
    }

    // performs a right-left double rotation on a tree/subtree.
    fn rotate_rightleft(&mut self, node: AvlNodeId) -> AvlNodeId {
        let r = node.get(self).right.unwrap();
        let new_r = self.rotate_right(r); // Right node needs to exist
        node.get_mut(self).right = Some(new_r);
        self.rotate_left(node)
    }

    // _rebalance rebalances the provided node
    fn rebalance(&mut self, node: AvlNodeId) -> AvlNodeId {
        let balance = self.height(node.get(self).left) - self.height(node.get(self).right);
        if balance == 2 { // left
            let lbalance = self.height(node.get(self).left.unwrap().get(self).left) -
                           self.height(node.get(self).left.unwrap().get(self).right);
            if lbalance == 0 || lbalance == 1 { // left left - need to rotate right
                return self.rotate_right(node);
            } else if lbalance == -1 { // left right
                return self.rotate_leftright(node); // function name is just a coincidence
            }
        } else if balance == -2 { // right
            let rbalance = self.height(node.get(self).right.unwrap().get(self).left) -
                           self.height(node.get(self).right.unwrap().get(self).right);
            if rbalance == 1 { // right left
                return self.rotate_rightleft(node); // function name is just a coincidence
            } else if rbalance == 0 || rbalance == -1 { // right right - need to rotate left
                return self.rotate_left(node);
            }
        }

        node
    }

    // height gets the height of a tree or subtree
    fn height(&self, node: Option<AvlNodeId>) -> i64 {
        match node {
            Some(node) => {
                let left_height = self.height(node.get(self).left);
                let right_height = self.height(node.get(self).right);

                if left_height > right_height {
                    left_height+1
                } else {
                    right_height+1
                }
            },
            None => { -1 },
        }
    }

    fn allocate_node(&mut self, value: T) -> AvlNodeId {
        match self.free_list.pop() {
            Some(index) => {
                AvlNodeId { time_stamp: self.nodes[index].time_stamp+1, index: index }
            },
            None => {
                // No free slots, create a new one
                let id = AvlNodeId { index: self.nodes.len(), time_stamp: 0 };
                self.nodes.push(AvlSlot { time_stamp: 0,
                                          node: Some(AvlNode { value: value, left: None, right: None }) });
                id
            },
        }
    }

    fn free_node(&mut self, id: AvlNodeId) -> AvlNode<T> {
        self.free_list.push(id.index);

        // NOTE: We unwrap here, because we trust that `id` points to a valid node, because
        // only we can create and free AvlNodes and their AvlNodeIds
        self.nodes[id.index].node.take().unwrap()
    }
}

struct AvlSlot<T> {
    time_stamp: u64,
    node: Option<AvlNode<T>>,
}
<commit_msg>AvlTree now uses usize instead of AvlNodeId internally<commit_after>use redox::Vec;

pub struct AvlNode<T> {
    value: T,
    left: Option<usize>, // ID for left node
    right: Option<usize>, // ID for right node
}

impl<T: PartialOrd> AvlNode<T> {
    pub fn value(&self) -> &T { &self.value }
    pub fn left(&self, tree: &AvlTree<T>) -> Option<AvlNodeId> {
        self.left.map(|l| AvlNodeId { index: l, time_stamp: tree.nodes[l].time_stamp })
    }
    pub fn right(&self, tree: &AvlTree<T>) -> Option<AvlNodeId> {
        self.right.map(|r| AvlNodeId { index: r, time_stamp: tree.nodes[r].time_stamp })
    }
}

#[derive(Copy, Clone)]
pub struct AvlNodeId {
    index: usize,
    time_stamp: u64,
}

impl AvlNodeId {
    pub fn get<'a, T: PartialOrd>(&self, avl: &'a AvlTree<T>) -> &'a AvlNode<T> {
        let ref slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_ref().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get<'a, T: PartialOrd>(&self, avl: &'a AvlTree<T>) -> Option<&'a AvlNode<T>> {
        avl.nodes
           .get(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_ref()
               } else {
                   None
               }
           })
    }

    pub fn get_mut<'a, T: PartialOrd>(&self, avl: &'a mut AvlTree<T>) -> &'a mut AvlNode<T> {
        let ref mut slot = avl.nodes[self.index];
        if slot.time_stamp == self.time_stamp {
            slot.node.as_mut().unwrap()
        } else {
            panic!("AvlNodeId had invalid time_stamp");
        }
    }

    pub fn try_get_mut<'a, T: PartialOrd>(&self, avl: &'a mut AvlTree<T>) -> Option<&'a mut AvlNode<T>> {
        avl.nodes
           .get_mut(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_mut()
               } else {
                   None
               }
           })
    }
}

pub struct AvlTree<T: PartialOrd> {
    root: Option<usize>, // Index of the root node
    nodes: Vec<AvlSlot<T>>,
    free_list: Vec<usize>,
}

impl<T: PartialOrd> AvlTree<T> {
    pub fn new() -> Self {
        AvlTree {
            root: None,
            nodes: Vec::new(),
            free_list: Vec::new(),
        }
    }

    // Inserts a value into the tree, keeping it balanced. Lesser values will be stored on
    // the left, while greater values will be stored on the right. No duplicates are allowed.
    pub fn insert(&mut self, value: T) {
        let root = self.root;
        self.root = Some(self._insert(value, root));
    }

    pub fn in_order<F: Fn(&AvlNode<T>)>(&self, f: &F) {
        if let Some(root) = self.root {
            self._in_order(f, root);
        }
    }

    // Implementation of insert
    fn _insert(&mut self, value: T, node: Option<usize>) -> usize {
        let node =
            match node{
                Some(node) => {
                    // Node exists, check which way to branch.
                    if value == self.node(node).value {
                        return node;
                    } else if value < self.node(node).value {
                        let l = self.node(node).left;
                        self.node_mut(node).left = Some(self._insert(value, l));
                    } else if value > self.node(node).value {
                        let r = self.node(node).right;
                        self.node_mut(node).right = Some(self._insert(value, r));
                    }

                    node
                },
                None => {
                    // The node doesn't exist, create it here.
                    self.allocate_node(value)
                },
            };

        self.rebalance(node)
    }

    pub fn _in_order<F: Fn(&AvlNode<T>)>(&self, f: &F, node: usize) {
        if let Some(l) = self.node(node).left {
            self._in_order(f, l);
        }
        f(self.node(node));
        if let Some(r) = self.node(node).right {
            self._in_order(f, r);
        }
    }

    // Performs a left rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_left(&mut self, node: usize) -> usize {
        // Keep track of the original node positions
        // For a rotate left, the right child node must exist
        let r = self.node(node).right.unwrap();
        let rl = self.node(r).left;

        let ret = r;
        self.node_mut(node).right = rl;
        self.node_mut(ret).left = Some(node);

        ret
    }

    // Performs a right rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_right(&mut self, node: usize) -> usize {
        // Keep track of the original node positions
        // For a rotate right, the left child node must exist
        let l = self.node(node).left.unwrap();
        let lr = self.node(l).right;

        let ret = l;
        self.node_mut(node).left = lr;
        self.node_mut(ret).right = Some(node);

        ret
    }

    // performs a left-right double rotation on a tree/subtree.
    fn rotate_leftright(&mut self, node: usize) -> usize {
        let l = self.node(node).left.unwrap();
        let new_l = self.rotate_left(l); // Left node needs to exist
        self.node_mut(node).left = Some(new_l);
        self.rotate_right(node)
    }

    // performs a right-left double rotation on a tree/subtree.
    fn rotate_rightleft(&mut self, node: usize) -> usize {
        let r = self.node(node).right.unwrap();
        let new_r = self.rotate_right(r); // Right node needs to exist
        self.node_mut(node).right = Some(new_r);
        self.rotate_left(node)
    }

    // _rebalance rebalances the provided node
    fn rebalance(&mut self, node: usize) -> usize {
        let balance = self.height(self.node(node).left) - self.height(self.node(node).right);
        if balance == 2 { // left
            let lbalance = self.height(self.node(self.node(node).left.unwrap()).left) -
                           self.height(self.node(self.node(node).left.unwrap()).right);
            if lbalance == 0 || lbalance == 1 { // left left - need to rotate right
                return self.rotate_right(node);
            } else if lbalance == -1 { // left right
                return self.rotate_leftright(node); // function name is just a coincidence
            }
        } else if balance == -2 { // right
            let rbalance = self.height(self.node(self.node(node).right.unwrap()).left) -
                           self.height(self.node(self.node(node).right.unwrap()).right);
            if rbalance == 1 { // right left
                return self.rotate_rightleft(node); // function name is just a coincidence
            } else if rbalance == 0 || rbalance == -1 { // right right - need to rotate left
                return self.rotate_left(node);
            }
        }

        node
    }

    // height gets the height of a tree or subtree
    fn height(&self, node: Option<usize>) -> i64 {
        match node {
            Some(node) => {
                let left_height = self.height(self.node(node).left);
                let right_height = self.height(self.node(node).right);

                if left_height > right_height {
                    left_height+1
                } else {
                    right_height+1
                }
            },
            None => { -1 },
        }
    }

    fn allocate_node(&mut self, value: T) -> usize {
        match self.free_list.pop() {
            Some(index) => {
                self.nodes[index].time_stamp += 1;
                index
            },
            None => {
                // No free slots, create a new one
                let index = self.nodes.len();
                self.nodes.push(AvlSlot { time_stamp: 0,
                                          node: Some(AvlNode { value: value, left: None, right: None }) });
                index
            },
        }
    }

    fn free_node(&mut self, id: AvlNodeId) -> AvlNode<T> {
        self.free_list.push(id.index);

        // NOTE: We unwrap here, because we trust that `id` points to a valid node, because
        // only we can create and free AvlNodes and their AvlNodeIds
        self.nodes[id.index].node.take().unwrap()
    }

    fn node(&self, index: usize) -> &AvlNode<T> {
        self.nodes[index].node.as_ref().unwrap()
    }

    fn node_mut(&mut self, index: usize) -> &mut AvlNode<T> {
        self.nodes[index].node.as_mut().unwrap()
    }
}

struct AvlSlot<T> {
    time_stamp: u64,
    node: Option<AvlNode<T>>,
}
<|endoftext|>


<commit_before><commit_msg>tuples for rectangle area<commit_after>fn main() {
    let rectangle = (50, 30);

    println!("Area of Rectangle with length {}cm and bredth {}cm is {}cm^2", rectangle.0, rectangle.1, area(rectangle) );

}

fn area(dimensions: (u32, u32)) -> u32 {
    dimensions.0 * dimensions.1
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #81430 - lcnr:elaborate-const-eval, r=oli-obk<commit_after>// run-pass
// Test that we use the elaborated predicates from traits
// to satisfy const evaluatable predicates.
#![feature(const_generics, const_evaluatable_checked)]
#![allow(incomplete_features)]
use std::mem::size_of;

trait Foo: Sized
where
    [(); size_of::<Self>()]: Sized,
{
}

impl Foo for u64 {}
impl Foo for u32 {}

fn foo<T: Foo>() -> [u8; size_of::<T>()] {
    [0; size_of::<T>()]
}

fn main() {
    assert_eq!(foo::<u32>(), [0; 4]);
    assert_eq!(foo::<u64>(), [0; 8]);
}
<|endoftext|>


<commit_before>use common::context::*;
use common::elf::*;
use common::memory::*;
use common::scheduler::*;

use programs::common::*;

pub struct Executor;

impl Executor {
    pub fn new() -> Executor {
        Executor
    }
}

impl SessionItem for Executor {
    fn main(&mut self, url: URL){
        unsafe{
            let mut physical_address = 0;
            let virtual_address = LOAD_ADDR;
            let mut virtual_size = 0;

            let mut entry = 0;
            {
                let mut resource = url.open();
                drop(url);

                let mut vec: Vec<u8> = Vec::new();
                resource.read_to_end(&mut vec);
                drop(resource);

                let executable = ELF::from_data(vec.as_ptr() as usize);
                drop(vec);

                if executable.data > 0 {
                    virtual_size = alloc_size(executable.data) - 4096;
                    physical_address = alloc(virtual_size);
                    ptr::copy((executable.data + 4096) as *const u8, physical_address as *mut u8, virtual_size);
                    entry = executable.entry();
                }
                drop(executable);
            }

            if physical_address > 0 && virtual_address > 0 && virtual_size > 0 && entry >= virtual_address && entry < virtual_address + virtual_size {
                let reenable = start_no_ints();

                let contexts = &mut *(*contexts_ptr);

                match contexts.get(context_i) {
                    Option::Some(mut current) => {
                        current.memory.push(ContextMemory {
                            physical_address: physical_address,
                            virtual_address: virtual_address,
                            virtual_size: virtual_size
                        });
                        current.map();
                    },
                    Option::None => ()
                }

                end_no_ints(reenable);

                //TODO: Free this
                asm!(
                    "push 0
                    push edx
                    push 0
                    push ecx
                    push ebx
                    jmp eax"
                    :
                    : "{eax}"(entry), "{ebx}"(1), "{ecx}"("Test".to_string().to_c_str()), "{edx}"("test=test".to_string().to_c_str())
                    : "memory"
                    : "intel", "volatile"
                )
            }else if physical_address > 0{
                unalloc(physical_address);
            }
        }
    }
}
<commit_msg>Executor will pass argument<commit_after>use common::context::*;
use common::elf::*;
use common::memory::*;
use common::scheduler::*;

use programs::common::*;

pub struct Executor;

impl Executor {
    pub fn new() -> Executor {
        Executor
    }
}

impl SessionItem for Executor {
    fn main(&mut self, url: URL){
        unsafe{
            let mut physical_address = 0;
            let virtual_address = LOAD_ADDR;
            let mut virtual_size = 0;
            let url_c_str = url.string.to_c_str();

            let mut entry = 0;
            {
                let mut resource = url.open();
                drop(url);

                let mut vec: Vec<u8> = Vec::new();
                resource.read_to_end(&mut vec);
                drop(resource);

                let executable = ELF::from_data(vec.as_ptr() as usize);
                drop(vec);

                if executable.data > 0 {
                    virtual_size = alloc_size(executable.data) - 4096;
                    physical_address = alloc(virtual_size);
                    ptr::copy((executable.data + 4096) as *const u8, physical_address as *mut u8, virtual_size);
                    entry = executable.entry();
                }
                drop(executable);
            }

            if physical_address > 0 && virtual_address > 0 && virtual_size > 0 && entry >= virtual_address && entry < virtual_address + virtual_size {
                let reenable = start_no_ints();

                let contexts = &mut *(*contexts_ptr);

                match contexts.get(context_i) {
                    Option::Some(mut current) => {
                        current.memory.push(ContextMemory {
                            physical_address: physical_address,
                            virtual_address: virtual_address,
                            virtual_size: virtual_size
                        });
                        current.map();
                    },
                    Option::None => ()
                }

                end_no_ints(reenable);

                //TODO: Free this, show environment
                asm!(
                    "push 0
                    push 0
                    push ecx
                    push ebx
                    jmp eax"
                    :
                    : "{eax}"(entry), "{ebx}"(1), "{ecx}"(url_c_str)
                    : "memory"
                    : "intel", "volatile"
                )
            }else if physical_address > 0{
                unalloc(physical_address);
            }
        }
    }
}
<|endoftext|>


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


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


<commit_before><commit_msg>Updated render_task.rs<commit_after><|endoftext|>


<commit_before><commit_msg>This barely works<commit_after>use std::io::net::tcp::TcpStream;
use std::str::from_utf8;

struct IRC {
  stream: TcpStream,
  connected: bool
}

impl IRC {
  fn connect() -> IRC {
    let mut irc: IRC;
    let mut stream = TcpStream::connect("irc.mozilla.org",6667).unwrap();
    stream.write("NICK homura-bot\n".as_bytes());
    stream.write("USER homura-bot 0 * :Best\n".as_bytes());
    stream.flush();
    let connected = false;
    return IRC { stream: stream, connected: connected };
  }
  fn read_line(&mut self) -> String {
    let mut buf = Vec::new();
    loop {
      let c = self.stream.read_byte().unwrap();
      if c == 0x0A {
        break;
      }
      buf.push(c);
    }
    let s = from_utf8(buf.as_slice()).unwrap();
    return s.to_string();
  }
  fn get_message(&mut self) -> String {
    loop {
      let line = self.read_line();
      let s = line.as_slice();
      println!("{}",s);
      if s.contains("PING") {
        println!("sending PONG");
        let split: Vec<&str> = s.as_slice().split(':').collect();
        self.stream.write("PONG ".as_bytes());
        self.stream.write(split[1].as_bytes());
        self.stream.write("\n".as_bytes());
        self.stream.flush();
      } else {
        return line.clone();
      }
    }
  }
  fn write(&mut self, s: &str) {
    self.stream.write(s.as_bytes());
  }
  fn flush(&mut self) {
    self.stream.flush();
  }
  fn msg(&mut self, channel: &str, msg: &str) {
    self.write("PRIVMSG ");
    self.write(channel);
    self.write(" :");
    self.write(msg);
    self.write("\n");
    self.flush();
  }
}

fn main() {
  let mut irc = IRC::connect();
  loop {
    let s = irc.get_message();
    if s.as_slice().contains(":homura-chan MODE") {
      println!("Registered!");
      irc.write("JOIN #interns\n");
    }
    if s.as_slice().contains("ben-せんぱい") {
      println!("Triggered");
      irc.msg("#interns","かわいいです");
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Add run-pass/never_coercions.rs test<commit_after>// Copyright 2012-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.

fn main() {
    let v: Vec<u32> = Vec::new();
    match 0u32 {
        0 => &v,
        1 => return,
        _ => &v[..],
    };
}

<|endoftext|>


<commit_before><commit_msg>Remove use of Itertools<commit_after><|endoftext|>


<commit_before><commit_msg>rollup merge of #17093 : nathantypanski/17021<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.
//
// This code used to produce the following ICE:
//
//    error: internal compiler error: get_unique_type_id_of_type() -
//    unexpected type: closure,
//    ty_unboxed_closure(syntax::ast::DefId{krate: 0u32, node: 66u32},
//    ReScope(63u32))
//
// This is a regression test for issue #17021.

#![feature(unboxed_closures, overloaded_calls)]

use std::ptr;

pub fn replace_map<'a, T, F>(src: &mut T, prod: F)
where F: |: T| -> T {
    unsafe { *src = prod(ptr::read(src as *mut T as *const T)); }
}

pub fn main() {
    let mut a = 7u;
    let b = &mut a;
    replace_map(b, |: x: uint| x * 2);
    assert_eq!(*b, 14u);
}
<|endoftext|>


<commit_before>use std::io;

use futures::{Poll, Task, Future};

use WriteTask;

/// A future used to fully flush an I/O object.
///
/// Resolves to the underlying I/O object once the flush operation is complete.
///
/// Created by the `flush` function.
pub struct Flush {
    a: Option,
}

/// Creates a future which will entirely flush an I/O object and then yield the
/// object itself.
///
/// This function will consume the object provided if an error happens, and
/// otherwise it will repeatedly call `flush` until it sees `Ok(())`, scheduling
/// a retry if `WouldBlock` is seen along the way.
pub fn flush(a: A) -> Flush
    where A: WriteTask,
{
    Flush {
        a: Some(a),
    }
}

impl Future for Flush
    where A: WriteTask,
{
    type Item = A;
    type Error = io::Error;

    fn poll(&mut self, task: &mut Task) -> Poll {
        match self.a.as_mut().unwrap().flush(task) {
            Ok(()) => Poll::Ok(self.a.take().unwrap()),
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                Poll::NotReady
            }
            Err(e) => Poll::Err(e),
        }
    }

    fn schedule(&mut self, task: &mut Task) {
        if let Some(ref mut a) = self.a {
            a.schedule(task);
        }
    }
}

<commit_msg>Wait for write readiness on Flush as well<commit_after>use std::io;

use futures::{Poll, Task, Future};

use WriteTask;

/// A future used to fully flush an I/O object.
///
/// Resolves to the underlying I/O object once the flush operation is complete.
///
/// Created by the `flush` function.
pub struct Flush {
    a: Option,
    first: bool,
}

/// Creates a future which will entirely flush an I/O object and then yield the
/// object itself.
///
/// This function will consume the object provided if an error happens, and
/// otherwise it will repeatedly call `flush` until it sees `Ok(())`, scheduling
/// a retry if `WouldBlock` is seen along the way.
pub fn flush(a: A) -> Flush
    where A: WriteTask,
{
    Flush {
        a: Some(a),
        first: true,
    }
}

impl Future for Flush
    where A: WriteTask,
{
    type Item = A;
    type Error = io::Error;

    fn poll(&mut self, task: &mut Task) -> Poll {
        if self.first {
            self.first = false;
        } else {
            match try_poll!(self.a.as_mut().unwrap().poll(task)) {
                Ok(Some(ref r)) if r.is_write() => {}
                Ok(Some(_)) => return Poll::NotReady,
                Ok(None) => panic!("need flush but can't write"),
                Err(e) => return Poll::Err(e)
            }
        }
        match self.a.as_mut().unwrap().flush(task) {
            Ok(()) => Poll::Ok(self.a.take().unwrap()),
            Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
                Poll::NotReady
            }
            Err(e) => Poll::Err(e),
        }
    }

    fn schedule(&mut self, task: &mut Task) {
        if let Some(ref mut a) = self.a {
            a.schedule(task);
        }
    }
}

<|endoftext|>


<commit_before>#![cfg_attr(feature = "dev", feature(plugin))]
#![cfg_attr(feature = "dev", plugin(clippy))]
#![feature(test)]

extern crate test;
extern crate time;
extern crate fruently;
extern crate rust_fluent;

#[cfg(test)]
mod tests {
    use test;
    use test::Bencher;
    use time;
    use fruently::fluent::Fluent;
    use std::collections::HashMap;

    #[bench]
    fn benchmark_rust_fluent_tcp(b: &mut Bencher) {
        use rust_fluent::tcp;
        let mut obj: HashMap<String, String> = HashMap::new();
        obj.insert("json".to_string(), "value".to_string());

        b.iter(|| {
            let fluentd = tcp::Fluentd::new("0.0.0.0:24224", "test");
            let _ = fluentd.write(&obj);
        });
    }

    #[bench]
    fn benchmark_json_forwardable(b: &mut Bencher) {
        use fruently::forwardable::JsonForwardable;

        let mut obj: HashMap<String, String> = HashMap::new();
        obj.insert("json".to_string(), "fruently".to_string());
        b.iter(|| {
            let fruently = Fluent::new("0.0.0.0:24224", "test");
            let _ = fruently.post(&obj);
        });
    }

    #[bench]
    fn benchmark_msgpack_forwardable(b: &mut Bencher) {
        use fruently::forwardable::MsgpackForwardable;

        let mut obj: HashMap<String, String> = HashMap::new();
        obj.insert("msgp".to_string(), "fruently".to_string());
        b.iter(|| {
            let fruently = Fluent::new("0.0.0.0:24224", "test");
            let _ = fruently.post(&obj);
        });
    }

    #[bench]
    fn benchmark_forwardable(b: &mut Bencher) {
        use fruently::forwardable::Forwardable;

        let mut obj = HashMap::new();
        let mut hmap = HashMap::new();
        let time = time::now().to_timespec().sec;
        b.iter(|| {
            let n = test::black_box(1000);
            let thmap = (0..n).fold(&mut obj, |mut acc, _| {
                {
                    acc.insert("fwd", "fruently".to_string());
                }
                acc
            });
            hmap = thmap.clone();
        });
        let entry = (time, hmap);
        let fruently = Fluent::new("0.0.0.0:24224", "test");
        let _ = fruently.post(vec![(entry)]);
    }
}
<commit_msg>bench: Use EventTime in forward mode<commit_after>#![cfg_attr(feature = "dev", feature(plugin))]
#![cfg_attr(feature = "dev", plugin(clippy))]
#![feature(test)]

extern crate test;
extern crate time;
extern crate fruently;
extern crate rust_fluent;

#[cfg(test)]
mod tests {
    use test;
    use test::Bencher;
    use time;
    use fruently::fluent::Fluent;
    use std::collections::HashMap;

    #[bench]
    fn benchmark_rust_fluent_tcp(b: &mut Bencher) {
        use rust_fluent::tcp;
        let mut obj: HashMap<String, String> = HashMap::new();
        obj.insert("json".to_string(), "value".to_string());

        b.iter(|| {
            let fluentd = tcp::Fluentd::new("0.0.0.0:24224", "test");
            let _ = fluentd.write(&obj);
        });
    }

    #[bench]
    fn benchmark_json_forwardable(b: &mut Bencher) {
        use fruently::forwardable::JsonForwardable;

        let mut obj: HashMap<String, String> = HashMap::new();
        obj.insert("json".to_string(), "fruently".to_string());
        b.iter(|| {
            let fruently = Fluent::new("0.0.0.0:24224", "test");
            let _ = fruently.post(&obj);
        });
    }

    #[bench]
    fn benchmark_msgpack_forwardable(b: &mut Bencher) {
        use fruently::forwardable::MsgpackForwardable;

        let mut obj: HashMap<String, String> = HashMap::new();
        obj.insert("msgp".to_string(), "fruently".to_string());
        b.iter(|| {
            let fruently = Fluent::new("0.0.0.0:24224", "test");
            let _ = fruently.post(&obj);
        });
    }

    #[bench]
    fn benchmark_forwardable(b: &mut Bencher) {
        use fruently::forwardable::Forwardable;
        use fruently::event_time::EventTime;

        let mut obj = HashMap::new();
        let mut hmap = HashMap::new();
        let time = time::now();
        b.iter(|| {
            let n = test::black_box(1000);
            let thmap = (0..n).fold(&mut obj, |mut acc, _| {
                {
                    acc.insert("fwd", "fruently".to_string());
                }
                acc
            });
            hmap = thmap.clone();
        });
        let entry = (EventTime::new(time), hmap);
        let fruently = Fluent::new("0.0.0.0:24224", "test");
        let _ = fruently.post(vec![(entry)]);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add (incomplete) rules for instruction selectoin<commit_after>rules!{
    // %(foo) refers to a register
    // 0(foo) refers to an immediate value
    // @(foo) refers to a static variable
    // FIXME: `load` -> handle statics

    // --- Arithmetics & binary operations  -------------------------------------

    // Addition
    [%(dst) = add %(lhs), %(rhs); ..] => {
        mov $dst, $lhs;
        add $dst, $rhs;
    },
    [%(dst) = add %(lhs), 0(rhs); ..] => {
        mov $dst, $lhs;
        add $dst, $rhs;
    },
    [%(dst) = add 0(lhs), %(rhs)]; ..] => {
        mov $dst, $lhs;
        add $dst, $rhs;
    },

    // Subtraction
    [%(dst) = sub %(lhs), %(rhs); ..] => {
        mov $dst, $lhs;
        sub $dst, $rhs;
    },
    [%(dst) = sub %(lhs), 0(rhs); ..] => {
        mov $dst, $lhs;
        sub $dst, $rhs;
    },
    [%(dst) = sub 0(lhs), %(rhs)]; ..] => {
        mov $dst, $lhs;
        sub $dst, $rhs;
    },

    // Multiplication
    [%(dst) = mul %(lhs), %(rhs); ..] => {
        mov $dst, $lhs;
        imul $dst, $rhs;
    },
    [%(dst) = mul %(lhs), 0(rhs); ..] => {
        // Use the three-operand form
        imu $dst, $lhs, $rhs;
    },
    [%(dst) = mul 0(lhs), %(rhs)]; ..] => {
        // Use the three-operand form
        imu $dst, $rhs, $lhs;
    },

    // Integer division
    [%(dst) = sub %(lhs), %(rhs); ..] => {
        xor rdx, rdx;
        mov rax, $lhs;
        idiv $rhs;
        mov $dst, rax;
    },
    [%(dst) = sub %(lhs), 0(rhs); ..] => {
        mov %(tmp), $rhs;  // Create a temporary virtual register
        xor rdx, rdx;
        mov rax, $lhs;
        idiv $tmp;
        mov $dst, rax;
    },
    [%(dst) = sub 0(lhs), %(rhs)]; ..] => {
        xor rdx, rdx;
        mov rax, $lhs;
        idiv rhs;
        mov $dst, rax;
    },

    // Note: pow will be implemented as an intrinsic

    // Modulo
    // Like div but use the remainder of the division
    [%(dst) = sub %(lhs), %(rhs); ..] => {
        xor rdx, rdx;
        mov rax, $lhs;
        idiv $rhs;
        mov $dst, rdx;
    },
    [%(dst) = sub %(lhs), 0(rhs); ..] => {
        mov %(tmp), $rhs;  // Create a temporary virtual register
        xor rdx, rdx;
        mov rax, $lhs;
        idiv $tmp;
        mov $dst, rdx;
    },
    [%(dst) = sub 0(lhs), %(rhs)]; ..] => {
        xor rdx, rdx;
        mov rax, $lhs;
        idiv rhs;
        mov $dst, rdx;
    },

    // Shift left
    [%(dst) = shl %(lhs), %(rhs); ..] => {
        mov $dst, $lhs;
        mov rcx, $rhs;
        sal $dst, cl;
    },
    [%(dst) = shl %(lhs), 0(rhs); ..] => {
        mov $dst, $lhs;
        sal $dst, $rhs;
    },
    [%(dst) = shl 0(lhs), %(rhs)]; ..] => {
        mov $dst, $lhs;
        mov rcx, $rhs;
        sal $dst, cl;
    },

    // Shift right
    [%(dst) = shr %(lhs), %(rhs); ..] => {
        mov $dst, $lhs;
        mov rcx, $rhs;
        sar $dst, cl;
    },
    [%(dst) = shr %(lhs), 0(rhs); ..] => {
        mov $dst, $lhs;
        sar $dst, $rhs;
    },
    [%(dst) = shr 0(lhs), %(rhs)]; ..] => {
        mov $dst, $lhs;
        mov rcx, $rhs;
        sar $dst, cl;
    },

    // And
    [%(dst) = and %(lhs), %(rhs); ..] => {
        mov $dst, $lhs;
        and $dst, $rhs;
    },
    [%(dst) = and %(lhs), 0(rhs); ..] => {
        mov $dst, $lhs;
        and $dst, $rhs;
    },
    [%(dst) = and 0(lhs), %(rhs)]; ..] => {
        mov $dst, $lhs;
        and $dst, $rhs;
    },

    // Or
    [%(dst) = or %(lhs), %(rhs); ..] => {
        mov $dst, $lhs;
        or $dst, $rhs;
    },
    [%(dst) = or %(lhs), 0(rhs); ..] => {
        mov $dst, $lhs;
        or $dst, $rhs;
    },
    [%(dst) = or 0(lhs), %(rhs)]; ..] => {
        mov $dst, $lhs;
        or $dst, $rhs;
    },

    // Xor
    [%(dst) = xor %(lhs), %(rhs); ..] => {
        mov $dst, $lhs;
        xor $dst, $rhs;
    },
    [%(dst) = xor %(lhs), 0(rhs); ..] => {
        mov $dst, $lhs;
        xor $dst, $rhs;
    },
    [%(dst) = xor 0(lhs), %(rhs)]; ..] => {
        mov $dst, $lhs;
        xor $dst, $rhs;
    },

    // Unary negation
    [%(dst) = not %(item); ..] => {
        mov $dst $item;
        not $dst;
    },

    // --- Comparisons ----------------------------------------------------------

    // Lower than: With branch
    [%(dst) = cmp lt %(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jl $conseq;
        jmp $altern;
    },
    [%(dst) = cmp lt %(lhs), 0(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jl $conseq;
        jmp $altern;
    },
    [%(dst) = cmp lt 0(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        jge $altern;
        jmp $conseq;
    },

    // Lower than: Without branch
    [%(dst) = cmp lt %(lhs), %(rhs); ..] => {
        cmp $lhs, $rhs;
        setl cl;
        and cl, 1;      // Truncate to first bit
        movzx $dst, cl; // Move with zero extension
    },
    [%(dst) = cmp lt %(lhs), 0(rhs); ..] => {
        cmp $lhs, $rhs;
        setl cl;
        and cl, 1;
        movzx $dst, cl;
    },
    [%(dst) = cmp lt 0(lhs), %(rhs); ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        setge cl;
        and cl, 1;
        movzx $dst, cl;
    },

    // Lower than or equal: With branch
    [%(dst) = cmp le %(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jle $conseq;
        jmp $altern;
    },
    [%(dst) = cmp le %(lhs), 0(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jle $conseq;
        jmp $altern;
    },
    [%(dst) = cmp le 0(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        jg $altern;
        jmp $conseq;
    },

    // Lower than or equal: Without branch
    [%(dst) = cmp le %(lhs), %(rhs); ..] => {
        cmp $lhs, $rhs;
        setle cl;
        and cl, 1;      // Truncate to first bit
        movzx $dst, cl; // Move with zero extension
    },
    [%(dst) = cmp le %(lhs), 0(rhs); ..] => {
        cmp $lhs, $rhs;
        setle cl;
        and cl, 1;
        movzx $dst, cl;
    },
    [%(dst) = cmp le 0(lhs), %(rhs); ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        setg cl;
        and cl, 1;
        movzx $dst, cl;
    },

    // Greater than or equal: With branch
    [%(dst) = cmp ge %(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jge $conseq;
        jmp $altern;
    },
    [%(dst) = cmp ge %(lhs), 0(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jge $conseq;
        jmp $altern;
    },
    [%(dst) = cmp ge 0(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        jl $altern;
        jmp $conseq;
    },

    // Greater than or equal: Without branch
    [%(dst) = cmp ge %(lhs), %(rhs); ..] => {
        cmp $lhs, $rhs;
        setge cl;
        and cl, 1;      // Truncate to first bit
        movzx $dst, cl; // Move with zero extension
    },
    [%(dst) = cmp ge %(lhs), 0(rhs); ..] => {
        cmp $lhs, $rhs;
        setge cl;
        and cl, 1;
        movzx $dst, cl;
    },
    [%(dst) = cmp ge 0(lhs), %(rhs); ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        setl cl;
        and cl, 1;
        movzx $dst, cl;
    },

    // Greater than: With branch
    [%(dst) = cmp gt %(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jg $conseq;
        jmp $altern;
    },
    [%(dst) = cmp gt %(lhs), 0(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jg $conseq;
        jmp $altern;
    },
    [%(dst) = cmp gt 0(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        jle $altern;
        jmp $conseq;
    },

    // Greater than: Without branch
    [%(dst) = cmp gt %(lhs), %(rhs); ..] => {
        cmp $lhs, $rhs;
        setg cl;
        and cl, 1;      // Truncate to first bit
        movzx $dst, cl; // Move with zero extension
    },
    [%(dst) = cmp gt %(lhs), 0(rhs); ..] => {
        cmp $lhs, $rhs;
        setg cl;
        and cl, 1;
        movzx $dst, cl;
    },
    [%(dst) = cmp gt 0(lhs), %(rhs); ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        setle cl;
        and cl, 1;
        movzx $dst, cl;
    },

    // Equality: With branch
    [%(dst) = cmp eq %(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        je $conseq;
        jmp $altern;
    },
    [%(dst) = cmp eq %(lhs), 0(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        je $conseq;
        jmp $altern;
    },
    [%(dst) = cmp eq 0(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        jne $altern;
        jmp $conseq;
    },

    // Equality: Without branch
    [%(dst) = cmp eq %(lhs), %(rhs); ..] => {
        cmp $lhs, $rhs;
        sete cl;
        and cl, 1;      // Truncate to first bit
        movzx $dst, cl; // Move with zero extension
    },
    [%(dst) = cmp eq %(lhs), 0(rhs); ..] => {
        cmp $lhs, $rhs;
        sete cl;
        and cl, 1;
        movzx $dst, cl;
    },
    [%(dst) = cmp eq 0(lhs), %(rhs); ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        setne cl;
        and cl, 1;
        movzx $dst, cl;
    },

    // Inequality: With branch
    [%(dst) = cmp eq %(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jne $conseq;
        jmp $altern;
    },
    [%(dst) = cmp eq %(lhs), 0(rhs); br %(cond), conseq, altern; ..] => {
        cmp $lhs, $rhs;
        jne $conseq;
        jmp $altern;
    },
    [%(dst) = cmp eq 0(lhs), %(rhs); br %(cond), conseq, altern; ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        je $altern;
        jmp $conseq;
    },

    // Inequality: Without branch
    [%(dst) = cmp eq %(lhs), %(rhs); ..] => {
        cmp $lhs, $rhs;
        setne cl;
        and cl, 1;      // Truncate to first bit
        movzx $dst, cl; // Move with zero extension
    },
    [%(dst) = cmp eq %(lhs), 0(rhs); ..] => {
        cmp $lhs, $rhs;
        setne cl;
        and cl, 1;
        movzx $dst, cl;
    },
    [%(dst) = cmp eq 0(lhs), %(rhs); ..] => {
        // Inverted cmp
        cmp $rhs, $lhs;
        sete cl;
        and cl, 1;
        movzx $dst, cl;
    },

    // TODO: Special case: a == 0 => jz

    // --- Alloca/load/store ----------------------------------------------------

    [%(dst) = alloca; ..] => {
        // TODO: Collect allocas and replace usage with indirect arguments
        mov $dst, rsp;
        sub rsi, 4;
    },
    [%(dst) = load %(src); ..] => {
        mov $dst, qword ptr [src];
    },
    [store %(val), %(dst); ..] => {
        mov qword ptr [dst], $val;
    },
    [store 0(val), %(dst); ..] => {
        mov qword ptr [dst], $val;
    },

    // --- Call -----------------------------------------------------------------

    [%dst = call func [args ...]] -> {
        //
    }

    // TODO: How are phi nodes handeled?
    // TODO: return/branch/jump
    // FIXME: How is neg handled?
}

/*
Result:

pub fn trans_instr(instr: &mut [ir::Instruction],
               last: &ir::ControlFlowInstruction,
               code: &mut machine::MachineCode)
               -> usize
{
    match instr {
        ...
    }
}<|endoftext|>


<commit_before>//! Server Responses
//!
//! These are responses sent by a `hyper::Server` to clients, after
//! receiving a request.
use header;
use http;
use status::StatusCode;
use version;

/// The outgoing half for a Tcp connection, created by a `Server` and given to a `Handler`.
///
/// The default `StatusCode` for a `Response` is `200 OK`.
#[derive(Debug)]
pub struct Response<'a> {
    head: &'a mut http::MessageHead<StatusCode>,
}

impl<'a> Response<'a> {
    /// The headers of this response.
    #[inline]
    pub fn headers(&self) -> &header::Headers { &self.head.headers }

    /// The status of this response.
    #[inline]
    pub fn status(&self) -> &StatusCode {
        &self.head.subject
    }

    /// The HTTP version of this response.
    #[inline]
    pub fn version(&self) -> &version::HttpVersion { &self.head.version }

    /// Get a mutable reference to the Headers.
    #[inline]
    pub fn headers_mut(&mut self) -> &mut header::Headers { &mut self.head.headers }

    /// Get a mutable reference to the status.
    #[inline]
    pub fn set_status(&mut self, status: StatusCode) {
        self.head.subject = status;
    }
}

/// Creates a new Response that can be used to write to a network stream.
pub fn new(head: &mut http::MessageHead<StatusCode>) -> Response {
    Response {
        head: head
    }
}
<commit_msg>docs(server): fix Response::set_status() documentation<commit_after>//! Server Responses
//!
//! These are responses sent by a `hyper::Server` to clients, after
//! receiving a request.
use header;
use http;
use status::StatusCode;
use version;

/// The outgoing half for a Tcp connection, created by a `Server` and given to a `Handler`.
///
/// The default `StatusCode` for a `Response` is `200 OK`.
#[derive(Debug)]
pub struct Response<'a> {
    head: &'a mut http::MessageHead<StatusCode>,
}

impl<'a> Response<'a> {
    /// The headers of this response.
    #[inline]
    pub fn headers(&self) -> &header::Headers { &self.head.headers }

    /// The status of this response.
    #[inline]
    pub fn status(&self) -> &StatusCode {
        &self.head.subject
    }

    /// The HTTP version of this response.
    #[inline]
    pub fn version(&self) -> &version::HttpVersion { &self.head.version }

    /// Get a mutable reference to the Headers.
    #[inline]
    pub fn headers_mut(&mut self) -> &mut header::Headers { &mut self.head.headers }

    /// Set the status of this response.
    #[inline]
    pub fn set_status(&mut self, status: StatusCode) {
        self.head.subject = status;
    }
}

/// Creates a new Response that can be used to write to a network stream.
pub fn new(head: &mut http::MessageHead<StatusCode>) -> Response {
    Response {
        head: head
    }
}
<|endoftext|>


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


<commit_before><commit_msg>added some more hashing algorithms<commit_after><|endoftext|>


<commit_before><commit_msg>Initial Work On Ping Format<commit_after><|endoftext|>


<commit_before><commit_msg>Clarify maths a little<commit_after><|endoftext|>


<commit_before><commit_msg>Revert support for router_id in ZMsgExtended. Better achieved by using `ZMsg::push<type>()`.<commit_after><|endoftext|>


<commit_before><commit_msg>Test if IoError is properly returned as cause()<commit_after>extern crate yaml;

use std::error::Error;
use std::io::{IoError, IoResult};
use std::io::IoErrorKind;

struct MockReader {
    _data: ()
}

impl MockReader {
    pub fn new() -> MockReader {
        MockReader { _data: () }
    }
}

impl Reader for MockReader {
    fn read(&mut self, _buf: &mut [u8]) -> IoResult<uint> {
        Err(IoError {
            kind: IoErrorKind::OtherIoError,
            desc: "",
            detail: Some("mock reader".to_string())
        })
    }
}

#[test]
fn error_cause_test() {
    let mut mock_reader = MockReader::new();
    match yaml::parse_io_utf8(&mut mock_reader) {
        Ok(_) => panic!("Should return an error"),
        Err(e) => assert_eq!(e.cause().and_then(|ioe| ioe.detail()), Some("mock reader".to_string()))
    }
}
<|endoftext|>


<commit_before><commit_msg>languages/rust/rust-book/3-chapter/13-code.rs<commit_after><|endoftext|>


<commit_before><commit_msg>(test) created an example for helper gt<commit_after>extern crate handlebars;
#[macro_use]
extern crate serde_json;

use handlebars::{Handlebars, RenderError, Helper, RenderContext};

#[test]
fn test_subexpression() {
    let mut hbs = Handlebars::new();

    hbs.register_helper(
        "gt",
        Box::new(|h: &Helper,
         _: &Handlebars,
         rc: &mut RenderContext|
         -> Result<(), RenderError> {
            let p1 = try!(h.param(0).and_then(|v| v.value().as_i64()).ok_or(
                RenderError::new("Param 0 with i64 type is required for gt helper."),
            ));
            let p2 = try!(h.param(1).and_then(|v| v.value().as_i64()).ok_or(
                RenderError::new("Param 1 with i64 type is required for gt helper."),
            ));

            if p1 > p2 {
                rc.writer.write("true".as_bytes())?;
            }

            Ok(())
        }),
    );

    assert_eq!(
        hbs.template_render(
            "{{#if (gt a b)}}Success{{else}}Failed{{/if}}",
            &json!({"a": 1, "b": 0}),
        ).unwrap(),
        "Success"
    );
}
<|endoftext|>


<commit_before>use std::io::{self, Read};

use hyper::client::IntoUrl;
use hyper::header::{Headers, ContentType, Location, Referer, UserAgent};
use hyper::method::Method;
use hyper::status::StatusCode;
use hyper::version::HttpVersion;
use hyper::{Url};

use serde::Serialize;
use serde_json;
use serde_urlencoded;

use ::body::{self, Body};

static DEFAULT_USER_AGENT: &'static str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

/// A `Client` to make Requests with.
///
/// The Client has various configuration values to tweak, but the defaults
/// are set to what is usually the most commonly desired value.
///
/// The `Client` holds a connection pool internally, so it is advised that
/// you create one and reuse it.
pub struct Client {
    inner: ::hyper::Client,
}

impl Client {
    /// Constructs a new `Client`.
    pub fn new() -> ::Result<Client> {
        let mut client = try!(new_hyper_client());
        client.set_redirect_policy(::hyper::client::RedirectPolicy::FollowNone);
        Ok(Client {
            inner: client
        })
    }

    /// Convenience method to make a `GET` request to a URL.
    pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Get, url)
    }

    /// Convenience method to make a `POST` request to a URL.
    pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Post, url)
    }

    /// Convenience method to make a `HEAD` request to a URL.
    pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Head, url)
    }

    /// Start building a `Request` with the `Method` and `Url`.
    ///
    /// Returns a `RequestBuilder`, which will allow setting headers and
    /// request body before sending.
    pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
        let url = url.into_url();
        RequestBuilder {
            client: self,
            method: method,
            url: url,
            _version: HttpVersion::Http11,
            headers: Headers::new(),

            body: None,
        }
    }
}

#[cfg(not(feature = "tls"))]
fn new_hyper_client() -> ::Result<::hyper::Client> {
    Ok(::hyper::Client::new())
}

#[cfg(feature = "tls")]
fn new_hyper_client() -> ::Result<::hyper::Client> {
    use tls::TlsClient;
    Ok(::hyper::Client::with_connector(
        ::hyper::client::Pool::with_connector(
            Default::default(),
            ::hyper::net::HttpsConnector::new(try!(TlsClient::new()))
        )
    ))
}

/// A builder to construct the properties of a `Request`.
pub struct RequestBuilder<'a> {
    client: &'a Client,

    method: Method,
    url: Result<Url, ::UrlError>,
    _version: HttpVersion,
    headers: Headers,

    body: Option<::Result<Body>>,
}

impl<'a> RequestBuilder<'a> {
    /// Add a `Header` to this Request.
    ///
    /// ```no_run
    /// use reqwest::header::UserAgent;
    /// let client = reqwest::Client::new().expect("client failed to construct");
    ///
    /// let res = client.get("https://www.rust-lang.org")
    ///     .header(UserAgent("foo".to_string()))
    ///     .send();
    /// ```
    pub fn header<H: ::header::Header + ::header::HeaderFormat>(mut self, header: H) -> RequestBuilder<'a> {
        self.headers.set(header);
        self
    }
    /// Add a set of Headers to the existing ones on this Request.
    ///
    /// The headers will be merged in to any already set.
    pub fn headers(mut self, headers: ::header::Headers) -> RequestBuilder<'a> {
        self.headers.extend(headers.iter());
        self
    }

    /// Set the request body.
    pub fn body<T: Into<Body>>(mut self, body: T) -> RequestBuilder<'a> {
        self.body = Some(Ok(body.into()));
        self
    }

    /// Send a form body.
    ///
    /// Sets the body to the url encoded serialization of the passed value,
    /// and also sets the `Content-Type: application/www-form-url-encoded`
    /// header.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// let mut params = HashMap::new();
    /// params.insert("lang", "rust");
    ///
    /// let client = reqwest::Client::new().unwrap();
    /// let res = client.post("http://httpbin.org")
    ///     .form(&params)
    ///     .send();
    /// ```
    pub fn form<T: Serialize>(mut self, form: &T) -> RequestBuilder<'a> {
        let body = serde_urlencoded::to_string(form).map_err(::Error::from);
        self.headers.set(ContentType::form_url_encoded());
        self.body = Some(body.map(|b| b.into()));
        self
    }

    /// Send a JSON body.
    ///
    /// Sets the body to the JSON serialization of the passed value, and
    /// also sets the `Content-Type: application/json` header.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// let mut map = HashMap::new();
    /// map.insert("lang", "rust");
    ///
    /// let client = reqwest::Client::new().unwrap();
    /// let res = client.post("http://httpbin.org")
    ///     .json(&map)
    ///     .send();
    /// ```
    pub fn json<T: Serialize>(mut self, json: &T) -> RequestBuilder<'a> {
        let body = serde_json::to_vec(json).expect("serde to_vec cannot fail");
        self.headers.set(ContentType::json());
        self.body = Some(Ok(body.into()));
        self
    }

    /// Constructs the Request and sends it the target URL, returning a Response.
    pub fn send(mut self) -> ::Result<Response> {
        if !self.headers.has::<UserAgent>() {
            self.headers.set(UserAgent(DEFAULT_USER_AGENT.to_owned()));
        }

        let client = self.client;
        let mut method = self.method;
        let mut url = try!(self.url);
        let mut headers = self.headers;
        let mut body = match self.body {
            Some(b) => Some(try!(b)),
            None => None,
        };

        let mut redirect_count = 0;

        loop {
            let res = {
                debug!("request {:?} \"{}\"", method, url);
                let mut req = client.inner.request(method.clone(), url.clone())
                    .headers(headers.clone());

                if let Some(ref mut b) = body {
                    let body = body::as_hyper_body(b);
                    req = req.body(body);
                }

                try!(req.send())
            };
            body.take();

            match res.status {
                StatusCode::MovedPermanently |
                StatusCode::Found => {

                    //TODO: turn this into self.redirect_policy.check()
                    if redirect_count > 10 {
                        return Err(::Error::TooManyRedirects);
                    }
                    redirect_count += 1;

                    method = match method {
                        Method::Post | Method::Put => Method::Get,
                        m => m
                    };

                    headers.set(Referer(url.to_string()));

                    let loc = {
                        let loc = res.headers.get::<Location>().map(|loc| url.join(loc));
                        if let Some(loc) = loc {
                            loc
                        } else {
                            return Ok(Response {
                                inner: res
                            });
                        }
                    };

                    url = match loc {
                        Ok(u) => u,
                        Err(e) => {
                            debug!("Location header had invalid URI: {:?}", e);
                            return Ok(Response {
                                inner: res
                            })
                        }
                    };

                    debug!("redirecting to '{}'", url);

                    //TODO: removeSensitiveHeaders(&mut headers, &url);

                },
                _ => {
                    return Ok(Response {
                        inner: res
                    });
                }
            }
        }
    }
}

/// A Response to a submitted `Request`.
pub struct Response {
    inner: ::hyper::client::Response,
}

impl Response {
    /// Get the `StatusCode`.
    pub fn status(&self) -> &StatusCode {
        &self.inner.status
    }

    /// Get the `Headers`.
    pub fn headers(&self) -> &Headers {
        &self.inner.headers
    }

    /// Get the `HttpVersion`.
    pub fn version(&self) -> &HttpVersion {
        &self.inner.version
    }
}

/// Read the body of the Response.
impl Read for Response {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.read(buf)
    }
}
<commit_msg>add 303 status code to redirect policy<commit_after>use std::io::{self, Read};

use hyper::client::IntoUrl;
use hyper::header::{Headers, ContentType, Location, Referer, UserAgent};
use hyper::method::Method;
use hyper::status::StatusCode;
use hyper::version::HttpVersion;
use hyper::{Url};

use serde::Serialize;
use serde_json;
use serde_urlencoded;

use ::body::{self, Body};

static DEFAULT_USER_AGENT: &'static str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

/// A `Client` to make Requests with.
///
/// The Client has various configuration values to tweak, but the defaults
/// are set to what is usually the most commonly desired value.
///
/// The `Client` holds a connection pool internally, so it is advised that
/// you create one and reuse it.
pub struct Client {
    inner: ::hyper::Client,
}

impl Client {
    /// Constructs a new `Client`.
    pub fn new() -> ::Result<Client> {
        let mut client = try!(new_hyper_client());
        client.set_redirect_policy(::hyper::client::RedirectPolicy::FollowNone);
        Ok(Client {
            inner: client
        })
    }

    /// Convenience method to make a `GET` request to a URL.
    pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Get, url)
    }

    /// Convenience method to make a `POST` request to a URL.
    pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Post, url)
    }

    /// Convenience method to make a `HEAD` request to a URL.
    pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Head, url)
    }

    /// Start building a `Request` with the `Method` and `Url`.
    ///
    /// Returns a `RequestBuilder`, which will allow setting headers and
    /// request body before sending.
    pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
        let url = url.into_url();
        RequestBuilder {
            client: self,
            method: method,
            url: url,
            _version: HttpVersion::Http11,
            headers: Headers::new(),

            body: None,
        }
    }
}

#[cfg(not(feature = "tls"))]
fn new_hyper_client() -> ::Result<::hyper::Client> {
    Ok(::hyper::Client::new())
}

#[cfg(feature = "tls")]
fn new_hyper_client() -> ::Result<::hyper::Client> {
    use tls::TlsClient;
    Ok(::hyper::Client::with_connector(
        ::hyper::client::Pool::with_connector(
            Default::default(),
            ::hyper::net::HttpsConnector::new(try!(TlsClient::new()))
        )
    ))
}

/// A builder to construct the properties of a `Request`.
pub struct RequestBuilder<'a> {
    client: &'a Client,

    method: Method,
    url: Result<Url, ::UrlError>,
    _version: HttpVersion,
    headers: Headers,

    body: Option<::Result<Body>>,
}

impl<'a> RequestBuilder<'a> {
    /// Add a `Header` to this Request.
    ///
    /// ```no_run
    /// use reqwest::header::UserAgent;
    /// let client = reqwest::Client::new().expect("client failed to construct");
    ///
    /// let res = client.get("https://www.rust-lang.org")
    ///     .header(UserAgent("foo".to_string()))
    ///     .send();
    /// ```
    pub fn header<H: ::header::Header + ::header::HeaderFormat>(mut self, header: H) -> RequestBuilder<'a> {
        self.headers.set(header);
        self
    }
    /// Add a set of Headers to the existing ones on this Request.
    ///
    /// The headers will be merged in to any already set.
    pub fn headers(mut self, headers: ::header::Headers) -> RequestBuilder<'a> {
        self.headers.extend(headers.iter());
        self
    }

    /// Set the request body.
    pub fn body<T: Into<Body>>(mut self, body: T) -> RequestBuilder<'a> {
        self.body = Some(Ok(body.into()));
        self
    }

    /// Send a form body.
    ///
    /// Sets the body to the url encoded serialization of the passed value,
    /// and also sets the `Content-Type: application/www-form-url-encoded`
    /// header.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// let mut params = HashMap::new();
    /// params.insert("lang", "rust");
    ///
    /// let client = reqwest::Client::new().unwrap();
    /// let res = client.post("http://httpbin.org")
    ///     .form(&params)
    ///     .send();
    /// ```
    pub fn form<T: Serialize>(mut self, form: &T) -> RequestBuilder<'a> {
        let body = serde_urlencoded::to_string(form).map_err(::Error::from);
        self.headers.set(ContentType::form_url_encoded());
        self.body = Some(body.map(|b| b.into()));
        self
    }

    /// Send a JSON body.
    ///
    /// Sets the body to the JSON serialization of the passed value, and
    /// also sets the `Content-Type: application/json` header.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// let mut map = HashMap::new();
    /// map.insert("lang", "rust");
    ///
    /// let client = reqwest::Client::new().unwrap();
    /// let res = client.post("http://httpbin.org")
    ///     .json(&map)
    ///     .send();
    /// ```
    pub fn json<T: Serialize>(mut self, json: &T) -> RequestBuilder<'a> {
        let body = serde_json::to_vec(json).expect("serde to_vec cannot fail");
        self.headers.set(ContentType::json());
        self.body = Some(Ok(body.into()));
        self
    }

    /// Constructs the Request and sends it the target URL, returning a Response.
    pub fn send(mut self) -> ::Result<Response> {
        if !self.headers.has::<UserAgent>() {
            self.headers.set(UserAgent(DEFAULT_USER_AGENT.to_owned()));
        }

        let client = self.client;
        let mut method = self.method;
        let mut url = try!(self.url);
        let mut headers = self.headers;
        let mut body = match self.body {
            Some(b) => Some(try!(b)),
            None => None,
        };

        let mut redirect_count = 0;

        loop {
            let res = {
                debug!("request {:?} \"{}\"", method, url);
                let mut req = client.inner.request(method.clone(), url.clone())
                    .headers(headers.clone());

                if let Some(ref mut b) = body {
                    let body = body::as_hyper_body(b);
                    req = req.body(body);
                }

                try!(req.send())
            };
            body.take();

            match res.status {
                StatusCode::MovedPermanently |
                StatusCode::Found |
                StatusCode::SeeOther => {

                    //TODO: turn this into self.redirect_policy.check()
                    if redirect_count > 10 {
                        return Err(::Error::TooManyRedirects);
                    }
                    redirect_count += 1;

                    method = match method {
                        Method::Post | Method::Put => Method::Get,
                        m => m
                    };

                    headers.set(Referer(url.to_string()));

                    let loc = {
                        let loc = res.headers.get::<Location>().map(|loc| url.join(loc));
                        if let Some(loc) = loc {
                            loc
                        } else {
                            return Ok(Response {
                                inner: res
                            });
                        }
                    };

                    url = match loc {
                        Ok(u) => u,
                        Err(e) => {
                            debug!("Location header had invalid URI: {:?}", e);
                            return Ok(Response {
                                inner: res
                            })
                        }
                    };

                    debug!("redirecting to '{}'", url);

                    //TODO: removeSensitiveHeaders(&mut headers, &url);

                },
                _ => {
                    return Ok(Response {
                        inner: res
                    });
                }
            }
        }
    }
}

/// A Response to a submitted `Request`.
pub struct Response {
    inner: ::hyper::client::Response,
}

impl Response {
    /// Get the `StatusCode`.
    pub fn status(&self) -> &StatusCode {
        &self.inner.status
    }

    /// Get the `Headers`.
    pub fn headers(&self) -> &Headers {
        &self.inner.headers
    }

    /// Get the `HttpVersion`.
    pub fn version(&self) -> &HttpVersion {
        &self.inner.version
    }
}

/// Read the body of the Response.
impl Read for Response {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.read(buf)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add debug print to chunk<commit_after><|endoftext|>


<commit_before><commit_msg>Add example how to make the main window transparent<commit_after>//! # Transparent main window example
//!
//! This example demonstrates how to create a main window with a transparent background.

extern crate gtk;
extern crate gdk;
extern crate cairo;

use gtk::prelude::*;
use gtk::{Window, WindowType, Fixed, Button};
use gdk::ScreenExt; //import get_rgba_visual

fn main() {
    if gtk::init().is_err() {
        println!("Failed to initialize GTK.");
        return;
    }

    let window = Window::new(WindowType::Toplevel);
    set_visual(&window, &None);

    window.connect_delete_event(quit);
    window.connect_screen_changed(set_visual);
    window.connect_draw(draw);

    window.set_title("Alpha Demo");
    window.set_default_size(500, 500);
    window.set_app_paintable(true); //crucial for transparency

    let fixed = Fixed::new();
    window.add(&fixed);
    let button = Button::new_with_label("Dummy");
    button.set_size_request(100, 30);
    fixed.add(&button);

    window.show_all();
    gtk::main();
}

fn set_visual(window: &Window, _screen: &Option<gdk::Screen>) {
    if let Some(screen) = window.get_screen() {
        if let Some(visual) = screen.get_rgba_visual() {
            window.set_visual(&visual); //crucial for transparency
        }
    }
}

fn draw(_window: &Window, ctx: &cairo::Context) -> Inhibit {
    //crucial for transparency
    ctx.set_source_rgba(1.0, 0.0, 0.0, 0.4);
    ctx.set_operator(cairo::enums::Operator::Screen);
    ctx.paint();
    Inhibit(false)
}

fn quit(_window: &Window, _event: &gdk::Event) -> Inhibit {
    gtk::main_quit();
    Inhibit(false)
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #65348<commit_after>// check-pass

struct Generic<T>(T);

impl<T> Generic<T> {
    const ARRAY: [T; 0] = [];
    const NEWTYPE_ARRAY: Generic<[T; 0]> = Generic([]);
    const ARRAY_FIELD: Generic<(i32, [T; 0])> = Generic((0, []));
}

pub const fn array<T>() ->  &'static T {
    &Generic::<T>::ARRAY[0]
}

pub const fn newtype_array<T>() ->  &'static T {
    &Generic::<T>::NEWTYPE_ARRAY.0[0]
}

pub const fn array_field<T>() ->  &'static T {
    &(Generic::<T>::ARRAY_FIELD.0).1[0]
}

fn main() {}
<|endoftext|>