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

//! # The Rust Standard Library
//!
//! The Rust Standard Library provides the essential runtime
//! functionality for building portable Rust software.
//!
//! The rust standard library is available to all rust crates by
//! default, just as if contained an `extern crate std` import at the
//! crate root. Therefore the standard library can be accessed in
//! `use` statements through the path `std`, as in `use std::thread`,
//! or in expressions through the absolute path `::std`, as in
//! `::std::thread::sleep_ms(100)`.
//!
//! Furthermore, the standard library defines [The Rust
//! Prelude](prelude/index.html), a small collection of items, mostly
//! traits, that are imported into and available in every module.
//!
//! ## What is in the standard library
//!
//! The standard library is minimal, a set of battle-tested
//! core types and shared abstractions for the [broader Rust
//! ecosystem][https://crates.io] to build on.
//!
//! The [primitive types](#primitives), though not defined in the
//! standard library, are documented here, as are the predefined
//! [macros](#macros).
//!
//! ## Containers and collections
//!
//! The [`option`](option/index.html) and
//! [`result`](result/index.html) modules define optional and
//! error-handling types, `Option` and `Result`. The
//! [`iter`](iter/index.html) module defines Rust's iterator trait,
//! [`Iterater`](iter/trait.Iterator.html), which works with the `for`
//! loop to access collections.
//!
//! The common container type, `Vec`, a growable vector backed by an array,
//! lives in the [`vec`](vec/index.html) module. Contiguous, unsized regions
//! of memory, `[T]`, commonly called "slices", and their borrowed versions,
//! `&[T]`, commonly called "borrowed slices", are built-in types for which the
//! [`slice`](slice/index.html) module defines many methods.
//!
//! `&str`, a UTF-8 string, is a built-in type, and the standard library
//! defines methods for it on a variety of traits in the
//! [`str`](str/index.html) module. Rust strings are immutable;
//! use the `String` type defined in [`string`](string/index.html)
//! for a mutable string builder.
//!
//! For converting to strings use the [`format!`](fmt/index.html)
//! macro, and for converting from strings use the
//! [`FromStr`](str/trait.FromStr.html) trait.
//!
//! Data may be shared by placing it in a reference-counted box or the
//! [`Rc`][rc/index.html] type, and if further contained in a [`Cell`
//! or `RefCell`](cell/index.html), may be mutated as well as shared.
//! Likewise, in a concurrent setting it is common to pair an
//! atomically-reference-counted box, [`Arc`](sync/struct.Arc.html),
//! with a [`Mutex`](sync/struct.Mutex.html) to get the same effect.
//!
//! The [`collections`](collections/index.html) module defines maps,
//! sets, linked lists and other typical collection types, including
//! the common [`HashMap`](collections/struct.HashMap.html).
//!
//! ## Platform abstractions and I/O
//!
//! Besides basic data types, the standard library is largely concerned
//! with abstracting over differences in common platforms, most notably
//! Windows and Unix derivatives.
//!
//! Common types of I/O, including [files](fs/struct.File.html),
//! [TCP](net/struct.TcpStream.html),
//! [UDP](net/struct.UdpSocket.html), are defined in the
//! [`io`](io/index.html), [`fs`](fs/index.html), and
//! [`net`](net/index.html) modules.
//!
//! The [`thread`](thread/index.html) module contains Rust's threading
//! abstractions. [`sync`](sync/index.html) contains further
//! primitive shared memory types, including
//! [`atomic`](sync/atomic/index.html) and
//! [`mpsc`](sync/mpsc/index.html), which contains the channel types
//! for message passing.

// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "std"]
#![stable(feature = "rust1", since = "1.0.0")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
       html_root_url = "http://doc.rust-lang.org/nightly/",
       html_playground_url = "http://play.rust-lang.org/")]
#![doc(test(no_crate_inject, attr(deny(warnings))))]
#![doc(test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]

#![feature(alloc)]
#![feature(allow_internal_unstable)]
#![feature(associated_consts)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(debug_builders)]
#![feature(into_cow)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(linkage, thread_local, asm)]
#![feature(macro_reexport)]
#![feature(optin_builtin_traits)]
#![feature(rand)]
#![feature(slice_patterns)]
#![feature(staged_api)]
#![feature(std_misc)]
#![feature(str_char)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unique)]
#![feature(unsafe_no_drop_flag, filling_drop)]
#![feature(zero_one)]
#![cfg_attr(test, feature(float_from_str_radix))]
#![cfg_attr(test, feature(test, rustc_private, std_misc))]

// Don't link to std. We are std.
#![feature(no_std)]
#![no_std]

#![allow(trivial_casts)]
#![deny(missing_docs)]

#[cfg(test)] extern crate test;
#[cfg(test)] #[macro_use] extern crate log;

#[macro_use]
#[macro_reexport(assert, assert_eq, debug_assert, debug_assert_eq,
    unreachable, unimplemented, write, writeln)]
extern crate core;

#[macro_use]
#[macro_reexport(vec, format)]
extern crate collections as core_collections;

#[allow(deprecated)] extern crate rand as core_rand;
extern crate alloc;
extern crate rustc_unicode;
extern crate libc;

#[macro_use] #[no_link] extern crate rustc_bitflags;

// Make std testable by not duplicating lang items. See #2912
#[cfg(test)] extern crate std as realstd;
#[cfg(test)] pub use realstd::marker;
#[cfg(test)] pub use realstd::ops;
#[cfg(test)] pub use realstd::cmp;
#[cfg(test)] pub use realstd::boxed;

// NB: These reexports are in the order they should be listed in rustdoc

pub use core::any;
pub use core::cell;
pub use core::clone;
#[cfg(not(test))] pub use core::cmp;
pub use core::convert;
pub use core::default;
pub use core::hash;
pub use core::intrinsics;
pub use core::iter;
#[cfg(not(test))] pub use core::marker;
pub use core::mem;
#[cfg(not(test))] pub use core::ops;
pub use core::ptr;
pub use core::raw;
pub use core::simd;
pub use core::result;
pub use core::option;
pub mod error;

#[cfg(not(test))] pub use alloc::boxed;
pub use alloc::rc;

pub use core_collections::borrow;
pub use core_collections::fmt;
pub use core_collections::slice;
pub use core_collections::str;
pub use core_collections::string;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core_collections::vec;

pub use rustc_unicode::char;

/* Exported macros */

#[macro_use]
mod macros;

mod rtdeps;

/* The Prelude. */

pub mod prelude;

/* Primitive types */

// NB: slice and str are primitive types too, but their module docs + primitive doc pages
// are inlined from the public re-exports of core_collections::{slice, str} above.

#[path = "num/float_macros.rs"]
#[macro_use]
mod float_macros;

#[path = "num/int_macros.rs"]
#[macro_use]
mod int_macros;

#[path = "num/uint_macros.rs"]
#[macro_use]
mod uint_macros;

#[path = "num/isize.rs"]  pub mod isize;
#[path = "num/i8.rs"]   pub mod i8;
#[path = "num/i16.rs"]  pub mod i16;
#[path = "num/i32.rs"]  pub mod i32;
#[path = "num/i64.rs"]  pub mod i64;

#[path = "num/usize.rs"] pub mod usize;
#[path = "num/u8.rs"]   pub mod u8;
#[path = "num/u16.rs"]  pub mod u16;
#[path = "num/u32.rs"]  pub mod u32;
#[path = "num/u64.rs"]  pub mod u64;

#[path = "num/f32.rs"]   pub mod f32;
#[path = "num/f64.rs"]   pub mod f64;

pub mod ascii;

pub mod thunk;

/* Common traits */

pub mod num;

/* Runtime and platform support */

#[macro_use]
pub mod thread;

pub mod collections;
pub mod dynamic_lib;
pub mod env;
pub mod ffi;
pub mod fs;
pub mod io;
pub mod net;
pub mod os;
pub mod path;
pub mod process;
pub mod sync;
pub mod time;

#[macro_use]
#[path = "sys/common/mod.rs"] mod sys_common;

#[cfg(unix)]
#[path = "sys/unix/mod.rs"] mod sys;
#[cfg(windows)]
#[path = "sys/windows/mod.rs"] mod sys;

pub mod rt;
mod panicking;
mod rand;

// Some external utilities of the standard library rely on randomness (aka
// rustc_back::TempDir and tests) and need a way to get at the OS rng we've got
// here. This module is not at all intended for stabilization as-is, however,
// but it may be stabilized long-term. As a result we're exposing a hidden,
// unstable module so we can get our build working.
#[doc(hidden)]
#[unstable(feature = "rand")]
pub mod __rand {
    pub use rand::{thread_rng, ThreadRng, Rng};
}

// Modules that exist purely to document + host impl docs for primitive types

mod array;
mod bool;
mod unit;
mod tuple;

// A curious inner-module that's not exported that contains the binding
// 'std' so that macro-expanded references to std::error and such
// can be resolved within libstd.
#[doc(hidden)]
mod std {
    pub use sync; // used for select!()
    pub use error; // used for try!()
    pub use fmt; // used for any formatting strings
    pub use option; // used for thread_local!{}
    pub use rt; // used for panic!()
    pub use vec; // used for vec![]
    pub use cell; // used for tls!
    pub use thread; // used for thread_local!
    pub use marker;  // used for tls!

    // The test runner calls ::std::env::args() but really wants realstd
    #[cfg(test)] pub use realstd::env as env;
    // The test runner requires std::slice::Vector, so re-export std::slice just for it.
    //
    // It is also used in vec![]
    pub use slice;

