<commit_before>//! # Serde
//!
//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data
//! structures efficiently and generically.
//!
//! The Serde ecosystem consists of data structures that know how to serialize
//! and deserialize themselves along with data formats that know how to
//! serialize and deserialize other things. Serde provides the layer by which
//! these two groups interact with each other, allowing any supported data
//! structure to be serialized and deserialized using any supported data format.
//!
//! See the Serde website https://serde.rs/ for additional documentation and
//! usage examples.
//!
//! ### Design
//!
//! Where many other languages rely on runtime reflection for serializing data,
//! Serde is instead built on Rust's powerful trait system. A data structure
//! that knows how to serialize and deserialize itself is one that implements
//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's code
//! generation to automatically derive implementations at compile time). This
//! avoids any overhead of reflection or runtime type information. In fact in
//! many situations the interaction between data structure and data format can
//! be completely optimized away by the Rust compiler, leaving Serde
//! serialization to perform roughly the same speed as a handwritten serializer
//! for the specific selection of data structure and data format.
//!
//! ### Data formats
//!
//! The following is a partial list of data formats that have been implemented
//! for Serde by the community.
//!
//! - [JSON](https://github.com/serde-rs/json), the ubiquitous JavaScript Object
//!   Notation used by many HTTP APIs.
//! - [Bincode](https://github.com/TyOverby/bincode), a compact binary format
//!   used for IPC within the Servo rendering engine.
//! - [CBOR](https://github.com/pyfisch/cbor), a Concise Binary Object
//!   Representation designed for small message size without the need for
//!   version negotiation.
//! - [YAML](https://github.com/dtolnay/serde-yaml), a popular human-friendly
//!   configuration language that ain't markup language.
//! - [MessagePack](https://github.com/3Hren/msgpack-rust), an efficient binary
//!   format that resembles a compact JSON.
//! - [TOML](https://github.com/alexcrichton/toml-rs), a minimal configuration
//!   format used by [Cargo](http://doc.crates.io/manifest.html).
//! - [Pickle](https://github.com/birkenfeld/serde-pickle), a format common in
//!   the Python world.
//! - [Hjson](https://github.com/laktak/hjson-rust), a variant of JSON designed
//!   to be readable and writable by humans.
//! - [BSON](https://github.com/zonyitoo/bson-rs), the data storage and network
//!   transfer format used by MongoDB.
//! - [URL](https://github.com/nox/serde_urlencoded), the x-www-form-urlencoded
//!   format.
//! - [XML](https://github.com/serde-rs/xml), the flexible machine-friendly W3C
//!   standard. *(deserialization only)*
//! - [Envy](https://github.com/softprops/envy), a way to deserialize
//!   environment variables into Rust structs. *(deserialization only)*
//! - [Redis](https://github.com/OneSignal/serde-redis), deserialize values from
//!   Redis when using [redis-rs](https://crates.io/crates/redis).
//!   *(deserialization only)*

#![doc(html_root_url="https://docs.serde.rs")]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "unstable", feature(nonzero, specialization, zero_one, into_boxed_c_str))]
#![cfg_attr(feature = "alloc", feature(alloc))]
#![cfg_attr(feature = "collections", feature(collections))]
#![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))]
#![deny(missing_docs, unused_imports)]

#[cfg(feature = "collections")]
extern crate collections;

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "unstable")]
extern crate core as actual_core;

#[cfg(feature = "std")]
mod core {
    pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
                  usize, f32, f64, char, str, num, slice, iter, cell, default, result, option,
                  clone, convert};
    #[cfg(feature = "unstable")]
    pub use actual_core::nonzero;
}

#[doc(inline)]
pub use ser::{Serialize, Serializer};
#[doc(inline)]
pub use de::{Deserialize, Deserializer};

#[macro_use]
mod macros;

pub mod de;
#[cfg(feature = "std")]
#[doc(hidden)]
pub mod iter;
pub mod ser;
#[cfg_attr(feature = "std", doc(hidden))]
pub mod error;
mod utils;

// Generated code uses these to support no_std. Not public API.
#[doc(hidden)]
pub mod export;

// Re-export #[derive(Serialize, Deserialize)].
//
// This is a workaround for https://github.com/rust-lang/cargo/issues/1286.
// Without this re-export, crates that put Serde derives behind a cfg_attr would
// need to use some silly feature name that depends on both serde and
// serde_derive.
//
//     [features]
//     serde-impls = ["serde", "serde_derive"]
//
//     [dependencies]
//     serde = { version = "1.0", optional = true }
//     serde_derive = { version = "1.0", optional = true }
//
//     # Used like this:
//     # #[cfg(feature = "serde-impls")]
//     # #[macro_use]
//     # extern crate serde_derive;
//     #
//     # #[cfg_attr(feature = "serde-impls", derive(Serialize, Deserialize))]
//     # struct S { /* ... */ }
//
// The re-exported derives allow crates to use "serde" as the name of their
// Serde feature which is more intuitive.
//
//     [dependencies]
//     serde = { version = "1.0", optional = true, features = ["derive"] }
//
//     # Used like this:
//     # #[cfg(feature = "serde")]
//     # #[macro_use]
//     # extern crate serde;
//     #
//     # #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
//     # struct S { /* ... */ }
//
// The reason re-exporting is not enabled by default is that disabling it would
// be annoying for crates that provide handwritten impls or data formats. They
// would need to disable default features and then explicitly re-enable std.
#[cfg(feature = "serde_derive")]
#[allow(unused_imports)]
#[macro_use]
extern crate serde_derive;
#[cfg(feature = "serde_derive")]
#[doc(hidden)]
pub use serde_derive::*;
<commit_msg>Fix unused feature gate warning<commit_after>//! # Serde
//!
//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data
//! structures efficiently and generically.
//!
//! The Serde ecosystem consists of data structures that know how to serialize
//! and deserialize themselves along with data formats that know how to
//! serialize and deserialize other things. Serde provides the layer by which
//! these two groups interact with each other, allowing any supported data
//! structure to be serialized and deserialized using any supported data format.
//!
//! See the Serde website https://serde.rs/ for additional documentation and
//! usage examples.
//!
//! ### Design
//!
//! Where many other languages rely on runtime reflection for serializing data,
//! Serde is instead built on Rust's powerful trait system. A data structure
//! that knows how to serialize and deserialize itself is one that implements
//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's code
//! generation to automatically derive implementations at compile time). This
//! avoids any overhead of reflection or runtime type information. In fact in
//! many situations the interaction between data structure and data format can
//! be completely optimized away by the Rust compiler, leaving Serde
//! serialization to perform roughly the same speed as a handwritten serializer
//! for the specific selection of data structure and data format.
//!
//! ### Data formats
//!
//! The following is a partial list of data formats that have been implemented
//! for Serde by the community.
//!
//! - [JSON](https://github.com/serde-rs/json), the ubiquitous JavaScript Object
//!   Notation used by many HTTP APIs.
//! - [Bincode](https://github.com/TyOverby/bincode), a compact binary format
//!   used for IPC within the Servo rendering engine.
//! - [CBOR](https://github.com/pyfisch/cbor), a Concise Binary Object
//!   Representation designed for small message size without the need for
//!   version negotiation.
//! - [YAML](https://github.com/dtolnay/serde-yaml), a popular human-friendly
//!   configuration language that ain't markup language.
//! - [MessagePack](https://github.com/3Hren/msgpack-rust), an efficient binary
//!   format that resembles a compact JSON.
//! - [TOML](https://github.com/alexcrichton/toml-rs), a minimal configuration
//!   format used by [Cargo](http://doc.crates.io/manifest.html).
//! - [Pickle](https://github.com/birkenfeld/serde-pickle), a format common in
//!   the Python world.
//! - [Hjson](https://github.com/laktak/hjson-rust), a variant of JSON designed
//!   to be readable and writable by humans.
//! - [BSON](https://github.com/zonyitoo/bson-rs), the data storage and network
//!   transfer format used by MongoDB.
//! - [URL](https://github.com/nox/serde_urlencoded), the x-www-form-urlencoded
//!   format.
//! - [XML](https://github.com/serde-rs/xml), the flexible machine-friendly W3C
//!   standard. *(deserialization only)*
//! - [Envy](https://github.com/softprops/envy), a way to deserialize
//!   environment variables into Rust structs. *(deserialization only)*
//! - [Redis](https://github.com/OneSignal/serde-redis), deserialize values from
//!   Redis when using [redis-rs](https://crates.io/crates/redis).
//!   *(deserialization only)*

#![doc(html_root_url="https://docs.serde.rs")]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "unstable", feature(nonzero, specialization, zero_one))]
#![cfg_attr(all(feature = "std", feature = "unstable"), feature(into_boxed_c_str))]
#![cfg_attr(feature = "alloc", feature(alloc))]
#![cfg_attr(feature = "collections", feature(collections))]
#![cfg_attr(feature = "cargo-clippy", allow(linkedlist, type_complexity, doc_markdown))]
#![deny(missing_docs, unused_imports)]

#[cfg(feature = "collections")]
extern crate collections;

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "unstable")]
extern crate core as actual_core;

#[cfg(feature = "std")]
mod core {
    pub use std::{ops, hash, fmt, cmp, marker, mem, i8, i16, i32, i64, u8, u16, u32, u64, isize,
                  usize, f32, f64, char, str, num, slice, iter, cell, default, result, option,
                  clone, convert};
    #[cfg(feature = "unstable")]
    pub use actual_core::nonzero;
}

#[doc(inline)]
pub use ser::{Serialize, Serializer};
#[doc(inline)]
pub use de::{Deserialize, Deserializer};

#[macro_use]
mod macros;

pub mod de;
#[cfg(feature = "std")]
#[doc(hidden)]
pub mod iter;
pub mod ser;
#[cfg_attr(feature = "std", doc(hidden))]
pub mod error;
mod utils;

// Generated code uses these to support no_std. Not public API.
#[doc(hidden)]
pub mod export;

// Re-export #[derive(Serialize, Deserialize)].
//
// This is a workaround for https://github.com/rust-lang/cargo/issues/1286.
// Without this re-export, crates that put Serde derives behind a cfg_attr would
// need to use some silly feature name that depends on both serde and
// serde_derive.
//
//     [features]
//     serde-impls = ["serde", "serde_derive"]
//
//     [dependencies]
//     serde = { version = "1.0", optional = true }
//     serde_derive = { version = "1.0", optional = true }
//
//     # Used like this:
//     # #[cfg(feature = "serde-impls")]
//     # #[macro_use]
//     # extern crate serde_derive;
//     #
//     # #[cfg_attr(feature = "serde-impls", derive(Serialize, Deserialize))]
//     # struct S { /* ... */ }
//
// The re-exported derives allow crates to use "serde" as the name of their
// Serde feature which is more intuitive.
//
//     [dependencies]
//     serde = { version = "1.0", optional = true, features = ["derive"] }
//
//     # Used like this:
//     # #[cfg(feature = "serde")]
//     # #[macro_use]
//     # extern crate serde;
//     #
//     # #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
//     # struct S { /* ... */ }
//
// The reason re-exporting is not enabled by default is that disabling it would
// be annoying for crates that provide handwritten impls or data formats. They
// would need to disable default features and then explicitly re-enable std.
#[cfg(feature = "serde_derive")]
#[allow(unused_imports)]
#[macro_use]
extern crate serde_derive;
#[cfg(feature = "serde_derive")]
#[doc(hidden)]
pub use serde_derive::*;
<|endoftext|>


<commit_before>use rand::os::OsRng;
use rand::XorShiftRng;
use rand::Rand;
use rand::Rng;

pub struct RoomGen {
    rand: XorShiftRng,
}
<commit_msg>started implementing roomgen<commit_after>use rand::os::OsRng;
use rand::XorShiftRng;
use rand::Rand;
use rand::Rng;

pub struct RoomGen {
    rand_x: XorShiftRng,
    rand_y: XorShiftRng,
    max_room_size: usize,
    min_room_size: usize,
    attempts: u64,
}
<|endoftext|>


