<commit_before>use std::env;
use std::fs;
use std::io::prelude::*;
use std::path::Path;

use rustc_serialize::{Decodable, Decoder};

use git2::Config as GitConfig;

use term::color::BLACK;

use util::{GitRepo, HgRepo, CargoResult, human, ChainError, internal};
use util::{Config, paths};

use toml;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VersionControl { Git, Hg, NoVcs }

pub struct NewOptions<'a> {
    pub version_control: Option<VersionControl>,
    pub bin: bool,
    pub path: &'a str,
    pub name: Option<&'a str>,
}

impl Decodable for VersionControl {
    fn decode<D: Decoder>(d: &mut D) -> Result<VersionControl, D::Error> {
        Ok(match &try!(d.read_str())[..] {
            "git" => VersionControl::Git,
            "hg" => VersionControl::Hg,
            "none" => VersionControl::NoVcs,
            n => {
                let err = format!("could not decode '{}' as version control", n);
                return Err(d.error(&err));
            }
        })
    }
}

struct CargoNewConfig {
    name: Option<String>,
    email: Option<String>,
    version_control: Option<VersionControl>,
}

pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> {
    let path = config.cwd().join(opts.path);
    if fs::metadata(&path).is_ok() {
        return Err(human(format!("Destination `{}` already exists",
                                 path.display())))
    }
    let name = match opts.name {
        Some(name) => name,
        None => {
            let dir_name = try!(path.file_name().and_then(|s| s.to_str()).chain_error(|| {
                human(&format!("cannot create a project with a non-unicode name: {:?}",
                               path.file_name().unwrap()))
            }));
            if opts.bin {
                dir_name
            } else {
                let new_name = strip_rust_affixes(dir_name);
                if new_name != dir_name {
                    let message = format!(
                        "note: package will be named `{}`; use --name to override",
                        new_name);
                    try!(config.shell().say(&message, BLACK));
                }
                new_name
            }
        }
    };
    for c in name.chars() {
        if c.is_alphanumeric() { continue }
        if c == '_' || c == '-' { continue }
        return Err(human(&format!("Invalid character `{}` in crate name: `{}`",
                                  c, name)));
    }
    mk(config, &path, name, &opts).chain_error(|| {
        human(format!("Failed to create project `{}` at `{}`",
                      name, path.display()))
    })
}

fn strip_rust_affixes(name: &str) -> &str {
    for &prefix in &["rust-", "rust_", "rs-", "rs_"] {
        if name.starts_with(prefix) {
            return &name[prefix.len()..];
        }
    }
    for &suffix in &["-rust", "_rust", "-rs", "_rs"] {
        if name.ends_with(suffix) {
            return &name[..name.len()-suffix.len()];
        }
    }
    name
}

fn existing_vcs_repo(path: &Path) -> bool {
    GitRepo::discover(path).is_ok() || HgRepo::discover(path).is_ok()
}