    pub use boxed; // used for vec![]
}
<commit_msg>Fix crates.io link.<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! # The Rust Standard Library
//!
//! The Rust Standard Library provides the essential runtime
//! functionality for building portable Rust software.
//!
//! The rust standard library is available to all rust crates by
//! default, just as if contained an `extern crate std` import at the
//! crate root. Therefore the standard library can be accessed in
//! `use` statements through the path `std`, as in `use std::thread`,
//! or in expressions through the absolute path `::std`, as in
//! `::std::thread::sleep_ms(100)`.
//!
//! Furthermore, the standard library defines [The Rust
//! Prelude](prelude/index.html), a small collection of items, mostly
//! traits, that are imported into and available in every module.
//!
//! ## What is in the standard library
//!
//! The standard library is minimal, a set of battle-tested
//! core types and shared abstractions for the [broader Rust
//! ecosystem](https://crates.io) to build on.
//!
//! The [primitive types](#primitives), though not defined in the
//! standard library, are documented here, as are the predefined
//! [macros](#macros).
//!
//! ## Containers and collections
//!
//! The [`option`](option/index.html) and
//! [`result`](result/index.html) modules define optional and
//! error-handling types, `Option` and `Result`. The
//! [`iter`](iter/index.html) module defines Rust's iterator trait,
//! [`Iterater`](iter/trait.Iterator.html), which works with the `for`
//! loop to access collections.
//!
//! The common container type, `Vec`, a growable vector backed by an array,
//! lives in the [`vec`](vec/index.html) module. Contiguous, unsized regions
//! of memory, `[T]`, commonly called "slices", and their borrowed versions,
//! `&[T]`, commonly called "borrowed slices", are built-in types for which the
//! [`slice`](slice/index.html) module defines many methods.
//!
//! `&str`, a UTF-8 string, is a built-in type, and the standard library
//! defines methods for it on a variety of traits in the
//! [`str`](str/index.html) module. Rust strings are immutable;
//! use the `String` type defined in [`string`](string/index.html)
//! for a mutable string builder.
//!
//! For converting to strings use the [`format!`](fmt/index.html)
//! macro, and for converting from strings use the
//! [`FromStr`](str/trait.FromStr.html) trait.
//!
//! Data may be shared by placing it in a reference-counted box or the
//! [`Rc`][rc/index.html] type, and if further contained in a [`Cell`
//! or `RefCell`](cell/index.html), may be mutated as well as shared.
//! Likewise, in a concurrent setting it is common to pair an
//! atomically-reference-counted box, [`Arc`](sync/struct.Arc.html),
//! with a [`Mutex`](sync/struct.Mutex.html) to get the same effect.
//!
//! The [`collections`](collections/index.html) module defines maps,
//! sets, linked lists and other typical collection types, including
//! the common [`HashMap`](collections/struct.HashMap.html).
//!
//! ## Platform abstractions and I/O
//!
//! Besides basic data types, the standard library is largely concerned
//! with abstracting over differences in common platforms, most notably
//! Windows and Unix derivatives.
//!
//! Common types of I/O, including [files](fs/struct.File.html),
//! [TCP](net/struct.TcpStream.html),
//! [UDP](net/struct.UdpSocket.html), are defined in the
//! [`io`](io/index.html), [`fs`](fs/index.html), and
//! [`net`](net/index.html) modules.
//!
//! The [`thread`](thread/index.html) module contains Rust's threading
//! abstractions. [`sync`](sync/index.html) contains further
//! primitive shared memory types, including
//! [`atomic`](sync/atomic/index.html) and
//! [`mpsc`](sync/mpsc/index.html), which contains the channel types
//! for message passing.

// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "std"]
#![stable(feature = "rust1", since = "1.0.0")]
#![staged_api]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
       html_favicon_url = "http://www.rust-lang.org/favicon.ico",
       html_root_url = "http://doc.rust-lang.org/nightly/",
       html_playground_url = "http://play.rust-lang.org/")]
#![doc(test(no_crate_inject, attr(deny(warnings))))]
#![doc(test(attr(allow(dead_code, deprecated, unused_variables, unused_mut))))]

#![feature(alloc)]
#![feature(allow_internal_unstable)]
#![feature(associated_consts)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(debug_builders)]
#![feature(into_cow)]
#![feature(lang_items)]
#![feature(libc)]
#![feature(linkage, thread_local, asm)]
#![feature(macro_reexport)]
#![feature(optin_builtin_traits)]
#![feature(rand)]
#![feature(slice_patterns)]
#![feature(staged_api)]
#![feature(std_misc)]
#![feature(str_char)]
#![feature(unboxed_closures)]
#![feature(unicode)]
#![feature(unique)]
#![feature(unsafe_no_drop_flag, filling_drop)]
#![feature(zero_one)]
#![cfg_attr(test, feature(float_from_str_radix))]
#![cfg_attr(test, feature(test, rustc_private, std_misc))]

// Don't link to std. We are std.
#![feature(no_std)]
#![no_std]

#![allow(trivial_casts)]
#![deny(missing_docs)]

#[cfg(test)] extern crate test;
#[cfg(test)] #[macro_use] extern crate log;

#[macro_use]
#[macro_reexport(assert, assert_eq, debug_assert, debug_assert_eq,
    unreachable, unimplemented, write, writeln)]
extern crate core;

#[macro_use]
#[macro_reexport(vec, format)]
extern crate collections as core_collections;

#[allow(deprecated)] extern crate rand as core_rand;
extern crate alloc;
extern crate rustc_unicode;
extern crate libc;

#[macro_use] #[no_link] extern crate rustc_bitflags;

// Make std testable by not duplicating lang items. See #2912
#[cfg(test)] extern crate std as realstd;
#[cfg(test)] pub use realstd::marker;
#[cfg(test)] pub use realstd::ops;
#[cfg(test)] pub use realstd::cmp;
#[cfg(test)] pub use realstd::boxed;

// NB: These reexports are in the order they should be listed in rustdoc

pub use core::any;
pub use core::cell;
pub use core::clone;
#[cfg(not(test))] pub use core::cmp;
pub use core::convert;
pub use core::default;
pub use core::hash;
pub use core::intrinsics;
pub use core::iter;
#[cfg(not(test))] pub use core::marker;
pub use core::mem;
#[cfg(not(test))] pub use core::ops;
pub use core::ptr;
pub use core::raw;
pub use core::simd;
pub use core::result;
pub use core::option;
pub mod error;

#[cfg(not(test))] pub use alloc::boxed;
pub use alloc::rc;

pub use core_collections::borrow;
pub use core_collections::fmt;
pub use core_collections::slice;
pub use core_collections::str;
pub use core_collections::string;
#[stable(feature = "rust1", since = "1.0.0")]
pub use core_collections::vec;

pub use rustc_unicode::char;

/* Exported macros */

#[macro_use]
mod macros;

mod rtdeps;

/* The Prelude. */

pub mod prelude;

/* Primitive types */

// NB: slice and str are primitive types too, but their module docs + primitive doc pages
// are inlined from the public re-exports of core_collections::{slice, str} above.

#[path = "num/float_macros.rs"]
#[macro_use]
mod float_macros;

#[path = "num/int_macros.rs"]
#[macro_use]
mod int_macros;

#[path = "num/uint_macros.rs"]
#[macro_use]
mod uint_macros;

#[path = "num/isize.rs"]  pub mod isize;
#[path = "num/i8.rs"]   pub mod i8;
#[path = "num/i16.rs"]  pub mod i16;
#[path = "num/i32.rs"]  pub mod i32;
#[path = "num/i64.rs"]  pub mod i64;

#[path = "num/usize.rs"] pub mod usize;
#[path = "num/u8.rs"]   pub mod u8;
#[path = "num/u16.rs"]  pub mod u16;
#[path = "num/u32.rs"]  pub mod u32;
#[path = "num/u64.rs"]  pub mod u64;

#[path = "num/f32.rs"]   pub mod f32;
#[path = "num/f64.rs"]   pub mod f64;

pub mod ascii;

pub mod thunk;

/* Common traits */

pub mod num;

/* Runtime and platform support */

#[macro_use]
pub mod thread;

pub mod collections;
pub mod dynamic_lib;
pub mod env;
pub mod ffi;
pub mod fs;
pub mod io;
pub mod net;
pub mod os;
pub mod path;
pub mod process;
pub mod sync;
pub mod time;

#[macro_use]
#[path = "sys/common/mod.rs"] mod sys_common;

#[cfg(unix)]
#[path = "sys/unix/mod.rs"] mod sys;
#[cfg(windows)]
#[path = "sys/windows/mod.rs"] mod sys;

pub mod rt;
mod panicking;
mod rand;

// Some external utilities of the standard library rely on randomness (aka
// rustc_back::TempDir and tests) and need a way to get at the OS rng we've got
// here. This module is not at all intended for stabilization as-is, however,
// but it may be stabilized long-term. As a result we're exposing a hidden,
// unstable module so we can get our build working.
#[doc(hidden)]
#[unstable(feature = "rand")]
pub mod __rand {
    pub use rand::{thread_rng, ThreadRng, Rng};
}

// Modules that exist purely to document + host impl docs for primitive types

mod array;
mod bool;
mod unit;
mod tuple;

// A curious inner-module that's not exported that contains the binding
// 'std' so that macro-expanded references to std::error and such
// can be resolved within libstd.
#[doc(hidden)]
mod std {
    pub use sync; // used for select!()
    pub use error; // used for try!()
    pub use fmt; // used for any formatting strings
    pub use option; // used for thread_local!{}
    pub use rt; // used for panic!()
    pub use vec; // used for vec![]
    pub use cell; // used for tls!
    pub use thread; // used for thread_local!
    pub use marker;  // used for tls!

    // The test runner calls ::std::env::args() but really wants realstd
    #[cfg(test)] pub use realstd::env as env;
    // The test runner requires std::slice::Vector, so re-export std::slice just for it.
    //
    // It is also used in vec![]
    pub use slice;

    pub use boxed; // used for vec![]
}
<|endoftext|>


<commit_before><commit_msg>Sign transaction unittest a little bit cryptic<commit_after><|endoftext|>