<commit_before>extern crate dominoes;

use CheckResult::*;

type Domino = (usize, usize);

#[derive(Debug)]
enum CheckResult {
    GotInvalid,             // chain returned None
    Correct,
    ChainingFailure(Vec<Domino>), // failure to match the dots at the right side of one domino with
    // the one on the left side of the next
    LengthMismatch(Vec<Domino>),
    DominoMismatch(Vec<Domino>), // different dominoes are used in input and output
}

fn normalize(d: &Domino) -> Domino {
    match d {
        &(m, n) if m > n => (n, m),
        &(m, n) => (m, n)
    }
}

fn check(input: &[Domino]) -> CheckResult {
    let output = match dominoes::chain(input) {
        None => return GotInvalid,
        Some(o) => o
    };
    if input.len() != output.len() {
        return LengthMismatch(output);
    }
    else if input.len() == 0 { // and thus output.len() == 0
        return Correct;
    }

    let mut output_sorted = output.iter().map(|d| normalize(d)).collect::<Vec<Domino>>();
    output_sorted.sort();
    let mut input_sorted = input.iter().map(|d| normalize(d)).collect::<Vec<Domino>>();
    input_sorted.sort();
    if input_sorted != output_sorted {
        return DominoMismatch(output);
    }

    // both input and output have at least 1 element
    // This essentially puts the first element after the last one, thereby making it
    // easy to check whether the domino chains "wraps around".
    let mut fail = false;
    {
        let mut n = output[0].1;
        let iter = output.iter().skip(1).chain(output.iter().take(1));
        for &(first, second) in iter {
            if n != first {
                fail = true;
                break
            }
            n = second
        }
    }
    if fail {
        ChainingFailure(output)
    }
    else {
        Correct
    }
}

fn assert_correct(input: &[Domino]) {
    match check(&input) {
        Correct => (),
        GotInvalid => panic!("Unexpectedly got invalid on input {:?}", input),
        ChainingFailure(output) => panic!("Chaining failure for input {:?}, output {:?}", input, output),
        LengthMismatch(output) => panic!("Length mismatch for input {:?}, output {:?}", input, output),
        DominoMismatch(output) => panic!("Domino mismatch for input {:?}, output {:?}", input, output),
    }
}

#[test]
fn empty_input_empty_output() {
    let input = vec!();
    assert_eq!(dominoes::chain(&input), Some(vec!()));
}

#[test]
#[ignore]
fn singleton_input_singleton_output() {
    let input = vec!((1, 1));
    assert_correct(&input);
}

#[test]
#[ignore]
fn singleton_that_cant_be_chained() {
    let input = vec![(1, 2)];
    assert_eq!(dominoes::chain(&input), None);
}

#[test]
#[ignore]
fn no_repeat_numbers() {
    let input = vec!((1, 2), (3, 1), (2, 3));
    assert_correct(&input);
}

#[test]
#[ignore]
fn can_reverse_dominoes() {
    let input = vec![(1, 2), (1, 3), (2, 3)];
    assert_correct(&input);
}

#[test]
#[ignore]
fn no_chains() {
    let input = vec!((1, 2), (4, 1), (2, 3));
    assert_eq!(dominoes::chain(&input), None);
}

#[test]
#[ignore]
fn disconnected_simple() {
    let input = vec![(1, 1), (2, 2)];
    assert_eq!(dominoes::chain(&input), None);
}

#[test]
#[ignore]
fn disconnected_double_loop() {
    let input = vec![(1, 2), (2, 1), (3, 4), (4, 3)];
    assert_eq!(dominoes::chain(&input), None);
}

#[test]
#[ignore]
fn disconnected_single_isolated() {
    let input = vec![(1, 2), (2, 3), (3, 1), (4, 4)];
    assert_eq!(dominoes::chain(&input), None);
}

#[test]
#[ignore]
fn need_backtrack() {
    let input = vec![(1, 2), (2, 3), (3, 1), (2, 4), (2, 4)];
    assert_correct(&input);
}

#[test]
#[ignore]
fn separate_loops() {
    let input = vec![(1, 2), (2, 3), (3, 1), (1, 1), (2, 2), (3, 3)];
    assert_correct(&input);
}

#[test]
#[ignore]
fn nine_elements() {
    let input = vec!((1, 2), (5, 3), (3, 1), (1, 2), (2, 4), (1, 6), (2, 3), (3, 4), (5, 6));
    assert_correct(&input);
}
<commit_msg>dominoes: Use &[T] instead of &Vec<T> for input<commit_after>extern crate dominoes;

use CheckResult::*;

type Domino = (usize, usize);

#[derive(Debug)]
enum CheckResult {
    GotInvalid,             // chain returned None
    Correct,
    ChainingFailure(Vec<Domino>), // failure to match the dots at the right side of one domino with
    // the one on the left side of the next
    LengthMismatch(Vec<Domino>),
    DominoMismatch(Vec<Domino>), // different dominoes are used in input and output
}

fn normalize(d: &Domino) -> Domino {
    match d {
        &(m, n) if m > n => (n, m),
        &(m, n) => (m, n)
    }
}

fn check(input: &[Domino]) -> CheckResult {
    let output = match dominoes::chain(input) {
        None => return GotInvalid,
        Some(o) => o
    };
    if input.len() != output.len() {
        return LengthMismatch(output);
    }
    else if input.len() == 0 { // and thus output.len() == 0
        return Correct;
    }

    let mut output_sorted = output.iter().map(|d| normalize(d)).collect::<Vec<Domino>>();
    output_sorted.sort();
    let mut input_sorted = input.iter().map(|d| normalize(d)).collect::<Vec<Domino>>();
    input_sorted.sort();
    if input_sorted != output_sorted {
        return DominoMismatch(output);
    }

    // both input and output have at least 1 element
    // This essentially puts the first element after the last one, thereby making it
    // easy to check whether the domino chains "wraps around".
    let mut fail = false;
    {
        let mut n = output[0].1;
        let iter = output.iter().skip(1).chain(output.iter().take(1));
        for &(first, second) in iter {
            if n != first {
                fail = true;
                break
            }
            n = second
        }
    }
    if fail {
        ChainingFailure(output)
    }
    else {
        Correct
    }
}

fn assert_correct(input: &[Domino]) {
    match check(&input) {
        Correct => (),
        GotInvalid => panic!("Unexpectedly got invalid on input {:?}", input),
        ChainingFailure(output) => panic!("Chaining failure for input {:?}, output {:?}", input, output),
        LengthMismatch(output) => panic!("Length mismatch for input {:?}, output {:?}", input, output),
        DominoMismatch(output) => panic!("Domino mismatch for input {:?}, output {:?}", input, output),
    }
}

#[test]
fn empty_input_empty_output() {
    let input = &[];
    assert_eq!(dominoes::chain(input), Some(vec!()));
}

#[test]
#[ignore]
fn singleton_input_singleton_output() {
    let input = &[(1, 1)];
    assert_correct(input);
}

#[test]
#[ignore]
fn singleton_that_cant_be_chained() {
    let input = &[(1, 2)];
    assert_eq!(dominoes::chain(input), None);
}

#[test]
#[ignore]
fn no_repeat_numbers() {
    let input = &[(1, 2), (3, 1), (2, 3)];
    assert_correct(input);
}

#[test]
#[ignore]
fn can_reverse_dominoes() {
    let input = &[(1, 2), (1, 3), (2, 3)];
    assert_correct(input);
}

#[test]
#[ignore]
fn no_chains() {
    let input = &[(1, 2), (4, 1), (2, 3)];
    assert_eq!(dominoes::chain(input), None);
}

#[test]
#[ignore]
fn disconnected_simple() {
    let input = &[(1, 1), (2, 2)];
    assert_eq!(dominoes::chain(input), None);
}

#[test]
#[ignore]
fn disconnected_double_loop() {
    let input = &[(1, 2), (2, 1), (3, 4), (4, 3)];
    assert_eq!(dominoes::chain(input), None);
}

#[test]
#[ignore]
fn disconnected_single_isolated() {
    let input = &[(1, 2), (2, 3), (3, 1), (4, 4)];
    assert_eq!(dominoes::chain(input), None);
}

#[test]
#[ignore]
fn need_backtrack() {
    let input = &[(1, 2), (2, 3), (3, 1), (2, 4), (2, 4)];
    assert_correct(input);
}

#[test]
#[ignore]
fn separate_loops() {
    let input = &[(1, 2), (2, 3), (3, 1), (1, 1), (2, 2), (3, 3)];
    assert_correct(input);
}

#[test]
#[ignore]
fn nine_elements() {
    let input = &[(1, 2), (5, 3), (3, 1), (1, 2), (2, 4), (1, 6), (2, 3), (3, 4), (5, 6)];
    assert_correct(input);
}
<|endoftext|>


<commit_before>extern crate rand;

use self::rand::ThreadRng;
use self::rand::Rng;

pub struct Cpu {
    pub registers: Reg,
    rng: ThreadRng,
}

impl Cpu {

    pub fn init() -> Self {
        Cpu {
            registers: Reg::default(),
            rng: rand::thread_rng(),
        }
    }
    /// Generates a random byte
    /// TODO: Implement
    pub fn random_byte(&mut self) -> u8 {
        self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX)
    }
}

#[derive(Default)]
pub struct Reg {
    pub v0: u8, pub v1: u8, pub v2: u8, pub v3: u8,
    pub v4: u8, pub v5: u8, pub v6: u8, pub v7: u8,
    pub v8: u8, pub v9: u8, pub va: u8, pub vb: u8,
    pub vc: u8, pub vd: u8, pub ve: u8, pub vf: u8,
    pub i: u16, pub pc: u16, pub sp: u8,
}

impl Reg {
    #[inline]
    pub fn get(&self, idx: u8) -> Option<u8> {
        match idx {
            0x0 =>  {Some(self.v0)},
            0x1 =>  {Some(self.v1)},
            0x2 =>  {Some(self.v2)},
            0x3 =>  {Some(self.v3)},
            0x4 =>  {Some(self.v4)},
            0x5 =>  {Some(self.v5)},
            0x6 =>  {Some(self.v6)},
            0x7 =>  {Some(self.v7)},
            0x8 =>  {Some(self.v8)},
            0x9 =>  {Some(self.v9)},
            0xa =>  {Some(self.va)},
            0xb =>  {Some(self.vb)},
            0xc =>  {Some(self.vc)},
            0xd =>  {Some(self.vd)},
            0xe =>  {Some(self.ve)},
            0xf =>  {Some(self.vf)},
            _ => {None},
        }
    }

    #[inline]
    pub fn set(&mut self, idx: u8, value: u8) {
        match idx {
            0x0 =>  {self.v0 = value},
            0x1 =>  {self.v1 = value},
            0x2 =>  {self.v2 = value},
            0x3 =>  {self.v3 = value},
            0x4 =>  {self.v4 = value},
            0x5 =>  {self.v5 = value},
            0x6 =>  {self.v6 = value},
            0x7 =>  {self.v7 = value},
            0x8 =>  {self.v8 = value},
            0x9 =>  {self.v9 = value},
            0xa =>  {self.va = value},
            0xb =>  {self.vb = value},
            0xc =>  {self.vc = value},
            0xd =>  {self.vd = value},
            0xe =>  {self.ve = value},
            0xf =>  {self.vf = value},
            _ => {},
        }
    }
}
<commit_msg>No more a todo<commit_after>extern crate rand;

use self::rand::ThreadRng;
use self::rand::Rng;

pub struct Cpu {
    pub registers: Reg,
    rng: ThreadRng,
}

impl Cpu {

    pub fn init() -> Self {
        Cpu {
            registers: Reg::default(),
            rng: rand::thread_rng(),
        }
    }
    /// Generates a random byte
    pub fn random_byte(&mut self) -> u8 {
        self.rng.gen_range(::std::u8::MIN, ::std::u8::MAX)
    }
}