fn mk(config: &Config, path: &Path, name: &str,
      opts: &NewOptions) -> CargoResult<()> {
    let cfg = try!(global_config(config));
    let mut ignore = "target\n".to_string();
    let in_existing_vcs_repo = existing_vcs_repo(path.parent().unwrap());
    if !opts.bin {
        ignore.push_str("Cargo.lock\n");
    }

    let vcs = match (opts.version_control, cfg.version_control, in_existing_vcs_repo) {
        (None, None, false) => VersionControl::Git,
        (None, Some(option), false) => option,
        (Some(option), _, _) => option,
        (_, _, true) => VersionControl::NoVcs,
    };

    match vcs {
        VersionControl::Git => {
            try!(GitRepo::init(path));
            try!(paths::write(&path.join(".gitignore"), ignore.as_bytes()));
        },
        VersionControl::Hg => {
            try!(HgRepo::init(path));
            try!(paths::write(&path.join(".hgignore"), ignore.as_bytes()));
        },
        VersionControl::NoVcs => {
            try!(fs::create_dir(path));
        },
    };

    let (author_name, email) = try!(discover_author());
    // Hoo boy, sure glad we've got exhaustivenes checking behind us.
    let author = match (cfg.name, cfg.email, author_name, email) {
        (Some(name), Some(email), _, _) |
        (Some(name), None, _, Some(email)) |
        (None, Some(email), name, _) |
        (None, None, name, Some(email)) => format!("{} <{}>", name, email),
        (Some(name), None, _, None) |
        (None, None, name, None) => name,
    };

    try!(paths::write(&path.join("Cargo.toml"), format!(
r#"[package]
name = "{}"
version = "0.1.0"
authors = [{}]
"#, name, toml::Value::String(author)).as_bytes()));

    try!(fs::create_dir(&path.join("src")));

    if opts.bin {
        try!(paths::write(&path.join("src/main.rs"), b"\
fn main() {
    println!(\"Hello, world!\");
}
"));
    } else {
        try!(paths::write(&path.join("src/lib.rs"), b"\
#[test]
fn it_works() {
}
"));
    }

    Ok(())
}

fn discover_author() -> CargoResult<(String, Option<String>)> {
    let git_config = GitConfig::open_default().ok();
    let git_config = git_config.as_ref();
    let name = git_config.and_then(|g| g.get_string("user.name").ok())
                         .map(|s| s.to_string())
                         .or_else(|| env::var("USER").ok())      // unix
                         .or_else(|| env::var("USERNAME").ok()); // windows
    let name = match name {
        Some(name) => name,
        None => {
            let username_var = if cfg!(windows) {"USERNAME"} else {"USER"};
            return Err(human(format!("could not determine the current \
                                      user, please set ${}", username_var)))
        }
    };
    let email = git_config.and_then(|g| g.get_string("user.email").ok())
                          .or_else(|| env::var("EMAIL").ok());

    let name = name.trim().to_string();
    let email = email.map(|s| s.trim().to_string());

    Ok((name, email))
}

fn global_config(config: &Config) -> CargoResult<CargoNewConfig> {
    let name = try!(config.get_string("cargo-new.name")).map(|s| s.0);
    let email = try!(config.get_string("cargo-new.email")).map(|s| s.0);
    let vcs = try!(config.get_string("cargo-new.vcs"));

    let vcs = match vcs.as_ref().map(|p| (&p.0[..], &p.1)) {
        Some(("git", _)) => Some(VersionControl::Git),
        Some(("hg", _)) => Some(VersionControl::Hg),
        Some(("none", _)) => Some(VersionControl::NoVcs),
        Some((s, p)) => {
            return Err(internal(format!("invalid configuration for key \
                                         `cargo-new.vcs`, unknown vcs `{}` \
                                         (found in {:?})", s, p)))
        }
        None => None
    };
    Ok(CargoNewConfig {
        name: name,
        email: email,
        version_control: vcs,
    })
}

#[cfg(test)]
mod tests {
    use super::strip_rust_affixes;

    #[test]
    fn affixes_stripped() {
        assert_eq!(strip_rust_affixes("rust-foo"), "foo");
        assert_eq!(strip_rust_affixes("foo-rs"), "foo");
        assert_eq!(strip_rust_affixes("rs_foo"), "foo");
        // Only one affix is stripped
        assert_eq!(strip_rust_affixes("rs-foo-rs"), "foo-rs");
        assert_eq!(strip_rust_affixes("foo-rs-rs"), "foo-rs");
        // It shouldn't touch the middle
        assert_eq!(strip_rust_affixes("some-rust-crate"), "some-rust-crate");
    }
}
<commit_msg>Auto merge of #2126 - johshoff:default_dependency_header, r=alexcrichton<commit_after>use std::env;
use std::fs;
use std::io::prelude::*;
use std::path::Path;

use rustc_serialize::{Decodable, Decoder};

use git2::Config as GitConfig;

use term::color::BLACK;

use util::{GitRepo, HgRepo, CargoResult, human, ChainError, internal};
use util::{Config, paths};

use toml;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum VersionControl { Git, Hg, NoVcs }

pub struct NewOptions<'a> {
    pub version_control: Option<VersionControl>,
    pub bin: bool,
    pub path: &'a str,
    pub name: Option<&'a str>,
}

impl Decodable for VersionControl {
    fn decode<D: Decoder>(d: &mut D) -> Result<VersionControl, D::Error> {
        Ok(match &try!(d.read_str())[..] {
            "git" => VersionControl::Git,
            "hg" => VersionControl::Hg,
            "none" => VersionControl::NoVcs,
            n => {
                let err = format!("could not decode '{}' as version control", n);
                return Err(d.error(&err));
            }
        })
    }
}

struct CargoNewConfig {
    name: Option<String>,
    email: Option<String>,
    version_control: Option<VersionControl>,
}

pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> {
    let path = config.cwd().join(opts.path);
    if fs::metadata(&path).is_ok() {
        return Err(human(format!("Destination `{}` already exists",
                                 path.display())))
    }
    let name = match opts.name {
        Some(name) => name,
        None => {
            let dir_name = try!(path.file_name().and_then(|s| s.to_str()).chain_error(|| {
                human(&format!("cannot create a project with a non-unicode name: {:?}",
                               path.file_name().unwrap()))
            }));
            if opts.bin {
                dir_name
            } else {
                let new_name = strip_rust_affixes(dir_name);
                if new_name != dir_name {
                    let message = format!(
                        "note: package will be named `{}`; use --name to override",
                        new_name);
                    try!(config.shell().say(&message, BLACK));
                }
                new_name
            }
        }
    };
    for c in name.chars() {
        if c.is_alphanumeric() { continue }
        if c == '_' || c == '-' { continue }
        return Err(human(&format!("Invalid character `{}` in crate name: `{}`",
                                  c, name)));
    }
    mk(config, &path, name, &opts).chain_error(|| {
        human(format!("Failed to create project `{}` at `{}`",
                      name, path.display()))
    })
}

fn strip_rust_affixes(name: &str) -> &str {
    for &prefix in &["rust-", "rust_", "rs-", "rs_"] {
        if name.starts_with(prefix) {
            return &name[prefix.len()..];
        }
    }
    for &suffix in &["-rust", "_rust", "-rs", "_rs"] {
        if name.ends_with(suffix) {
            return &name[..name.len()-suffix.len()];
        }
    }
    name
}

fn existing_vcs_repo(path: &Path) -> bool {
    GitRepo::discover(path).is_ok() || HgRepo::discover(path).is_ok()
}

fn mk(config: &Config, path: &Path, name: &str,
      opts: &NewOptions) -> CargoResult<()> {
    let cfg = try!(global_config(config));
    let mut ignore = "target\n".to_string();
    let in_existing_vcs_repo = existing_vcs_repo(path.parent().unwrap());
    if !opts.bin {
        ignore.push_str("Cargo.lock\n");
    }

    let vcs = match (opts.version_control, cfg.version_control, in_existing_vcs_repo) {
        (None, None, false) => VersionControl::Git,
        (None, Some(option), false) => option,
        (Some(option), _, _) => option,
        (_, _, true) => VersionControl::NoVcs,
    };

    match vcs {
        VersionControl::Git => {
            try!(GitRepo::init(path));
            try!(paths::write(&path.join(".gitignore"), ignore.as_bytes()));
        },
        VersionControl::Hg => {
            try!(HgRepo::init(path));
            try!(paths::write(&path.join(".hgignore"), ignore.as_bytes()));
        },
        VersionControl::NoVcs => {
            try!(fs::create_dir(path));
        },
    };

    let (author_name, email) = try!(discover_author());
    // Hoo boy, sure glad we've got exhaustivenes checking behind us.
    let author = match (cfg.name, cfg.email, author_name, email) {
        (Some(name), Some(email), _, _) |
        (Some(name), None, _, Some(email)) |
        (None, Some(email), name, _) |
        (None, None, name, Some(email)) => format!("{} <{}>", name, email),
        (Some(name), None, _, None) |
        (None, None, name, None) => name,
    };

    try!(paths::write(&path.join("Cargo.toml"), format!(
r#"[package]
name = "{}"
version = "0.1.0"
authors = [{}]

[dependencies]
"#, name, toml::Value::String(author)).as_bytes()));

    try!(fs::create_dir(&path.join("src")));

    if opts.bin {
        try!(paths::write(&path.join("src/main.rs"), b"\
fn main() {
    println!(\"Hello, world!\");
}
"));
    } else {
        try!(paths::write(&path.join("src/lib.rs"), b"\
#[test]
fn it_works() {
}
"));
    }

    Ok(())
}

fn discover_author() -> CargoResult<(String, Option<String>)> {
    let git_config = GitConfig::open_default().ok();
    let git_config = git_config.as_ref();
    let name = git_config.and_then(|g| g.get_string("user.name").ok())
                         .map(|s| s.to_string())
                         .or_else(|| env::var("USER").ok())      // unix
                         .or_else(|| env::var("USERNAME").ok()); // windows
    let name = match name {
        Some(name) => name,
        None => {
            let username_var = if cfg!(windows) {"USERNAME"} else {"USER"};
            return Err(human(format!("could not determine the current \
                                      user, please set ${}", username_var)))
        }
    };
    let email = git_config.and_then(|g| g.get_string("user.email").ok())
                          .or_else(|| env::var("EMAIL").ok());

    let name = name.trim().to_string();
    let email = email.map(|s| s.trim().to_string());

    Ok((name, email))
}

fn global_config(config: &Config) -> CargoResult<CargoNewConfig> {
    let name = try!(config.get_string("cargo-new.name")).map(|s| s.0);
    let email = try!(config.get_string("cargo-new.email")).map(|s| s.0);
    let vcs = try!(config.get_string("cargo-new.vcs"));

    let vcs = match vcs.as_ref().map(|p| (&p.0[..], &p.1)) {
        Some(("git", _)) => Some(VersionControl::Git),
        Some(("hg", _)) => Some(VersionControl::Hg),
        Some(("none", _)) => Some(VersionControl::NoVcs),
        Some((s, p)) => {
            return Err(internal(format!("invalid configuration for key \
                                         `cargo-new.vcs`, unknown vcs `{}` \
                                         (found in {:?})", s, p)))
        }
        None => None
    };
    Ok(CargoNewConfig {
        name: name,
        email: email,
        version_control: vcs,
    })
}

#[cfg(test)]
mod tests {
    use super::strip_rust_affixes;

    #[test]
    fn affixes_stripped() {
        assert_eq!(strip_rust_affixes("rust-foo"), "foo");
        assert_eq!(strip_rust_affixes("foo-rs"), "foo");
        assert_eq!(strip_rust_affixes("rs_foo"), "foo");
        // Only one affix is stripped
        assert_eq!(strip_rust_affixes("rs-foo-rs"), "foo-rs");
        assert_eq!(strip_rust_affixes("foo-rs-rs"), "foo-rs");
        // It shouldn't touch the middle
        assert_eq!(strip_rust_affixes("some-rust-crate"), "some-rust-crate");
    }
}
<|endoftext|>


<commit_before><commit_msg>Codeforces 762B<commit_after>macro_rules! read_line {
    ($v:ident) => {
        let mut temp = String::new();
        std::io::stdin().read_line(&mut temp).unwrap();
        let $v = temp;
    };
    (var, $t:ty, $($v:ident), *) => {
        read_line!(input_line);
        let mut iter = parse_token!($t, input_line);
        $(
            let $v = iter.next().unwrap();
        )*
    };
    (vec, $t:ty, $v:ident) => {
        read_line!(input_line);
        let iter = parse_token!($t, input_line);
        let $v: Vec<$t> = iter.collect();
    };
    ($($v:ident; $t:ty), *) => {
        read_line!(input_line);
        let mut iter = input_line.split_whitespace();
        $(
            let $v: $t = iter.next().unwrap().parse().unwrap();
        )*
    };
}

macro_rules! parse_token {
    ($t:ty, $e:expr) => {
        $e.split_whitespace().map(|x| x.parse::<$t>().unwrap());
    };
}

enum MousePort {
    USB,
    PS2
}

fn main() {
    read_line!(usb_only;usize, ps2_only;usize, both_ports;usize);
    let mut usb_only = usb_only;
    let mut ps2_only = ps2_only;
    let mut both_ports = both_ports;
    read_line!(mice_cnt;usize);
    let mut mice = Vec::with_capacity(mice_cnt);
    for _ in 0..mice_cnt {
        read_line!(price;u32, ty;String);
        match ty.as_ref() {
            "USB" => mice.push((price, MousePort::USB)),
            "PS/2" => mice.push((price, MousePort::PS2)),
            _ => unreachable!()
        }
    }

    mice.sort_by_key(|k| k.0);

    let need_to_purchase = usb_only + ps2_only + both_ports;
    let mut total_price: u64 = 0;
    let mut purchased = 0;

    for (price, ty) in mice {
        if purchased == need_to_purchase {
            break;
        }
        match ty {
            MousePort::USB => {
                if usb_only > 0 {
                    usb_only -= 1
                } else if both_ports > 0 {
                    both_ports -= 1
                } else {
                    continue
                }
            },
            MousePort::PS2 => {
                if ps2_only > 0 {
                    ps2_only -= 1
                } else if both_ports > 0 {
                    both_ports -= 1
                } else {
                    continue
                }
            }
        }
        total_price += price as u64;
        purchased += 1;
    }

    println!("{} {}", purchased, total_price);
}<|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.

//! Unix-specific extensions to general I/O primitives

#![stable(feature = "rust1", since = "1.0.0")]

use fs;
use net;
use os::raw;
use sys;
use sys_common::{self, AsInner, FromInner, IntoInner};

/// Raw file descriptors.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawFd = raw::c_int;

/// A trait to extract the raw unix file descriptor from an underlying
/// object.
///
/// This is only available on unix platforms and must be imported in order
/// to call the method. Windows platforms have a corresponding `AsRawHandle`
/// and `AsRawSocket` set of traits.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawFd {
    /// Extracts the raw file descriptor.
    ///
    /// This method does **not** pass ownership of the raw file descriptor
    /// to the caller. The descriptor is only guaranteed to be valid while
    /// the original object has not yet been destroyed.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_raw_fd(&self) -> RawFd;
}

/// A trait to express the ability to construct an object from a raw file
/// descriptor.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawFd {
    /// Constructs a new instances of `Self` from the given raw file
    /// descriptor.
    ///
    /// This function **consumes ownership** of the specified file
    /// descriptor. The returned object will take responsibility for closing
    /// it when the object goes out of scope.
    ///
    /// This function is also unsafe as the primitives currently returned
    /// have the contract that they are the sole owner of the file
    /// descriptor they are wrapping. Usage of this function could
    /// accidentally allow violating this contract which can cause memory
    /// unsafety in code that relies on it being true.
    #[stable(feature = "from_raw_os", since = "1.1.0")]
    unsafe fn from_raw_fd(fd: RawFd) -> Self;
}

/// A trait to express the ability to consume an object and acquire ownership of
/// its raw file descriptor.
#[stable(feature = "into_raw_os", since = "1.4.0")]
pub trait IntoRawFd {
    /// Consumes this object, returning the raw underlying file descriptor.
    ///
    /// This function **transfers ownership** of the underlying file descriptor
    /// to the caller. Callers are then the unique owners of the file descriptor
    /// and must close the descriptor once it's no longer needed.
    #[stable(feature = "into_raw_os", since = "1.4.0")]
    fn into_raw_fd(self) -> RawFd;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for fs::File {
    fn as_raw_fd(&self) -> RawFd {
        self.as_inner().fd().raw()
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for fs::File {
    unsafe fn from_raw_fd(fd: RawFd) -> fs::File {
        fs::File::from_inner(sys::fs::File::from_inner(fd))
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for fs::File {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_fd().into_raw()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::TcpStream {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::TcpListener {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::UdpSocket {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}

#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::TcpStream {
    unsafe fn from_raw_fd(fd: RawFd) -> net::TcpStream {
        let socket = sys::net::Socket::from_inner(fd);
        net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(socket))
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::TcpListener {
    unsafe fn from_raw_fd(fd: RawFd) -> net::TcpListener {
        let socket = sys::net::Socket::from_inner(fd);
        net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(socket))
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::UdpSocket {
    unsafe fn from_raw_fd(fd: RawFd) -> net::UdpSocket {
        let socket = sys::net::Socket::from_inner(fd);
        net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(socket))
    }
}

#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::TcpStream {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::TcpListener {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::UdpSocket {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
<commit_msg>Fix small typo<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.

//! Unix-specific extensions to general I/O primitives

#![stable(feature = "rust1", since = "1.0.0")]

use fs;
use net;
use os::raw;
use sys;
use sys_common::{self, AsInner, FromInner, IntoInner};

/// Raw file descriptors.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawFd = raw::c_int;

/// A trait to extract the raw unix file descriptor from an underlying
/// object.
///
/// This is only available on unix platforms and must be imported in order
/// to call the method. Windows platforms have a corresponding `AsRawHandle`
/// and `AsRawSocket` set of traits.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawFd {
    /// Extracts the raw file descriptor.
    ///
    /// This method does **not** pass ownership of the raw file descriptor
    /// to the caller. The descriptor is only guaranteed to be valid while
    /// the original object has not yet been destroyed.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_raw_fd(&self) -> RawFd;
}

/// A trait to express the ability to construct an object from a raw file
/// descriptor.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawFd {
    /// Constructs a new instance of `Self` from the given raw file
    /// descriptor.
    ///
    /// This function **consumes ownership** of the specified file
    /// descriptor. The returned object will take responsibility for closing
    /// it when the object goes out of scope.
    ///
    /// This function is also unsafe as the primitives currently returned
    /// have the contract that they are the sole owner of the file
    /// descriptor they are wrapping. Usage of this function could
    /// accidentally allow violating this contract which can cause memory
    /// unsafety in code that relies on it being true.
    #[stable(feature = "from_raw_os", since = "1.1.0")]
    unsafe fn from_raw_fd(fd: RawFd) -> Self;
}

/// A trait to express the ability to consume an object and acquire ownership of
/// its raw file descriptor.
#[stable(feature = "into_raw_os", since = "1.4.0")]
pub trait IntoRawFd {
    /// Consumes this object, returning the raw underlying file descriptor.
    ///
    /// This function **transfers ownership** of the underlying file descriptor
    /// to the caller. Callers are then the unique owners of the file descriptor
    /// and must close the descriptor once it's no longer needed.
    #[stable(feature = "into_raw_os", since = "1.4.0")]
    fn into_raw_fd(self) -> RawFd;
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for fs::File {
    fn as_raw_fd(&self) -> RawFd {
        self.as_inner().fd().raw()
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for fs::File {
    unsafe fn from_raw_fd(fd: RawFd) -> fs::File {
        fs::File::from_inner(sys::fs::File::from_inner(fd))
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for fs::File {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_fd().into_raw()
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::TcpStream {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::TcpListener {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawFd for net::UdpSocket {
    fn as_raw_fd(&self) -> RawFd { *self.as_inner().socket().as_inner() }
}

#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::TcpStream {
    unsafe fn from_raw_fd(fd: RawFd) -> net::TcpStream {
        let socket = sys::net::Socket::from_inner(fd);
        net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(socket))
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::TcpListener {
    unsafe fn from_raw_fd(fd: RawFd) -> net::TcpListener {
        let socket = sys::net::Socket::from_inner(fd);
        net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(socket))
    }
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawFd for net::UdpSocket {
    unsafe fn from_raw_fd(fd: RawFd) -> net::UdpSocket {
        let socket = sys::net::Socket::from_inner(fd);
        net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(socket))
    }
}

#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::TcpStream {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::TcpListener {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
#[stable(feature = "into_raw_os", since = "1.4.0")]
impl IntoRawFd for net::UdpSocket {
    fn into_raw_fd(self) -> RawFd {
        self.into_inner().into_socket().into_inner()
    }
}
<|endoftext|>


<commit_before><commit_msg>Removed some extraneous code/comments<commit_after><|endoftext|>


<commit_before><commit_msg>Added SendJson response extension<commit_after><|endoftext|>


<commit_before>extern crate piston;
extern crate image;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;

use std::cell::RefCell;
use opengl_graphics::{ GlGraphics, OpenGL, Texture };
use sdl2_window::Sdl2Window;
use image::GenericImage;
use piston::input::{ Button, MouseButton };

fn main() {
    let opengl = OpenGL::_3_2;
    let (width, height) = (300, 300);
    let window = Sdl2Window::new(
        opengl,
        piston::window::WindowSettings {
            title: "piston-example-paint".to_string(),
            size: [width, height],
            fullscreen: false,
            exit_on_esc: true,
            samples: 0,
        }
    );

    let mut image = image::ImageBuffer::new(width, height);
    let mut draw = false;
    let mut texture = Texture::from_image(&image);
    let ref mut gl = GlGraphics::new(opengl);
    let window = RefCell::new(window);
    for e in piston::events(&window) {
        use piston::event::*;

        if let Some(args) = e.render_args() {
            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                graphics::clear([1.0; 4], gl);
                graphics::image(&texture, c.transform, gl);
            });
        };
        if let Some(button) = e.press_args() {
            if button == Button::Mouse(MouseButton::Left) {
                draw = true
            }
        };
        if let Some(button) = e.release_args() {
            if button == Button::Mouse(MouseButton::Left) {
                draw = false
            }
        };
        if draw {
            if let Some([x, y]) = e.mouse_cursor_args() {
                let (x, y) = (x as u32, y as u32);
                if x < width && y < height {
                    image.put_pixel(x, y, image::Rgba([0, 0, 0, 255]));
                    texture.update(&image);
                }
            };
        }
    }
}

<commit_msg>Upgraded paint example<commit_after>extern crate piston;
extern crate image;
extern crate graphics;
extern crate sdl2_window;
extern crate opengl_graphics;

use std::rc::Rc;
use std::cell::RefCell;
use opengl_graphics::{ GlGraphics, OpenGL, Texture };
use sdl2_window::Sdl2Window;
use image::GenericImage;
use piston::input::{ Button, MouseButton };

fn main() {
    let opengl = OpenGL::_3_2;
    let (width, height) = (300, 300);
    let window = Sdl2Window::new(
        opengl,
        piston::window::WindowSettings {
            title: "piston-example-paint".to_string(),
            size: [width, height],
            fullscreen: false,
            exit_on_esc: true,
            samples: 0,
        }
    );

    let mut image = image::ImageBuffer::new(width, height);
    let mut draw = false;
    let mut texture = Texture::from_image(&image);
    let ref mut gl = GlGraphics::new(opengl);
    let window = Rc::new(RefCell::new(window));
    for e in piston::events(window) {
        use piston::event::*;

        if let Some(args) = e.render_args() {
            gl.draw([0, 0, args.width as i32, args.height as i32], |c, gl| {
                graphics::clear([1.0; 4], gl);
                graphics::image(&texture, c.transform, gl);
            });
        };
        if let Some(button) = e.press_args() {
            if button == Button::Mouse(MouseButton::Left) {
                draw = true
            }
        };
        if let Some(button) = e.release_args() {
            if button == Button::Mouse(MouseButton::Left) {
                draw = false
            }
        };
        if draw {
            if let Some(pos) = e.mouse_cursor_args() {
                let (x, y) = (pos[0] as u32, pos[1] as u32);
                if x < width && y < height {
                    image.put_pixel(x, y, image::Rgba([0, 0, 0, 255]));
                    texture.update(&image);
                }
            };
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Regression test for issue #54477.<commit_after>// rust-lang/rust#54477: runtime bug in the VecDeque library that was
// exposed by this test case, derived from test suite of crates.io
// `collection` crate.

use std::collections::VecDeque;

fn main() {
    let mut vecdeque_13 = VecDeque::from(vec![ ]);
    let mut vecdeque_29 = VecDeque::from(vec![ 0 ]);
    vecdeque_29.insert(0,  30 );
    vecdeque_29.insert(1,  31 );
    vecdeque_29.insert(2,  32 );
    vecdeque_29.insert(3,  33 );
    vecdeque_29.insert(4,  34 );
    vecdeque_29.insert(5,  35 );
    // println!("vecdeque_13: {:?}", vecdeque_13);
    // println!("vecdeque_29: {:?}", vecdeque_29);

    // println!("Invoking: `vecdeque_13.append(&mut vecdeque_29)`");
    vecdeque_13.append(&mut vecdeque_29);

    // println!("vecdeque_13: {:?}", vecdeque_13);

    assert_eq!(vecdeque_13, VecDeque::from(vec![30, 31, 32, 33, 34, 35, 0]));
}
<|endoftext|>


<commit_before><commit_msg>bidirectional dijkstra example<commit_after>extern crate rand;
extern crate timely;
extern crate differential_dataflow;

use rand::{Rng, SeedableRng, StdRng};

use timely::dataflow::*;
use timely::dataflow::operators::probe::Handle;

use differential_dataflow::input::Input;
use differential_dataflow::Collection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
use differential_dataflow::operators::iterate::Variable;

type Node = u32;
type Edge = (Node, Node);

fn main() {

    let nodes: u32 = std::env::args().nth(1).unwrap().parse().unwrap();
    let edges: u32 = std::env::args().nth(2).unwrap().parse().unwrap();
    let batch: u32 = std::env::args().nth(3).unwrap().parse().unwrap();
    let rounds: u32 = std::env::args().nth(4).unwrap().parse().unwrap();
    let inspect: bool = std::env::args().nth(5).unwrap() == "inspect";

    // define a new computational scope, in which to run BFS
    timely::execute_from_args(std::env::args().skip(6), move |worker| {

        let timer = ::std::time::Instant::now();

        // define BFS dataflow; return handles to roots and edges inputs
        let mut probe = Handle::new();
        let (mut roots, mut graph) = worker.dataflow(|scope| {

            let (root_input, roots) = scope.new_collection();
            let (edge_input, graph) = scope.new_collection();

            let mut result = bidijkstra(&graph, &roots);

            if !inspect {
                result = result.filter(|_| false);
            }

            result.map(|(_,l)| l)
                  .consolidate()
                  .inspect(|x| println!("\t{:?}", x))
                  .probe_with(&mut probe);

            (root_input, edge_input)
        });

        let seed: &[_] = &[1, 2, 3, 4];
        let mut rng1: StdRng = SeedableRng::from_seed(seed);    // rng for edge additions
        let mut rng2: StdRng = SeedableRng::from_seed(seed);    // rng for edge deletions

        roots.insert((0, 1));
        roots.close();

        println!("performing BFS on {} nodes, {} edges:", nodes, edges);

        if worker.index() == 0 {
            for _ in 0 .. edges {
                graph.insert((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes)));
            }
        }

        println!("loaded; elapsed: {:?}", timer.elapsed());

        graph.advance_to(1);
        graph.flush();
        worker.step_while(|| probe.less_than(graph.time()));

        println!("stable");

        for round in 0 .. rounds {
            for element in 0 .. batch {
                if worker.index() == 0 {
                    graph.insert((rng1.gen_range(0, nodes), rng1.gen_range(0, nodes)));
                    graph.remove((rng2.gen_range(0, nodes), rng2.gen_range(0, nodes)));
                }
                graph.advance_to(2 + round * batch + element);
            }
            graph.flush();

            let timer = ::std::time::Instant::now();
            worker.step_while(|| probe.less_than(&graph.time()));

            if worker.index() == 0 {
                let elapsed = timer.elapsed();
                println!("{:?}:\t{}", round, elapsed.as_secs() * 1000000000 + (elapsed.subsec_nanos() as u64));
            }
        }
        println!("finished; elapsed: {:?}", timer.elapsed());
    }).unwrap();
}

// returns pairs (n, s) indicating node n can be reached from a root in s steps.
fn bidijkstra<G: Scope>(edges: &Collection<G, Edge>, goals: &Collection<G, (Node, Node)>) -> Collection<G, ((Node, Node), u32)>
where G::Timestamp: Lattice+Ord {

    edges.scope().scoped(|inner| {

        // Our plan is to start evolving distances from both sources and destinations.
        // The evolution from a source or destination should continue as long as there
        // is a corresponding destination or source that has not yet been reached.

        // forward and reverse (node, (root, dist))
        let forward = Variable::from(goals.map(|(x,_)| (x,(x,0))).enter(inner));
        let reverse = Variable::from(goals.map(|(_,y)| (y,(y,0))).enter(inner));

        let goals = goals.enter(inner);
        let edges = edges.enter(inner);

        // Let's determine which (src, dst) pairs are ready to return.
        //
        //   done(src, dst) := forward(src, med), reverse(dst, med), goal(src, dst).
        //
        // This is a cyclic join, which should scare us a bunch.
        let reached =
        forward
            .join_map_u(&reverse, |_, &(src,d1), &(dst,d2)| ((src, dst), d1 + d2))
            .group(|_key, s, t| t.push((s[0].0, 1)));
            // .inspect(|x| println!("reached: {:?}", x));

        let active =
        reached
            .semijoin(&goals)
            .negate()
            .map(|(srcdst,_)| srcdst)
            .concat(&goals)
            // .inspect(|x| println!("active: {:?}", x))
            .consolidate();

        // Let's expand out forward queries that are active.
        let forward_active = active.map(|(x,_y)| x).distinct_u();
        let forward_next =
        forward
            // .inspect(|x| println!("forward: {:?}", x))
            .map(|(med, (src, dist))| (src, (med, dist)))
            .semijoin_u(&forward_active)
            .map(|(src, (med, dist))| (med, (src, dist)))
            .join_map_u(&edges, |_med, &(src, dist), &next| (next, (src, dist+1)))
            .concat(&forward)
            .map(|(next, (src, dist))| ((next, src), dist))
            .group(|_key, s, t| t.push((s[0].0, 1)))
            .map(|((next, src), dist)| (next, (src, dist)));

        forward.set(&forward_next);

        // Let's expand out reverse queries that are active.
        let reverse_active = active.map(|(_x,y)| y).distinct_u();
        let reverse_next =
        reverse
            // .inspect(|x| println!("reverse: {:?}", x))
            .map(|(med, (rev, dist))| (rev, (med, dist)))
            .semijoin_u(&reverse_active)
            .map(|(rev, (med, dist))| (med, (rev, dist)))
            .join_map_u(&edges.map(|(x,y)| (y,x)), |_med, &(rev, dist), &next| (next, (rev, dist+1)))
            .concat(&reverse)
            .map(|(next, (rev, dist))| ((next, rev), dist))
            .group(|_key, s, t| t.push((s[0].0, 1)))
            .map(|((next,rev), dist)| (next, (rev, dist)));

        reverse.set(&reverse_next);

        reached.leave()
    })
}<|endoftext|>


<commit_before><commit_msg>Add client for rust (#29)<commit_after>extern crate serde;
extern crate serde_json;

use std::io;
use std::net::TcpStream;
use self::serde::{Serialize, Serializer};
use self::serde::ser::SerializeStruct;

// Usage example:
//
// #[path = "rewind_client.rs"]
// mod rewind_client;
//
// use self::rewind_client::{RewindClient, Circle, SendToRewind, DEFAULT_LAYER};
//
// let mut rewind = RewindClient::new().expect("Failed to create rewind client");
//
// Circle {x: 1.0, y: 2.0, r: 3.0, color: 0xAABBCC, layer: DEFAULT_LAYER}
//     .send_to_rewind(&mut rewind).unwrap();

#[allow(dead_code)]
pub struct RewindClient {
    stream: TcpStream,
}

#[allow(dead_code)]
impl RewindClient {
    pub fn new() -> io::Result<Self> {
        Self::with_host_port("127.0.0.1", 9111)
    }

    pub fn with_host_port<'r>(host: &'r str, port: u16) -> io::Result<Self> {
        let stream = TcpStream::connect((host, port))?;
        stream.set_nodelay(true)?;
        Ok(RewindClient { stream: stream })
    }

    pub fn send<T: Serialize>(&mut self, value: &T) -> io::Result<()> {
        self.stream.write_as_json(value)
    }
}

pub trait SendToRewind: Serialize {
    fn send_to_rewind(&self, rewind: &mut RewindClient) -> io::Result<()> {
        rewind.send(&self)
    }
}

#[allow(dead_code)]
pub const DEFAULT_LAYER: i32 = 3;

impl<T: Serialize + ?Sized> SendToRewind for T {}

pub trait WriteAsJson: io::Write {
    fn write_as_json<T: Serialize>(&mut self, value: &T) -> io::Result<()> {
        use self::serde_json;
        self.write_all(serde_json::to_string(value)?.as_bytes())
    }
}

impl<T: io::Write + ?Sized> WriteAsJson for T {}

#[allow(dead_code)]
pub struct Circle {
    pub x: f64,
    pub y: f64,
    pub r: f64,
    pub color: u32,
    pub layer: i32,
}

impl Serialize for Circle {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
        let mut state = serializer.serialize_struct("Circle", 5)?;
        state.serialize_field("type", "circle")?;
        state.serialize_field("x", &self.x)?;
        state.serialize_field("y", &self.y)?;
        state.serialize_field("r", &self.r)?;
        state.serialize_field("color", &self.color)?;
        state.serialize_field("layer", &self.layer)?;
        state.end()
    }
}

#[allow(dead_code)]
pub struct Popup<'r> {
    pub x: f64,
    pub y: f64,
    pub r: f64,
    pub text: &'r str,
}

impl<'r> Serialize for Popup<'r> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
        let mut state = serializer.serialize_struct("Popup", 5)?;
        state.serialize_field("type", "popup")?;
        state.serialize_field("x", &self.x)?;
        state.serialize_field("y", &self.y)?;
        state.serialize_field("r", &self.r)?;
        state.serialize_field("text", self.text)?;
        state.end()
    }
}

#[allow(dead_code)]
pub struct Rectangle {
    pub x1: f64,
    pub y1: f64,
    pub x2: f64,
    pub y2: f64,
    pub color: u32,
    pub layer: i32,
}

impl Serialize for Rectangle {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
        let mut state = serializer.serialize_struct("Rectangle", 7)?;
        state.serialize_field("type", "rectangle")?;
        state.serialize_field("x1", &self.x1)?;
        state.serialize_field("y1", &self.y1)?;
        state.serialize_field("x2", &self.x2)?;
        state.serialize_field("y2", &self.y2)?;
        state.serialize_field("color", &self.color)?;
        state.serialize_field("layer", &self.layer)?;
        state.end()
    }
}

#[allow(dead_code)]
pub struct Line {
    pub x1: f64,
    pub y1: f64,
    pub x2: f64,
    pub y2: f64,
    pub color: u32,
    pub layer: i32,
}

impl Serialize for Line {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
        let mut state = serializer.serialize_struct("Line", 7)?;
        state.serialize_field("type", "line")?;
        state.serialize_field("x1", &self.x1)?;
        state.serialize_field("y1", &self.y1)?;
        state.serialize_field("x2", &self.x2)?;
        state.serialize_field("y2", &self.y2)?;
        state.serialize_field("color", &self.color)?;
        state.serialize_field("layer", &self.layer)?;
        state.end()
    }
}

#[allow(dead_code)]
pub struct Unit {
    pub x: f64,
    pub y: f64,
    pub r: f64,
    pub hp: i32,
    pub max_hp: i32,
    pub rem_cooldown: i32,
    pub cooldown: i32,
    pub enemy: Side,
    pub course: f64,
    pub selected: bool,
    pub unit_type: UnitType,
}

#[allow(dead_code)]
#[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub enum Side {
    Ally = -1,
    Neutral = 0,
    Enemy = 1,
}

#[allow(dead_code)]
#[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub enum UnitType {
    Unknown = 0,
    Tank = 1,
    Ifv = 2,
    Arrv = 3,
    Helicopter = 4,
    Fighter = 5,
}

impl Serialize for Unit {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
        let mut state = serializer.serialize_struct("Unit", 12)?;
        state.serialize_field("type", "unit")?;
        state.serialize_field("x", &self.x)?;
        state.serialize_field("y", &self.y)?;
        state.serialize_field("r", &self.r)?;
        state.serialize_field("hp", &self.hp)?;
        state.serialize_field("max_hp", &self.max_hp)?;
        state.serialize_field("rem_cooldown", &self.rem_cooldown)?;
        state.serialize_field("cooldown", &self.cooldown)?;
        state.serialize_field("enemy", &(self.enemy as i32))?;
        state.serialize_field("course", &self.course)?;
        state.serialize_field("selected", &self.selected)?;
        state.serialize_field("unit_type", &(self.unit_type as i32))?;
        state.end()
    }
}

#[allow(dead_code)]
pub struct Area {
    pub x: i32,
    pub y: i32,
    pub area_type: AreaType,
}

#[allow(dead_code)]
#[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub enum AreaType {
    Unknown = 0,
    Forest = 1,
    Swamp = 2,
    Rain = 3,
    Cloud = 4,
}

impl Serialize for Area {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
        let mut state = serializer.serialize_struct("Area", 4)?;
        state.serialize_field("type", "area")?;
        state.serialize_field("x", &self.x)?;
        state.serialize_field("y", &self.y)?;
        state.serialize_field("area_type", &(self.area_type as i32))?;
        state.end()
    }
}

#[allow(dead_code)]
pub struct End;

impl Serialize for End {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
        let mut state = serializer.serialize_struct("End", 1)?;
        state.serialize_field("type", "end")?;
        state.end()
    }
}

#[allow(dead_code)]
pub struct Message<'r> {
    pub message: &'r str,
}

impl<'r> Serialize for Message<'r> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer {
        let mut state = serializer.serialize_struct("Message", 2)?;
        state.serialize_field("type", "message")?;
        state.serialize_field("message", self.message)?;
        state.end()
    }
}
<|endoftext|>


<commit_before><commit_msg>Impl Eq for DFA<commit_after><|endoftext|>


<commit_before><commit_msg>'collatz-conjecture': functional implementation based on Iterator.<commit_after><|endoftext|>


<commit_before><commit_msg>Finish ffi bindings<commit_after><|endoftext|>


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


<commit_before><commit_msg>Add domain/ip input checking to appropriate functions.<commit_after><|endoftext|>


<commit_before><commit_msg>Removed unneeded implementation<commit_after><|endoftext|>


<commit_before><commit_msg>Simplify with_srgb signature and clarify its docs<commit_after><|endoftext|>


<commit_before><commit_msg>Delay morphism composition; fix #3<commit_after><|endoftext|>


<commit_before><commit_msg>examples: Add AppSettings example<commit_after>extern crate clap;

use clap::{App, AppSettings, SubCommand};

fn main() {
    // You can use AppSettings to change the application level behavior of clap. .setting() function
    // of App struct takes AppSettings enum as argument. There is also .settings() function which
    // takes slice of AppSettings enum.  You can learn more about AppSettings in the documentation,
    // which also has examples on each setting.
    //
    // This example will only show usage of one AppSettings setting. See documentation for more
    // information.

    let matches = App::new("myapp")
                        .setting(AppSettings::SubcommandsNegateReqs)
                                            // Negates requirement of parent command.

                        .arg_from_usage("<input> 'input file to use'")
                                            // Required positional argument called input.  This
                                            // will be only required if subcommand is not present.

                        .subcommand(SubCommand::with_name("help")
                                                .about("shows help message"))
                                            // if program is invoked with subcommand, you do not
                                            // need to specify the <input> argument anymore due to
                                            // the AppSettings::SubcommandsNegateReqs setting.

                        .get_matches();

    // Contiued program logic goes here...
}
<|endoftext|>


<commit_before><commit_msg>Add Debug deriving<commit_after><|endoftext|>


<commit_before><commit_msg>test only if test flag is true<commit_after><|endoftext|>


<commit_before>use collections::VecDeque;
// Temporary hack until libredox get hashmaps
use redox::*;

#[derive(Clone, PartialEq, Copy, Hash)]
pub enum InsertMode {
    Append,
    Insert,
    Replace,
}

#[derive(Clone, PartialEq, Copy, Hash)]
pub struct InsertOptions {
    mode: InsertMode,
}

/// A mode
#[derive(Clone, PartialEq, Copy, Hash)]
pub enum Mode {
    /// A primitive mode (no repeat, no delimiters, no preprocessing)
    Primitive(PrimitiveMode),
    /// Command mode
    Command(CommandMode),
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A command mode
pub enum CommandMode {
//    Visual(VisualOptions),
    /// Normal mode
    Normal,
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A primitive mode
pub enum PrimitiveMode {
    /// Insert mode
    Insert(InsertOptions),
}

#[derive(Clone, PartialEq, Hash)]
/// The state of the editor
pub struct State {
    /// The current cursor
    pub current_cursor: u8,
    /// The cursors
    pub cursors: Vec<Cursor>,
    /// The text (document)
    pub text: VecDeque<VecDeque<char>>,
    /// The x coordinate of the scroll
    pub scroll_x: u32,
    /// The y coordinate of the scroll
    pub scroll_y: u32,
    /// Number of repeation entered
    pub n: u16,
}

impl State {
    fn insert(&mut self, c: char) {

    }
    fn new() -> State {
        State {
            current_cursor: 0,
            cursors: Vec::new(),
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
        }
    }
}

/// A command char
#[derive(Clone, Copy, Hash, PartialEq)]
pub enum CommandChar {
    /// A char
    Char(char),
    /// A wildcard
    Wildcard,
}

/// The editor
pub struct Editor {
    /// The state of the editor
    pub state: State,
}

impl Editor {
    pub fn new() -> Self {
        Editor {
            state: State::new(),
        }
    }

    /// Execute a instruction n times
    pub fn exec(&mut self, n: u16, cmd: char) {

        match cmd {

        }
    }

    /// Feed a char to the editor (as input)
    fn feed(&mut self, c: char) {
        match self.state.cursors[self.state.current_cursor as usize].mode {
            Mode::Primitive(_) => {
                self.exec(0, c);
            },
            Mode::Command(_) => {
                self.n = match c {
                    '0' if self.n != 0 => self.n * 10,
                    '1'           => self.n * 10 + 1,
                    '2'           => self.n * 10 + 2,
                    '3'           => self.n * 10 + 3,
                    '4'           => self.n * 10 + 4,
                    '5'           => self.n * 10 + 5,
                    '6'           => self.n * 10 + 6,
                    '7'           => self.n * 10 + 7,
                    '8'           => self.n * 10 + 8,
                    '9'           => self.n * 10 + 9,
                    _             => {
                        self.exec(if self.n == 0 { 1 } else { self.n }, c);
                        self.n
                    }
                }

            }
        }
    }
}

#[derive(Clone, PartialEq, Hash)]
/// A cursor
pub struct Cursor {
    /// The x coordinate of the cursor
    pub x: u32,
    /// The y coordinate of the cursor
    pub y: u32,
    /// The mode of the cursor
    pub mode: Mode,
    /// The history of the cursor
    pub history: Vec<Unit>,

<commit_msg>Refactor<commit_after>use collections::VecDeque;
// Temporary hack until libredox get hashmaps
use redox::*;

#[derive(Clone, PartialEq, Copy, Hash)]
pub enum InsertMode {
    Append,
    Insert,
    Replace,
}

#[derive(Clone, PartialEq, Copy, Hash)]
pub struct InsertOptions {
    mode: InsertMode,
}

/// A mode
#[derive(Clone, PartialEq, Copy, Hash)]
pub enum Mode {
    /// A primitive mode (no repeat, no delimiters, no preprocessing)
    Primitive(PrimitiveMode),
    /// Command mode
    Command(CommandMode),
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A command mode
pub enum CommandMode {
//    Visual(VisualOptions),
    /// Normal mode
    Normal,
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A primitive mode
pub enum PrimitiveMode {
    /// Insert mode
    Insert(InsertOptions),
}

#[derive(Clone, PartialEq, Hash)]
/// The state of the editor
pub struct Editor {
    /// The current cursor
    pub current_cursor: u8,
    /// The cursors
    pub cursors: Vec<Cursor>,
    /// The text (document)
    pub text: VecDeque<VecDeque<char>>,
    /// The x coordinate of the scroll
    pub scroll_x: u32,
    /// The y coordinate of the scroll
    pub scroll_y: u32,
    /// Number of repeation entered
    pub n: u16,
}

impl Editor {

    /// Execute a instruction n times
    pub fn exec(&mut self, n: u16, cmd: char) {

        match cmd {

        }
    }

    /// Feed a char to the editor (as input)
    fn feed(&mut self, c: char) {
        match self.cursors[self.current_cursor as usize].mode {
            Mode::Primitive(_) => {
                self.exec(0, c);
            },
            Mode::Command(_) => {
                self.n = match c {
                    '0' if self.n != 0 => self.n * 10,
                    '1'           => self.n * 10 + 1,
                    '2'           => self.n * 10 + 2,
                    '3'           => self.n * 10 + 3,
                    '4'           => self.n * 10 + 4,
                    '5'           => self.n * 10 + 5,
                    '6'           => self.n * 10 + 6,
                    '7'           => self.n * 10 + 7,
                    '8'           => self.n * 10 + 8,
                    '9'           => self.n * 10 + 9,
                    _             => {
                        self.exec(if self.n == 0 { 1 } else { self.n }, c);
                        self.n
                    }
                }

            }
        }
    }

    /// Insert text
    fn insert(&mut self, c: char) {

    }

    /// Create new default state editor
    fn new() -> Editor {
        Editor {
            current_cursor: 0,
            cursors: Vec::new(),
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
            n: 0,
        }
    }
}

/// A command char
#[derive(Clone, Copy, Hash, PartialEq)]
pub enum CommandChar {
    /// A char
    Char(char),
    /// A wildcard
    Wildcard,
}

#[derive(Clone, PartialEq, Hash)]
/// A cursor
pub struct Cursor {
    /// The x coordinate of the cursor
    pub x: u32,
    /// The y coordinate of the cursor
    pub y: u32,
    /// The mode of the cursor
    pub mode: Mode,
    /// The history of the cursor
    pub history: Vec<Unit>,

<|endoftext|>


<commit_before><commit_msg>Examples: Basic JSON example without macros, incomplete<commit_after>extern crate chomp;

use std::collections::HashMap;
use std::mem::transmute;

use chomp::ascii::{is_digit, is_whitespace};
use chomp::combinators::{matched_by, or, option, sep_by};
use chomp::parsers::{SimpleResult, any, token, scan, skip_while, skip_while1, string};
use chomp::parsers::Error as ChompError;
use chomp::types::{Buffer, Input, ParseResult};

pub type Error = ChompError<u8>;

/// A JSON Value
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    Array(Vec<Value>),
    Number(f64),
    Object(HashMap<String, Value>),
    String(String),
    True,
    False,
    Null,
}

/// Parses a `Value` from the supplied input.
pub fn parse<I: Input<Token=u8>>(i: I) -> ParseResult<I, Value, Error> {
    skip_while(i, is_whitespace).then(|i|
    or(i, |i|
        parse_object(i).map(Value::Object),        |i| or(i, |i|
        parse_array(i).map(Value::Array),          |i| or(i, |i|
        parse_string(i).map(Value::String),        |i| or(i, |i|
        parse_number(i).map(Value::Number),        |i| or(i, |i|
        string(i, b"true").map(|_|  Value::True),  |i| or(i, |i|
        string(i, b"false").map(|_| Value::False), |i| or(i, |i|
        string(i, b"null").map(|_|  Value::Null),  |i|
        i.err(Error::unexpected())))))))))
}

// AKA match_float + FromStr
//
// TODO: Move to ascii module with proper tests
/// Parses a floating point number from the input
fn parse_number<I: Input<Token=u8>>(i: I) -> ParseResult<I, f64, Error> {
    fn sign<I: Input<Token=u8>>(i: I) -> SimpleResult<I, u8> {
        or(i, |i| token(i, b'+'), |i| token(i, b'-'))
    }
    fn signed_decimal<I: Input<Token=u8>>(i: I) -> SimpleResult<I, ()> {
        option(i, sign, b'+').then(|i| skip_while1(i, is_digit))
    }
    fn e<I: Input<Token=u8>>(i: I) -> SimpleResult<I, u8> {
        or(i, |i| token(i, b'e'), |i| token(i, b'E'))
    }
    fn make_num<B: Buffer<Token=u8>>(b: B) -> f64 {
        // If we add a restriction that Input<Buffer=&[u8]> then we can skip this allocation,
        // or if we reimplement float-parsing properly (or find a library where we can supply
        // numbers instead of a string-slice.
        let v = b.to_vec();

        // v only contains [-+0-9.eE], utf-8 safe
        let s: &str = unsafe { transmute(&v[..]) };

        s.parse().expect("Invalid floating number")
    }

    matched_by(i, |i|
        signed_decimal(i).then(|i|
        option(i, |i| token(i, b'.').then(|i| skip_while1(i, is_digit)), ()).then(|i|
        option(i, |i| e(i).then(signed_decimal), ())))).map(|(b, _)| make_num(b))
}

/// Parse a quoted string
fn parse_string<I: Input<Token=u8>>(i: I) -> ParseResult<I, String, Error> {
    token(i, b'"').then(|i| scan(i, b'\0', |s, c| match (s, c) {
        (b'\\', b'"')  => Some(c),
        (b'\\', b'\\') => Some(b'\0'), // null here because we need \\" to end
        (_,     b'"')  => None,
        (_,     _)     => Some(c),
    }).bind(|i, b| any(i).map(|_| unescape(b))))
}

/// Unescape the contents of a quoted string.
fn unescape<B: Buffer<Token=u8>>(b: B) -> String {
    // FIXME: Implement escape sequence parsing
    unsafe { String::from_utf8_unchecked(b.to_vec()) }
}

/// Parses a JSON Object
fn parse_object<I: Input<Token=u8>>(i: I) -> ParseResult<I, HashMap<String, Value>, Error> {
    token(i, b'{').then(|i|
    skip_while(i, is_whitespace).then(|i|
    sep_by(i, parse_key_value, separator).bind(|i, m|
    skip_while(i, is_whitespace).then(|i|
    token(i, b'}').map(|_| m)))))
}

/// Whitespace + comma, separates key-value pairs in objects and values in arrays
fn separator<I: Input<Token=u8>>(i: I) -> ParseResult<I, (), Error> {
    skip_while(i, is_whitespace).then(|i|
    token(i, b',').then(|i|
    skip_while(i, is_whitespace))).map_err(From::from)
}

/// Parses string-key: value
fn parse_key_value<I: Input<Token=u8>>(i: I) -> ParseResult<I, (String, Value), Error> {
    parse_string(i).bind(|i, s|
    skip_while(i, is_whitespace).then(|i|
    token(i, b':').then(|i|
    skip_while(i, is_whitespace).then(|i|
    parse(i).map(|v| (s, v))))))
}

/// Parses a JSON array
fn parse_array<I: Input<Token=u8>>(i: I) -> ParseResult<I, Vec<Value>, Error> {
    token(i, b'[').then(|i|
    sep_by(i, parse, separator).bind(|i, v|
    token(i, b']').map(|_| v)))
}

use chomp::parse_only;
use chomp::combinators::many;

fn main() {
    let t: Vec<_> = parse_only(|i| many(i, parse), &b"{\"foo\": 1.23, \"some_more\": [1, 2, 3, \"lol\"]}"[..]).unwrap();

    println!("{:?}", t);
}
<|endoftext|>


<commit_before><commit_msg>Add main<commit_after>fn main() {

}
<|endoftext|>


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


<commit_before><commit_msg>Add rust code for nth-prime<commit_after>pub fn nth(index: u32) -> Result<u32, String> {
    if index == 0 {
        return Err("Invalid index".to_string());
    }

    let mut number = 3;
    let mut primes = Vec::with_capacity(index as usize);
    primes.push(2);

    while primes.len() < index as usize {
        if primes.iter().all(|&x| number % x != 0) {
            primes.push(number);
        }

        number += 2;
    }

    Ok(*primes.last().unwrap())
}
<|endoftext|>


<commit_before>//! HTTP Client
//!
//! The HTTP `Client` uses asynchronous IO, and utilizes the `Handler` trait
//! to convey when IO events are available for a given request.

use std::cell::RefCell;
use std::fmt;
use std::io;
use std::rc::Rc;
use std::time::Duration;

use futures::{Poll, Async, Future};
use relay;
use tokio::io::Io;
use tokio::reactor::Handle;
use tokio_proto::BindClient;
use tokio_proto::streaming::Message;
use tokio_proto::streaming::pipeline::ClientProto;
use tokio_proto::util::client_proxy::ClientProxy;
pub use tokio_service::Service;

use header::{Headers, Host};
use http::{self, TokioBody};
use method::Method;
use self::pool::{Pool, Pooled};
use {Url};

pub use self::connect::{HttpConnector, Connect};
pub use self::request::Request;
pub use self::response::Response;

mod connect;
mod dns;
mod pool;
mod request;
mod response;

/// A Client to make outgoing HTTP requests.
// If the Connector is clone, then the Client can be clone easily.
#[derive(Clone)]
pub struct Client<C> {
    connector: C,
    handle: Handle,
    pool: Pool<TokioClient>,
}

impl Client<HttpConnector> {
    /// Configure a Client.
    ///
    /// # Example
    ///
    /// ```dont_run
    /// # use hyper::Client;
    /// let client = Client::configure()
    ///     .keep_alive(true)
    ///     .build().unwrap();
    /// ```
    #[inline]
    pub fn configure() -> Config<UseDefaultConnector> {
        Config::default()
    }
}

impl Client<HttpConnector> {
    /// Create a new Client with the default config.
    #[inline]
    pub fn new(handle: &Handle) -> Client<HttpConnector> {
        Client::configure().build(handle)
    }
}

impl<C: Connect> Client<C> {
    /// Create a new client with a specific connector.
    #[inline]
    fn configured(config: Config<C>, handle: &Handle) -> Client<C> {
        Client {
            connector: config.connector,
            handle: handle.clone(),
            pool: Pool::new(config.keep_alive, config.keep_alive_timeout),
        }
    }

    /// Send a GET Request using this Client.
    #[inline]
    pub fn get(&self, url: Url) -> FutureResponse {
        self.request(Request::new(Method::Get, url))
    }

    /// Send a constructed Request using this Client.
    #[inline]
    pub fn request(&self, req: Request) -> FutureResponse {
        self.call(req)
    }
}

/// A `Future` that will resolve to an HTTP Response.
pub struct FutureResponse(Box<Future<Item=Response, Error=::Error> + 'static>);

impl fmt::Debug for FutureResponse {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Future<Response>")
    }
}

impl Future for FutureResponse {
    type Item = Response;
    type Error = ::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.0.poll()
    }
}

impl<C: Connect> Service for Client<C> {
    type Request = Request;
    type Response = Response;
    type Error = ::Error;
    type Future = FutureResponse;

    fn call(&self, req: Request) -> Self::Future {
        let url = req.url().clone();
        let (mut head, body) = request::split(req);
        let mut headers = Headers::new();
        headers.set(Host::new(url.host_str().unwrap().to_owned(), url.port()));
        headers.extend(head.headers.iter());
        head.headers = headers;

        let checkout = self.pool.checkout(&url[..::url::Position::BeforePath]);
        let connect = {
            let handle = self.handle.clone();
            let pool = self.pool.clone();
            let pool_key = Rc::new(url[..::url::Position::BeforePath].to_owned());
            self.connector.connect(url)
                .map(move |io| {
                    let (tx, rx) = relay::channel();
                    let client = HttpClient {
                        client_rx: RefCell::new(Some(rx)),
                    }.bind_client(&handle, io);
                    let pooled = pool.pooled(pool_key, client);
                    tx.complete(pooled.clone());
                    pooled
                })
        };

        let race = checkout.select(connect)
            .map(|(client, _work)| client)
            .map_err(|(e, _work)| {
                // the Pool Checkout cannot error, so the only error
                // is from the Connector
                // XXX: should wait on the Checkout? Problem is
                // that if the connector is failing, it may be that we
                // never had a pooled stream at all
                e.into()
            });
        let req = race.and_then(move |client| {
            let msg = match body {
                Some(body) => {
                    Message::WithBody(head, body.into())
                },
                None => Message::WithoutBody(head),
            };
            client.call(msg)
        });
        FutureResponse(Box::new(req.map(|msg| {
            match msg {
                Message::WithoutBody(head) => response::new(head, None),
                Message::WithBody(head, body) => response::new(head, Some(body.into())),
            }
        })))
    }

}

impl<C> fmt::Debug for Client<C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Client")
    }
}

type TokioClient = ClientProxy<Message<http::RequestHead, TokioBody>, Message<http::ResponseHead, TokioBody>, ::Error>;

struct HttpClient {
    client_rx: RefCell<Option<relay::Receiver<Pooled<TokioClient>>>>,
}

impl<T: Io + 'static> ClientProto<T> for HttpClient {
    type Request = http::RequestHead;
    type RequestBody = http::Chunk;
    type Response = http::ResponseHead;
    type ResponseBody = http::Chunk;
    type Error = ::Error;
    type Transport = http::Conn<T, http::ClientTransaction, Pooled<TokioClient>>;
    type BindTransport = BindingClient<T>;

    fn bind_transport(&self, io: T) -> Self::BindTransport {
        BindingClient {
            rx: self.client_rx.borrow_mut().take().expect("client_rx was lost"),
            io: Some(io),
        }
    }
}

struct BindingClient<T> {
    rx: relay::Receiver<Pooled<TokioClient>>,
    io: Option<T>,
}

impl<T: Io + 'static> Future for BindingClient<T> {
    type Item = http::Conn<T, http::ClientTransaction, Pooled<TokioClient>>;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.rx.poll() {
            Ok(Async::Ready(client)) => Ok(Async::Ready(
                    http::Conn::new(self.io.take().expect("binding client io lost"), client)
            )),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(_canceled) => unreachable!(),
        }
    }
}

/// Configuration for a Client
#[derive(Debug, Clone)]
pub struct Config<C> {
    //connect_timeout: Duration,
    connector: C,
    keep_alive: bool,
    keep_alive_timeout: Option<Duration>,
    //TODO: make use of max_idle config
    max_idle: usize,
}

/// Phantom type used to signal that `Config` should create a `HttpConnector`.
#[derive(Debug, Clone, Copy)]
pub struct UseDefaultConnector(());

impl Config<UseDefaultConnector> {
    fn default() -> Config<UseDefaultConnector> {
        Config {
            //connect_timeout: Duration::from_secs(10),
            connector: UseDefaultConnector(()),
            keep_alive: true,
            keep_alive_timeout: Some(Duration::from_secs(90)),
            max_idle: 5,
        }
    }
}

impl<C> Config<C> {
    /// Set the `Connect` type to be used.
    #[inline]
    pub fn connector<CC: Connect>(self, val: CC) -> Config<CC> {
        Config {
            //connect_timeout: self.connect_timeout,
            connector: val,
            keep_alive: self.keep_alive,
            keep_alive_timeout: self.keep_alive_timeout,
            max_idle: self.max_idle,
        }
    }

    /// Enable or disable keep-alive mechanics.
    ///
    /// Default is enabled.
    #[inline]
    pub fn keep_alive(mut self, val: bool) -> Config<C> {
        self.keep_alive = val;
        self
    }

    /// Set an optional timeout for idle sockets being kept-alive.
    ///
    /// Pass `None` to disable timeout.
    ///
    /// Default is 2 minutes.
    #[inline]
    pub fn keep_alive_timeout(mut self, val: Option<Duration>) -> Config<C> {
        self.keep_alive_timeout = val;
        self
    }

    /*
    /// Set the timeout for connecting to a URL.
    ///
    /// Default is 10 seconds.
    #[inline]
    pub fn connect_timeout(mut self, val: Duration) -> Config<C> {
        self.connect_timeout = val;
        self
    }
    */
}

impl<C: Connect> Config<C> {
    /// Construct the Client with this configuration.
    #[inline]
    pub fn build(self, handle: &Handle) -> Client<C> {
        Client::configured(self, handle)
    }
}

impl Config<UseDefaultConnector> {
    /// Construct the Client with this configuration.
    #[inline]
    pub fn build(self, handle: &Handle) -> Client<HttpConnector> {
        self.connector(HttpConnector::new(4, handle)).build(handle)
    }
}

#[cfg(test)]
mod tests {
    /*
    use std::io::Read;
    use header::Server;
    use super::{Client};
    use super::pool::Pool;
    use url::Url;

    mock_connector!(Issue640Connector {
        b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\n",
        b"GET",
        b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n",
        b"HEAD",
        b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n",
        b"POST"
    });

    // see issue #640
    #[test]
    fn test_head_response_body_keep_alive() {
        let client = Client::with_connector(Pool::with_connector(Default::default(), Issue640Connector));

        let mut s = String::new();
        client.get("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap();
        assert_eq!(s, "GET");

        let mut s = String::new();
        client.head("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap();
        assert_eq!(s, "");

        let mut s = String::new();
        client.post("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap();
        assert_eq!(s, "POST");
    }
    */
}
<commit_msg>docs(client): Update `Client::configure` example to compile<commit_after>//! HTTP Client
//!
//! The HTTP `Client` uses asynchronous IO, and utilizes the `Handler` trait
//! to convey when IO events are available for a given request.

use std::cell::RefCell;
use std::fmt;
use std::io;
use std::rc::Rc;
use std::time::Duration;

use futures::{Poll, Async, Future};
use relay;
use tokio::io::Io;
use tokio::reactor::Handle;
use tokio_proto::BindClient;
use tokio_proto::streaming::Message;
use tokio_proto::streaming::pipeline::ClientProto;
use tokio_proto::util::client_proxy::ClientProxy;
pub use tokio_service::Service;

use header::{Headers, Host};
use http::{self, TokioBody};
use method::Method;
use self::pool::{Pool, Pooled};
use {Url};

pub use self::connect::{HttpConnector, Connect};
pub use self::request::Request;
pub use self::response::Response;

mod connect;
mod dns;
mod pool;
mod request;
mod response;

/// A Client to make outgoing HTTP requests.
// If the Connector is clone, then the Client can be clone easily.
#[derive(Clone)]
pub struct Client<C> {
    connector: C,
    handle: Handle,
    pool: Pool<TokioClient>,
}

impl Client<HttpConnector> {
    /// Configure a Client.
    ///
    /// # Example
    ///
    /// ```no_run
    /// extern crate hyper;
    /// extern crate tokio_core;
    ///
    /// fn main() {
    /// let mut core = tokio_core::reactor::Core::new().unwrap();
    /// let handle = core.handle();
    /// let client = hyper::Client::configure()
    ///     .keep_alive(true)
    ///     .build(&handle);
    /// }
    /// ```
    #[inline]
    pub fn configure() -> Config<UseDefaultConnector> {
        Config::default()
    }
}

impl Client<HttpConnector> {
    /// Create a new Client with the default config.
    #[inline]
    pub fn new(handle: &Handle) -> Client<HttpConnector> {
        Client::configure().build(handle)
    }
}

impl<C: Connect> Client<C> {
    /// Create a new client with a specific connector.
    #[inline]
    fn configured(config: Config<C>, handle: &Handle) -> Client<C> {
        Client {
            connector: config.connector,
            handle: handle.clone(),
            pool: Pool::new(config.keep_alive, config.keep_alive_timeout),
        }
    }

    /// Send a GET Request using this Client.
    #[inline]
    pub fn get(&self, url: Url) -> FutureResponse {
        self.request(Request::new(Method::Get, url))
    }

    /// Send a constructed Request using this Client.
    #[inline]
    pub fn request(&self, req: Request) -> FutureResponse {
        self.call(req)
    }
}

/// A `Future` that will resolve to an HTTP Response.
pub struct FutureResponse(Box<Future<Item=Response, Error=::Error> + 'static>);

impl fmt::Debug for FutureResponse {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Future<Response>")
    }
}

impl Future for FutureResponse {
    type Item = Response;
    type Error = ::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.0.poll()
    }
}

impl<C: Connect> Service for Client<C> {
    type Request = Request;
    type Response = Response;
    type Error = ::Error;
    type Future = FutureResponse;

    fn call(&self, req: Request) -> Self::Future {
        let url = req.url().clone();
        let (mut head, body) = request::split(req);
        let mut headers = Headers::new();
        headers.set(Host::new(url.host_str().unwrap().to_owned(), url.port()));
        headers.extend(head.headers.iter());
        head.headers = headers;

        let checkout = self.pool.checkout(&url[..::url::Position::BeforePath]);
        let connect = {
            let handle = self.handle.clone();
            let pool = self.pool.clone();
            let pool_key = Rc::new(url[..::url::Position::BeforePath].to_owned());
            self.connector.connect(url)
                .map(move |io| {
                    let (tx, rx) = relay::channel();
                    let client = HttpClient {
                        client_rx: RefCell::new(Some(rx)),
                    }.bind_client(&handle, io);
                    let pooled = pool.pooled(pool_key, client);
                    tx.complete(pooled.clone());
                    pooled
                })
        };

        let race = checkout.select(connect)
            .map(|(client, _work)| client)
            .map_err(|(e, _work)| {
                // the Pool Checkout cannot error, so the only error
                // is from the Connector
                // XXX: should wait on the Checkout? Problem is
                // that if the connector is failing, it may be that we
                // never had a pooled stream at all
                e.into()
            });
        let req = race.and_then(move |client| {
            let msg = match body {
                Some(body) => {
                    Message::WithBody(head, body.into())
                },
                None => Message::WithoutBody(head),
            };
            client.call(msg)
        });
        FutureResponse(Box::new(req.map(|msg| {
            match msg {
                Message::WithoutBody(head) => response::new(head, None),
                Message::WithBody(head, body) => response::new(head, Some(body.into())),
            }
        })))
    }

}

impl<C> fmt::Debug for Client<C> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.pad("Client")
    }
}

type TokioClient = ClientProxy<Message<http::RequestHead, TokioBody>, Message<http::ResponseHead, TokioBody>, ::Error>;

struct HttpClient {
    client_rx: RefCell<Option<relay::Receiver<Pooled<TokioClient>>>>,
}

impl<T: Io + 'static> ClientProto<T> for HttpClient {
    type Request = http::RequestHead;
    type RequestBody = http::Chunk;
    type Response = http::ResponseHead;
    type ResponseBody = http::Chunk;
    type Error = ::Error;
    type Transport = http::Conn<T, http::ClientTransaction, Pooled<TokioClient>>;
    type BindTransport = BindingClient<T>;

    fn bind_transport(&self, io: T) -> Self::BindTransport {
        BindingClient {
            rx: self.client_rx.borrow_mut().take().expect("client_rx was lost"),
            io: Some(io),
        }
    }
}

struct BindingClient<T> {
    rx: relay::Receiver<Pooled<TokioClient>>,
    io: Option<T>,
}

impl<T: Io + 'static> Future for BindingClient<T> {
    type Item = http::Conn<T, http::ClientTransaction, Pooled<TokioClient>>;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.rx.poll() {
            Ok(Async::Ready(client)) => Ok(Async::Ready(
                    http::Conn::new(self.io.take().expect("binding client io lost"), client)
            )),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(_canceled) => unreachable!(),
        }
    }
}

/// Configuration for a Client
#[derive(Debug, Clone)]
pub struct Config<C> {
    //connect_timeout: Duration,
    connector: C,
    keep_alive: bool,
    keep_alive_timeout: Option<Duration>,
    //TODO: make use of max_idle config
    max_idle: usize,
}

/// Phantom type used to signal that `Config` should create a `HttpConnector`.
#[derive(Debug, Clone, Copy)]
pub struct UseDefaultConnector(());

impl Config<UseDefaultConnector> {
    fn default() -> Config<UseDefaultConnector> {
        Config {
            //connect_timeout: Duration::from_secs(10),
            connector: UseDefaultConnector(()),
            keep_alive: true,
            keep_alive_timeout: Some(Duration::from_secs(90)),
            max_idle: 5,
        }
    }
}

impl<C> Config<C> {
    /// Set the `Connect` type to be used.
    #[inline]
    pub fn connector<CC: Connect>(self, val: CC) -> Config<CC> {
        Config {
            //connect_timeout: self.connect_timeout,
            connector: val,
            keep_alive: self.keep_alive,
            keep_alive_timeout: self.keep_alive_timeout,
            max_idle: self.max_idle,
        }
    }

    /// Enable or disable keep-alive mechanics.
    ///
    /// Default is enabled.
    #[inline]
    pub fn keep_alive(mut self, val: bool) -> Config<C> {
        self.keep_alive = val;
        self
    }

    /// Set an optional timeout for idle sockets being kept-alive.
    ///
    /// Pass `None` to disable timeout.
    ///
    /// Default is 2 minutes.
    #[inline]
    pub fn keep_alive_timeout(mut self, val: Option<Duration>) -> Config<C> {
        self.keep_alive_timeout = val;
        self
    }

    /*
    /// Set the timeout for connecting to a URL.
    ///
    /// Default is 10 seconds.
    #[inline]
    pub fn connect_timeout(mut self, val: Duration) -> Config<C> {
        self.connect_timeout = val;
        self
    }
    */
}

impl<C: Connect> Config<C> {
    /// Construct the Client with this configuration.
    #[inline]
    pub fn build(self, handle: &Handle) -> Client<C> {
        Client::configured(self, handle)
    }
}

impl Config<UseDefaultConnector> {
    /// Construct the Client with this configuration.
    #[inline]
    pub fn build(self, handle: &Handle) -> Client<HttpConnector> {
        self.connector(HttpConnector::new(4, handle)).build(handle)
    }
}

#[cfg(test)]
mod tests {
    /*
    use std::io::Read;
    use header::Server;
    use super::{Client};
    use super::pool::Pool;
    use url::Url;

    mock_connector!(Issue640Connector {
        b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\r\n",
        b"GET",
        b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n",
        b"HEAD",
        b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\n",
        b"POST"
    });

    // see issue #640
    #[test]
    fn test_head_response_body_keep_alive() {
        let client = Client::with_connector(Pool::with_connector(Default::default(), Issue640Connector));

        let mut s = String::new();
        client.get("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap();
        assert_eq!(s, "GET");

        let mut s = String::new();
        client.head("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap();
        assert_eq!(s, "");

        let mut s = String::new();
        client.post("http://127.0.0.1").send().unwrap().read_to_string(&mut s).unwrap();
        assert_eq!(s, "POST");
    }
    */
}
<|endoftext|>


<commit_before><commit_msg>(fix) Fixed infinite recursion for bare functions.<commit_after><|endoftext|>


<commit_before><commit_msg>day 21 solved.<commit_after>use std::cmp::max;
use std::io::prelude::*;
use std::fs::File;
use std::path::Path;

const INFTY: u32 = 1 << 30;

#[derive(Clone)]
struct Warrior {
    hp : u32,
    dmg: u32,
    arm: u32
}

impl Warrior {
    fn new(hp: u32, dmg: u32, arm: u32) -> Warrior {
        Warrior {
            hp : hp,
            dmg: dmg,
            arm: arm
        }
    }

    fn defeats(&self, w : Warrior) -> bool{ // self plays first
        let dmg_a = if self.dmg > w.arm {
            self.dmg - w.arm
        } else {
            1
        };
        let dmg_b = if w.dmg > self.arm {
            w.dmg - self.arm
        } else {
            1
        };
        let turns_a = if w.hp % dmg_a > 0 {
            w.hp / dmg_a + 1
        } else {
            w.hp / dmg_a
        };
        let turns_b = if self.hp % dmg_b > 0 {
            self.hp / dmg_b + 1
        } else {
            self.hp / dmg_b
        };
        turns_a <= turns_b
    }
}

fn main() {
    let mut f = File::open(Path::new("/Users/PetarV/rust-proj/advent-of-rust/target/input.txt"))
    	.ok()
    	.expect("Failed to open the input file!");

	let mut input = String::new();
	f.read_to_string(&mut input)
		.ok()
		.expect("Failed to read from the input file!");

    let weapons = vec![(8, 4, 0), (10, 5, 0), (25, 6, 0), (40, 7, 0), (74, 8, 0)];
    let armor = vec![(0, 0, 0), (13, 0, 1), (31, 0, 2), (53, 0, 3), (75, 0, 4), (102, 0, 5)];
    let rings = vec![(25, 1, 0), (50, 2, 0), (100, 3, 0), (20, 0, 1), (40, 0, 2), (80, 0, 3)];

    let mut hp = 0;
    let mut dmg = 0;
    let mut arm = 0;
    let mut ret = INFTY;

    for line in input.lines() {
        let parts: Vec<_> = line.split_whitespace().collect();
        if parts[0] == "Hit" {
            hp = parts[2].parse().ok().expect("Could not parse into an integer!");
        } else if parts[0] == "Damage:" {
            dmg = parts[1].parse().ok().expect("Could not parse into an integer!");
        } else if parts[0] == "Armor:" {
            arm = parts[1].parse().ok().expect("Could not parse into an integer!");
        }
    }

    let opponent = Warrior::new(hp, dmg, arm);

    hp = 100;
    arm = 0;
    let mut curr;

    for wpn in weapons.iter() {
        let (cost, damage, _) = *wpn;
        if cost >= ret {
            continue;
        }
        if Warrior::new(hp, damage, arm).defeats(opponent.clone()) {
            ret = cost;
            continue;
        }
        curr = cost;
        dmg = damage;
        for armr in armor.iter() {
            let (cost, _, armor) = *armr;
            if curr + cost >= ret {
                continue;
            }
            if Warrior::new(hp, dmg, armor).defeats(opponent.clone()) {
                ret = curr + cost;
                continue;
            }
            curr += cost;
            arm = armor;
            for (i, ring_1) in rings.iter().enumerate() {
                let (cost, damage, armor) = *ring_1;
                if curr + cost >= ret {
                    continue;
                }
                if Warrior::new(hp, dmg + damage, arm + armor).defeats(opponent.clone()) {
                    ret = curr + cost;
                    continue;
                }
                curr += cost;
                dmg += damage;
                arm += armor;
                for ring_2 in rings[i + 1..].iter() {
                    let (cost, damage, armor) = *ring_2;
                        if curr + cost >= ret {
                        continue;
                    }
                    if Warrior::new(hp, dmg + damage, arm + armor).defeats(opponent.clone()) {
                        ret = curr + cost;
                        continue;
                    }
                }
                curr -= cost;
                dmg -= damage;
                arm -= armor;
            }
            curr -= cost;
            arm -= armor;
        }
    }

    println!("The minimal amount of gold needed is {}.", ret);

    ret = 0;
    arm = 0;

    for wpn in weapons.iter() {
        let (cost, damage, _) = *wpn;
        if !Warrior::new(hp, damage, arm).defeats(opponent.clone()) {
            ret = max(ret, cost);
        } else {
            continue;
        }
        curr = cost;
        dmg = damage;
        for armr in armor.iter() {
            let (cost, _, armor) = *armr;
            if !Warrior::new(hp, dmg, armor).defeats(opponent.clone()) {
                ret = max(ret, curr + cost);
            } else {
                continue;
            }
            curr += cost;
            arm = armor;
            for (i, ring_1) in rings.iter().enumerate() {
                let (cost, damage, armor) = *ring_1;
                if !Warrior::new(hp, dmg + damage, arm + armor).defeats(opponent.clone()) {
                    ret = max(ret, curr + cost);
                } else {
                    continue;
                }
                curr += cost;
                dmg += damage;
                arm += armor;
                for ring_2 in rings[i + 1..].iter() {
                    let (cost, damage, armor) = *ring_2;
                    if !Warrior::new(hp, dmg + damage, arm + armor).defeats(opponent.clone()) {
                        ret = max(ret, curr + cost);
                    }
                }
                curr -= cost;
                dmg -= damage;
                arm -= armor;
            }
            curr -= cost;
            arm -= armor;
        }
    }

    println!("The maximal amount of gold possible is {}.", ret);
}<|endoftext|>


<commit_before><commit_msg>refactor(stack): make stack mor idiomatic<commit_after><|endoftext|>


<commit_before><commit_msg>autocommit 2015-05-16 17:35:23 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/.

#[prelude_import] use base::prelude::*;
use core::{mem};
use core::ops::{BitOr, Not, BitAnd};
use cty::{c_int, PATH_MAX, MNT_FORCE, MNT_DETACH, MNT_EXPIRE, UMOUNT_NOFOLLOW};
use fmt::{Debug, Write};
use syscall::{self};
use str_three::{ToCString};
use alloc::{FbHeap};
use rmo::{Rmo};

/// Unmounts a filesystem.
///
/// [argument, dst]
/// The path of the mountpoint to be unmounted.
///
/// [argument, flags]
/// The flags to be used to unmount the filesystem.
///
/// = Remarks
///
/// :flags: link:lrs::fs::flags
///
/// See {flags} for pre-defined unmount flags. If the path is relative, it is interpreted
/// relative to the current working directory.
///
/// = Examples
///
/// The example in link:lrs::fs::mount[mount] shows how to bind-mount a directory `a` at
/// the path `b`. The following example unmounts `b`.
///
/// ----
/// unmount("b", UNMOUNT_LAZY).unwrap();
/// ----
///
/// = See also
///
/// * link:man:unmount(2)
/// * {flags}
pub fn unmount<P>(dst: P, flags: UnmountFlags) -> Result
    where P: ToCString,
{
    let mut buf: [u8; PATH_MAX] = unsafe { mem::uninit() };
    let dst: Rmo<_, FbHeap> = try!(dst.rmo_cstr(&mut buf));
    rv!(syscall::umount(&dst, flags.0))
}

/// Flags used for unmounting.
///
/// = Remarks
///
/// :flags: link:lrs::fs::flags
///
/// See {flags} for pre-defined unmount flags.
///
/// = See also
///
/// * flags
pub struct UnmountFlags(c_int);

impl BitOr for UnmountFlags {
    type Output = UnmountFlags;
    fn bitor(self, other: UnmountFlags) -> UnmountFlags {
        UnmountFlags(self.0 | other.0)
    }
}

impl BitAnd for UnmountFlags {
    type Output = UnmountFlags;
    fn bitand(self, other: UnmountFlags) -> UnmountFlags {
        UnmountFlags(self.0 & other.0)
    }
}

impl Not for UnmountFlags {
    type Output = UnmountFlags;
    fn not(self) -> UnmountFlags {
        UnmountFlags(!self.0)
    }
}

pub const UNMOUNT_NONE: UnmountFlags = UnmountFlags(0);

macro_rules! create {
    ($($(#[$meta:meta])* flag $name:ident = $val:expr;)*) => {
        $($(#[$meta])* pub const $name: UnmountFlags = UnmountFlags($val);)*

        impl Debug for UnmountFlags {
            fn fmt<W: Write>(&self, w: &mut W) -> Result {
                let mut first = true;
                $(
                    if self.0 & $val != 0 {
                        if !first { try!(w.write(b"|")); }
                        first = false;
                        try!(w.write_all(stringify!($name).as_bytes()));
                    }
                )*
                let _ = first;
                Ok(())
            }
        }
    }
}

create! {
    #[doc = "Unmount the filesystem even if the device is busy.\n"]
    #[doc = "= Remarks"]
    #[doc = "This can cause data loss and only works on NFS mounts.\n"]
    #[doc = "= See also"]
    #[doc = "* link:man:umount(2) and MNT_FORCE therein"]
    flag UNMOUNT_FORCE = MNT_FORCE;

    #[doc = "Disallow further access to the mount point and unmount the device when the \
             last pending access has been completed.\n"]
    #[doc = "= See also"]
    #[doc = "* link:man:umount(2) and MNT_DETACH therein"]
    flag UNMOUNT_LAZY = MNT_DETACH;

    #[doc = "Set the \"expire\" flag on the filesystem.\n"]
    #[doc = "= Remarks"]
    #[doc = "The \"expire\" flag is automatically unset when the filesystem is accessed \
             again. If an unmount operation with this flag set is used and the \
             \"expire\" flag is already set on the filesystem, then the device is \
             unmounted.\n"]
    #[doc = "= See also"]
    #[doc = "* link:man:umount(2) and MNT_EXPIRE therein"]
    flag UNMOUNT_EXPIRE = MNT_EXPIRE;

    #[doc = "Don't follow the unmount path if it's a symbolic link.\n"]
    #[doc = "= See also"]
    #[doc = "* link:man:umount(2) and UMOUNT_NOFOLLOW therein"]
    flag UNMOUNT_NO_FOLLOW = UMOUNT_NOFOLLOW;
}

impl UnmountFlags {
    /// Sets a flag.
    ///
    /// [argument, flag]
    /// The flag to be set.
    pub fn set(&mut self, flag: UnmountFlags) {
        self.0 |= flag.0
    }

    /// Clears a flag.
    ///
    /// [argument, flag]
    /// The flag to be cleared.
    pub fn unset(&mut self, flag: UnmountFlags) {
        self.0 &= !flag.0
    }

    /// Returns whether a flag is set.
    ///
    /// [argument, flag]
    /// The flag to be checked.
    pub fn is_set(&self, flag: UnmountFlags) -> bool {
        self.0 & flag.0 != 0
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix character addition/deletion<commit_after><|endoftext|>


<commit_before><commit_msg>stdlib: Add missing unsafe.rs. Puts out burning tinderbox.<commit_after>// Unsafe operations.

native "rust-intrinsic" mod rusti {
    fn cast[T,U](&T src) -> U;
}

// Casts the value at `src` to U. The two types must have the same length.
fn reinterpret_cast[T,U](&T src) -> U { ret rusti::cast(src); }

<|endoftext|>