<commit_before><commit_msg>Shell::readln now completes to a filename if the last word is a file  (#342)<commit_after><|endoftext|>


<commit_before><commit_msg>sysftest<commit_after>#[cfg(unix)]
#[cfg(test)]
mod sysfstest {
	use super::*;

	#[test]
	fn test_testing() {
		assert_eq!(1,1);
	}
}
<|endoftext|>


<commit_before><commit_msg>Add code for spiral-matrix<commit_after>fn spiral_index(x: i32, y: i32) -> i32 {
    let mut p: i32;

    if y * y >= x * x {
        p = 4 * y * y - y - x;
        if y < x {
            p -= 2 * (y - x);
        }
    } else {
        p = 4 * x * x - y - x;
        if y < x {
            p += 2 * (y - x);
        }
    }

    p
}

pub fn spiral_matrix(size: u32) -> Vec<Vec<u32>> {
    let mut result = Vec::new();

    if size == 0 {
        return result;
    }

    let width: i32 = size as i32;

    let sx = if width % 2 == 1 {
        width / 2
    } else {
        (1 - width) / 2
    };
    let ex = if width % 2 == 1 {
        (1 - width) / 2 - 1
    } else {
        width / 2 + 1
    };
    let dx = if width % 2 == 1 { -1 } else { 1 };
    let sy = if width % 2 == 1 {
        (1 - width) / 2
    } else {
        width / 2
    };
    let ey = if width % 2 == 1 {
        width / 2 + 1
    } else {
        (1 - width) / 2 - 1
    };
    let dy = if width % 2 == 1 { 1 } else { -1 };

    let mut y = sy;
    while y != ey {
        let mut v = Vec::new();

        let mut x = sx;
        while x != ex {
            let r = width * width - spiral_index(x, y);
            v.push(r as u32);
            x += dx;
        }

        result.push(v);
        y += dy;
    }

    result
}
<|endoftext|>


<commit_before><commit_msg>Clarify whether password is optional in registration endpoint.<commit_after><|endoftext|>


<commit_before><commit_msg>Implement SIGINT Control Flow Logic Abortion<commit_after><|endoftext|>


<commit_before>use std::path::{Path, PathBuf, Component};
use std::error::Error;
use std::fs::{self, metadata, File};

/// This is copied from the rust source code until Path_ Ext stabilizes.
/// You can use it, but be aware that it will be removed when those features go to rust stable
pub trait PathExt {
    fn exists(&self) -> bool;
    fn is_file(&self) -> bool;
    fn is_dir(&self) -> bool;
}

impl PathExt for Path {
    fn exists(&self) -> bool {
        metadata(self).is_ok()
    }

    fn is_file(&self) -> bool {
       metadata(self).map(|s| s.is_file()).unwrap_or(false)
    }

    fn is_dir(&self) -> bool {
       metadata(self).map(|s| s.is_dir()).unwrap_or(false)
    }
}

/// Takes a path and returns a path containing just enough `../` to point to the root of the given path.
///
/// This is mostly interesting for a relative path to point back to the directory from where the
/// path starts.
///
/// ```ignore
/// let mut path = Path::new("some/relative/path");
///
/// println!("{}", path_to_root(&path));
/// ```
///
/// **Outputs**
///
/// ```text
/// "../../"
/// ```
///
/// **note:** it's not very fool-proof, if you find a situation where it doesn't return the correct
/// path. Consider [submitting a new issue](https://github.com/azerupi/mdBook/issues) or a
/// [pull-request](https://github.com/azerupi/mdBook/pulls) to improve it.

pub fn path_to_root(path: &Path) -> String {
    debug!("[fn]: path_to_root");
    // Remove filename and add "../" for every directory

    path.to_path_buf().parent().expect("")
        .components().fold(String::new(), |mut s, c| {
            match c {
                Component::Normal(_) => s.push_str("../"),
                _ => {
                    debug!("[*]: Other path component... {:?}", c);
                }
            }
            s
        })
}

/// This function checks for every component in a path if the directory exists,
/// if it does not it is created.

pub fn create_path(path: &Path) -> Result<(), Box<Error>> {
    debug!("[fn]: create_path");

    // Create directories if they do not exist
    let mut constructed_path = PathBuf::new();

    for component in path.components() {

        let mut dir;
        match component {
            Component::Normal(_) => { dir = PathBuf::from(component.as_os_str()); },
            Component::RootDir => {
                debug!("[*]: Root directory");
                // This doesn't look very compatible with Windows...
                constructed_path.push("/");
                continue
            },
            _ => continue,
        }

        constructed_path.push(&dir);
        debug!("[*]: {:?}", constructed_path);

        if !constructed_path.exists() || !constructed_path.is_dir() {
            try!(fs::create_dir(&constructed_path));
            debug!("[*]: Directory created {:?}", constructed_path);
        } else {
            debug!("[*]: Directory exists {:?}", constructed_path);
            continue
        }

    }

    debug!("[*]: Constructed path: {:?}", constructed_path);

    Ok(())
}

/// This function creates a file and returns it. But before creating the file it checks every
/// directory in the path to see if it exists, and if it does not it will be created.

pub fn create_file(path: &Path) -> Result<File, Box<Error>> {
    debug!("[fn]: create_file");

    // Construct path
    if let Some(p) = path.parent() {
        try!(create_path(p));
    }

    debug!("[*]: Create file: {:?}", path);
    let f = try!(File::create(path));

    Ok(f)
}

/// Removes all the content of a directory but not the directory itself

pub fn remove_dir_content(dir: &Path) -> Result<(), Box<Error>> {
    for item in try!(fs::read_dir(dir)) {
        if let Ok(item) = item {
            let item = item.path();
            if item.is_dir() { try!(fs::remove_dir_all(item)); } else { try!(fs::remove_file(item)); }
        }
    }
    Ok(())
}

/// **Untested!**
///
/// Copies all files of a directory to another one except the files with the extensions given in the
/// `ext_blacklist` array

pub fn copy_files_except_ext(from: &Path, to: &Path, recursive: bool, ext_blacklist: &[String]) -> Result<(), Box<Error>> {

    // Check that from and to are different
    if from == to { return Ok(()) }

    for entry in try!(fs::read_dir(from)) {
        let entry = try!(entry);
        let metadata = try!(entry.metadata());

        // If the entry is a dir and the recursive option is enabled, call itself
        if metadata.is_dir() && recursive {
            try!(copy_files_except_ext(
                &from.join(entry.file_name()),
                &to.join(entry.file_name()),
                true,
                ext_blacklist
            ));
        } else if metadata.is_file() {

            // Check if it is in the blacklist
            if let Some(ext) = entry.path().extension() {
                if ext_blacklist.contains(&String::from(ext.to_str().unwrap())) { continue }

                try!(fs::copy(entry.path(), &to.join(entry.path().file_name().expect("a file should have a file name..."))));
            }
        }
    }
    Ok(())
}
<commit_msg>Added my first test!! :) For copy_files_except_ext function<commit_after>use std::path::{Path, PathBuf, Component};
use std::error::Error;
use std::fs::{self, metadata, File};

/// This is copied from the rust source code until Path_ Ext stabilizes.
/// You can use it, but be aware that it will be removed when those features go to rust stable
pub trait PathExt {
    fn exists(&self) -> bool;
    fn is_file(&self) -> bool;
    fn is_dir(&self) -> bool;
}

impl PathExt for Path {
    fn exists(&self) -> bool {
        metadata(self).is_ok()
    }

    fn is_file(&self) -> bool {
       metadata(self).map(|s| s.is_file()).unwrap_or(false)
    }

    fn is_dir(&self) -> bool {
       metadata(self).map(|s| s.is_dir()).unwrap_or(false)
    }
}

/// Takes a path and returns a path containing just enough `../` to point to the root of the given path.
///
/// This is mostly interesting for a relative path to point back to the directory from where the
/// path starts.
///
/// ```ignore
/// let mut path = Path::new("some/relative/path");
///
/// println!("{}", path_to_root(&path));
/// ```
///
/// **Outputs**
///
/// ```text
/// "../../"
/// ```
///
/// **note:** it's not very fool-proof, if you find a situation where it doesn't return the correct
/// path. Consider [submitting a new issue](https://github.com/azerupi/mdBook/issues) or a
/// [pull-request](https://github.com/azerupi/mdBook/pulls) to improve it.

pub fn path_to_root(path: &Path) -> String {
    debug!("[fn]: path_to_root");
    // Remove filename and add "../" for every directory

    path.to_path_buf().parent().expect("")
        .components().fold(String::new(), |mut s, c| {
            match c {
                Component::Normal(_) => s.push_str("../"),
                _ => {
                    debug!("[*]: Other path component... {:?}", c);
                }
            }
            s
        })
}

/// This function checks for every component in a path if the directory exists,
/// if it does not it is created.

pub fn create_path(path: &Path) -> Result<(), Box<Error>> {
    debug!("[fn]: create_path");

    // Create directories if they do not exist
    let mut constructed_path = PathBuf::new();

    for component in path.components() {

        let mut dir;
        match component {
            Component::Normal(_) => { dir = PathBuf::from(component.as_os_str()); },
            Component::RootDir => {
                debug!("[*]: Root directory");
                // This doesn't look very compatible with Windows...
                constructed_path.push("/");
                continue
            },
            _ => continue,
        }

        constructed_path.push(&dir);
        debug!("[*]: {:?}", constructed_path);

        if !constructed_path.exists() || !constructed_path.is_dir() {
            try!(fs::create_dir(&constructed_path));
            debug!("[*]: Directory created {:?}", constructed_path);
        } else {
            debug!("[*]: Directory exists {:?}", constructed_path);
            continue
        }

    }

    debug!("[*]: Constructed path: {:?}", constructed_path);

    Ok(())
}

/// This function creates a file and returns it. But before creating the file it checks every
/// directory in the path to see if it exists, and if it does not it will be created.

pub fn create_file(path: &Path) -> Result<File, Box<Error>> {
    debug!("[fn]: create_file");

    // Construct path
    if let Some(p) = path.parent() {
        try!(create_path(p));
    }

    debug!("[*]: Create file: {:?}", path);
    let f = try!(File::create(path));

    Ok(f)
}

/// Removes all the content of a directory but not the directory itself

pub fn remove_dir_content(dir: &Path) -> Result<(), Box<Error>> {
    for item in try!(fs::read_dir(dir)) {
        if let Ok(item) = item {
            let item = item.path();
            if item.is_dir() { try!(fs::remove_dir_all(item)); } else { try!(fs::remove_file(item)); }
        }
    }
    Ok(())
}

/// **Untested!**
///
/// Copies all files of a directory to another one except the files with the extensions given in the
/// `ext_blacklist` array