#[derive(Default)]
pub struct Reg {
    pub v0: u8, pub v1: u8, pub v2: u8, pub v3: u8,
    pub v4: u8, pub v5: u8, pub v6: u8, pub v7: u8,
    pub v8: u8, pub v9: u8, pub va: u8, pub vb: u8,
    pub vc: u8, pub vd: u8, pub ve: u8, pub vf: u8,
    pub i: u16, pub pc: u16, pub sp: u8,
}

impl Reg {
    #[inline]
    pub fn get(&self, idx: u8) -> Option<u8> {
        match idx {
            0x0 =>  {Some(self.v0)},
            0x1 =>  {Some(self.v1)},
            0x2 =>  {Some(self.v2)},
            0x3 =>  {Some(self.v3)},
            0x4 =>  {Some(self.v4)},
            0x5 =>  {Some(self.v5)},
            0x6 =>  {Some(self.v6)},
            0x7 =>  {Some(self.v7)},
            0x8 =>  {Some(self.v8)},
            0x9 =>  {Some(self.v9)},
            0xa =>  {Some(self.va)},
            0xb =>  {Some(self.vb)},
            0xc =>  {Some(self.vc)},
            0xd =>  {Some(self.vd)},
            0xe =>  {Some(self.ve)},
            0xf =>  {Some(self.vf)},
            _ => {None},
        }
    }

    #[inline]
    pub fn set(&mut self, idx: u8, value: u8) {
        match idx {
            0x0 =>  {self.v0 = value},
            0x1 =>  {self.v1 = value},
            0x2 =>  {self.v2 = value},
            0x3 =>  {self.v3 = value},
            0x4 =>  {self.v4 = value},
            0x5 =>  {self.v5 = value},
            0x6 =>  {self.v6 = value},
            0x7 =>  {self.v7 = value},
            0x8 =>  {self.v8 = value},
            0x9 =>  {self.v9 = value},
            0xa =>  {self.va = value},
            0xb =>  {self.vb = value},
            0xc =>  {self.vc = value},
            0xd =>  {self.vd = value},
            0xe =>  {self.ve = value},
            0xf =>  {self.vf = value},
            _ => {},
        }
    }
}
<|endoftext|>


<commit_before>use alga::general::Id;
use na;
use query::{PointQuery, PointProjection};
use shape::{BaseMesh, BaseMeshElement, TriMesh, Polyline};
use bounding_volume::AABB;
use partitioning::{BVTCostFn, BVTVisitor};
use math::{Point, Isometry};

impl<P, M, I, E> PointQuery<P, M> for BaseMesh<P, I, E>
    where P: Point,
          M: Isometry<P>,
          E: BaseMeshElement<I, P> + PointQuery<P, Id> {
    #[inline]
    fn project_point(&self, m: &M, point: &P, _: bool) -> PointProjection<P> {
        let ls_pt = m.inverse_transform_point(point);
        let mut cost_fn = BaseMeshPointProjCostFn { mesh: self, point: &ls_pt };

        let mut proj = self.bvt().best_first_search(&mut cost_fn).unwrap().1;
        proj.point = m.transform_point(&proj.point);

        proj
    }

    #[inline]
    fn contains_point(&self, m: &M, point: &P) -> bool {
        let ls_pt = m.inverse_transform_point(point);
        let mut test = PointContainementTest { mesh: self, point: &ls_pt, found: false };

        self.bvt().visit(&mut test);

        test.found
    }
}

/*
 * Costs function.
 */
struct BaseMeshPointProjCostFn<'a, P: 'a + Point, I: 'a, E: 'a> {
    mesh:  &'a BaseMesh<P, I, E>,
    point: &'a P
}

impl<'a, P, I, E> BVTCostFn<P::Real, usize, AABB<P>> for BaseMeshPointProjCostFn<'a, P, I, E>
    where P: Point,
          E: BaseMeshElement<I, P> + PointQuery<P, Id> {
    type UserData = PointProjection<P>;

    #[inline]
    fn compute_bv_cost(&mut self, aabb: &AABB<P>) -> Option<P::Real> {
        Some(aabb.distance_to_point(&Id::new(), self.point, true))
    }

    #[inline]
    fn compute_b_cost(&mut self, b: &usize) -> Option<(P::Real, Self::UserData)> {
        let proj = self.mesh.element_at(*b).project_point(&Id::new(), self.point, true);

        Some((na::distance(self.point, &proj.point), proj))
    }
}

/*
 * Visitor.
 */
/// Bounding Volume Tree visitor collecting nodes that may contain a given point.
struct PointContainementTest<'a, P: 'a + Point, I: 'a, E: 'a> {
    mesh:  &'a BaseMesh<P, I, E>,
    point: &'a P,
    found: bool
}

impl<'a, P, I, E> BVTVisitor<usize, AABB<P>> for PointContainementTest<'a, P, I, E>
    where P: Point,
          E: BaseMeshElement<I, P> + PointQuery<P, Id> {
    #[inline]
    fn visit_internal(&mut self, bv: &AABB<P>) -> bool {
        !self.found && bv.contains_point(&Id::new(), self.point)
    }

    #[inline]
    fn visit_leaf(&mut self, b: &usize, bv: &AABB<P>) {
        if !self.found &&
           bv.contains_point(&Id::new(), self.point) &&
           self.mesh.element_at(*b).contains_point(&Id::new(), self.point) {
            self.found = true;
        }
    }
}

/*
 * fwd impls to exact meshes.
 */
impl<P: Point, M: Isometry<P>> PointQuery<P, M> for TriMesh<P> {
    #[inline]
    fn project_point(&self, m: &M, point: &P, solid: bool) -> PointProjection<P> {
        self.base_mesh().project_point(m, point, solid)
    }

    #[inline]
    fn distance_to_point(&self, m: &M, point: &P, solid: bool) -> P::Real {
        self.base_mesh().distance_to_point(m, point, solid)
    }

    #[inline]
    fn contains_point(&self, m: &M, point: &P) -> bool {
        self.base_mesh().contains_point(m, point)
    }
}

impl<P: Point, M: Isometry<P>> PointQuery<P, M> for Polyline<P> {
    #[inline]
    fn project_point(&self, m: &M, point: &P, solid: bool) -> PointProjection<P> {
        self.base_mesh().project_point(m, point, solid)
    }

    #[inline]
    fn distance_to_point(&self, m: &M, point: &P, solid: bool) -> P::Real {
        self.base_mesh().distance_to_point(m, point, solid)
    }

    #[inline]
    fn contains_point(&self, m: &M, point: &P) -> bool {
        self.base_mesh().contains_point(m, point)
    }
}
<commit_msg>Implement `RichPointQuery` for `BaseMesh`<commit_after>use alga::general::Id;
use na;
use query::{PointQuery, PointProjection, RichPointQuery};
use shape::{BaseMesh, BaseMeshElement, TriMesh, Polyline};
use bounding_volume::AABB;
use partitioning::{BVTCostFn, BVTVisitor};
use math::{Point, Isometry};

impl<P, M, I, E> PointQuery<P, M> for BaseMesh<P, I, E>
    where P: Point,
          M: Isometry<P>,
          E: BaseMeshElement<I, P> + PointQuery<P, Id> + RichPointQuery<P, Id> {
    #[inline]
    fn project_point(&self, m: &M, point: &P, solid: bool) -> PointProjection<P> {
        let (projection, _) = self.project_point_with_extra_info(m, point, solid);
        projection
    }

    #[inline]
    fn contains_point(&self, m: &M, point: &P) -> bool {
        let ls_pt = m.inverse_transform_point(point);
        let mut test = PointContainementTest { mesh: self, point: &ls_pt, found: false };

        self.bvt().visit(&mut test);

        test.found
    }
}

impl<P, M, I, E> RichPointQuery<P, M> for BaseMesh<P, I, E>
    where P: Point,
          M: Isometry<P>,
          E: BaseMeshElement<I, P> + RichPointQuery<P, Id>
{
    type ExtraInfo = PointProjectionInfo<E::ExtraInfo>;

    #[inline]
    fn project_point_with_extra_info(&self, m: &M, point: &P, _: bool)
        -> (PointProjection<P>, Self::ExtraInfo)
    {
        let ls_pt = m.inverse_transform_point(point);
        let mut cost_fn = BaseMeshPointProjCostFn { mesh: self, point: &ls_pt };

        let (mut proj, extra_info) = self.bvt().best_first_search(&mut cost_fn).unwrap().1;
        proj.point = m.transform_point(&proj.point);

        (proj, extra_info)
    }
}

/*
 * Costs function.
 */
struct BaseMeshPointProjCostFn<'a, P: 'a + Point, I: 'a, E: 'a> {
    mesh:  &'a BaseMesh<P, I, E>,
    point: &'a P
}

impl<'a, P, I, E> BVTCostFn<P::Real, usize, AABB<P>> for BaseMeshPointProjCostFn<'a, P, I, E>
    where P: Point,
          E: BaseMeshElement<I, P> + RichPointQuery<P, Id> {
    type UserData = (PointProjection<P>, PointProjectionInfo<E::ExtraInfo>);

    #[inline]
    fn compute_bv_cost(&mut self, aabb: &AABB<P>) -> Option<P::Real> {
        Some(aabb.distance_to_point(&Id::new(), self.point, true))
    }

    #[inline]
    fn compute_b_cost(&mut self, b: &usize) -> Option<(P::Real, Self::UserData)> {
        let (proj, extra_info) = self.mesh
            .element_at(*b)
            .project_point_with_extra_info(&Id::new(), self.point, true);

        let extra_info = PointProjectionInfo {
            element_index          : *b,
            barycentric_coordinates: extra_info,
        };

        Some((na::distance(self.point, &proj.point), (proj, extra_info)))
    }
}

/*
 * Visitor.
 */
/// Bounding Volume Tree visitor collecting nodes that may contain a given point.
struct PointContainementTest<'a, P: 'a + Point, I: 'a, E: 'a> {
    mesh:  &'a BaseMesh<P, I, E>,
    point: &'a P,
    found: bool
}

impl<'a, P, I, E> BVTVisitor<usize, AABB<P>> for PointContainementTest<'a, P, I, E>
    where P: Point,
          E: BaseMeshElement<I, P> + PointQuery<P, Id> {
    #[inline]
    fn visit_internal(&mut self, bv: &AABB<P>) -> bool {
        !self.found && bv.contains_point(&Id::new(), self.point)
    }

    #[inline]
    fn visit_leaf(&mut self, b: &usize, bv: &AABB<P>) {
        if !self.found &&
           bv.contains_point(&Id::new(), self.point) &&
           self.mesh.element_at(*b).contains_point(&Id::new(), self.point) {
            self.found = true;
        }
    }
}

/// Additional point pojection info for base meshes
pub struct PointProjectionInfo<C> {
    /// The index of the base mesh element the point was projected on
    ///
    /// The terminology is a bit confusing here, as this is not the index of a
    /// base mesh vertex, but rather of a base mesh element. Meaning, it is
    /// intended to be passed to `BaseMesh::element_at`.
    pub element_index: usize,

    /// The barycentry coordinates of the projected point
    ///
    /// The type of this field depends on the type of the base mesh element.
    pub barycentric_coordinates: C,
}

/*
 * fwd impls to exact meshes.
 */
impl<P: Point, M: Isometry<P>> PointQuery<P, M> for TriMesh<P> {
    #[inline]
    fn project_point(&self, m: &M, point: &P, solid: bool) -> PointProjection<P> {
        self.base_mesh().project_point(m, point, solid)
    }

    #[inline]
    fn distance_to_point(&self, m: &M, point: &P, solid: bool) -> P::Real {
        self.base_mesh().distance_to_point(m, point, solid)
    }

    #[inline]
    fn contains_point(&self, m: &M, point: &P) -> bool {
        self.base_mesh().contains_point(m, point)
    }
}