pub fn copy_files_except_ext(from: &Path, to: &Path, recursive: bool, ext_blacklist: &[&str]) -> Result<(), Box<Error>> {

    // Check that from and to are different
    if from == to { return Ok(()) }
    println!("[*] Loop");
    for entry in try!(fs::read_dir(from)) {
        let entry = try!(entry);
        println!("[*] {:?}", entry.path());
        let metadata = try!(entry.metadata());

        // If the entry is a dir and the recursive option is enabled, call itself
        if metadata.is_dir() && recursive {
            if entry.path() == to.to_path_buf() { continue }
            println!("[*] is dir");
            try!(fs::create_dir(&to.join(entry.file_name())));
            try!(copy_files_except_ext(
                &from.join(entry.file_name()),
                &to.join(entry.file_name()),
                true,
                ext_blacklist
            ));
        } else if metadata.is_file() {

            // Check if it is in the blacklist
            if let Some(ext) = entry.path().extension() {
                if ext_blacklist.contains(&ext.to_str().unwrap()) { continue }
                println!("[*] creating path for file: {:?}", &to.join(entry.path().file_name().expect("a file should have a file name...")));
                //try!(create_path(&to.join(entry.path())));
                println!("[*] creating file: {:?}", &to.join(entry.path().file_name().expect("a file should have a file name...")));
                try!(fs::copy(entry.path(), &to.join(entry.path().file_name().expect("a file should have a file name..."))));
            }
        }
    }
    Ok(())
}

// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------

// tests

#[cfg(test)]
mod tests {
    extern crate tempdir;

    use super::copy_files_except_ext;
    use super::PathExt;
    use std::fs;

    #[test]
    fn copy_files_except_ext_test() {
        let tmp = match tempdir::TempDir::new("") {
            Ok(t) => t,
            Err(_) => panic!("Could not create a temp dir"),
        };

        // Create a couple of files
        if let Err(_) =  fs::File::create(&tmp.path().join("file.txt")) { panic!("Could not create file.txt") }
        if let Err(_) =  fs::File::create(&tmp.path().join("file.md")) { panic!("Could not create file.md") }
        if let Err(_) =  fs::File::create(&tmp.path().join("file.png")) { panic!("Could not create file.png") }
        if let Err(_) =  fs::create_dir(&tmp.path().join("sub_dir")) { panic!("Could not create sub_dir") }
        if let Err(_) =  fs::File::create(&tmp.path().join("sub_dir/file.png")) { panic!("Could not create sub_dir/file.png") }

        // Create output dir
        if let Err(_) =  fs::create_dir(&tmp.path().join("output")) { panic!("Could not create output") }

        match copy_files_except_ext(&tmp.path(), &tmp.path().join("output"), true, &["md"]) {
            Err(e) => panic!("Error while executing the function:\n{:?}", e),
            Ok(_) => {},
        }

        // Check if the correct files where created
        for entry in fs::read_dir(&tmp.path().join("output")).unwrap() {
            println!("{:?}", entry.ok().unwrap().path())
        }

        if !(&tmp.path().join("output/file.txt")).exists() { panic!("output/file.txt should exist") }
        if (&tmp.path().join("output/file.md")).exists() { panic!("output/file.md should not exist") }
        if !(&tmp.path().join("output/file.png")).exists() { panic!("output/file.png should exist") }
        if !(&tmp.path().join("output/sub_dir/file.png")).exists() { panic!("output/sub_dir/file.png should exist") }

    }
}
<|endoftext|>


<commit_before><commit_msg>Wrap parser in Rust<commit_after>mod ffi {
#![allow(dead_code)]
#![allow(non_camel_case_types)]

include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
}

use std::ptr;
use std::ffi::CStr;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use std::os::raw::*;

pub use self::ffi::ParseTreeNodeType as ParseTreeNodeType;
pub use self::ffi::ParseTreeOperatorType as ParseTreeOperatorType;
pub use self::ffi::ParseTreeRangeDirection as ParseTreeRangeDirection;
pub use self::ffi::ParseTreeForceMode as ParseTreeForceMode;
pub use self::ffi::ParseTreeFunctionPurity as ParseTreeFunctionPurity;
pub use self::ffi::ParseTreeInterfaceObjectMode as ParseTreeInterfaceObjectMode;
pub use self::ffi::ParseTreeSubprogramKind as ParseTreeSubprogramKind;
pub use self::ffi::ParseTreeEntityClass as ParseTreeEntityClass;
pub use self::ffi::ParseTreeSignalKind as ParseTreeSignalKind;

// FIXME: Copypasta problems?
pub struct VhdlParseTreeNode {
    pub node_type: ParseTreeNodeType,
    pub str1: String,
    pub str2: String,
    pub chr: u8,
    pub integer: i32,
    pub boolean: bool,
    pub boolean2: bool,
    pub boolean3: bool,
    pub pieces: Vec<VhdlParseTreeNode>,
    pub op_type: ParseTreeOperatorType,
    pub range_dir: ParseTreeRangeDirection,
    pub force_mode: ParseTreeForceMode,
    pub purity: ParseTreeFunctionPurity,
    pub interface_mode: ParseTreeInterfaceObjectMode,
    pub subprogram_kind: ParseTreeSubprogramKind,
    pub entity_class: ParseTreeEntityClass,
    pub signal_kind: ParseTreeSignalKind,
    pub first_line: i32,
    pub first_column: i32,
    pub last_line: i32,
    pub last_column: i32,

    raw_node: *mut ffi::VhdlParseTreeNode
}

unsafe fn rustify_str(input: *mut c_char) -> String {
    // Get the string into something Rust can handle
    let string_rs = CStr::from_ptr(input);
    let string_rs = String::from(string_rs.to_str().unwrap());
    // Free the C string
    ffi::VhdlParserFreeString(input);

    string_rs
}

unsafe fn rustify_stdstring(input: *mut c_void) -> String {
    let null_terminated_string = ffi::VhdlParserCifyString(input);
    rustify_str(null_terminated_string)
}

unsafe fn rustify_node(
    input: *mut ffi::VhdlParseTreeNode) -> VhdlParseTreeNode {

    let str1 = rustify_stdstring((*input).str);
    let str2 = rustify_stdstring((*input).str2);

    let mut inner_nodes = Vec::with_capacity(ffi::NUM_FIXED_PIECES as usize);
    // Recursively convert inner nodes first
    for i in 0..ffi::NUM_FIXED_PIECES {
        let this_child = (*input).pieces[i as usize];
        if this_child.is_null() {
            break;
        }
        inner_nodes.push(rustify_node(this_child));
    }

    let ret = VhdlParseTreeNode {
        node_type: (*input).type_,
        chr: (*input).chr as u8,
        integer: (*input).integer,
        boolean: (*input).boolean,
        boolean2: (*input).boolean2,
        boolean3: (*input).boolean3,
        op_type: (*input).op_type,
        range_dir: (*input).range_dir,
        force_mode: (*input).force_mode,
        purity: (*input).purity,
        interface_mode: (*input).interface_mode,
        subprogram_kind: (*input).subprogram_kind,
        entity_class: (*input).entity_class,
        signal_kind: (*input).signal_kind,
        first_line: (*input).first_line,
        first_column: (*input).first_column,
        last_line: (*input).last_line,
        last_column: (*input).last_column,

        str1: str1,
        str2: str2,

        pieces: inner_nodes,

        raw_node: input,
    };

    ret
}

pub fn parse_file(filename: &OsStr) -> (Option<VhdlParseTreeNode>, String) {
    unsafe {
        let mut errors: *mut c_char = ptr::null_mut::<c_char>();
        let ret = ffi::VhdlParserParseFile(
            filename.as_bytes().as_ptr() as *const i8,
            &mut errors);

        let errors_rs = rustify_str(errors);

        if ret.is_null() {
            (None, errors_rs)
        } else {
            // Need to Rust-ify the struct
            (Some(rustify_node(ret)), errors_rs)
        }
    }
}

impl Drop for VhdlParseTreeNode {
    fn drop(&mut self) {
        unsafe {
            ffi::VhdlParserFreePT(self.raw_node);
        }
    }
}

impl VhdlParseTreeNode {
    pub fn debug_print(&self) {
        unsafe {
            // FIXME: This isn't a C function, does it matter?
            ffi::VhdlParseTreeNode_debug_print(self.raw_node);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add helper functions to check whether a mail is passed, replied,...<commit_after><|endoftext|>


<commit_before><commit_msg>Updates to eqtest<commit_after><|endoftext|>


<commit_before><commit_msg>auto merge of #10478 : TeXitoi/rust/shootout-meteor, r=brson<commit_after>// Copyright 2013 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.

//
// Utilities.
//

// returns an infinite iterator of repeated applications of f to x,
// i.e. [x, f(x), f(f(x)), ...], as haskell iterate function.
fn iterate<'a, T>(x: T, f: &'a fn(&T) -> T) -> Iterate<'a, T> {
    Iterate {f: f, next: x}
}
struct Iterate<'self, T> {
    priv f: &'self fn(&T) -> T,
    priv next: T
}
impl<'self, T> Iterator<T> for Iterate<'self, T> {
    fn next(&mut self) -> Option<T> {
        let mut res = (self.f)(&self.next);
        std::util::swap(&mut res, &mut self.next);
        Some(res)
    }
}

// a linked list using borrowed next.
enum List<'self, T> {
    Nil,
    Cons(T, &'self List<'self, T>)
}
struct ListIterator<'self, T> {
    priv cur: &'self List<'self, T>
}
impl<'self, T> List<'self, T> {
    fn iter(&'self self) -> ListIterator<'self, T> {
        ListIterator{cur: self}
    }
}
impl<'self, T> Iterator<&'self T> for ListIterator<'self, T> {
    fn next(&mut self) -> Option<&'self T> {
        match *self.cur {
            Nil => None,
            Cons(ref elt, next) => {
                self.cur = next;
                Some(elt)
            }
        }
    }
}

//
// preprocess
//

// Takes a pieces p on the form [(y1, x1), (y2, x2), ...] and returns
// every possible transformations (the 6 rotations with their
// corresponding mirrored piece), with, as minimum coordinates, (0,
// 0).  If all is false, only generate half of the possibilities (used
// to break the symetry of the board).
fn transform(piece: ~[(int, int)], all: bool) -> ~[~[(int, int)]] {
    let mut res =
        // rotations
        iterate(piece, |rot| rot.iter().map(|&(y, x)| (x + y, -y)).collect())
        .take(if all {6} else {3})
        // mirror
        .flat_map(|cur_piece| {
            iterate(cur_piece, |mir| mir.iter().map(|&(y, x)| (x, y)).collect())
            .take(2)
        }).to_owned_vec();

    // translating to (0, 0) as minimum coordinates.
    for cur_piece in res.mut_iter() {
        let (dy, dx) = *cur_piece.iter().min_by(|e| *e).unwrap();
        for &(ref mut y, ref mut x) in cur_piece.mut_iter() {
            *y -= dy; *x -= dx;
        }
    }

    res
}

// A mask is a piece somewere on the board.  It is represented as a
// u64: for i in the first 50 bits, m[i] = 1 if the cell at (i/5, i%5)
// is occuped.  m[50 + id] = 1 if the identifier of the piece is id.

// Takes a piece with minimum coordinate (0, 0) (as generated by
// transform).  Returns the corresponding mask if p translated by (dy,
// dx) is on the board.
fn mask(dy: int, dx: int, id: uint, p: &[(int, int)]) -> Option<u64> {
    let mut m = 1 << (50 + id);
    for &(y, x) in p.iter() {
        let x = x + dx + (y + (dy % 2)) / 2;
        if x < 0 || x > 4 {return None;}
        let y = y + dy;
        if y < 0 || y > 9 {return None;}
        m |= 1 << (y * 5 + x);
    }
    Some(m)
}

// Makes every possible masks.  masks[id][i] correspond to every
// possible masks for piece with identifier id with minimum coordinate
// (i/5, i%5).
fn make_masks() -> ~[~[~[u64]]] {
    let pieces = ~[
        ~[(0,0),(0,1),(0,2),(0,3),(1,3)],
        ~[(0,0),(0,2),(0,3),(1,0),(1,1)],
        ~[(0,0),(0,1),(0,2),(1,2),(2,1)],
        ~[(0,0),(0,1),(0,2),(1,1),(2,1)],
        ~[(0,0),(0,2),(1,0),(1,1),(2,1)],
        ~[(0,0),(0,1),(0,2),(1,1),(1,2)],
        ~[(0,0),(0,1),(1,1),(1,2),(2,1)],
        ~[(0,0),(0,1),(0,2),(1,0),(1,2)],
        ~[(0,0),(0,1),(0,2),(1,2),(1,3)],
        ~[(0,0),(0,1),(0,2),(0,3),(1,2)]];
    let mut res = ~[];
    for (id, p) in pieces.move_iter().enumerate() {
        // To break the central symetry of the problem, every
        // transformation must be taken except for one piece (piece 3
        // here).
        let trans = transform(p, id != 3);
        let mut cur_piece = ~[];
        for dy in range(0, 10) {
            for dx in range(0, 5) {
                let masks =
                    trans.iter()
                    .filter_map(|t| mask(dy, dx, id, *t))
                    .collect();
                cur_piece.push(masks);
            }
        }
        res.push(cur_piece);
    }
    res
}

// Check if all coordinates can be covered by an unused piece and that
// all unused piece can be placed on the board.
fn is_board_unfeasible(board: u64, masks: &[~[~[u64]]]) -> bool {
    let mut coverable = board;
    for i in range(0, 50).filter(|&i| board & 1 << i == 0) {
        for (cur_id, pos_masks) in masks.iter().enumerate() {
            if board & 1 << (50 + cur_id) != 0 {continue;}
            for &cur_m in pos_masks[i].iter() {
                if cur_m & board == 0 {coverable |= cur_m;}
            }
        }
        if coverable & (1 << i) == 0 {return true;}
    }
    // check if every coordinates can be covered and every piece can
    // be used.
    coverable != (1 << 60) - 1
}

// Filter the masks that we can prove to result to unfeasible board.
fn filter_masks(masks: &[~[~[u64]]]) -> ~[~[~[u64]]] {
    masks.iter().map(
        |p| p.iter().map(
            |p| p.iter()
                .map(|&m| m)
                .filter(|&m| !is_board_unfeasible(m, masks))
                .collect())
            .collect())
        .collect()
}

// Gets the identifier of a mask.
fn get_id(m: u64) -> u8 {
    for id in range(0, 10) {
        if m & (1 << (id + 50)) != 0 {return id as u8;}
    }
    fail!("{:016x} does not have a valid identifier", m);
}

// Converts a list of mask to a ~str.
fn to_utf8(raw_sol: &List<u64>) -> ~str {
    let mut sol: ~[u8] = std::vec::from_elem(50, '.' as u8);
    for &m in raw_sol.iter() {
        let id = get_id(m);
        for i in range(0, 50) {
            if m & 1 << i != 0 {sol[i] = '0' as u8 + id;}
        }
    }
    std::str::from_utf8_owned(sol)
}

// Prints a solution in ~str form.
fn print_sol(sol: &str) {
    for (i, c) in sol.iter().enumerate() {
        if (i) % 5 == 0 {println("");}
        if (i + 5) % 10 == 0 {print(" ");}
        print!("{} ", c);
    }
    println("");
}

// The data managed during the search
struct Data {
    // If more than stop_after is found, stop the search.
    stop_after: int,
    // Number of solution found.
    nb: int,
    // Lexicographically minimal solution found.
    min: ~str,
    // Lexicographically maximal solution found.
    max: ~str
}

// Records a new found solution.  Returns false if the search must be
// stopped.
fn handle_sol(raw_sol: &List<u64>, data: &mut Data) -> bool {
    // because we break the symetry, 2 solutions correspond to a call
    // to this method: the normal solution, and the same solution in
    // reverse order, i.e. the board rotated by half a turn.
    data.nb += 2;
    let sol1 = to_utf8(raw_sol);
    let sol2: ~str = sol1.iter().invert().collect();

    if data.nb == 2 {
        data.min = sol1.clone();
        data.max = sol1.clone();
    }

    if sol1 < data.min {data.min = sol1.clone();}
    if sol2 < data.min {data.min = sol2.clone();}
    if sol1 > data.max {data.max = sol1;}
    if sol2 > data.max {data.max = sol2;}
    data.nb < data.stop_after
}

// Search for every solutions.  Returns false if the search was
// stopped before the end.
fn search(
    masks: &[~[~[u64]]],
    board: u64,
    mut i: int,
    cur: List<u64>,
    data: &mut Data)
    -> bool
{
    // Search for the lesser empty coordinate.
    while board & (1 << i)  != 0 && i < 50 {i += 1;}
    // the board is full: a solution is found.
    if i >= 50 {return handle_sol(&cur, data);}

    // for every unused piece
    for id in range(0, 10).filter(|id| board & (1 << (id + 50)) == 0) {
        // for each mask that fits on the board
        for &m in masks[id][i].iter().filter(|&m| board & *m == 0) {
            // This check is too costy.
            //if is_board_unfeasible(board | m, masks) {continue;}
            if !search(masks, board | m, i + 1, Cons(m, &cur), data) {
                return false;
            }
        }
    }
    return true;
}

fn main () {
    let args = std::os::args();
    let stop_after = if args.len() <= 1 {
        2098
    } else {
        from_str(args[1]).unwrap()
    };
    let masks = make_masks();
    let masks = filter_masks(masks);
    let mut data = Data {stop_after: stop_after, nb: 0, min: ~"", max: ~""};
    search(masks, 0, 0, Nil, &mut data);
    println!("{} solutions found", data.nb);
    print_sol(data.min);
    print_sol(data.max);
    println("");
}
<|endoftext|>


<commit_before><commit_msg>Add missing file from previous commit.<commit_after>use hyper::net::Openssl;
use openssl::crypto::pkey::PKey;
use openssl::ssl::{SslContext, SslMethod, SSL_VERIFY_NONE};
use openssl::ssl::error::SslError;
use openssl::x509::X509;
use std::io::Cursor;
use std::sync::Arc;

static SPOTILOCAL_CERT : &'static [u8] = include_bytes!("data/spotilocal.cert");
static SPOTILOCAL_KEY : &'static [u8] = include_bytes!("data/spotilocal.key");