impl<P: Point, M: Isometry<P>> PointQuery<P, M> for Polyline<P> {
    #[inline]
    fn project_point(&self, m: &M, point: &P, solid: bool) -> PointProjection<P> {
        self.base_mesh().project_point(m, point, solid)
    }

    #[inline]
    fn distance_to_point(&self, m: &M, point: &P, solid: bool) -> P::Real {
        self.base_mesh().distance_to_point(m, point, solid)
    }

    #[inline]
    fn contains_point(&self, m: &M, point: &P) -> bool {
        self.base_mesh().contains_point(m, point)
    }
}
<|endoftext|>


<commit_before>use crate::{
    key::{BeaconChainKey, LocalMetricsKey, MetricsRegistryKey},
    map_persistent_err_to_500,
};
use beacon_chain::{BeaconChain, BeaconChainTypes};
use iron::prelude::*;
use iron::{status::Status, Handler, IronResult, Request, Response};
use persistent::Read;
use prometheus::{Encoder, IntGauge, Opts, Registry, TextEncoder};
use slot_clock::SlotClock;
use std::sync::Arc;
use types::Slot;

/// Yields a handler for the metrics endpoint.
pub fn build_handler<T: BeaconChainTypes + 'static>(
    beacon_chain: Arc<BeaconChain<T>>,
    metrics_registry: Registry,
) -> impl Handler {
    let mut chain = Chain::new(handle_metrics::<T>);

    let local_metrics = LocalMetrics::new().unwrap();
    local_metrics.register(&metrics_registry).unwrap();

    chain.link(Read::<BeaconChainKey<T>>::both(beacon_chain));
    chain.link(Read::<MetricsRegistryKey>::both(metrics_registry));
    chain.link(Read::<LocalMetricsKey>::both(local_metrics));

    chain
}

pub struct LocalMetrics {
    present_slot: IntGauge,
    validator_count: IntGauge,
}

impl LocalMetrics {
    pub fn new() -> Result<Self, prometheus::Error> {
        Ok(Self {
            present_slot: {
                let opts = Opts::new("present_slot", "slot_at_time_of_scrape");
                IntGauge::with_opts(opts)?
            },
            validator_count: {
                let opts = Opts::new("validator_count", "number_of_validators");
                IntGauge::with_opts(opts)?
            },
        })
    }

    pub fn register(&self, registry: &Registry) -> Result<(), prometheus::Error> {
        registry.register(Box::new(self.present_slot.clone()))?;

        Ok(())
    }
}

/// Handle a request for Prometheus metrics.
///
/// Returns a text string containing all metrics.
fn handle_metrics<T: BeaconChainTypes + 'static>(req: &mut Request) -> IronResult<Response> {
    let beacon_chain = req
        .get::<Read<BeaconChainKey<T>>>()
        .map_err(map_persistent_err_to_500)?;

    let r = req
        .get::<Read<MetricsRegistryKey>>()
        .map_err(map_persistent_err_to_500)?;

    let local_metrics = req
        .get::<Read<LocalMetricsKey>>()
        .map_err(map_persistent_err_to_500)?;

    let present_slot = beacon_chain
        .slot_clock
        .present_slot()
        .unwrap_or_else(|_| None)
        .unwrap_or_else(|| Slot::new(0));
    local_metrics.present_slot.set(present_slot.as_u64() as i64);

    let validator_count = beacon_chain.head().beacon_state.validator_registry.len();
    local_metrics.validator_count.set(validator_count as i64);

    // Gather the metrics.
    let mut buffer = vec![];
    let encoder = TextEncoder::new();
    let metric_families = r.gather();
    encoder.encode(&metric_families, &mut buffer).unwrap();

    let prom_string = String::from_utf8(buffer).unwrap();

    Ok(Response::with((Status::Ok, prom_string)))
}
<commit_msg>Add `best_slot` metric<commit_after>use crate::{
    key::{BeaconChainKey, LocalMetricsKey, MetricsRegistryKey},
    map_persistent_err_to_500,
};
use beacon_chain::{BeaconChain, BeaconChainTypes};
use iron::prelude::*;
use iron::{status::Status, Handler, IronResult, Request, Response};
use persistent::Read;
use prometheus::{Encoder, IntGauge, Opts, Registry, TextEncoder};
use slot_clock::SlotClock;
use std::sync::Arc;
use types::Slot;

/// Yields a handler for the metrics endpoint.
pub fn build_handler<T: BeaconChainTypes + 'static>(
    beacon_chain: Arc<BeaconChain<T>>,
    metrics_registry: Registry,
) -> impl Handler {
    let mut chain = Chain::new(handle_metrics::<T>);

    let local_metrics = LocalMetrics::new().unwrap();
    local_metrics.register(&metrics_registry).unwrap();

    chain.link(Read::<BeaconChainKey<T>>::both(beacon_chain));
    chain.link(Read::<MetricsRegistryKey>::both(metrics_registry));
    chain.link(Read::<LocalMetricsKey>::both(local_metrics));

    chain
}

pub struct LocalMetrics {
    present_slot: IntGauge,
    best_slot: IntGauge,
    validator_count: IntGauge,
}

impl LocalMetrics {
    pub fn new() -> Result<Self, prometheus::Error> {
        Ok(Self {
            present_slot: {
                let opts = Opts::new("present_slot", "slot_at_time_of_scrape");
                IntGauge::with_opts(opts)?
            },
            best_slot: {
                let opts = Opts::new("present_slot", "slot_of_block_at_chain_head");
                IntGauge::with_opts(opts)?
            },
            validator_count: {
                let opts = Opts::new("validator_count", "number_of_validators");
                IntGauge::with_opts(opts)?
            },
        })
    }

    pub fn register(&self, registry: &Registry) -> Result<(), prometheus::Error> {
        registry.register(Box::new(self.present_slot.clone()))?;
        registry.register(Box::new(self.best_slot.clone()))?;
        registry.register(Box::new(self.validator_count.clone()))?;

        Ok(())
    }
}

/// Handle a request for Prometheus metrics.
///
/// Returns a text string containing all metrics.
fn handle_metrics<T: BeaconChainTypes + 'static>(req: &mut Request) -> IronResult<Response> {
    let beacon_chain = req
        .get::<Read<BeaconChainKey<T>>>()
        .map_err(map_persistent_err_to_500)?;

    let r = req
        .get::<Read<MetricsRegistryKey>>()
        .map_err(map_persistent_err_to_500)?;

    let local_metrics = req
        .get::<Read<LocalMetricsKey>>()
        .map_err(map_persistent_err_to_500)?;

    let present_slot = beacon_chain
        .slot_clock
        .present_slot()
        .unwrap_or_else(|_| None)
        .unwrap_or_else(|| Slot::new(0));
    local_metrics.present_slot.set(present_slot.as_u64() as i64);

    let best_slot = beacon_chain.head().beacon_block.slot;
    local_metrics.best_slot.set(best_slot.as_u64() as i64);

    let validator_count = beacon_chain.head().beacon_state.validator_registry.len();
    local_metrics.validator_count.set(validator_count as i64);

    // Gather the metrics.
    let mut buffer = vec![];
    let encoder = TextEncoder::new();
    let metric_families = r.gather();
    encoder.encode(&metric_families, &mut buffer).unwrap();

    let prom_string = String::from_utf8(buffer).unwrap();

    Ok(Response::with((Status::Ok, prom_string)))
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::convert::TryInto;
use std::env;

use crate::error::*;
use crate::source::Source;
use crate::value::{Value, ValueKind};

#[derive(Clone, Debug)]
pub struct Environment {
    /// Optional prefix that will limit access to the environment to only keys that
    /// begin with the defined prefix.
    ///
    /// A prefix with a separator of `_` is tested to be present on each key before its considered
    /// to be part of the source environment.
    ///
    /// For example, the key `CONFIG_DEBUG` would become `DEBUG` with a prefix of `config`.
    prefix: Option<String>,

    /// Optional character sequence that separates each key segment in an environment key pattern.
    /// Consider a nested configuration such as `redis.password`, a separator of `_` would allow
    /// an environment key of `REDIS_PASSWORD` to match.
    separator: Option<String>,

    /// Ignore empty env values (treat as unset).
    ignore_empty: bool,

    /// Parses booleans, integers and floats if they're detected (can be safely parsed).
    try_parsing: bool,
}

impl Environment {
    pub fn new() -> Self {
        Environment::default()
    }

    pub fn with_prefix(s: &str) -> Self {
        Environment {
            prefix: Some(s.into()),
            ..Environment::default()
        }
    }

    pub fn prefix(mut self, s: &str) -> Self {
        self.prefix = Some(s.into());
        self
    }

    pub fn separator(mut self, s: &str) -> Self {
        self.separator = Some(s.into());
        self
    }

    pub fn ignore_empty(mut self, ignore: bool) -> Self {
        self.ignore_empty = ignore;
        self
    }

    pub fn try_parsing(mut self, try_parsing: bool) -> Self {
        self.try_parsing = try_parsing;
        self
    }
}

impl Default for Environment {
    fn default() -> Environment {
        Environment {
            prefix: None,
            separator: None,
            ignore_empty: false,
            try_parsing: false,
        }
    }
}

impl Source for Environment {
    fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
        Box::new((*self).clone())
    }

    fn collect(&self) -> Result<HashMap<String, Value>> {
        let mut m = HashMap::new();
        let uri: String = "the environment".into();

        let separator = match self.separator {
            Some(ref separator) => separator,
            _ => "",
        };

        let group_separator = match self.separator {
            Some(ref separator) => separator,
            _ => "_",
        };

        // Define a prefix pattern to test and exclude from keys
        let prefix_pattern = self
            .prefix
            .as_ref()
            .map(|prefix| format!("{}{}", prefix.clone(), group_separator));

        for (key, value) in env::vars() {
            // Treat empty environment variables as unset
            if self.ignore_empty && value.is_empty() {
                continue;
            }

            let mut key = key.to_string();

            // Check for prefix
            if let Some(ref prefix_pattern) = prefix_pattern {
                if key
                    .to_lowercase()
                    .starts_with(&prefix_pattern.to_lowercase())
                {
                    // Remove this prefix from the key
                    key = key[prefix_pattern.len()..].to_string();
                } else {
                    // Skip this key
                    continue;
                }
            }

            // If separator is given replace with `.`
            if !separator.is_empty() {
                key = key.replace(separator, ".");
            }

            let value = if self.try_parsing {
                // convert to lowercase because bool parsing expects all lowercase
                if let Ok(parsed) = value.to_lowercase().parse::<bool>() {
                    Value::new(Some(&uri), ValueKind::Boolean(parsed))
                } else if let Ok(parsed) = value.parse::<i64>() {
                    Value::new(Some(&uri), ValueKind::Integer(parsed))
                } else if let Ok(parsed) = value.parse::<f64>() {
                    Value::new(Some(&uri), ValueKind::Float(parsed))
                } else {
                    Value::new(Some(&uri), ValueKind::String(value))
                }
            } else {
                Value::new(Some(&uri), ValueKind::String(value))
            };

            m.insert(key.to_lowercase(), value);
        }

        Ok(m)
    }
}
<commit_msg>reduce env parsing repetition<commit_after>use std::collections::HashMap;
use std::convert::TryInto;
use std::env;

use crate::error::*;
use crate::source::Source;
use crate::value::{Value, ValueKind};

#[derive(Clone, Debug)]
pub struct Environment {
    /// Optional prefix that will limit access to the environment to only keys that
    /// begin with the defined prefix.
    ///
    /// A prefix with a separator of `_` is tested to be present on each key before its considered
    /// to be part of the source environment.
    ///
    /// For example, the key `CONFIG_DEBUG` would become `DEBUG` with a prefix of `config`.
    prefix: Option<String>,

    /// Optional character sequence that separates each key segment in an environment key pattern.
    /// Consider a nested configuration such as `redis.password`, a separator of `_` would allow
    /// an environment key of `REDIS_PASSWORD` to match.
    separator: Option<String>,

    /// Ignore empty env values (treat as unset).
    ignore_empty: bool,

    /// Parses booleans, integers and floats if they're detected (can be safely parsed).
    try_parsing: bool,
}

impl Environment {
    pub fn new() -> Self {
        Environment::default()
    }

    pub fn with_prefix(s: &str) -> Self {
        Environment {
            prefix: Some(s.into()),
            ..Environment::default()
        }
    }

    pub fn prefix(mut self, s: &str) -> Self {
        self.prefix = Some(s.into());
        self
    }

    pub fn separator(mut self, s: &str) -> Self {
        self.separator = Some(s.into());
        self
    }

    pub fn ignore_empty(mut self, ignore: bool) -> Self {
        self.ignore_empty = ignore;
        self
    }

    pub fn try_parsing(mut self, try_parsing: bool) -> Self {
        self.try_parsing = try_parsing;
        self
    }
}

impl Default for Environment {
    fn default() -> Environment {
        Environment {
            prefix: None,
            separator: None,
            ignore_empty: false,
            try_parsing: false,
        }
    }
}

impl Source for Environment {
    fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
        Box::new((*self).clone())
    }

    fn collect(&self) -> Result<HashMap<String, Value>> {
        let mut m = HashMap::new();
        let uri: String = "the environment".into();

        let separator = match self.separator {
            Some(ref separator) => separator,
            _ => "",
        };

        let group_separator = match self.separator {
            Some(ref separator) => separator,
            _ => "_",
        };

        // Define a prefix pattern to test and exclude from keys
        let prefix_pattern = self
            .prefix
            .as_ref()
            .map(|prefix| format!("{}{}", prefix.clone(), group_separator));

        for (key, value) in env::vars() {
            // Treat empty environment variables as unset
            if self.ignore_empty && value.is_empty() {
                continue;
            }

            let mut key = key.to_string();

            // Check for prefix
            if let Some(ref prefix_pattern) = prefix_pattern {
                if key
                    .to_lowercase()
                    .starts_with(&prefix_pattern.to_lowercase())
                {
                    // Remove this prefix from the key
                    key = key[prefix_pattern.len()..].to_string();
                } else {
                    // Skip this key
                    continue;
                }
            }

            // If separator is given replace with `.`
            if !separator.is_empty() {
                key = key.replace(separator, ".");
            }

            let value = if self.try_parsing {
                // convert to lowercase because bool parsing expects all lowercase
                if let Ok(parsed) = value.to_lowercase().parse::<bool>() {
                    ValueKind::Boolean(parsed)
                } else if let Ok(parsed) = value.parse::<i64>() {
                    ValueKind::Integer(parsed)
                } else if let Ok(parsed) = value.parse::<f64>() {
                    ValueKind::Float(parsed)
                } else {
                    ValueKind::String(value)
                }
            } else {
                ValueKind::String(value)
            };

            m.insert(key.to_lowercase(), Value::new(Some(&uri), value));
        }

        Ok(m)
    }
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(iter_arith)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(optin_builtin_traits)]
#![feature(peekable_is_empty)]
#![feature(plugin)]
#![feature(slice_patterns)]
#![feature(stmt_expr_attributes)]
#![feature(question_mark)]

#![deny(unsafe_code)]
#![allow(non_snake_case)]

#![doc = "The script crate contains all matters DOM."]

#![plugin(heapsize_plugin)]
#![plugin(phf_macros)]
#![plugin(plugins)]

extern crate angle;
extern crate app_units;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate bitflags;
extern crate canvas;
extern crate canvas_traits;
extern crate caseless;
extern crate core;
extern crate cssparser;
extern crate devtools_traits;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate gfx_traits;
extern crate heapsize;
extern crate html5ever;
extern crate hyper;
extern crate image;
extern crate ipc_channel;
extern crate js;
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate mime;
extern crate msg;
extern crate net_traits;
extern crate num_traits;
extern crate offscreen_gl_context;
extern crate open;
extern crate phf;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate ref_filter_map;
extern crate ref_slice;
extern crate regex;
extern crate rustc_serialize;
extern crate script_traits;
extern crate selectors;
extern crate serde;
extern crate smallvec;
#[macro_use(atom, ns)] extern crate string_cache;
#[macro_use]
extern crate style;
extern crate time;
#[cfg(any(target_os = "macos", target_os = "linux"))]
extern crate tinyfiledialogs;
extern crate unicase;
extern crate url;
#[macro_use]
extern crate util;
extern crate uuid;
extern crate webrender_traits;
extern crate websocket;
extern crate xml5ever;

pub mod bluetooth_blacklist;
pub mod clipboard_provider;
pub mod cors;
mod devtools;
pub mod document_loader;
#[macro_use]
pub mod dom;
pub mod layout_interface;
mod mem;
mod network_listener;
pub mod origin;
pub mod parse;
pub mod reporter;
pub mod script_runtime;
#[allow(unsafe_code)]
pub mod script_thread;
mod task_source;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;

use dom::bindings::codegen::RegisterBindings;
use js::jsapi::SetDOMProxyInformation;
use std::ptr;

#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
    use std::mem;
    // 4096 is default max on many linux systems
    const MAX_FILE_LIMIT: libc::rlim_t = 4096;

    // Bump up our number of file descriptors to save us from impending doom caused by an onslaught
    // of iframes.
    unsafe {
        let mut rlim: libc::rlimit = mem::uninitialized();
        match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
            0 => {
                if rlim.rlim_cur >= MAX_FILE_LIMIT {
                    // we have more than enough
                    return;
                }

                rlim.rlim_cur = match rlim.rlim_max {
                    libc::RLIM_INFINITY => MAX_FILE_LIMIT,
                    _ => {
                        if rlim.rlim_max < MAX_FILE_LIMIT {
                            rlim.rlim_max
                        } else {
                            MAX_FILE_LIMIT
                        }
                    }
                };
                match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
                    0 => (),
                    _ => warn!("Failed to set file count limit"),
                };
            },
            _ => warn!("Failed to get file count limit"),
        };
    }
}

#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}

#[allow(unsafe_code)]
pub fn init() {
    unsafe {
        assert_eq!(js::jsapi::JS_Init(), true);
        SetDOMProxyInformation(ptr::null(), 0, Some(script_thread::shadow_check_callback));
    }

    // Create the global vtables used by the (generated) DOM
    // bindings to implement JS proxies.
    RegisterBindings::RegisterProxyHandlers();

    perform_platform_specific_initialization();
}
<commit_msg>Auto merge of #11553 - Ms2ger:init, r=nox<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/. */

#![feature(as_unsafe_cell)]
#![feature(borrow_state)]
#![feature(box_syntax)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(custom_attribute)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(iter_arith)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(optin_builtin_traits)]
#![feature(peekable_is_empty)]
#![feature(plugin)]
#![feature(slice_patterns)]
#![feature(stmt_expr_attributes)]
#![feature(question_mark)]

#![deny(unsafe_code)]
#![allow(non_snake_case)]

#![doc = "The script crate contains all matters DOM."]

#![plugin(heapsize_plugin)]
#![plugin(phf_macros)]
#![plugin(plugins)]

extern crate angle;
extern crate app_units;
#[allow(unused_extern_crates)]
#[macro_use]
extern crate bitflags;
extern crate canvas;
extern crate canvas_traits;
extern crate caseless;
extern crate core;
extern crate cssparser;
extern crate devtools_traits;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate gfx_traits;
extern crate heapsize;
extern crate html5ever;
extern crate hyper;
extern crate image;
extern crate ipc_channel;
extern crate js;
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate mime;
extern crate msg;
extern crate net_traits;
extern crate num_traits;
extern crate offscreen_gl_context;
extern crate open;
extern crate phf;
#[macro_use]
extern crate profile_traits;
extern crate rand;
extern crate ref_filter_map;
extern crate ref_slice;
extern crate regex;
extern crate rustc_serialize;
extern crate script_traits;
extern crate selectors;
extern crate serde;
extern crate smallvec;
#[macro_use(atom, ns)] extern crate string_cache;
#[macro_use]
extern crate style;
extern crate time;
#[cfg(any(target_os = "macos", target_os = "linux"))]
extern crate tinyfiledialogs;
extern crate unicase;
extern crate url;
#[macro_use]
extern crate util;
extern crate uuid;
extern crate webrender_traits;
extern crate websocket;
extern crate xml5ever;

pub mod bluetooth_blacklist;
pub mod clipboard_provider;
pub mod cors;
mod devtools;
pub mod document_loader;
#[macro_use]
pub mod dom;
pub mod layout_interface;
mod mem;
mod network_listener;
pub mod origin;
pub mod parse;
pub mod reporter;
pub mod script_runtime;
#[allow(unsafe_code)]
pub mod script_thread;
mod task_source;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;

use dom::bindings::codegen::RegisterBindings;
use js::jsapi::SetDOMProxyInformation;
use std::ptr;

#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
    use std::mem;
    // 4096 is default max on many linux systems
    const MAX_FILE_LIMIT: libc::rlim_t = 4096;

    // Bump up our number of file descriptors to save us from impending doom caused by an onslaught
    // of iframes.
    unsafe {
        let mut rlim: libc::rlimit = mem::uninitialized();
        match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
            0 => {
                if rlim.rlim_cur >= MAX_FILE_LIMIT {
                    // we have more than enough
                    return;
                }

                rlim.rlim_cur = match rlim.rlim_max {
                    libc::RLIM_INFINITY => MAX_FILE_LIMIT,
                    _ => {
                        if rlim.rlim_max < MAX_FILE_LIMIT {
                            rlim.rlim_max
                        } else {
                            MAX_FILE_LIMIT
                        }
                    }
                };
                match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
                    0 => (),
                    _ => warn!("Failed to set file count limit"),
                };
            },
            _ => warn!("Failed to get file count limit"),
        };
    }
}

#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}