pub fn ssl_context() -> Result<Openssl, SslError> {
    let cert = try!(X509::from_pem(&mut Cursor::new(SPOTILOCAL_CERT)));
    let key = try!(PKey::private_key_from_pem(&mut Cursor::new(SPOTILOCAL_KEY)));

    let mut ctx = try!(SslContext::new(SslMethod::Sslv23));
    try!(ctx.set_cipher_list("DEFAULT"));
    try!(ctx.set_private_key(&key));
    try!(ctx.set_certificate(&cert));
    ctx.set_verify(SSL_VERIFY_NONE, None);
    Ok(Openssl { context: Arc::new(ctx) })
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for issue-77475<commit_after>// check-pass
// Regression test of #77475, this used to be ICE.

#![feature(decl_macro)]

use crate as _;

pub macro ice(){}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add a test<commit_after>#![deny(broken_intra_doc_links)]

// ignore-tidy-linelength

// @has intra_link_primitive_non_default_impl/fn.f.html
/// [`str::trim`]
// @has - '//*[@href="https://doc.rust-lang.org/nightly/std/primitive.str.html#method.trim"]' 'str::trim'
/// [`str::to_lowercase`]
// @has - '//*[@href="https://doc.rust-lang.org/nightly/std/primitive.str.html#method.to_lowercase"]' 'str::to_lowercase'
/// [`str::into_boxed_bytes`]
// @has - '//*[@href="https://doc.rust-lang.org/nightly/std/primitive.str.html#method.into_boxed_bytes"]' 'str::into_boxed_bytes'
/// [`str::replace`]
// @has - '//*[@href="https://doc.rust-lang.org/nightly/std/primitive.str.html#method.replace"]' 'str::replace'
pub fn f() {}
<|endoftext|>


<commit_before><commit_msg>it is also legal to call unsafe functions from other unsafe functions<commit_after>// -*- rust -*-
//
// See also: compile-fail/unsafe-fn-called-from-safe.rs

unsafe fn f() { ret; }

unsafe fn g() {
    f();
}

<|endoftext|>


<commit_before><commit_msg>add tests to user.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Fix(commands): if showing metadata for binary file, print message about omitted data<commit_after><|endoftext|>


<commit_before><commit_msg>Uptime shows remained instead of total for minutes and hours.<commit_after><|endoftext|>


<commit_before><commit_msg>add kinesis firehose.  account for services with typed errors and methods that explicitly declare no errors<commit_after>//! Amazon Kinesis Firehose

include!(concat!(env!("OUT_DIR"), "/firehose.rs"));
<|endoftext|>


<commit_before><commit_msg>style(tmux/mod.rs): Push return value arrow out<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests for impl macros<commit_after><|endoftext|>


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

use std::{mem, ptr};
use d3dcompiler;
use dxguid;
use winapi;
use gfx_core as core;
use gfx_core::shade as s;

pub fn reflect_shader(code: &[u8]) -> *mut winapi::ID3D11ShaderReflection {
    let mut reflection = ptr::null_mut();
    let hr = unsafe {
        d3dcompiler::D3DReflect(code.as_ptr() as *const winapi::VOID,
            code.len() as winapi::SIZE_T, &dxguid::IID_ID3D11ShaderReflection, &mut reflection)
    };
    if !winapi::SUCCEEDED(hr) {
        error!("Shader reflection failed with code {:x}", hr);
    }
    reflection as *mut winapi::ID3D11ShaderReflection
}

fn convert_str(pchar: *const i8) -> String {
    use std::ffi::CStr;
    unsafe {
        CStr::from_ptr(pchar).to_string_lossy().into_owned()
    }
}

fn map_base_type(ct: winapi::D3D_REGISTER_COMPONENT_TYPE) -> s::BaseType {
    match ct {
        winapi::D3D_REGISTER_COMPONENT_UINT32 => s::BaseType::U32,
        winapi::D3D_REGISTER_COMPONENT_SINT32 => s::BaseType::I32,
        winapi::D3D_REGISTER_COMPONENT_FLOAT32 => s::BaseType::F32,
        winapi::D3D_REGISTER_COMPONENT_TYPE(t) => {
            error!("Unknown register component type {} detected!", t);
            s::BaseType::F32
        },
    }
}

pub fn populate_info(info: &mut s::ProgramInfo, stage: s::Stage,
                     reflection: *mut winapi::ID3D11ShaderReflection) {
    use winapi::{UINT, SUCCEEDED};
    let usage = stage.into();
    let (shader_desc, _feature_level) = unsafe {
        let mut desc = mem::zeroed();
        let mut level = winapi::D3D_FEATURE_LEVEL_9_1;
        (*reflection).GetDesc(&mut desc);
        (*reflection).GetMinFeatureLevel(&mut level);
        (desc, level)
    };
    if stage == s::Stage::Vertex {
        // record vertex attributes
        for i in 0 .. shader_desc.InputParameters {
            let (hr, desc) = unsafe {
                let mut desc = mem::zeroed();
                let hr = (*reflection).GetInputParameterDesc(i as UINT, &mut desc);
                (hr, desc)
            };
            assert!(SUCCEEDED(hr));
            debug!("Attribute {}, system type {:?}, mask {}, read-write mask {}",
                convert_str(desc.SemanticName), desc.SystemValueType, desc.Mask, desc.ReadWriteMask);
            if desc.SystemValueType != winapi::D3D_NAME_UNDEFINED {
                // system value semantic detected, skipping
                continue
            }
            if desc.Mask == 0 {
                // not used, skipping
                continue
            }
            info.vertex_attributes.push(s::AttributeVar {
                name: convert_str(desc.SemanticName),
                slot: desc.Register as core::AttributeSlot,
                base_type: map_base_type(desc.ComponentType),
                container: s::ContainerType::Vector(4), // how to get it?
            });
        }
    }
    if stage == s::Stage::Pixel {
        // record pixel outputs
        for i in 0 .. shader_desc.OutputParameters {
            let (hr, desc) = unsafe {
                let mut desc = mem::zeroed();
                let hr = (*reflection).GetOutputParameterDesc(i as UINT, &mut desc);
                (hr, desc)
            };
            assert!(SUCCEEDED(hr));
            debug!("Output {}, system type {:?}, mask {}, read-write mask {}",
                convert_str(desc.SemanticName), desc.SystemValueType, desc.Mask, desc.ReadWriteMask);
            if desc.SystemValueType != winapi::D3D_NAME_UNDEFINED {
                // system value semantic detected, skipping
                continue
            }
            info.outputs.push(s::OutputVar {
                name: convert_str(desc.SemanticName),
                slot: desc.Register as core::ColorSlot,
                base_type: map_base_type(desc.ComponentType),
                container: s::ContainerType::Vector(4), // how to get it?
            });
        }
    }
    // record resources
    for i in 0 .. shader_desc.BoundResources {
        let (hr, res_desc) = unsafe {
            let mut desc = mem::zeroed();
            let hr = (*reflection).GetResourceBindingDesc(i as UINT, &mut desc);
            (hr, desc)
        };
        assert!(SUCCEEDED(hr));
        let name = convert_str(res_desc.Name);
        debug!("Resource {}, type {:?}", name, res_desc.Type);
        if res_desc.Type == winapi::D3D_SIT_CBUFFER {
            if let Some(cb) = info.constant_buffers.iter_mut().find(|cb| cb.name == name) {
                cb.usage = cb.usage | usage;
                continue;
            }
            let desc = unsafe {
                let cbuf = (*reflection).GetConstantBufferByName(res_desc.Name);
                let mut desc = mem::zeroed();
                let hr = (*cbuf).GetDesc(&mut desc);
                assert!(SUCCEEDED(hr));
                desc
            };
            info.constant_buffers.push(s::ConstantBufferVar {
                name: name,
                slot: res_desc.BindPoint as core::ConstantBufferSlot,
                size: desc.Size as usize,
                usage: usage,
            });
        }else if res_desc.Type == winapi::D3D_SIT_TEXTURE {
            //TODO
        }else if res_desc.Type == winapi::D3D_SIT_SAMPLER {
            if let Some(s) = info.samplers.iter_mut().find(|s| s.name == name) {
                s.usage = s.usage | usage;
                continue;
            }
            let cmp = if res_desc.uFlags & winapi::D3D_SIF_COMPARISON_SAMPLER.0 != 0 {
                s::IsComparison::Compare
            }else {
                s::IsComparison::NoCompare
            };
            info.samplers.push(s::SamplerVar {
                name: name,
                slot: res_desc.BindPoint as core::SamplerSlot,
                ty: s::SamplerType(cmp, s::IsRect::NoRect),
                usage: usage,
            });
        }else {
            error!("Unsupported resource type {:?} for {}", res_desc.Type, name);
        }
    }
}
<commit_msg>DX - shader texture queries<commit_after>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{mem, ptr};
use d3dcompiler;
use dxguid;
use winapi;
use gfx_core as core;
use gfx_core::shade as s;

pub fn reflect_shader(code: &[u8]) -> *mut winapi::ID3D11ShaderReflection {
    let mut reflection = ptr::null_mut();
    let hr = unsafe {
        d3dcompiler::D3DReflect(code.as_ptr() as *const winapi::VOID,
            code.len() as winapi::SIZE_T, &dxguid::IID_ID3D11ShaderReflection, &mut reflection)
    };
    if !winapi::SUCCEEDED(hr) {
        error!("Shader reflection failed with code {:x}", hr);
    }
    reflection as *mut winapi::ID3D11ShaderReflection
}

fn convert_str(pchar: *const i8) -> String {
    use std::ffi::CStr;
    unsafe {
        CStr::from_ptr(pchar).to_string_lossy().into_owned()
    }
}

fn map_base_type_from_component(ct: winapi::D3D_REGISTER_COMPONENT_TYPE) -> s::BaseType {
    match ct {
        winapi::D3D_REGISTER_COMPONENT_UINT32 => s::BaseType::U32,
        winapi::D3D_REGISTER_COMPONENT_SINT32 => s::BaseType::I32,
        winapi::D3D_REGISTER_COMPONENT_FLOAT32 => s::BaseType::F32,
        winapi::D3D_REGISTER_COMPONENT_TYPE(t) => {
            error!("Unknown register component type {} detected!", t);
            s::BaseType::F32
        }
    }
}

fn map_base_type_from_return(rt: winapi::D3D_RESOURCE_RETURN_TYPE) -> s::BaseType {
    match rt {
        winapi::D3D_RETURN_TYPE_UINT => s::BaseType::U32,
        winapi::D3D_RETURN_TYPE_SINT => s::BaseType::I32,
        winapi::D3D_RETURN_TYPE_FLOAT => s::BaseType::F32,
        winapi::D3D_RESOURCE_RETURN_TYPE(t) => {
            error!("Unknown return type {} detected!", t);
            s::BaseType::F32
        }
    }
}

fn map_texture_type(tt: winapi::D3D_SRV_DIMENSION) -> s::TextureType {
    use winapi::*;
    use gfx_core::shade::IsArray::*;
    use gfx_core::shade::IsMultiSample::*;
    match tt {
        D3D_SRV_DIMENSION_BUFFER            => s::TextureType::Buffer,
        D3D_SRV_DIMENSION_TEXTURE1D         => s::TextureType::D1(NoArray),
        D3D_SRV_DIMENSION_TEXTURE1DARRAY    => s::TextureType::D1(Array),
        D3D_SRV_DIMENSION_TEXTURE2D         => s::TextureType::D2(NoArray, NoMultiSample),
        D3D_SRV_DIMENSION_TEXTURE2DARRAY    => s::TextureType::D2(Array, NoMultiSample),
        D3D_SRV_DIMENSION_TEXTURE2DMS       => s::TextureType::D2(NoArray, MultiSample),
        D3D_SRV_DIMENSION_TEXTURE2DMSARRAY  => s::TextureType::D2(Array, MultiSample),
        D3D_SRV_DIMENSION_TEXTURE3D         => s::TextureType::D3,
        D3D_SRV_DIMENSION_TEXTURECUBE       => s::TextureType::Cube(NoArray),
        D3D_SRV_DIMENSION_TEXTURECUBEARRAY  => s::TextureType::Cube(Array),
        D3D_SRV_DIMENSION(t) => {
            error!("Unknow texture dimension {}", t);
            s::TextureType::Buffer
        }
    }
}

pub fn populate_info(info: &mut s::ProgramInfo, stage: s::Stage,
                     reflection: *mut winapi::ID3D11ShaderReflection) {
    use winapi::{UINT, SUCCEEDED};
    let usage = stage.into();
    let (shader_desc, _feature_level) = unsafe {
        let mut desc = mem::zeroed();
        let mut level = winapi::D3D_FEATURE_LEVEL_9_1;
        (*reflection).GetDesc(&mut desc);
        (*reflection).GetMinFeatureLevel(&mut level);
        (desc, level)
    };
    if stage == s::Stage::Vertex {
        // record vertex attributes
        for i in 0 .. shader_desc.InputParameters {
            let (hr, desc) = unsafe {
                let mut desc = mem::zeroed();
                let hr = (*reflection).GetInputParameterDesc(i as UINT, &mut desc);
                (hr, desc)
            };
            assert!(SUCCEEDED(hr));
            debug!("Attribute {}, system type {:?}, mask {}, read-write mask {}",
                convert_str(desc.SemanticName), desc.SystemValueType, desc.Mask, desc.ReadWriteMask);
            if desc.SystemValueType != winapi::D3D_NAME_UNDEFINED {
                // system value semantic detected, skipping
                continue
            }
            if desc.Mask == 0 {
                // not used, skipping
                continue
            }
            info.vertex_attributes.push(s::AttributeVar {
                name: convert_str(desc.SemanticName),
                slot: desc.Register as core::AttributeSlot,
                base_type: map_base_type_from_component(desc.ComponentType),
                container: s::ContainerType::Vector(4), // how to get it?
            });
        }
    }
    if stage == s::Stage::Pixel {
        // record pixel outputs
        for i in 0 .. shader_desc.OutputParameters {
            let (hr, desc) = unsafe {
                let mut desc = mem::zeroed();
                let hr = (*reflection).GetOutputParameterDesc(i as UINT, &mut desc);
                (hr, desc)
            };
            assert!(SUCCEEDED(hr));
            debug!("Output {}, system type {:?}, mask {}, read-write mask {}",
                convert_str(desc.SemanticName), desc.SystemValueType, desc.Mask, desc.ReadWriteMask);
            if desc.SystemValueType != winapi::D3D_NAME_UNDEFINED {
                // system value semantic detected, skipping
                continue
            }
            info.outputs.push(s::OutputVar {
                name: convert_str(desc.SemanticName),
                slot: desc.Register as core::ColorSlot,
                base_type: map_base_type_from_component(desc.ComponentType),
                container: s::ContainerType::Vector(4), // how to get it?
            });
        }
    }
    // record resources
    for i in 0 .. shader_desc.BoundResources {
        let (hr, res_desc) = unsafe {
            let mut desc = mem::zeroed();
            let hr = (*reflection).GetResourceBindingDesc(i as UINT, &mut desc);
            (hr, desc)
        };
        assert!(SUCCEEDED(hr));
        let name = convert_str(res_desc.Name);
        debug!("Resource {}, type {:?}", name, res_desc.Type);
        if res_desc.Type == winapi::D3D_SIT_CBUFFER {
            if let Some(cb) = info.constant_buffers.iter_mut().find(|cb| cb.name == name) {
                cb.usage = cb.usage | usage;
                continue;
            }
            let desc = unsafe {
                let cbuf = (*reflection).GetConstantBufferByName(res_desc.Name);
                let mut desc = mem::zeroed();
                let hr = (*cbuf).GetDesc(&mut desc);
                assert!(SUCCEEDED(hr));
                desc
            };
            info.constant_buffers.push(s::ConstantBufferVar {
                name: name,
                slot: res_desc.BindPoint as core::ConstantBufferSlot,
                size: desc.Size as usize,
                usage: usage,
            });
        }else if res_desc.Type == winapi::D3D_SIT_TEXTURE {
            if let Some(t) = info.textures.iter_mut().find(|t| t.name == name) {
                t.usage = t.usage | usage;
                continue;
            }
            info.textures.push(s::TextureVar {
                name: name,
                slot: res_desc.BindPoint as core::ResourceViewSlot,
                base_type: map_base_type_from_return(res_desc.ReturnType),
                ty: map_texture_type(res_desc.Dimension),
                usage: usage,
            });
        }else if res_desc.Type == winapi::D3D_SIT_SAMPLER {
            if let Some(s) = info.samplers.iter_mut().find(|s| s.name == name) {
                s.usage = s.usage | usage;
                continue;
            }
            let cmp = if res_desc.uFlags & winapi::D3D_SIF_COMPARISON_SAMPLER.0 != 0 {
                s::IsComparison::Compare
            }else {
                s::IsComparison::NoCompare
            };
            info.samplers.push(s::SamplerVar {
                name: name,
                slot: res_desc.BindPoint as core::SamplerSlot,
                ty: s::SamplerType(cmp, s::IsRect::NoRect),
                usage: usage,
            });
        }else {
            error!("Unsupported resource type {:?} for {}", res_desc.Type, name);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement Error and Display for DotenvError #48<commit_after><|endoftext|>


<commit_before><commit_msg>add apache log benchmarks<commit_after>#![feature(test)]

extern crate grok;
extern crate test;

use test::Bencher;
use grok::Grok;

#[bench]
fn bench_apache_log_match(b: &mut Bencher) {
    let msg = r#"220.181.108.96 - - [13/Jun/2015:21:14:28 +0000] "GET /blog/geekery/xvfb-firefox.html HTTP/1.1" 200 10975 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)""#;

    let mut grok = Grok::default();
    let pattern = grok.compile(r#"%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response} %{NUMBER:bytes} %{QS:referrer} %{QS:agent}"#, false)
        .expect("Error while compiling!");

    b.iter(|| match pattern.match_against(msg) {
        Some(found) => {
            test::black_box(found);
        }
        None => (),
    });
}

#[bench]
fn bench_apache_log_no_match_start(b: &mut Bencher) {
    let msg = r#"tash-scale11x/css/fonts/Roboto-Regular.ttf HTTP/1.1" 200 41820 "http://semicomplete.com/presentations/logs"#;

    let mut grok = Grok::default();
    let pattern = grok.compile(r#"%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response} %{NUMBER:bytes} %{QS:referrer} %{QS:agent}"#, false)
        .expect("Error while compiling!");

    b.iter(|| match pattern.match_against(msg) {
        Some(found) => {
            test::black_box(found);
        }
        None => (),
    });
}

#[bench]
fn bench_apache_log_no_match_middle(b: &mut Bencher) {
    let msg = r#"220.181.108.96 - - [13/Jun/2015:21:14:28 +0000] "111 /blog/geekery/xvfb-firefox.html HTTP/1.1" 200 10975 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)""#;

    let mut grok = Grok::default();
    let pattern = grok.compile(r#"%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response} %{NUMBER:bytes} %{QS:referrer} %{QS:agent}"#, false)
        .expect("Error while compiling!");

    b.iter(|| match pattern.match_against(msg) {
        Some(found) => {
            test::black_box(found);
        }
        None => (),
    });
}

#[bench]
fn bench_apache_log_no_match_end(b: &mut Bencher) {
    let msg = r#"220.181.108.96 - - [13/Jun/2015:21:14:28 +0000] "GET /blog/geekery/xvfb-firefox.html HTTP/1.1" 200 10975 "-" 1"#;

    let mut grok = Grok::default();
    let pattern = grok.compile(r#"%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response} %{NUMBER:bytes} %{QS:referrer} %{QS:agent}"#, false)
        .expect("Error while compiling!");

    b.iter(|| match pattern.match_against(msg) {
        Some(found) => {
            test::black_box(found);
        }
        None => (),
    });
}

#[bench]
fn bench_apache_log_match_anchor(b: &mut Bencher) {
    let msg = r#"220.181.108.96 - - [13/Jun/2015:21:14:28 +0000] "GET /blog/geekery/xvfb-firefox.html HTTP/1.1" 200 10975 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)""#;

    let mut grok = Grok::default();
    let pattern = grok.compile(r#"^%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response} %{NUMBER:bytes} %{QS:referrer} %{QS:agent}$"#, false)
        .expect("Error while compiling!");

    b.iter(|| match pattern.match_against(msg) {
        Some(found) => {
            test::black_box(found);
        }
        None => (),
    });
}

#[bench]
fn bench_apache_log_no_match_start_anchor(b: &mut Bencher) {
    let msg = r#"tash-scale11x/css/fonts/Roboto-Regular.ttf HTTP/1.1" 200 41820 "http://semicomplete.com/presentations/logs"#;

    let mut grok = Grok::default();
    let pattern = grok.compile(r#"^%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response} %{NUMBER:bytes} %{QS:referrer} %{QS:agent}$"#, false)
        .expect("Error while compiling!");

    b.iter(|| match pattern.match_against(msg) {
        Some(found) => {
            test::black_box(found);
        }
        None => (),
    });
}

#[bench]
fn bench_apache_log_no_match_middle_anchor(b: &mut Bencher) {
    let msg = r#"220.181.108.96 - - [13/Jun/2015:21:14:28 +0000] "111 /blog/geekery/xvfb-firefox.html HTTP/1.1" 200 10975 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)""#;

    let mut grok = Grok::default();
    let pattern = grok.compile(r#"^%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response} %{NUMBER:bytes} %{QS:referrer} %{QS:agent}$"#, false)
        .expect("Error while compiling!");

    b.iter(|| match pattern.match_against(msg) {
        Some(found) => {
            test::black_box(found);
        }
        None => (),
    });
}

#[bench]
fn bench_apache_log_no_match_end_anchor(b: &mut Bencher) {
    let msg = r#"220.181.108.96 - - [13/Jun/2015:21:14:28 +0000] "GET /blog/geekery/xvfb-firefox.html HTTP/1.1" 200 10975 "-" 1"#;

    let mut grok = Grok::default();
    let pattern = grok.compile(r#"^%{IPORHOST:clientip} %{USER:ident} %{USER:auth} \[%{HTTPDATE:timestamp}\] "%{WORD:verb} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response} %{NUMBER:bytes} %{QS:referrer} %{QS:agent}$"#, false)
        .expect("Error while compiling!");

    b.iter(|| match pattern.match_against(msg) {
        Some(found) => {
            test::black_box(found);
        }
        None => (),
    });
}<|endoftext|>


<commit_before><commit_msg>Prepare code for a flat_map test<commit_after>#[macro_use]
extern crate nom;

use nom::{IResult, Needed, alphanumeric, is_alphanumeric};

named!(certain_length<&[u8], &[u8]>, take!(10));

named!(value<&[u8], &[u8]>,
       take_while!(is_alphanumeric));

named!(comment<&[u8], &[u8]>,
      do_parse!(
          tag!("/") >>
              comment: alphanumeric >>
              (comment)
      ));

named!(record<&[u8], (&[u8], Option<&[u8]>)>,
       do_parse!(
           v: value >>
               c: opt!(comment) >>
               ((v, c))
       ));

#[test]
fn certain_length_test() {
    assert_eq!(certain_length(&b"0123456789"[..]), IResult::Done(&b""[..], &b"0123456789"[..]));
    assert_eq!(certain_length(&b"012345678"[..]), IResult::Incomplete(Needed::Size(10)));
    assert_eq!(certain_length(&b"abcdefghijk"[..]), IResult::Done(&b"k"[..], &b"abcdefghij"[..]));
}

#[test]
fn value_test() {
    assert_eq!(value(&b""[..]),
               IResult::Done(&b""[..], &b""[..]));
    assert_eq!(value(&b"a"[..]),
               IResult::Done(&b""[..], &b"a"[..]));
    assert_eq!(value(&b"ab"[..]),
               IResult::Done(&b""[..], &b"ab"[..]));
    assert_eq!(value(&b"abc"[..]),
               IResult::Done(&b""[..], &b"abc"[..]));
}

#[test]
fn comment_test() {
    assert_eq!(comment(&b"/a"[..]), IResult::Done(&b""[..], &b"a"[..]));
    assert_eq!(comment(&b"/ab"[..]), IResult::Done(&b""[..], &b"ab"[..]));
    assert_eq!(comment(&b"/abc"[..]), IResult::Done(&b""[..], &b"abc"[..]));
}

#[test]
fn record_test() {
    assert_eq!(record(&b"abcd/123"[..]),
               IResult::Done(&b""[..], (&b"abcd"[..], Option::Some(&b"123"[..]))));
    assert_eq!(record(&b"abcd/123  "[..]),
               IResult::Done(&b"  "[..], (&b"abcd"[..], Option::Some(&b"123"[..]))));
    assert_eq!(record(&b"abcd  "[..]),
               IResult::Done(&b"  "[..], (&b"abcd"[..], Option::None)));
}
<|endoftext|>


<commit_before><commit_msg>Add a test for #2941.<commit_after>// rustfmt-wrap_comments: true

//! ```
//! \
//! ```
<|endoftext|>


<commit_before>extern crate regex;
use std::env::*;
use std::fs::File;
use std::path::Path;
use std::error::Error;
use std::io::prelude::*;

#[derive(Clone, Debug)]
pub struct AWSCredentials {
    key: String,
    secret: String
}

#[derive(Debug)]
enum CredentialErr {
    NoEnvironmentVariables,
    NoCredentialsFile,
}

impl AWSCredentials {
    pub fn new(key:&str, secret:&str) -> AWSCredentials {
        AWSCredentials {
            key: key.to_string(),
            secret: secret.to_string()
        }
    }

    pub fn get_aws_access_key_id(&self) -> &str {
    	&self.key
    }

    pub fn get_aws_secret_key(&self) -> &str {
    	&self.secret
    }
}

pub trait AWSCredentialsProvider {
	fn get_credentials(&self) -> &AWSCredentials;
	fn refresh(&mut self);
}

pub struct EnvironmentCredentialsProvider;

pub struct DefaultAWSCredentialsProviderChain {
	credentials: AWSCredentials
}

impl AWSCredentialsProvider for DefaultAWSCredentialsProviderChain {
	fn refresh(&mut self) {
		let env_creds = DefaultAWSCredentialsProviderChain::get_credentials();
        match env_creds {
            Ok(creds) => {
                self.credentials = creds;
	            return;
            }
            Err(why) => panic!("Couldn't open credentials anywhere."),
        }

		//let file_creds = DefaultAWSCredentialsProviderChain::creds_from_profile();
	}

	fn get_credentials(&self) -> &AWSCredentials {
		&self.credentials
	}

}

struct ProfileCredentialsError;

// From http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs
// 1. environment variables
// 2. central credentials file (named profile is supplied, otherwise default)
// 3. IAM role (if running on an EC2 instance)
impl DefaultAWSCredentialsProviderChain {

    fn get_credentials() -> Result<AWSCredentials, CredentialErr> {
        let usable_creds : AWSCredentials;

        let env_return = match DefaultAWSCredentialsProviderChain::creds_from_env() {
            Ok(v) => {
                println!("working with version: {:?}", v);
            }
            Err(e) => {
                println!("error parsing header: {:?}", e);
            }
        };

        // Ok(usable_creds)
    }

	fn creds_from_env() -> Result<AWSCredentials, CredentialErr> {
        // these except to be able to return a VarError if things go poorly:
		let env_key = try!(var("AWS_ACCESS_KEY_ID"));
		let env_secret = try!(var("AWS_SECRET_KEY"));

        if env_key.len() <= 0 || env_secret.len() <= 0 {
            return Err(CredentialErr::NoEnvironmentVariables);
        }

		Ok(AWSCredentials { key: env_key, secret: env_secret })
	}

	// fn creds_from_profile() -> Result<AWSCredentials, ProfileCredentialsError> {
    //     let path = Path::new("sample-credentials");
    //     let display = path.display();
    //
    //     let mut file = match File::open(&path) {
    //         Err(why) => panic!("couldn't open {}: {}", display,
    //                                                    Error::description(&why)),
    //         Ok(file) => file,
    //     };
    //
    //     let mut contents = String::new();
    //     match file.read_to_string(&mut contents) {
    //         Err(why) => panic!("couldn't read {}: {}", display,
    //                                                    Error::description(&why)),
    //         Ok(_) => {},
    //     }
    //
    //     let profile_key = String::from("foo");
    //     let secret_key = String::from("bar");
    //
    //     return Ok(AWSCredentials{ key: profile_key, secret: secret_key });
    //
	// 	// Err(ProfileCredentialsError)
	// }

    // IAM role
}
<commit_msg>Reinserting the creds from profile file.<commit_after>extern crate regex;
use std::env::*;
use std::fs::File;
use std::path::Path;
use std::error::Error;
use std::io::prelude::*;

#[derive(Clone, Debug)]
pub struct AWSCredentials {
    key: String,
    secret: String
}

#[derive(Debug)]
enum CredentialErr {
    NoEnvironmentVariables,
    NoCredentialsFile,
}

impl AWSCredentials {
    pub fn new(key:&str, secret:&str) -> AWSCredentials {
        AWSCredentials {
            key: key.to_string(),
            secret: secret.to_string()
        }
    }

    pub fn get_aws_access_key_id(&self) -> &str {
    	&self.key
    }

    pub fn get_aws_secret_key(&self) -> &str {
    	&self.secret
    }
}

pub trait AWSCredentialsProvider {
	fn get_credentials(&self) -> &AWSCredentials;
	fn refresh(&mut self);
}

pub struct EnvironmentCredentialsProvider;

pub struct DefaultAWSCredentialsProviderChain {
	credentials: AWSCredentials
}

impl AWSCredentialsProvider for DefaultAWSCredentialsProviderChain {
	fn refresh(&mut self) {
		let env_creds = DefaultAWSCredentialsProviderChain::get_credentials();
        match env_creds {
            Ok(creds) => {
                self.credentials = creds;
	            return;
            }
            Err(_) => panic!("Couldn't open credentials anywhere."),
        }

		//let file_creds = DefaultAWSCredentialsProviderChain::creds_from_profile();
	}

	fn get_credentials(&self) -> &AWSCredentials {
		&self.credentials
	}

}

struct ProfileCredentialsError;

// From http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs
// 1. environment variables
// 2. central credentials file (named profile is supplied, otherwise default)
// 3. IAM role (if running on an EC2 instance)
impl DefaultAWSCredentialsProviderChain {

    fn get_credentials() -> Result<AWSCredentials, CredentialErr> {
        let env_return = match DefaultAWSCredentialsProviderChain::creds_from_env() {
            Ok(creds) => creds,
            Err(_) => AWSCredentials {key: "".to_string(), secret: "".to_string()},
        };
        if env_return.get_aws_secret_key().len() > 0 && env_return.get_aws_access_key_id().len() > 0 {
            return Ok(env_return)
        }

        let file_return = match DefaultAWSCredentialsProviderChain::creds_from_profile() {
            Ok(creds) => creds,
            Err(_) => AWSCredentials {key: "".to_string(), secret: "".to_string()},
        };
        if file_return.get_aws_secret_key().len() > 0 && file_return.get_aws_access_key_id().len() > 0 {
            return Ok(file_return)
        }
        panic!("ftp");
        // Ok(usable_creds)
    }

	fn creds_from_env() -> Result<AWSCredentials, CredentialErr> {
        let env_key = match var("AWS_ACCESS_KEY_ID") {
            Ok(val) => val,
            Err(_) => {println!("couldn't find access key");
                "".to_string() }
        };
        let env_secret = match var("AWS_SECRET_KEY") {
            Ok(val) => val,
            Err(_) => {println!("couldn't find secret key");
                "".to_string() }
        };

        if env_key.len() <= 0 || env_secret.len() <= 0 {
            return Err(CredentialErr::NoEnvironmentVariables);
        }
		Ok(AWSCredentials { key: env_key, secret: env_secret })
	}

	fn creds_from_profile() -> Result<AWSCredentials, ProfileCredentialsError> {
        let path = Path::new("sample-credentials");
        let display = path.display();

        let mut file = match File::open(&path) {
            Err(why) => panic!("couldn't open {}: {}", display,
                                                       Error::description(&why)),
            Ok(file) => file,
        };

        let mut contents = String::new();
        match file.read_to_string(&mut contents) {
            Err(why) => panic!("couldn't read {}: {}", display,
                                                       Error::description(&why)),
            Ok(_) => {},
        }

        let profile_key = String::from("foo");
        let secret_key = String::from("bar");

        return Ok(AWSCredentials{ key: profile_key, secret: secret_key });

		// Err(ProfileCredentialsError)
	}

    // IAM role
}
<|endoftext|>