#[allow(unsafe_code)]
pub fn init() {
    unsafe {
        SetDOMProxyInformation(ptr::null(), 0, Some(script_thread::shadow_check_callback));
    }

    // Create the global vtables used by the (generated) DOM
    // bindings to implement JS proxies.
    RegisterBindings::RegisterProxyHandlers();

    perform_platform_specific_initialization();
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! The `servo` test application.
//!
//! Creates a `Browser` instance with a simple implementation of
//! the compositor's `WindowMethods` to create a working web browser.
//!
//! This browser's implementation of `WindowMethods` is built on top
//! of [glutin], the cross-platform OpenGL utility and windowing
//! library.
//!
//! For the engine itself look next door in lib.rs.
//!
//! [glutin]: https://github.com/tomaka/glutin

#![feature(start)]

// The Servo engine
extern crate servo;
// Window graphics compositing and message dispatch
extern crate compositing;
// Servo networking
extern crate net;
// Servo common utilitiess
extern crate util;
// The window backed by glutin
extern crate glutin_app as app;
extern crate time;

#[cfg(target_os="android")]
#[macro_use]
extern crate android_glue;

use std::rc::Rc;
use util::opts;
use net::resource_task;
use servo::Browser;
use compositing::windowing::WindowEvent;

#[cfg(target_os="android")]
use std::borrow::ToOwned;

fn main() {
    // Parse the command line options and store them globally
    if opts::from_cmdline_args(&*get_args()) {
        setup_logging();

        // Possibly interpret the `HOST_FILE` environment variable
        resource_task::global_init();

        let window = if opts::get().headless {
            None
        } else {
            Some(app::create_window(std::ptr::null_mut()))
        };

        // Our wrapper around `Browser` that also implements some
        // callbacks required by the glutin window implementation.
        let mut browser = BrowserWrapper {
            browser: Browser::new(window.clone()),
        };

        maybe_register_glutin_resize_handler(&window, &mut browser);

        browser.browser.handle_event(WindowEvent::InitializeCompositing);

        // Feed events from the window to the browser until the browser
        // says to stop.
        loop {
            let should_continue = match window {
                None => browser.browser.handle_event(WindowEvent::Idle),
                Some(ref window) => {
                    let event = window.wait_events();
                    browser.browser.handle_event(event)
                }
            };
            if !should_continue {
                break
            }
        };

        maybe_unregister_glutin_resize_handler(&window);

        let BrowserWrapper {
            browser
        } = browser;
        browser.shutdown();
    }
}

fn maybe_register_glutin_resize_handler(window: &Option<Rc<app::window::Window>>,
                                        browser: &mut BrowserWrapper) {
    match *window {
        None => {}
        Some(ref window) => {
            unsafe {
                window.set_nested_event_loop_listener(browser);
            }
        }
    }
}

fn maybe_unregister_glutin_resize_handler(window: &Option<Rc<app::window::Window>>) {
    match *window {
        None => {}
        Some(ref window) => {
            unsafe {
                window.remove_nested_event_loop_listener();
            }
        }
    }
}

struct BrowserWrapper {
    browser: Browser,
}

impl app::NestedEventLoopListener for BrowserWrapper {
    fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool {
        let is_resize = match event {
            WindowEvent::Resize(..) => true,
            _ => false,
        };
        if !self.browser.handle_event(event) {
            return false
        }
        if is_resize {
            self.browser.repaint_synchronously()
        }
        true
    }
}

#[cfg(target_os="android")]
fn setup_logging() {
    android::setup_logging();
}

#[cfg(not(target_os="android"))]
fn setup_logging() {
}

#[cfg(target_os="android")]
fn get_args() -> Vec<String> {
    vec![
        "servo".to_owned(),
        "http://en.wikipedia.org/wiki/Rust".to_owned()
    ]
}

#[cfg(not(target_os="android"))]
fn get_args() -> Vec<String> {
    use std::env;
    env::args().collect()
}

// This macro must be used at toplevel because it defines a nested
// module, but macros can only accept identifiers - not paths -
// preventing the expansion of this macro within the android module
// without use of an additionl stub method or other hackery.
#[cfg(target_os = "android")]
android_start!(main);

#[cfg(target_os = "android")]
mod android {
    extern crate libc;
    extern crate android_glue;

    use self::libc::c_int;
    use std::borrow::ToOwned;

    pub fn setup_logging() {
        use self::libc::consts::os::posix88::{STDERR_FILENO, STDOUT_FILENO};
        //use std::env;

        //env::set_var("RUST_LOG", "servo,gfx,msg,util,layers,js,std,rt,extra");
        redirect_output(STDERR_FILENO);
        redirect_output(STDOUT_FILENO);
    }

    struct FilePtr(*mut self::libc::types::common::c95::FILE);

    unsafe impl Send for FilePtr {}

    fn redirect_output(file_no: c_int) {
        use self::libc::funcs::posix88::unistd::{pipe, dup2};
        use self::libc::funcs::posix88::stdio::fdopen;
        use self::libc::funcs::c95::stdio::fgets;
        use util::task::spawn_named;
        use std::ffi::CString;
        use std::str::from_utf8;

        unsafe {
            let mut pipes: [c_int; 2] = [ 0, 0 ];
            pipe(pipes.as_mut_ptr());
            dup2(pipes[1], file_no);
            let mode = CString::new("r").unwrap();
            let input_file = FilePtr(fdopen(pipes[0], mode.as_ptr()));
            spawn_named("android-logger".to_owned(), move || {
                loop {
                    let mut read_buffer: Vec<u8> = vec!();
                    read_buffer.reserve(1024);
                    let FilePtr(input_file) = input_file;
                    fgets(read_buffer.as_mut_ptr() as *mut i8, read_buffer.len() as i32, input_file);
                    let cs = CString::new(read_buffer).unwrap();
                    match from_utf8(cs.as_bytes()) {
                        Ok(s) => android_glue::write_log(s),
                        _ => {}
                    }
                }
            });
        }
    }

}
<commit_msg>Fix android logging since the rustup<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/. */

//! The `servo` test application.
//!
//! Creates a `Browser` instance with a simple implementation of
//! the compositor's `WindowMethods` to create a working web browser.
//!
//! This browser's implementation of `WindowMethods` is built on top
//! of [glutin], the cross-platform OpenGL utility and windowing
//! library.
//!
//! For the engine itself look next door in lib.rs.
//!
//! [glutin]: https://github.com/tomaka/glutin

#![feature(start)]

// The Servo engine
extern crate servo;
// Window graphics compositing and message dispatch
extern crate compositing;
// Servo networking
extern crate net;
// Servo common utilitiess
extern crate util;
// The window backed by glutin
extern crate glutin_app as app;
extern crate time;

#[cfg(target_os="android")]
#[macro_use]
extern crate android_glue;

use std::rc::Rc;
use util::opts;
use net::resource_task;
use servo::Browser;
use compositing::windowing::WindowEvent;

#[cfg(target_os="android")]
use std::borrow::ToOwned;

fn main() {
    // Parse the command line options and store them globally
    if opts::from_cmdline_args(&*get_args()) {
        setup_logging();

        // Possibly interpret the `HOST_FILE` environment variable
        resource_task::global_init();

        let window = if opts::get().headless {
            None
        } else {
            Some(app::create_window(std::ptr::null_mut()))
        };

        // Our wrapper around `Browser` that also implements some
        // callbacks required by the glutin window implementation.
        let mut browser = BrowserWrapper {
            browser: Browser::new(window.clone()),
        };

        maybe_register_glutin_resize_handler(&window, &mut browser);

        browser.browser.handle_event(WindowEvent::InitializeCompositing);

        // Feed events from the window to the browser until the browser
        // says to stop.
        loop {
            let should_continue = match window {
                None => browser.browser.handle_event(WindowEvent::Idle),
                Some(ref window) => {
                    let event = window.wait_events();
                    browser.browser.handle_event(event)
                }
            };
            if !should_continue {
                break
            }
        };

        maybe_unregister_glutin_resize_handler(&window);

        let BrowserWrapper {
            browser
        } = browser;
        browser.shutdown();
    }
}

fn maybe_register_glutin_resize_handler(window: &Option<Rc<app::window::Window>>,
                                        browser: &mut BrowserWrapper) {
    match *window {
        None => {}
        Some(ref window) => {
            unsafe {
                window.set_nested_event_loop_listener(browser);
            }
        }
    }
}

fn maybe_unregister_glutin_resize_handler(window: &Option<Rc<app::window::Window>>) {
    match *window {
        None => {}
        Some(ref window) => {
            unsafe {
                window.remove_nested_event_loop_listener();
            }
        }
    }
}

struct BrowserWrapper {
    browser: Browser,
}

impl app::NestedEventLoopListener for BrowserWrapper {
    fn handle_event_from_nested_event_loop(&mut self, event: WindowEvent) -> bool {
        let is_resize = match event {
            WindowEvent::Resize(..) => true,
            _ => false,
        };
        if !self.browser.handle_event(event) {
            return false
        }
        if is_resize {
            self.browser.repaint_synchronously()
        }
        true
    }
}

#[cfg(target_os="android")]
fn setup_logging() {
    android::setup_logging();
}

#[cfg(not(target_os="android"))]
fn setup_logging() {
}

#[cfg(target_os="android")]
fn get_args() -> Vec<String> {
    vec![
        "servo".to_owned(),
        "http://en.wikipedia.org/wiki/Rust".to_owned()
    ]
}

#[cfg(not(target_os="android"))]
fn get_args() -> Vec<String> {
    use std::env;
    env::args().collect()
}

// This macro must be used at toplevel because it defines a nested
// module, but macros can only accept identifiers - not paths -
// preventing the expansion of this macro within the android module
// without use of an additionl stub method or other hackery.
#[cfg(target_os = "android")]
android_start!(main);

#[cfg(target_os = "android")]
mod android {
    extern crate libc;
    extern crate android_glue;

    use self::libc::c_int;
    use std::borrow::ToOwned;

    pub fn setup_logging() {
        use self::libc::consts::os::posix88::{STDERR_FILENO, STDOUT_FILENO};
        //use std::env;

        //env::set_var("RUST_LOG", "servo,gfx,msg,util,layers,js,std,rt,extra");
        redirect_output(STDERR_FILENO);
        redirect_output(STDOUT_FILENO);
    }

    struct FilePtr(*mut self::libc::types::common::c95::FILE);

    unsafe impl Send for FilePtr {}

    fn redirect_output(file_no: c_int) {
        use self::libc::funcs::posix88::unistd::{pipe, dup2};
        use self::libc::funcs::posix88::stdio::fdopen;
        use self::libc::funcs::c95::stdio::fgets;
        use util::task::spawn_named;
        use std::ffi::CString;
        use std::str::from_utf8;
        use std::ffi::CStr;

        unsafe {
            let mut pipes: [c_int; 2] = [ 0, 0 ];
            pipe(pipes.as_mut_ptr());
            dup2(pipes[1], file_no);
            let mode = CString::new("r").unwrap();
            let input_file = FilePtr(fdopen(pipes[0], mode.as_ptr()));
            spawn_named("android-logger".to_owned(), move || {
                static READ_SIZE: usize = 1024;
                let mut read_buffer = vec![0; READ_SIZE];
                let FilePtr(input_file) = input_file;
                loop {
                    fgets(read_buffer.as_mut_ptr(), (read_buffer.len() as i32)-1, input_file);
                    let c_str = CStr::from_ptr(read_buffer.as_ptr());
                    let slice = from_utf8(c_str.to_bytes()).unwrap();
                    android_glue::write_log(slice);
                }
            });
        }
    }

}
<|endoftext|>


<commit_before>use constant::*;
use lib::fs::*;
use std::collections::BTreeSet;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::PathBuf;

pub fn working_dir() -> PathBuf {
    path_buf![WORKING_DIR_NAME]
}

pub fn config_file() -> PathBuf {
    path_buf![working_dir(), CONFIG_FILE_NAME]
}

pub fn ignore_file() -> PathBuf {
    path_buf![working_dir(), IGNORE_FILE_NAME]
}

pub fn working_dir_exists() -> bool {
    working_dir().is_dir()
}

pub fn config_file_exists() -> bool {
    config_file().is_file()
}

pub fn ignore_file_exists() -> bool {
    ignore_file().is_file()
}

pub fn create_working_dir() {
    if working_dir_exists() {
        println!(r#"  NOTICE: "{}" directory has already exist."#, WORKING_DIR_NAME);
    } else {
        match fs::create_dir(working_dir()) {
            Ok(_)    => println!(r#"  OK: Created "{}" directory."#, WORKING_DIR_NAME),
            Err(why) => panic!("  ERROR: {}", why),
        }
    }
}

pub fn create_config_file<S: AsRef<str>>(contents: S) {
    create_setting_file(config_file(), contents);
}

pub fn create_ignore_file<S: AsRef<str>>(contents: S) {
    create_setting_file(ignore_file(), contents);
}

fn create_setting_file<S: AsRef<str>>(path_to_file: PathBuf, contents: S) {
    let file_name = extract_file_name(&path_to_file);

    if path_to_file.is_file() {
        println!(r#"  NOTICE: "{}" file has already exist."#, file_name);
    } else {
        match File::create(&path_to_file) {
            Ok(mut f) => {
                println!(r#"  OK: Created "{}" file."#, file_name);
                if let Err(why) = f.write(contents.as_ref().as_bytes()) {
                    panic!("  ERROR: {}", why);
                }
            },
            Err(why) => panic!("  ERROR: {}", why),
        }
    }
}

pub fn read_ignore_file() -> BTreeSet<String> {
    let mut f       = match File::open(ignore_file()) {
        Ok(f)    => f,
        Err(why) => panic!("  ERROR: {}", why),
    };
    let mut contents = String::new();
    if let Err(why) = f.read_to_string(&mut contents) {
        panic!("  ERROR: {}", why);
    }
    contents
        .lines()
        .map(|l| l.trim().to_string())
        .collect::<BTreeSet<String>>()
}

pub fn delete_all_setting_files() {
    match fs::remove_dir_all(WORKING_DIR_NAME) {
        Ok(_)    => println!(r#"  OK: Removed "{}" directory."#, WORKING_DIR_NAME),
        Err(why) => println!("  ERROR: {}", why),
    }
}
<commit_msg>Delete indentations of messages<commit_after>use constant::*;
use lib::fs::*;
use std::collections::BTreeSet;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::PathBuf;

pub fn working_dir() -> PathBuf {
    path_buf![WORKING_DIR_NAME]
}

pub fn config_file() -> PathBuf {
    path_buf![working_dir(), CONFIG_FILE_NAME]
}

pub fn ignore_file() -> PathBuf {
    path_buf![working_dir(), IGNORE_FILE_NAME]
}

pub fn working_dir_exists() -> bool {
    working_dir().is_dir()
}

pub fn config_file_exists() -> bool {
    config_file().is_file()
}

pub fn ignore_file_exists() -> bool {
    ignore_file().is_file()
}

pub fn create_working_dir() {
    if working_dir_exists() {
        println!(r#"NOTICE: "{}" directory has already exist."#, WORKING_DIR_NAME);
    } else {
        match fs::create_dir(working_dir()) {
            Ok(_)    => println!(r#"OK: Created "{}" directory."#, WORKING_DIR_NAME),
            Err(why) => panic!("ERROR: {}", why),
        }
    }
}

pub fn create_config_file<S: AsRef<str>>(contents: S) {
    create_setting_file(config_file(), contents);
}

pub fn create_ignore_file<S: AsRef<str>>(contents: S) {
    create_setting_file(ignore_file(), contents);
}

fn create_setting_file<S: AsRef<str>>(path_to_file: PathBuf, contents: S) {
    let file_name = extract_file_name(&path_to_file);

    if path_to_file.is_file() {
        println!(r#"NOTICE: "{}" file has already exist."#, file_name);
    } else {
        match File::create(&path_to_file) {
            Ok(mut f) => {
                println!(r#"OK: Created "{}" file."#, file_name);
                if let Err(why) = f.write(contents.as_ref().as_bytes()) {
                    panic!("ERROR: {}", why);
                }
            },
            Err(why) => panic!("ERROR: {}", why),
        }
    }
}

pub fn read_ignore_file() -> BTreeSet<String> {
    let mut f       = match File::open(ignore_file()) {
        Ok(f)    => f,
        Err(why) => panic!("ERROR: {}", why),
    };
    let mut contents = String::new();
    if let Err(why) = f.read_to_string(&mut contents) {
        panic!("ERROR: {}", why);
    }
    contents
        .lines()
        .map(|l| l.trim().to_string())
        .collect::<BTreeSet<String>>()
}

pub fn delete_all_setting_files() {
    match fs::remove_dir_all(WORKING_DIR_NAME) {
        Ok(_)    => println!(r#"OK: Removed "{}" directory."#, WORKING_DIR_NAME),
        Err(why) => panic!("ERROR: {}", why),
    }
}
<|endoftext|>


<commit_before>//! Unsafe pointer utility functions

#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];

use cmp::{Eq, Ord};
use libc::{c_void, size_t};

#[nolink]
#[abi = "cdecl"]
extern mod libc_ {
    #[rust_stack]
    fn memcpy(dest: *mut c_void, src: *const c_void,
              n: libc::size_t) -> *c_void;

    #[rust_stack]
    fn memmove(dest: *mut c_void, src: *const c_void,
               n: libc::size_t) -> *c_void;

    #[rust_stack]
    fn memset(dest: *mut c_void, c: libc::c_int,
              len: libc::size_t) -> *c_void;
}

#[abi = "rust-intrinsic"]
extern mod rusti {
    fn addr_of<T>(&&val: T) -> *T;
}

/// Get an unsafe pointer to a value
#[inline(always)]
pub pure fn addr_of<T>(val: &T) -> *T { unsafe { rusti::addr_of(*val) } }

/// Get an unsafe mut pointer to a value
#[inline(always)]
pub pure fn mut_addr_of<T>(val: &T) -> *mut T {
    unsafe {
        cast::reinterpret_cast(&rusti::addr_of(*val))
    }
}

/// Calculate the offset from a pointer
#[inline(always)]
pub pure fn offset<T>(ptr: *T, count: uint) -> *T {
    unsafe {
        (ptr as uint + count * sys::size_of::<T>()) as *T
    }
}

/// Calculate the offset from a const pointer
#[inline(always)]
pub pure fn const_offset<T>(ptr: *const T, count: uint) -> *const T {
    unsafe {
        (ptr as uint + count * sys::size_of::<T>()) as *T
    }
}

/// Calculate the offset from a mut pointer
#[inline(always)]
pub pure fn mut_offset<T>(ptr: *mut T, count: uint) -> *mut T {
    (ptr as uint + count * sys::size_of::<T>()) as *mut T
}

/// Return the offset of the first null pointer in `buf`.
#[inline(always)]
pub unsafe fn buf_len<T>(buf: **T) -> uint {
    position(buf, |i| *i == null())
}

/// Return the first offset `i` such that `f(buf[i]) == true`.
#[inline(always)]
pub unsafe fn position<T>(buf: *T, f: fn(&T) -> bool) -> uint {
    let mut i = 0;
    loop {
        if f(&(*offset(buf, i))) { return i; }
        else { i += 1; }
    }
}

/// Create an unsafe null pointer
#[inline(always)]
pub pure fn null<T>() -> *T { unsafe { cast::reinterpret_cast(&0u) } }

/// Create an unsafe mutable null pointer
#[inline(always)]
pub pure fn mut_null<T>() -> *mut T { unsafe { cast::reinterpret_cast(&0u) } }

/// Returns true if the pointer is equal to the null pointer.
pub pure fn is_null<T>(ptr: *const T) -> bool { ptr == null() }

/// Returns true if the pointer is not equal to the null pointer.
pub pure fn is_not_null<T>(ptr: *const T) -> bool { !is_null(ptr) }

/**
 * Copies data from one location to another
 *
 * Copies `count` elements (not bytes) from `src` to `dst`. The source
 * and destination may not overlap.
 */
#[inline(always)]
pub unsafe fn memcpy<T>(dst: *mut T, src: *const T, count: uint) {
    let n = count * sys::size_of::<T>();
    libc_::memcpy(dst as *mut c_void, src as *c_void, n as size_t);
}

/**
 * Copies data from one location to another
 *
 * Copies `count` elements (not bytes) from `src` to `dst`. The source
 * and destination may overlap.
 */
#[inline(always)]
pub unsafe fn memmove<T>(dst: *mut T, src: *const T, count: uint) {
    let n = count * sys::size_of::<T>();
    libc_::memmove(dst as *mut c_void, src as *c_void, n as size_t);
}

#[inline(always)]
pub unsafe fn memset<T>(dst: *mut T, c: int, count: uint) {
    let n = count * sys::size_of::<T>();
    libc_::memset(dst as *mut c_void, c as libc::c_int, n as size_t);
}

/**
  Transform a region pointer - &T - to an unsafe pointer - *T.
  This is safe, but is implemented with an unsafe block due to
  reinterpret_cast.
*/
#[inline(always)]
pub pure fn to_unsafe_ptr<T>(thing: &T) -> *T {
    unsafe { cast::reinterpret_cast(&thing) }
}

/**
  Transform a const region pointer - &const T - to a const unsafe pointer -
  *const T. This is safe, but is implemented with an unsafe block due to
  reinterpret_cast.
*/
#[inline(always)]
pub pure fn to_const_unsafe_ptr<T>(thing: &const T) -> *const T {
    unsafe { cast::reinterpret_cast(&thing) }
}

/**
  Transform a mutable region pointer - &mut T - to a mutable unsafe pointer -
  *mut T. This is safe, but is implemented with an unsafe block due to
  reinterpret_cast.
*/
#[inline(always)]
pub pure fn to_mut_unsafe_ptr<T>(thing: &mut T) -> *mut T {
    unsafe { cast::reinterpret_cast(&thing) }
}

/**
  Cast a region pointer - &T - to a uint.
  This is safe, but is implemented with an unsafe block due to
  reinterpret_cast.

  (I couldn't think of a cutesy name for this one.)
*/
#[inline(always)]
pub fn to_uint<T>(thing: &T) -> uint unsafe {
    cast::reinterpret_cast(&thing)
}

/// Determine if two borrowed pointers point to the same thing.
#[inline(always)]
pub fn ref_eq<T>(thing: &a/T, other: &b/T) -> bool {
    to_uint(thing) == to_uint(other)
}

pub trait Ptr<T> {
    pure fn is_null() -> bool;
    pure fn is_not_null() -> bool;
    pure fn offset(count: uint) -> self;
}

/// Extension methods for pointers
impl<T> *T: Ptr<T> {
    /// Returns true if the pointer is equal to the null pointer.
    #[inline(always)]
    pure fn is_null() -> bool { is_null(self) }

    /// Returns true if the pointer is not equal to the null pointer.
    #[inline(always)]
    pure fn is_not_null() -> bool { is_not_null(self) }

    /// Calculates the offset from a pointer.
    #[inline(always)]
    pure fn offset(count: uint) -> *T { offset(self, count) }
}

// Equality for pointers
impl<T> *const T : Eq {
    pure fn eq(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a == b;
    }
    pure fn ne(other: &*const T) -> bool { !self.eq(other) }
}

// Comparison for pointers
impl<T> *const T : Ord {
    pure fn lt(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a < b;
    }
    pure fn le(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a <= b;
    }
    pure fn ge(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a >= b;
    }
    pure fn gt(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a > b;
    }
}

// Equality for region pointers
impl<T:Eq> &const T : Eq {
    pure fn eq(other: & &self/const T) -> bool { return *self == *(*other); }
    pure fn ne(other: & &self/const T) -> bool { return *self != *(*other); }
}

// Comparison for region pointers
impl<T:Ord> &const T : Ord {
    pure fn lt(other: & &self/const T) -> bool { *self < *(*other) }
    pure fn le(other: & &self/const T) -> bool { *self <= *(*other) }
    pure fn ge(other: & &self/const T) -> bool { *self >= *(*other) }
    pure fn gt(other: & &self/const T) -> bool { *self > *(*other) }
}

#[test]
pub fn test() {
    unsafe {
        type Pair = {mut fst: int, mut snd: int};
        let p = {mut fst: 10, mut snd: 20};
        let pptr: *mut Pair = mut_addr_of(&p);
        let iptr: *mut int = cast::reinterpret_cast(&pptr);
        assert (*iptr == 10);;
        *iptr = 30;
        assert (*iptr == 30);
        assert (p.fst == 30);;

        *pptr = {mut fst: 50, mut snd: 60};
        assert (*iptr == 50);
        assert (p.fst == 50);
        assert (p.snd == 60);

        let mut v0 = ~[32000u16, 32001u16, 32002u16];
        let mut v1 = ~[0u16, 0u16, 0u16];

        ptr::memcpy(ptr::mut_offset(vec::raw::to_mut_ptr(v1), 1u),
                    ptr::offset(vec::raw::to_ptr(v0), 1u), 1u);
        assert (v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16);
        ptr::memcpy(vec::raw::to_mut_ptr(v1),
                    ptr::offset(vec::raw::to_ptr(v0), 2u), 1u);
        assert (v1[0] == 32002u16 && v1[1] == 32001u16 && v1[2] == 0u16);
        ptr::memcpy(ptr::mut_offset(vec::raw::to_mut_ptr(v1), 2u),
                    vec::raw::to_ptr(v0), 1u);
        assert (v1[0] == 32002u16 && v1[1] == 32001u16 && v1[2] == 32000u16);
    }
}

#[test]
pub fn test_position() {
    use str::as_c_str;
    use libc::c_char;

    let s = ~"hello";
    unsafe {
        assert 2u == as_c_str(s, |p| position(p, |c| *c == 'l' as c_char));
        assert 4u == as_c_str(s, |p| position(p, |c| *c == 'o' as c_char));
        assert 5u == as_c_str(s, |p| position(p, |c| *c == 0 as c_char));
    }
}

#[test]
pub fn test_buf_len() {
    let s0 = ~"hello";
    let s1 = ~"there";
    let s2 = ~"thing";
    do str::as_c_str(s0) |p0| {
        do str::as_c_str(s1) |p1| {
            do str::as_c_str(s2) |p2| {
                let v = ~[p0, p1, p2, null()];
                do vec::as_imm_buf(v) |vp, len| {
                    assert unsafe { buf_len(vp) } == 3u;
                    assert len == 4u;
                }
            }
        }
    }
}

#[test]
pub fn test_is_null() {
   let p: *int = ptr::null();
   assert p.is_null();
   assert !p.is_not_null();

   let q = ptr::offset(p, 1u);
   assert !q.is_null();
   assert q.is_not_null();
}
<commit_msg>Implement Ptr trait for mutable unsafe pointers. Closes #3926.<commit_after>//! Unsafe pointer utility functions

#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];

use cmp::{Eq, Ord};
use libc::{c_void, size_t};

#[nolink]
#[abi = "cdecl"]
extern mod libc_ {
    #[rust_stack]
    fn memcpy(dest: *mut c_void, src: *const c_void,
              n: libc::size_t) -> *c_void;

    #[rust_stack]
    fn memmove(dest: *mut c_void, src: *const c_void,
               n: libc::size_t) -> *c_void;

    #[rust_stack]
    fn memset(dest: *mut c_void, c: libc::c_int,
              len: libc::size_t) -> *c_void;
}

#[abi = "rust-intrinsic"]
extern mod rusti {
    fn addr_of<T>(&&val: T) -> *T;
}

/// Get an unsafe pointer to a value
#[inline(always)]
pub pure fn addr_of<T>(val: &T) -> *T { unsafe { rusti::addr_of(*val) } }

/// Get an unsafe mut pointer to a value
#[inline(always)]
pub pure fn mut_addr_of<T>(val: &T) -> *mut T {
    unsafe {
        cast::reinterpret_cast(&rusti::addr_of(*val))
    }
}

/// Calculate the offset from a pointer
#[inline(always)]
pub pure fn offset<T>(ptr: *T, count: uint) -> *T {
    unsafe {
        (ptr as uint + count * sys::size_of::<T>()) as *T
    }
}

/// Calculate the offset from a const pointer
#[inline(always)]
pub pure fn const_offset<T>(ptr: *const T, count: uint) -> *const T {
    unsafe {
        (ptr as uint + count * sys::size_of::<T>()) as *T
    }
}

/// Calculate the offset from a mut pointer
#[inline(always)]
pub pure fn mut_offset<T>(ptr: *mut T, count: uint) -> *mut T {
    (ptr as uint + count * sys::size_of::<T>()) as *mut T
}

/// Return the offset of the first null pointer in `buf`.
#[inline(always)]
pub unsafe fn buf_len<T>(buf: **T) -> uint {
    position(buf, |i| *i == null())
}

/// Return the first offset `i` such that `f(buf[i]) == true`.
#[inline(always)]
pub unsafe fn position<T>(buf: *T, f: fn(&T) -> bool) -> uint {
    let mut i = 0;
    loop {
        if f(&(*offset(buf, i))) { return i; }
        else { i += 1; }
    }
}

/// Create an unsafe null pointer
#[inline(always)]
pub pure fn null<T>() -> *T { unsafe { cast::reinterpret_cast(&0u) } }

/// Create an unsafe mutable null pointer
#[inline(always)]
pub pure fn mut_null<T>() -> *mut T { unsafe { cast::reinterpret_cast(&0u) } }

/// Returns true if the pointer is equal to the null pointer.
pub pure fn is_null<T>(ptr: *const T) -> bool { ptr == null() }

/// Returns true if the pointer is not equal to the null pointer.
pub pure fn is_not_null<T>(ptr: *const T) -> bool { !is_null(ptr) }

/**
 * Copies data from one location to another
 *
 * Copies `count` elements (not bytes) from `src` to `dst`. The source
 * and destination may not overlap.
 */
#[inline(always)]
pub unsafe fn memcpy<T>(dst: *mut T, src: *const T, count: uint) {
    let n = count * sys::size_of::<T>();
    libc_::memcpy(dst as *mut c_void, src as *c_void, n as size_t);
}

/**
 * Copies data from one location to another
 *
 * Copies `count` elements (not bytes) from `src` to `dst`. The source
 * and destination may overlap.
 */
#[inline(always)]
pub unsafe fn memmove<T>(dst: *mut T, src: *const T, count: uint) {
    let n = count * sys::size_of::<T>();
    libc_::memmove(dst as *mut c_void, src as *c_void, n as size_t);
}

#[inline(always)]
pub unsafe fn memset<T>(dst: *mut T, c: int, count: uint) {
    let n = count * sys::size_of::<T>();
    libc_::memset(dst as *mut c_void, c as libc::c_int, n as size_t);
}

/**
  Transform a region pointer - &T - to an unsafe pointer - *T.
  This is safe, but is implemented with an unsafe block due to
  reinterpret_cast.
*/
#[inline(always)]
pub pure fn to_unsafe_ptr<T>(thing: &T) -> *T {
    unsafe { cast::reinterpret_cast(&thing) }
}

/**
  Transform a const region pointer - &const T - to a const unsafe pointer -
  *const T. This is safe, but is implemented with an unsafe block due to
  reinterpret_cast.
*/
#[inline(always)]
pub pure fn to_const_unsafe_ptr<T>(thing: &const T) -> *const T {
    unsafe { cast::reinterpret_cast(&thing) }
}

/**
  Transform a mutable region pointer - &mut T - to a mutable unsafe pointer -
  *mut T. This is safe, but is implemented with an unsafe block due to
  reinterpret_cast.
*/
#[inline(always)]
pub pure fn to_mut_unsafe_ptr<T>(thing: &mut T) -> *mut T {
    unsafe { cast::reinterpret_cast(&thing) }
}

/**
  Cast a region pointer - &T - to a uint.
  This is safe, but is implemented with an unsafe block due to
  reinterpret_cast.

  (I couldn't think of a cutesy name for this one.)
*/
#[inline(always)]
pub fn to_uint<T>(thing: &T) -> uint unsafe {
    cast::reinterpret_cast(&thing)
}

/// Determine if two borrowed pointers point to the same thing.
#[inline(always)]
pub fn ref_eq<T>(thing: &a/T, other: &b/T) -> bool {
    to_uint(thing) == to_uint(other)
}

pub trait Ptr<T> {
    pure fn is_null() -> bool;
    pure fn is_not_null() -> bool;
    pure fn offset(count: uint) -> self;
}

/// Extension methods for immutable pointers
impl<T> *T: Ptr<T> {
    /// Returns true if the pointer is equal to the null pointer.
    #[inline(always)]
    pure fn is_null() -> bool { is_null(self) }

    /// Returns true if the pointer is not equal to the null pointer.
    #[inline(always)]
    pure fn is_not_null() -> bool { is_not_null(self) }

    /// Calculates the offset from a pointer.
    #[inline(always)]
    pure fn offset(count: uint) -> *T { offset(self, count) }
}

/// Extension methods for mutable pointers
impl<T> *mut T: Ptr<T> {
    /// Returns true if the pointer is equal to the null pointer.
    #[inline(always)]
    pure fn is_null() -> bool { is_null(self) }

    /// Returns true if the pointer is not equal to the null pointer.
    #[inline(always)]
    pure fn is_not_null() -> bool { is_not_null(self) }

    /// Calculates the offset from a mutable pointer.
    #[inline(always)]
    pure fn offset(count: uint) -> *mut T { mut_offset(self, count) }
}

// Equality for pointers
impl<T> *const T : Eq {
    pure fn eq(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a == b;
    }
    pure fn ne(other: &*const T) -> bool { !self.eq(other) }
}

// Comparison for pointers
impl<T> *const T : Ord {
    pure fn lt(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a < b;
    }
    pure fn le(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a <= b;
    }
    pure fn ge(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a >= b;
    }
    pure fn gt(other: &*const T) -> bool unsafe {
        let a: uint = cast::reinterpret_cast(&self);
        let b: uint = cast::reinterpret_cast(&(*other));
        return a > b;
    }
}

// Equality for region pointers
impl<T:Eq> &const T : Eq {
    pure fn eq(other: & &self/const T) -> bool { return *self == *(*other); }
    pure fn ne(other: & &self/const T) -> bool { return *self != *(*other); }
}

// Comparison for region pointers
impl<T:Ord> &const T : Ord {
    pure fn lt(other: & &self/const T) -> bool { *self < *(*other) }
    pure fn le(other: & &self/const T) -> bool { *self <= *(*other) }
    pure fn ge(other: & &self/const T) -> bool { *self >= *(*other) }
    pure fn gt(other: & &self/const T) -> bool { *self > *(*other) }
}

#[test]
pub fn test() {
    unsafe {
        type Pair = {mut fst: int, mut snd: int};
        let p = {mut fst: 10, mut snd: 20};
        let pptr: *mut Pair = mut_addr_of(&p);
        let iptr: *mut int = cast::reinterpret_cast(&pptr);
        assert (*iptr == 10);;
        *iptr = 30;
        assert (*iptr == 30);
        assert (p.fst == 30);;

        *pptr = {mut fst: 50, mut snd: 60};
        assert (*iptr == 50);
        assert (p.fst == 50);
        assert (p.snd == 60);

        let mut v0 = ~[32000u16, 32001u16, 32002u16];
        let mut v1 = ~[0u16, 0u16, 0u16];

        ptr::memcpy(ptr::mut_offset(vec::raw::to_mut_ptr(v1), 1u),
                    ptr::offset(vec::raw::to_ptr(v0), 1u), 1u);
        assert (v1[0] == 0u16 && v1[1] == 32001u16 && v1[2] == 0u16);
        ptr::memcpy(vec::raw::to_mut_ptr(v1),
                    ptr::offset(vec::raw::to_ptr(v0), 2u), 1u);
        assert (v1[0] == 32002u16 && v1[1] == 32001u16 && v1[2] == 0u16);
        ptr::memcpy(ptr::mut_offset(vec::raw::to_mut_ptr(v1), 2u),
                    vec::raw::to_ptr(v0), 1u);
        assert (v1[0] == 32002u16 && v1[1] == 32001u16 && v1[2] == 32000u16);
    }
}

#[test]
pub fn test_position() {
    use str::as_c_str;
    use libc::c_char;

    let s = ~"hello";
    unsafe {
        assert 2u == as_c_str(s, |p| position(p, |c| *c == 'l' as c_char));
        assert 4u == as_c_str(s, |p| position(p, |c| *c == 'o' as c_char));
        assert 5u == as_c_str(s, |p| position(p, |c| *c == 0 as c_char));
    }
}

#[test]
pub fn test_buf_len() {
    let s0 = ~"hello";
    let s1 = ~"there";
    let s2 = ~"thing";
    do str::as_c_str(s0) |p0| {
        do str::as_c_str(s1) |p1| {
            do str::as_c_str(s2) |p2| {
                let v = ~[p0, p1, p2, null()];
                do vec::as_imm_buf(v) |vp, len| {
                    assert unsafe { buf_len(vp) } == 3u;
                    assert len == 4u;
                }
            }
        }
    }
}

#[test]
pub fn test_is_null() {
   let p: *int = ptr::null();
   assert p.is_null();
   assert !p.is_not_null();

   let q = ptr::offset(p, 1u);
   assert !q.is_null();
   assert q.is_not_null();

   let mp: *mut int = ptr::mut_null();
   assert mp.is_null();
   assert !mp.is_not_null();

   let mq = mp.offset(1u);
   assert !mq.is_null();
   assert mq.is_not_null();
}
<|endoftext|>