<commit_before>//! This crate allows one-liners to read from a terminal
//! A minimal example to get an i32 from the command line is
//!
//! ```rust,no_run
//! #[macro_use] extern crate text_io;
//! fn main() {
//!     let i: i32 = read!();
//! }
//! ```
//!
//! The `read!()` macro will always read until the next ascii whitespace character
//! (`\n`, `\r`, `\t` or space).
//!
//! Any type that implements the `FromStr` trait can be read with the `read!` macro.
//!
//! # Advanced
//! Text parsing can be done similar to `println!` by adding a format string
//! to the macro:
//!
//! ```rust,no_run
//! # #[macro_use]
//! # extern crate text_io;
//! # fn main() {
//! let i: i32 = read!("The answer: {}!");
//! # }
//! ```
//!
//! This will read `"The answer: "`, then an integer, then an exclamation mark. Any deviation from
//! the format string will result in a panic.
//!
//! Note: only a single value can be read per `read!` invocation.

use std::error;
use std::fmt;
use std::str::FromStr;

#[derive(Debug, PartialEq)]
pub enum Error {
    MissingMatch,
    MissingClosingBrace,
    UnexpectedValue(u8, Option<u8>),
    InvalidUtf8(Vec<u8>),
    PartialUtf8(usize, Vec<u8>),
    Parse(String, &'static str),
    #[doc(hidden)]
    __NonExhaustive__,
}

impl error::Error for Error {
    fn description(&self) -> &str {
        use crate::Error::*;

        match *self {
            MissingMatch => "Bad read! format string: did not contain {{}}",
            MissingClosingBrace => "found single open curly brace at the end of the format string",
            UnexpectedValue(..) => "found value not matching the pattern",
            InvalidUtf8(..) => "input was not valid utf8",
            PartialUtf8(..) => "input was only partially valid utf8",
            Parse(..) => "could not parse input as target type",
            __NonExhaustive__ => unreachable!(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use crate::Error::*;
        use std::str::from_utf8;

        match *self {
            InvalidUtf8(ref raw) => write!(f, "input was not valid utf8: {:?}", raw),
            Parse(ref s, arg) => write!(f, "could not parse {} as target type of {}", s, arg),
            UnexpectedValue(exp, act) => write!(
                f,
                "found value {:?} not matching the pattern value {}",
                act.map(|b| b as char),
                exp as char
            ),
            PartialUtf8(n, ref raw) => write!(
                f,
                "input was only partially valid utf8: \"{}\" followed by {:?}",
                from_utf8(&raw[..n]).unwrap(),
                &raw[n..]
            ),
            _ => write!(f, "{}", <Error as error::Error>::description(self)),
        }
    }
}

pub fn match_next(expected: u8, iter: &mut dyn Iterator<Item = u8>) -> Result<(), Error> {
    let next = iter.next();
    if next != Some(expected) {
        return Err(Error::UnexpectedValue(expected, next))?;
    }
    Ok(())
}

pub fn parse_capture<T>(
    name: &'static str,
    next: Option<u8>,
    iter: &mut dyn Iterator<Item = u8>,
) -> Result<T, Error>
where
    T: FromStr,
    <T as FromStr>::Err: ::std::fmt::Debug,
{
    static WHITESPACES: &'static [u8] = b"\t\r\n ";
    let raw: Vec<u8> = match next {
        Some(c) => iter.take_while(|&ch| ch != c).collect(),
        None => iter
            .skip_while(|ch| WHITESPACES.contains(ch))
            .take_while(|ch| !WHITESPACES.contains(ch))
            .collect(),
    };
    match String::from_utf8(raw) {
        Ok(s) => FromStr::from_str(&s).map_err(|_| Error::Parse(s, name)),
        Err(e) => {
            let n = e.utf8_error().valid_up_to();
            let raw = e.into_bytes();
            if n == 0 {
                Err(Error::InvalidUtf8(raw))
            } else {
                Err(Error::PartialUtf8(n, raw))
            }
        }
    }
}

/// ```rust,no_run
/// # #[macro_use]
/// # extern crate text_io;
/// # fn main() {
/// let i: i32 = try_read!("The answer: {}!").unwrap();
/// let i: Result<i32, _> = try_read!("The {}{{}}!", "The answer is 42!".bytes());
/// assert!(i.is_err());
/// # }
/// ```
///
/// ```rust
/// # #[macro_use]
/// # extern crate text_io;
/// # fn main() {
/// let i: Result<i32, _> = try_read!("The answer is {}!", "The answer is 42!".bytes());
/// assert!(i.is_ok());
///
/// let i: Result<i32, _> = try_read!("The {}{{}}!", "The answer is 42!".bytes());
/// assert!(i.is_err());
/// # }
/// ```
#[macro_export]
macro_rules! try_read(
    () => { try_read!("{}") };
    ($text:expr) => {{
        (|| -> Result<_, $crate::Error> {
            let __try_read_var__;
            try_scan!($text, __try_read_var__);
            Ok(__try_read_var__)
        })()
    }};
    ($text:expr, $input:expr) => {{
        (|| -> Result<_, $crate::Error> {
            let __try_read_var__;
            try_scan!($input => $text, __try_read_var__);
            Ok(__try_read_var__)
        })()
    }};
);

/// ```rust,no_run
/// # #[macro_use]
/// # extern crate text_io;
/// # use std::error::Error;
/// # fn main() {}
/// fn parser() -> Result<i32, Box<Error>> {
///     let i: i32;
///     let text = "The answer is 42!";
///
///     try_scan!(text.bytes() => "The answer is {}!", i);
///
///     assert_eq!(i, 1);
///     Ok(i)
/// }
/// ```
#[macro_export]
macro_rules! try_scan(
    ($pattern:expr, $($arg:expr),*) => {
        use ::std::io::Read;
        try_scan!(::std::io::stdin().bytes().map(std::result::Result::unwrap) => $pattern, $($arg),*);
        format_args!($pattern, $($arg),*);
    };
    ($input:expr => $pattern:expr, $($arg:expr),*) => {{
        try_scan!(@impl question_mark; $input => $pattern, $($arg),*)
    }};
    (@question_mark: $($e:tt)+) => {{
        ($($e)+)?
    }};
    (@unwrap: $($e:tt)+) => {{
        ($($e)+).unwrap()
    }};
    (@impl $action:tt; $input:expr => $pattern:expr, $($arg:expr),*) => {{
        use $crate::{Error, match_next, parse_capture};

        // typesafe macros :)
        let pattern: &'static str = $pattern;
        let stdin: &mut Iterator<Item = u8> = &mut ($input);

        let mut pattern = pattern.bytes();

        $(
            $arg = loop {
                match try_scan!(@$action: pattern.next().ok_or(Error::MissingMatch)) {
                    b'{' => match try_scan!(@$action: pattern.next().ok_or(Error::MissingClosingBrace)) {
                        b'{' => try_scan!(@$action: match_next(b'{', stdin)),
                        b'}' => break try_scan!(@$action: parse_capture(stringify!($arg), pattern.next(), stdin)),
                        _ => return try_scan!(@$action: Err(Error::MissingClosingBrace)),
                    },
                    c => try_scan!(@$action: match_next(c, stdin)),
                }
            };
        )*

        for c in pattern {
            try_scan!(@$action: match_next(c, stdin))
        }

        format_args!($pattern, $($arg),*);
    }};
);

/// All text input is handled through this macro
#[macro_export]
macro_rules! read(
    ($($arg:tt)*) => {
        try_read!($($arg)*).unwrap()
    };
);

/// This macro allows to pass several variables so multiple values can be read
#[macro_export]
macro_rules! scan(
    ($text:expr, $($arg:expr),*) => {
        use ::std::io::Read;
        scan!(::std::io::stdin().bytes().map(std::result::Result::unwrap) => $text, $($arg),*);
        format_args!($text, $($arg),*);
    };
    ($input:expr => $pattern:expr, $($arg:expr),*) => {{
        try_scan!(@impl unwrap; $input => $pattern, $($arg),*)
    }};
);
<commit_msg>Add `$crate::` prefixes<commit_after>//! This crate allows one-liners to read from a terminal
//! A minimal example to get an i32 from the command line is
//!
//! ```rust,no_run
//! #[macro_use] extern crate text_io;
//! fn main() {
//!     let i: i32 = read!();
//! }
//! ```
//!
//! The `read!()` macro will always read until the next ascii whitespace character
//! (`\n`, `\r`, `\t` or space).
//!
//! Any type that implements the `FromStr` trait can be read with the `read!` macro.
//!
//! # Advanced
//! Text parsing can be done similar to `println!` by adding a format string
//! to the macro:
//!
//! ```rust,no_run
//! # #[macro_use]
//! # extern crate text_io;
//! # fn main() {
//! let i: i32 = read!("The answer: {}!");
//! # }
//! ```
//!
//! This will read `"The answer: "`, then an integer, then an exclamation mark. Any deviation from
//! the format string will result in a panic.
//!
//! Note: only a single value can be read per `read!` invocation.

use std::error;
use std::fmt;
use std::str::FromStr;

#[derive(Debug, PartialEq)]
pub enum Error {
    MissingMatch,
    MissingClosingBrace,
    UnexpectedValue(u8, Option<u8>),
    InvalidUtf8(Vec<u8>),
    PartialUtf8(usize, Vec<u8>),
    Parse(String, &'static str),
    #[doc(hidden)]
    __NonExhaustive__,
}

impl error::Error for Error {
    fn description(&self) -> &str {
        use crate::Error::*;

        match *self {
            MissingMatch => "Bad read! format string: did not contain {{}}",
            MissingClosingBrace => "found single open curly brace at the end of the format string",
            UnexpectedValue(..) => "found value not matching the pattern",
            InvalidUtf8(..) => "input was not valid utf8",
            PartialUtf8(..) => "input was only partially valid utf8",
            Parse(..) => "could not parse input as target type",
            __NonExhaustive__ => unreachable!(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use crate::Error::*;
        use std::str::from_utf8;

        match *self {
            InvalidUtf8(ref raw) => write!(f, "input was not valid utf8: {:?}", raw),
            Parse(ref s, arg) => write!(f, "could not parse {} as target type of {}", s, arg),
            UnexpectedValue(exp, act) => write!(
                f,
                "found value {:?} not matching the pattern value {}",
                act.map(|b| b as char),
                exp as char
            ),
            PartialUtf8(n, ref raw) => write!(
                f,
                "input was only partially valid utf8: \"{}\" followed by {:?}",
                from_utf8(&raw[..n]).unwrap(),
                &raw[n..]
            ),
            _ => write!(f, "{}", <Error as error::Error>::description(self)),
        }
    }
}

pub fn match_next(expected: u8, iter: &mut dyn Iterator<Item = u8>) -> Result<(), Error> {
    let next = iter.next();
    if next != Some(expected) {
        return Err(Error::UnexpectedValue(expected, next))?;
    }
    Ok(())
}

pub fn parse_capture<T>(
    name: &'static str,
    next: Option<u8>,
    iter: &mut dyn Iterator<Item = u8>,
) -> Result<T, Error>
where
    T: FromStr,
    <T as FromStr>::Err: ::std::fmt::Debug,
{
    static WHITESPACES: &'static [u8] = b"\t\r\n ";
    let raw: Vec<u8> = match next {
        Some(c) => iter.take_while(|&ch| ch != c).collect(),
        None => iter
            .skip_while(|ch| WHITESPACES.contains(ch))
            .take_while(|ch| !WHITESPACES.contains(ch))
            .collect(),
    };
    match String::from_utf8(raw) {
        Ok(s) => FromStr::from_str(&s).map_err(|_| Error::Parse(s, name)),
        Err(e) => {
            let n = e.utf8_error().valid_up_to();
            let raw = e.into_bytes();
            if n == 0 {
                Err(Error::InvalidUtf8(raw))
            } else {
                Err(Error::PartialUtf8(n, raw))
            }
        }
    }
}

/// ```rust,no_run
/// # #[macro_use]
/// # extern crate text_io;
/// # fn main() {
/// let i: i32 = try_read!("The answer: {}!").unwrap();
/// let i: Result<i32, _> = try_read!("The {}{{}}!", "The answer is 42!".bytes());
/// assert!(i.is_err());
/// # }
/// ```
///
/// ```rust
/// # #[macro_use]
/// # extern crate text_io;
/// # fn main() {
/// let i: Result<i32, _> = try_read!("The answer is {}!", "The answer is 42!".bytes());
/// assert!(i.is_ok());
///
/// let i: Result<i32, _> = try_read!("The {}{{}}!", "The answer is 42!".bytes());
/// assert!(i.is_err());
/// # }
/// ```
#[macro_export]
macro_rules! try_read(
    () => { $crate::try_read!("{}") };
    ($text:expr) => {{
        (|| -> Result<_, $crate::Error> {
            let __try_read_var__;
            $crate::try_scan!($text, __try_read_var__);
            Ok(__try_read_var__)
        })()
    }};
    ($text:expr, $input:expr) => {{
        (|| -> Result<_, $crate::Error> {
            let __try_read_var__;
            $crate::try_scan!($input => $text, __try_read_var__);
            Ok(__try_read_var__)
        })()
    }};
);

/// ```rust,no_run
/// # #[macro_use]
/// # extern crate text_io;
/// # use std::error::Error;
/// # fn main() {}
/// fn parser() -> Result<i32, Box<Error>> {
///     let i: i32;
///     let text = "The answer is 42!";
///
///     try_scan!(text.bytes() => "The answer is {}!", i);
///
///     assert_eq!(i, 1);
///     Ok(i)
/// }
/// ```
#[macro_export]
macro_rules! try_scan(
    ($pattern:expr, $($arg:expr),*) => {
        use ::std::io::Read;
        $crate::try_scan!(::std::io::stdin().bytes().map(std::result::Result::unwrap) => $pattern, $($arg),*);
        format_args!($pattern, $($arg),*);
    };
    ($input:expr => $pattern:expr, $($arg:expr),*) => {{
        $crate::try_scan!(@impl question_mark; $input => $pattern, $($arg),*)
    }};
    (@question_mark: $($e:tt)+) => {{
        ($($e)+)?
    }};
    (@unwrap: $($e:tt)+) => {{
        ($($e)+).unwrap()
    }};
    (@impl $action:tt; $input:expr => $pattern:expr, $($arg:expr),*) => {{
        use $crate::{Error, match_next, parse_capture};

        // typesafe macros :)
        let pattern: &'static str = $pattern;
        let stdin: &mut Iterator<Item = u8> = &mut ($input);

        let mut pattern = pattern.bytes();

        $(
            $arg = loop {
                match $crate::try_scan!(@$action: pattern.next().ok_or(Error::MissingMatch)) {
                    b'{' => match $crate::try_scan!(@$action: pattern.next().ok_or(Error::MissingClosingBrace)) {
                        b'{' => $crate::try_scan!(@$action: match_next(b'{', stdin)),
                        b'}' => break $crate::try_scan!(@$action: parse_capture(stringify!($arg), pattern.next(), stdin)),
                        _ => return $crate::try_scan!(@$action: Err(Error::MissingClosingBrace)),
                    },
                    c => $crate::try_scan!(@$action: match_next(c, stdin)),
                }
            };
        )*

        for c in pattern {
            $crate::try_scan!(@$action: match_next(c, stdin))
        }

        format_args!($pattern, $($arg),*);
    }};
);

/// All text input is handled through this macro
#[macro_export]
macro_rules! read(
    ($($arg:tt)*) => {
        $crate::try_read!($($arg)*).unwrap()
    };
);

/// This macro allows to pass several variables so multiple values can be read
#[macro_export]
macro_rules! scan(
    ($text:expr, $($arg:expr),*) => {
        use ::std::io::Read;
        $crate::scan!(::std::io::stdin().bytes().map(std::result::Result::unwrap) => $text, $($arg),*);
        format_args!($text, $($arg),*);
    };
    ($input:expr => $pattern:expr, $($arg:expr),*) => {{
        $crate::try_scan!(@impl unwrap; $input => $pattern, $($arg),*)
    }};
);
<|endoftext|>


<commit_before>#![crate_id = "iron"]
#![comment = "Rapid Web Development in Rust"]
#![license = "MIT"]

//#![deny(missing_doc)]
#![deny(unused_result)]
#![deny(unnecessary_qualification)]
#![deny(non_camel_case_types)]
#![deny(unused_variable)]
#![deny(unnecessary_typecast)]

#![feature(macro_rules, phase)]
//! The main crate for the Iron library.

extern crate http;
extern crate anymap;

pub use request::Request;
pub use request::ironrequest::IronRequest;

pub use response::Response;
pub use response::ironresponse::IronResponse;

pub use iron::{Iron, ServerT};
pub use ingot::Ingot;

pub use furnace::Furnace;
pub use furnace::ironfurnace::IronFurnace;

pub use alloy::Alloy;

pub mod request;
pub mod response;
pub mod ingot;
pub mod alloy;
pub mod furnace;
pub mod iron;
<commit_msg>(doc) Fixed formatting in lib.rs<commit_after>#![crate_id = "iron"]
#![comment = "Rapid Web Development in Rust"]
#![license = "MIT"]

//#![deny(missing_doc)]
#![deny(unused_result)]
#![deny(unnecessary_qualification)]
#![deny(non_camel_case_types)]
#![deny(unused_variable)]
#![deny(unnecessary_typecast)]

#![feature(macro_rules, phase)]
//! The main crate for the Iron library.

extern crate http;
extern crate anymap;

pub use request::Request;
pub use request::ironrequest::IronRequest;

pub use response::Response;
pub use response::ironresponse::IronResponse;

pub use iron::{Iron, ServerT};
pub use ingot::Ingot;

pub use furnace::Furnace;
pub use furnace::ironfurnace::IronFurnace;

pub use alloy::Alloy;

pub mod request;
pub mod response;
pub mod ingot;
pub mod alloy;
pub mod furnace;
pub mod iron;

<|endoftext|>


<commit_before>//! Providing the features between "full" and "derive" of syn.
//!
//! This crate provides the following two unique data structures.
//!
//! - [`syn_mid::ItemFn`] -- A function whose body is not parsed.
//!
//!   ```text
//!   fn process(n: usize) -> Result<()> { ... }
//!   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^     ^
//!   ```
//!
//! - [`syn_mid::Block`] -- A block whose body is not parsed.
//!
//!   ```text
//!   { ... }
//!   ^     ^
//!   ```
//!
//! Other data structures are the same as data structures of [syn]. These are
//! defined in this crate because they cannot be used in [syn] without "full"
//! feature.
//!
//! # Optional features
//!
//! - **`clone-impls`** — Clone impls for all syntax tree types.
//!
//! [`syn_mid::ItemFn`]: ItemFn
//! [`syn_mid::Block`]: Block
//! [syn]: https://github.com/dtolnay/syn

#![doc(test(
    no_crate_inject,
    attr(
        deny(warnings, rust_2018_idioms, single_use_lifetimes),
        allow(dead_code, unused_variables)
    )
))]
#![forbid(unsafe_code)]
#![warn(rust_2018_idioms, single_use_lifetimes, unreachable_pub)]
#![warn(
    clippy::pedantic,
    // lints for public library
    clippy::alloc_instead_of_core,
    // clippy::exhaustive_enums, // TODO
    // clippy::exhaustive_structs, // TODO
    clippy::std_instead_of_alloc,
    clippy::std_instead_of_core,
)]
#![allow(clippy::mixed_read_write_in_expression, clippy::large_enum_variant)]

// Many of the code contained in this crate are copies from https://github.com/dtolnay/syn.

#[macro_use]
mod macros;

mod func;
mod pat;
mod path;

pub use crate::{
    func::{Block, FnArg, ItemFn, Receiver, Signature},
    pat::{
        FieldPat, Pat, PatIdent, PatPath, PatReference, PatStruct, PatTuple, PatTupleStruct,
        PatType, PatWild,
    },
};
<commit_msg>Disable clippy::std_instead_of_alloc lint<commit_after>//! Providing the features between "full" and "derive" of syn.
//!
//! This crate provides the following two unique data structures.
//!
//! - [`syn_mid::ItemFn`] -- A function whose body is not parsed.
//!
//!   ```text
//!   fn process(n: usize) -> Result<()> { ... }
//!   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^     ^
//!   ```
//!
//! - [`syn_mid::Block`] -- A block whose body is not parsed.
//!
//!   ```text
//!   { ... }
//!   ^     ^
//!   ```
//!
//! Other data structures are the same as data structures of [syn]. These are
//! defined in this crate because they cannot be used in [syn] without "full"
//! feature.
//!
//! # Optional features
//!
//! - **`clone-impls`** — Clone impls for all syntax tree types.
//!
//! [`syn_mid::ItemFn`]: ItemFn
//! [`syn_mid::Block`]: Block
//! [syn]: https://github.com/dtolnay/syn

#![doc(test(
    no_crate_inject,
    attr(
        deny(warnings, rust_2018_idioms, single_use_lifetimes),
        allow(dead_code, unused_variables)
    )
))]
#![forbid(unsafe_code)]
#![warn(rust_2018_idioms, single_use_lifetimes, unreachable_pub)]
#![warn(
    clippy::pedantic,
    // lints for public library
    clippy::alloc_instead_of_core,
    // clippy::exhaustive_enums, // TODO
    // clippy::exhaustive_structs, // TODO
    // clippy::std_instead_of_alloc, // alloc requires Rust 1.36
    clippy::std_instead_of_core,
)]
#![allow(clippy::mixed_read_write_in_expression, clippy::large_enum_variant)]

// Many of the code contained in this crate are copies from https://github.com/dtolnay/syn.

#[macro_use]
mod macros;

mod func;
mod pat;
mod path;

pub use crate::{
    func::{Block, FnArg, ItemFn, Receiver, Signature},
    pat::{
        FieldPat, Pat, PatIdent, PatPath, PatReference, PatStruct, PatTuple, PatTupleStruct,
        PatType, PatWild,
    },
};
<|endoftext|>


<commit_before>#![feature(alloc, core)]

extern crate alloc;

use self::alloc::heap;

use std::mem;
use std::ptr;
use std::iter::Iterator;
use std::marker::PhantomData;
use std::slice;

/// A two-dimensional array with whose dimensions are fixed at construction.
pub struct Grid<T> {
    ptr: *mut T,
    width: u16,
    height: u16,
}

impl<T: Clone> Grid<T> {
    /// Constructs a grid with the given width and height by cloning `element`.
    /// Returns None if width, height or size of T are zero.
    pub fn new(width: u16, height: u16, element: T) -> Option<Grid<T>> {
    	if mem::size_of::<T>() == 0 || width == 0 || height == 0 {
            None
        } else {
            let count = width as usize * height as usize;
            let bytes = count * mem::size_of::<T>();
            let ptr = unsafe { heap::allocate(bytes, mem::align_of::<T>()) as *mut T };
            for i in 0..count as isize {
        	    unsafe { ptr::write(ptr.offset(i), element.clone()); };
        	}
        	Some(Grid { ptr: ptr, width: width, height: height })
        }
    }
}

impl<T> Grid<T> {
    pub fn iter<'a>(&'a self) -> Iter<'a, T> {
        Iter { ptr: self.ptr, end: self.end(), marker: PhantomData }
    }

    pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
        IterMut { ptr: self.ptr, end: self.end_mut(), marker: PhantomData }
    }

    pub fn rows<'a>(&'a self) -> Rows<'a, T> {
        Rows { ptr: self.ptr, end: self.end(), len: self.width as usize, marker: PhantomData }
    }

    pub fn rows_mut<'a>(&'a mut self) -> RowsMut<'a, T> {
        RowsMut { ptr: self.ptr, end: self.end_mut(), len: self.width as usize, marker: PhantomData }
    }

    pub fn get(&self, x: u16, y: u16) -> Option<&T> {
    	if x < self.width && y < self.height {
    	    unsafe { self.ptr.offset(x as isize + y as isize * self.width as isize).as_ref() }
    	} else {
            None
        }
    }

    pub fn get_mut(&mut self, x: u16, y: u16) -> Option<&mut T> {
    	if x < self.width && y < self.height {
    	    unsafe { self.ptr.offset(x as isize + y as isize * self.width as isize).as_mut() }
    	} else {
            None
        }
    }

    pub fn width(&self) -> u16 {
	   self.width
    }

    pub fn height(&self) -> u16 {
	   self.height
    }

    #[inline]
    fn end(&self) -> *const T {
        unsafe { self.ptr.offset(self.width as isize * self.height as isize) }
    }

    #[inline]
    fn end_mut(&mut self) -> *mut T {
        unsafe { self.ptr.offset(self.width as isize * self.height as isize) }
    }
}

impl<T> Drop for Grid<T> {
    fn drop(&mut self) {
        unsafe {
           for e in self.iter_mut() { ptr::read(e); }
    	   let bytes = self.width as usize * self.height as usize * mem::size_of::<T>();
    	   heap::deallocate(self.ptr as *mut u8, bytes, mem::align_of::<T>());
        }
    }
}

pub struct Iter<'a, T: 'a> {
    ptr: *const T,
    end: *const T,
    marker: PhantomData<&'a T>
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<&'a T> {
        if self.ptr == self.end {
            None
        } else {
            let reference: &T = unsafe { mem::transmute(self.ptr) };
            self.ptr = unsafe { self.ptr.offset(1) };
            Some(reference)
        }
    }
}

pub struct IterMut<'a, T: 'a> {
    ptr: *mut T,
    end: *mut T,
    marker: PhantomData<&'a mut T>
}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;
    fn next(&mut self) -> Option<&'a mut T> {
        if self.ptr == self.end {
            None
        } else {
            let reference: &mut T = unsafe { mem::transmute(self.ptr) };
            self.ptr = unsafe { self.ptr.offset(1) };
            Some(reference)
        }
    }
}

pub struct Rows<'a, T: 'a> {
    ptr: *const T,
    end: *const T,
    len: usize,
    marker: PhantomData<&'a T>
}

impl<'a, T> Iterator for Rows<'a, T> {
    type Item = &'a [T];
    fn next(&mut self) -> Option<&'a [T]> {
        if self.ptr == self.end {
            None
        } else {
            let slice = unsafe { slice::from_raw_parts(self.ptr, self.len) };
            self.ptr = unsafe { self.ptr.offset(self.len as isize) };
            Some(slice)
        }
    }
}

pub struct RowsMut<'a, T: 'a> {
    ptr: *mut T,
    end: *mut T,
    len: usize,
    marker: PhantomData<&'a mut T>
}

impl<'a, T> Iterator for RowsMut<'a, T> {
    type Item = &'a mut [T];
    fn next(&mut self) -> Option<&'a mut [T]> {
        if self.ptr == self.end {
            None
        } else {
            let slice = unsafe { slice::from_raw_parts_mut(self.ptr, self.len) };
            self.ptr = unsafe { self.ptr.offset(self.len as isize) };
            Some(slice)
        }
    }
}

#[cfg(test)]
mod test {
    extern crate core;
    use super::Grid;
    use self::core::array::FixedSizeArray;
    use std::cell::Cell;

    #[test]
    fn get_get_mut() {
    	let mut grid = Grid::new(2, 2, 0u8).unwrap();
    	assert_eq!(grid.get(0, 0), Some(&0u8));
    	assert_eq!(grid.get(0, 1), Some(&0u8));
    	assert_eq!(grid.get(1, 0), Some(&0u8));
    	assert_eq!(grid.get(1, 1), Some(&0u8));
    	assert_eq!(grid.get(2, 0), None);
    	*grid.get_mut(1, 0).unwrap() = 1u8;
    	*grid.get_mut(0, 1).unwrap() = 2u8;
    	*grid.get_mut(1, 1).unwrap() = 3u8;
    	assert_eq!(grid.get(0, 0), Some(&0u8));
    	assert_eq!(grid.get(1, 0), Some(&1u8));
    	assert_eq!(grid.get(0, 1), Some(&2u8));
    	assert_eq!(grid.get(1, 1), Some(&3u8));
    	assert_eq!(grid.get(2, 0), None);
    }

    #[test]
    fn iter() {
    	let mut grid = Grid::new(2, 2, 0u8).unwrap();
    	*grid.get_mut(1, 0).unwrap() = 1;
    	*grid.get_mut(0, 1).unwrap() = 2;
    	*grid.get_mut(1, 1).unwrap() = 3;
    	let mut iter = grid.iter();
    	assert_eq!(iter.next(), Some(&0));
    	assert_eq!(iter.next(), Some(&1));
    	assert_eq!(iter.next(), Some(&2));
    	assert_eq!(iter.next(), Some(&3));
    	assert_eq!(iter.next(), None);
    }

    #[test]
    fn iter_mut() {
    	let mut grid = Grid::new(2, 2, 0u8).unwrap();
    	*grid.get_mut(1, 0).unwrap() = 1;
    	*grid.get_mut(0, 1).unwrap() = 2;
    	*grid.get_mut(1, 1).unwrap() = 3;
    	let mut iter = grid.iter_mut();
    	assert_eq!(iter.next(), Some(&mut 0));
    	assert_eq!(iter.next(), Some(&mut 1));
    	assert_eq!(iter.next(), Some(&mut 2));
    	assert_eq!(iter.next(), Some(&mut 3));
    	assert_eq!(iter.next(), None);
    }

    #[test]
    fn rows() {
    	let mut grid = Grid::new(2, 2, 'A').unwrap();
    	*grid.get_mut(1, 0).unwrap() = 'B';
    	*grid.get_mut(0, 1).unwrap() = 'C';
    	*grid.get_mut(1, 1).unwrap() = 'D';
    	let mut iter = grid.rows();
    	assert_eq!(iter.next(), Some(['A', 'B'].as_slice()));
    	assert_eq!(iter.next(), Some(['C', 'D'].as_slice()));
    	assert_eq!(iter.next(), None);
    }

    #[test]
    fn rows_mut() {
    	let mut grid = Grid::new(2, 2, 'A').unwrap();
    	*grid.get_mut(1, 0).unwrap() = 'B';
    	*grid.get_mut(0, 1).unwrap() = 'C';
    	*grid.get_mut(1, 1).unwrap() = 'D';
    	let mut iter = grid.rows_mut();
    	assert_eq!(iter.next(), Some(['A', 'B'].as_mut_slice()));
    	assert_eq!(iter.next(), Some(['C', 'D'].as_mut_slice()));
    	assert_eq!(iter.next(), None);
    }

    #[test]
    fn dealloc() {
    	#[derive(Clone)]
    	struct Foo<'a>(&'a Cell<u8>);
    	impl<'a> Drop for Foo<'a> {
    	    fn drop(&mut self) {
    		let Foo(ref cell) = *self;
    		cell.set(cell.get() + 1);
    	    }
    	}
    	let count = Cell::new(0u8);
    	{
    	    let grid = Grid::new(2, 2, Foo(&count));
    	}
    	// Four allocations plus the Foo passed to Grid::new.
    	assert_eq!(count.get(), 5);
    }

    #[test]
    fn new_with_bad_input() {
        #[derive(Copy, Clone)]
        struct Foo;
        assert!(Grid::new(3, 0, 1u8).is_none());
        assert!(Grid::new(0, 3, 1u8).is_none());
        assert!(Grid::new(3, 3, Foo).is_none());
    }
}<commit_msg>fixed tabs<commit_after>#![feature(alloc, core)]

extern crate alloc;

use self::alloc::heap;

use std::mem;
use std::ptr;
use std::iter::Iterator;
use std::marker::PhantomData;
use std::slice;

/// A two-dimensional array with whose dimensions are fixed at construction.
pub struct Grid<T> {
    ptr: *mut T,
    width: u16,
    height: u16,
}

impl<T: Clone> Grid<T> {
    /// Constructs a grid with the given width and height by cloning `element`.
    /// Returns None if width, height or size of T are zero.
    pub fn new(width: u16, height: u16, element: T) -> Option<Grid<T>> {
        if mem::size_of::<T>() > 0 && width > 0 && height > 0 {
            let count = width as usize * height as usize;
            let bytes = count * mem::size_of::<T>();
            let ptr = unsafe { heap::allocate(bytes, mem::align_of::<T>()) as *mut T };
            for i in 0..count as isize {
                unsafe { ptr::write(ptr.offset(i), element.clone()); };
            }
            Some(Grid { ptr: ptr, width: width, height: height })
        } else {
            None
        }
    }
}

impl<T> Grid<T> {
    pub fn iter<'a>(&'a self) -> Iter<'a, T> {
        Iter { ptr: self.ptr, end: self.end(), marker: PhantomData }
    }

    pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
        IterMut { ptr: self.ptr, end: self.end_mut(), marker: PhantomData }
    }

    pub fn rows<'a>(&'a self) -> Rows<'a, T> {
        Rows { ptr: self.ptr, end: self.end(), len: self.width as usize, marker: PhantomData }
    }

    pub fn rows_mut<'a>(&'a mut self) -> RowsMut<'a, T> {
        RowsMut { ptr: self.ptr, end: self.end_mut(), len: self.width as usize, marker: PhantomData }
    }

    pub fn get(&self, x: u16, y: u16) -> Option<&T> {
        if x < self.width && y < self.height {
            unsafe { self.ptr.offset(x as isize + y as isize * self.width as isize).as_ref() }
        } else {
            None
        }
    }

    pub fn get_mut(&mut self, x: u16, y: u16) -> Option<&mut T> {
        if x < self.width && y < self.height {
            unsafe { self.ptr.offset(x as isize + y as isize * self.width as isize).as_mut() }
        } else {
            None
        }
    }

    pub fn width(&self) -> u16 {
       self.width
    }

    pub fn height(&self) -> u16 {
       self.height
    }

    #[inline]
    fn end(&self) -> *const T {
        unsafe { self.ptr.offset(self.width as isize * self.height as isize) }
    }

    #[inline]
    fn end_mut(&mut self) -> *mut T {
        unsafe { self.ptr.offset(self.width as isize * self.height as isize) }
    }
}

impl<T> Drop for Grid<T> {
    fn drop(&mut self) {
        unsafe {
           for e in self.iter_mut() { ptr::read(e); }
           let bytes = self.width as usize * self.height as usize * mem::size_of::<T>();
           heap::deallocate(self.ptr as *mut u8, bytes, mem::align_of::<T>());
        }
    }
}

pub struct Iter<'a, T: 'a> {
    ptr: *const T,
    end: *const T,
    marker: PhantomData<&'a T>
}

impl<'a, T> Iterator for Iter<'a, T> {
    type Item = &'a T;
    fn next(&mut self) -> Option<&'a T> {
        if self.ptr == self.end {
            None
        } else {
            let reference: &T = unsafe { mem::transmute(self.ptr) };
            self.ptr = unsafe { self.ptr.offset(1) };
            Some(reference)
        }
    }
}

pub struct IterMut<'a, T: 'a> {
    ptr: *mut T,
    end: *mut T,
    marker: PhantomData<&'a mut T>
}

impl<'a, T> Iterator for IterMut<'a, T> {
    type Item = &'a mut T;
    fn next(&mut self) -> Option<&'a mut T> {
        if self.ptr == self.end {
            None
        } else {
            let reference: &mut T = unsafe { mem::transmute(self.ptr) };
            self.ptr = unsafe { self.ptr.offset(1) };
            Some(reference)
        }
    }
}

pub struct Rows<'a, T: 'a> {
    ptr: *const T,
    end: *const T,
    len: usize,
    marker: PhantomData<&'a T>
}

impl<'a, T> Iterator for Rows<'a, T> {
    type Item = &'a [T];
    fn next(&mut self) -> Option<&'a [T]> {
        if self.ptr == self.end {
            None
        } else {
            let slice = unsafe { slice::from_raw_parts(self.ptr, self.len) };
            self.ptr = unsafe { self.ptr.offset(self.len as isize) };
            Some(slice)
        }
    }
}

pub struct RowsMut<'a, T: 'a> {
    ptr: *mut T,
    end: *mut T,
    len: usize,
    marker: PhantomData<&'a mut T>
}

impl<'a, T> Iterator for RowsMut<'a, T> {
    type Item = &'a mut [T];
    fn next(&mut self) -> Option<&'a mut [T]> {
        if self.ptr == self.end {
            None
        } else {
            let slice = unsafe { slice::from_raw_parts_mut(self.ptr, self.len) };
            self.ptr = unsafe { self.ptr.offset(self.len as isize) };
            Some(slice)
        }
    }
}

#[cfg(test)]
mod test {
    extern crate core;
    use super::Grid;
    use self::core::array::FixedSizeArray;
    use std::cell::Cell;

    #[test]
    fn get_get_mut() {
        let mut grid = Grid::new(2, 2, 0u8).unwrap();
        assert_eq!(grid.get(0, 0), Some(&0u8));
        assert_eq!(grid.get(0, 1), Some(&0u8));
        assert_eq!(grid.get(1, 0), Some(&0u8));
        assert_eq!(grid.get(1, 1), Some(&0u8));
        assert_eq!(grid.get(2, 0), None);
        *grid.get_mut(1, 0).unwrap() = 1u8;
        *grid.get_mut(0, 1).unwrap() = 2u8;
        *grid.get_mut(1, 1).unwrap() = 3u8;
        assert_eq!(grid.get(0, 0), Some(&0u8));
        assert_eq!(grid.get(1, 0), Some(&1u8));
        assert_eq!(grid.get(0, 1), Some(&2u8));
        assert_eq!(grid.get(1, 1), Some(&3u8));
        assert_eq!(grid.get(2, 0), None);
    }

    #[test]
    fn iter() {
        let mut grid = Grid::new(2, 2, 0u8).unwrap();
        *grid.get_mut(1, 0).unwrap() = 1;
        *grid.get_mut(0, 1).unwrap() = 2;
        *grid.get_mut(1, 1).unwrap() = 3;
        let mut iter = grid.iter();
        assert_eq!(iter.next(), Some(&0));
        assert_eq!(iter.next(), Some(&1));
        assert_eq!(iter.next(), Some(&2));
        assert_eq!(iter.next(), Some(&3));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn iter_mut() {
        let mut grid = Grid::new(2, 2, 0u8).unwrap();
        *grid.get_mut(1, 0).unwrap() = 1;
        *grid.get_mut(0, 1).unwrap() = 2;
        *grid.get_mut(1, 1).unwrap() = 3;
        let mut iter = grid.iter_mut();
        assert_eq!(iter.next(), Some(&mut 0));
        assert_eq!(iter.next(), Some(&mut 1));
        assert_eq!(iter.next(), Some(&mut 2));
        assert_eq!(iter.next(), Some(&mut 3));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn rows() {
        let mut grid = Grid::new(2, 2, 'A').unwrap();
        *grid.get_mut(1, 0).unwrap() = 'B';
        *grid.get_mut(0, 1).unwrap() = 'C';
        *grid.get_mut(1, 1).unwrap() = 'D';
        let mut iter = grid.rows();
        assert_eq!(iter.next(), Some(['A', 'B'].as_slice()));
        assert_eq!(iter.next(), Some(['C', 'D'].as_slice()));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn rows_mut() {
        let mut grid = Grid::new(2, 2, 'A').unwrap();
        *grid.get_mut(1, 0).unwrap() = 'B';
        *grid.get_mut(0, 1).unwrap() = 'C';
        *grid.get_mut(1, 1).unwrap() = 'D';
        let mut iter = grid.rows_mut();
        assert_eq!(iter.next(), Some(['A', 'B'].as_mut_slice()));
        assert_eq!(iter.next(), Some(['C', 'D'].as_mut_slice()));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn dealloc() {
        #[derive(Clone)]
        struct Foo<'a>(&'a Cell<u8>);
        impl<'a> Drop for Foo<'a> {
            fn drop(&mut self) {
            let Foo(ref cell) = *self;
            cell.set(cell.get() + 1);
            }
        }
        let count = Cell::new(0u8);
        {
            let grid = Grid::new(2, 2, Foo(&count));
        }
        // Four allocations plus the Foo passed to Grid::new.
        assert_eq!(count.get(), 5);
    }

    #[test]
    fn new_with_bad_input() {
        #[derive(Copy, Clone)]
        struct Foo;
        assert!(Grid::new(3, 0, 1u8).is_none());
        assert!(Grid::new(0, 3, 1u8).is_none());
        assert!(Grid::new(3, 3, Foo).is_none());
    }
}<|endoftext|>


<commit_before>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! libc - Raw FFI bindings to platforms' system libraries
#![crate_name = "libc"]
#![crate_type = "rlib"]
#![cfg_attr(not(feature = "rustc-dep-of-std"), deny(warnings))]
#![allow(bad_style, overflowing_literals, improper_ctypes, unknown_lints)]
// Attributes needed when building as part of the standard library
#![cfg_attr(
    feature = "rustc-dep-of-std",
    feature(cfg_target_vendor, link_cfg, no_core)
)]
// Enable extra lints:
#![cfg_attr(feature = "extra_traits", deny(missing_debug_implementations))]
#![deny(missing_copy_implementations, safe_packed_borrows)]
#![no_std]
#![cfg_attr(feature = "rustc-dep-of-std", no_core)]

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

#[macro_use]
mod macros;

cfg_if! {
    if #[cfg(feature = "rustc-dep-of-std")] {
        extern crate rustc_std_workspace_core as core;
        #[allow(unused_imports)]
        use core::iter;
        #[allow(unused_imports)]
        use core::option;
    }
}

cfg_if! {
    if #[cfg(libc_priv_mod_use)] {
        #[cfg(libc_core_cvoid)]
        #[allow(unused_imports)]
        use core::ffi;
        #[allow(unused_imports)]
        use core::fmt;
        #[allow(unused_imports)]
        use core::hash;
        #[allow(unused_imports)]
        use core::num;
        #[allow(unused_imports)]
        use core::mem;
        #[doc(hidden)]
        #[allow(unused_imports)]
        use core::clone::Clone;
        #[doc(hidden)]
        #[allow(unused_imports)]
        use core::marker::Copy;
        #[doc(hidden)]
        #[allow(unused_imports)]
        use core::option::Option;
    } else {
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::fmt;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::hash;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::num;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::mem;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::clone::Clone;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::marker::Copy;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::option::Option;
    }
}

cfg_if! {
    if #[cfg(windows)] {
        mod windows;
        pub use windows::*;
    } else if #[cfg(target_os = "redox")] {
        mod redox;
        pub use redox::*;
    } else if #[cfg(target_os = "cloudabi")] {
        mod cloudabi;
        pub use cloudabi::*;
    } else if #[cfg(target_os = "fuchsia")] {
        mod fuchsia;
        pub use fuchsia::*;
    } else if #[cfg(target_os = "switch")] {
        mod switch;
        pub use switch::*;
    } else if #[cfg(unix)] {
        mod unix;
        pub use unix::*;
    } else if #[cfg(target_env = "sgx")] {
        mod sgx;
        pub use sgx::*;
    }  else {
        // non-supported targets: empty...
    }
}
<commit_msg>Auto merge of #1270 - gnzlbg:no_extern_std, r=gnzlbg<commit_after>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! libc - Raw FFI bindings to platforms' system libraries
#![crate_name = "libc"]
#![crate_type = "rlib"]
#![cfg_attr(not(feature = "rustc-dep-of-std"), deny(warnings))]
#![allow(bad_style, overflowing_literals, improper_ctypes, unknown_lints)]
// Attributes needed when building as part of the standard library
#![cfg_attr(
    feature = "rustc-dep-of-std",
    feature(cfg_target_vendor, link_cfg, no_core)
)]
// Enable extra lints:
#![cfg_attr(feature = "extra_traits", deny(missing_debug_implementations))]
#![deny(missing_copy_implementations, safe_packed_borrows)]
#![no_std]
#![cfg_attr(feature = "rustc-dep-of-std", no_core)]

#[macro_use]
mod macros;

cfg_if! {
    if #[cfg(feature = "rustc-dep-of-std")] {
        extern crate rustc_std_workspace_core as core;
        #[allow(unused_imports)]
        use core::iter;
        #[allow(unused_imports)]
        use core::option;
    }
}

cfg_if! {
    if #[cfg(libc_priv_mod_use)] {
        #[cfg(libc_core_cvoid)]
        #[allow(unused_imports)]
        use core::ffi;
        #[allow(unused_imports)]
        use core::fmt;
        #[allow(unused_imports)]
        use core::hash;
        #[allow(unused_imports)]
        use core::num;
        #[allow(unused_imports)]
        use core::mem;
        #[doc(hidden)]
        #[allow(unused_imports)]
        use core::clone::Clone;
        #[doc(hidden)]
        #[allow(unused_imports)]
        use core::marker::Copy;
        #[doc(hidden)]
        #[allow(unused_imports)]
        use core::option::Option;
    } else {
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::fmt;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::hash;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::num;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::mem;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::clone::Clone;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::marker::Copy;
        #[doc(hidden)]
        #[allow(unused_imports)]
        pub use core::option::Option;
    }
}

cfg_if! {
    if #[cfg(windows)] {
        mod windows;
        pub use windows::*;
    } else if #[cfg(target_os = "redox")] {
        mod redox;
        pub use redox::*;
    } else if #[cfg(target_os = "cloudabi")] {
        mod cloudabi;
        pub use cloudabi::*;
    } else if #[cfg(target_os = "fuchsia")] {
        mod fuchsia;
        pub use fuchsia::*;
    } else if #[cfg(target_os = "switch")] {
        mod switch;
        pub use switch::*;
    } else if #[cfg(unix)] {
        mod unix;
        pub use unix::*;
    } else if #[cfg(target_env = "sgx")] {
        mod sgx;
        pub use sgx::*;
    }  else {
        // non-supported targets: empty...
    }
}
<|endoftext|>


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

#![feature(core)]

extern crate "rustc-serialize" as rustc_serialize;

pub use types::pos::Pos;

pub use types::ring::Ring;

pub use types::point::Point;
pub use types::multipoint::MultiPoint;

pub use types::linestring::LineString;
pub use types::multilinestring::MultiLineString;

pub use types::poly::Poly;
pub use types::polygon::Polygon;
pub use types::multipolygon::MultiPolygon;

pub use types::geometry::Geometry;
pub use types::geometrycollection::GeometryCollection;

pub use types::feature::Feature;
pub use types::featurecollection::FeatureCollection;

macro_rules! expect_string {
    ($value:expr) => (try!(
        match $value.as_string() {
            Some(v) => Ok(v),
            None => Err({use GeoJsonError; GeoJsonError::new("Expected string value")})
        }
    ))
}

macro_rules! expect_f64 {
    ($value:expr) => (try!(
        match $value.as_f64() {
            Some(v) => Ok(v),
            None => Err({use GeoJsonError; GeoJsonError::new("Expected f64 value")})
        }
    ))
}

macro_rules! expect_array {
    ($value:expr) => (try!(
        match $value.as_array() {
            Some(v) => Ok(v),
            None => Err({use GeoJsonError; GeoJsonError::new("Expected array value")})
        }
    ))
}

macro_rules! expect_object {
    ($value:expr) => (try!(
        match $value.as_object() {
            Some(v) => Ok(v),
            None => Err({use GeoJsonError; GeoJsonError::new("Expected object value")})
        }
    ))
}

macro_rules! expect_property {
    ($obj:expr, $name:expr, $desc:expr) => (
        match $obj.get($name) {
            Some(v) => v,
            None => return Err({use GeoJsonError; GeoJsonError::new($desc)}),
        };
    )
}

mod types;

#[derive(Copy)]
pub struct GeoJsonError {
    pub desc: &'static str,
}

impl GeoJsonError {
    pub fn new(desc: &'static str) -> GeoJsonError {
        return GeoJsonError{desc: desc};
    }
}

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

extern crate "rustc-serialize" as rustc_serialize;

pub use types::pos::Pos;

pub use types::ring::Ring;

pub use types::point::Point;
pub use types::multipoint::MultiPoint;

pub use types::linestring::LineString;
pub use types::multilinestring::MultiLineString;

pub use types::poly::Poly;
pub use types::polygon::Polygon;
pub use types::multipolygon::MultiPolygon;

pub use types::geometry::Geometry;
pub use types::geometrycollection::GeometryCollection;

pub use types::feature::Feature;
pub use types::featurecollection::FeatureCollection;

macro_rules! expect_string {
    ($value:expr) => (try!(
        match $value.as_string() {
            Some(v) => Ok(v),
            None => Err({use GeoJsonError; GeoJsonError::new("Expected string value")})
        }
    ))
}

macro_rules! expect_f64 {
    ($value:expr) => (try!(
        match $value.as_f64() {
            Some(v) => Ok(v),
            None => Err({use GeoJsonError; GeoJsonError::new("Expected f64 value")})
        }
    ))
}

macro_rules! expect_array {
    ($value:expr) => (try!(
        match $value.as_array() {
            Some(v) => Ok(v),
            None => Err({use GeoJsonError; GeoJsonError::new("Expected array value")})
        }
    ))
}

macro_rules! expect_object {
    ($value:expr) => (try!(
        match $value.as_object() {
            Some(v) => Ok(v),
            None => Err({use GeoJsonError; GeoJsonError::new("Expected object value")})
        }
    ))
}

macro_rules! expect_property {
    ($obj:expr, $name:expr, $desc:expr) => (
        match $obj.get($name) {
            Some(v) => v,
            None => return Err({use GeoJsonError; GeoJsonError::new($desc)}),
        };
    )
}

mod types;

#[derive(Copy)]
pub struct GeoJsonError {
    pub desc: &'static str,
}

impl GeoJsonError {
    pub fn new(desc: &'static str) -> GeoJsonError {
        return GeoJsonError{desc: desc};
    }
}

pub type GeoJsonResult<T> = Result<T, GeoJsonError>;
<|endoftext|>


<commit_before>//! A reference-counted pointer that accepts DST: `Rc<str>`, `Rc<[T]>`, `Rc<Fn>`, etc

#![cfg_attr(test, plugin(quickcheck_macros))]
#![deny(missing_docs)]
#![deny(warnings)]
#![feature(alloc)]
#![feature(collections)]
#![feature(core)]
#![feature(custom_attribute)]
#![feature(filling_drop)]
#![feature(optin_builtin_traits)]
#![feature(plugin)]
#![feature(unsafe_no_drop_flag)]

#[cfg(test)] extern crate quickcheck;
#[cfg(test)] extern crate rand;

extern crate alloc;
extern crate core;

use core::nonzero::NonZero;
use std::borrow::Borrow;
use std::boxed;
use std::cell::Cell;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops::Deref;

/// A reference-counted pointer type over an immutable value.
///
/// # Examples
///
/// ```
/// # #![feature(convert)]
/// # extern crate rc;
/// # use rc::Rc;
/// # fn main() {
/// let boxed_fn: Box<Fn() -> i32> = Box::new(|| { 0 });
/// //boxed_fn.clone();  //~ error: does not implement `clone`
/// let original: Rc<Fn() -> i32> = Rc::from(boxed_fn);  // moves `boxed_fn`
/// let rc_fn = original.clone();  // increases refcount to 2
///
/// drop(original);  // decreases refcount to 1
///
/// // overloaded calls work with `Rc<Fn(..) -> ..>`s
/// assert_eq!(rc_fn(), 0);
///
/// // `rc_fn` dropped here, refcount reaches zero, `boxed_fn` is deallocated
/// # }
/// ```
///
/// # Layout
///
/// A single layer of indirection.
///
/// ``` text
///    Stack       |   Heap
///                |
///    Rc<str>     |
/// +------------+ |
/// | *mut str   |-|-> "Hello, world!"
/// | *mut usize |-|-> 3
/// +------------+ |
/// ```
///
/// ^ NOTE: `Cell`/`NonZero` wrappers omitted for brevity. String and reference count are not
/// (necessarily) stored in contiguous memory.
///
/// # Size
///
/// For sized types: 2 words, for DST: 3 words.
///
/// ```
/// # extern crate rc;
/// # use std::mem;
/// # use rc::Rc;
/// # fn main() {
/// assert_eq!(mem::size_of::<Rc<()>>(),    2 * mem::size_of::<usize>());
/// assert_eq!(mem::size_of::<Rc<[i32]>>(), 3 * mem::size_of::<usize>());
/// assert_eq!(mem::size_of::<Rc<str>>(),   3 * mem::size_of::<usize>());
/// # }
/// ```
#[unsafe_no_drop_flag]
pub struct Rc<T: ?Sized> {
    /// The number of references
    count: NonZero<*mut Cell<usize>>,
    /// A pointer to the heap allocated data
    data: NonZero<*mut T>,
}

impl<T> Rc<T> {
    /// Creates a new `Rc` pointer.
    ///
    /// NOTE: `value` will be allocated in the heap. If you have a heap allocated value like `Box`,
    /// `String` or `Vec`, use the `Rc::from()` method instead.
    pub fn new(value: T) -> Rc<T> {
        Rc::from(Box::new(value))
    }
}

impl<T: ?Sized> Rc<T> {
    /// Returns the number of references to this value.
    pub fn count(&self) -> usize {
        unsafe {
            (**self.count).get()
        }
    }

    fn dec_count(&self) {
        unsafe {
            (**self.count).set(self.count() - 1)
        }
    }

    fn inc_count(&self) {
        unsafe {
            (**self.count).set(self.count() + 1)
        }
    }
}

impl<T: ?Sized> Borrow<T> for Rc<T> {
    fn borrow(&self) -> &T {
        self
    }
}

impl<T: ?Sized> Clone for Rc<T> {
    fn clone(&self) -> Rc<T> {
        self.inc_count();

        Rc {
            count: self.count,
            data: self.data,
        }
    }
}

impl<T: ?Sized> Eq for Rc<T> where T: Eq {}

impl<'a, T> From<&'a [T]> for Rc<[T]> where T: Clone {
    /// NOTE: This requires allocating the `slice` first (`Vec::to_vec`).
    fn from(slice: &[T]) -> Rc<[T]> {
        Rc::from(slice.to_vec())
    }
}

impl<'a> From<&'a str> for Rc<str> {
    /// NOTE: This requires allocating the `string` first (`String::from_str`).
    fn from(string: &str) -> Rc<str> {
        Rc::from(String::from_str(string))
    }
}

impl<T: ?Sized> From<Box<T>> for Rc<T> {
    /// NOTE: this involves a single, small heap allocation for the reference count. `boxed_value`
    /// will *not* be reallocated.
    fn from(boxed_value: Box<T>) -> Rc<T> {
        unsafe {
            Rc {
                count: NonZero::new(boxed::into_raw(Box::new(Cell::new(1)))),
                data: NonZero::new(boxed::into_raw(boxed_value)),
            }
        }
    }
}

// TODO(rust-lang/rust#18283) use `Rc::from(string.into_boxed_str())` instead of `transmute`
impl From<String> for Rc<str> {
    /// NOTE: This calls `shrink_to_fit` on `string` (on the underlying `Vec<u8>`), which may incur
    /// in a reallocation.
    fn from(string: String) -> Rc<str> {
        // Create a `Rc<[u8]>` first, and then transmute that into a `Rc<str>`
        unsafe {
            mem::transmute(Rc::from(string.into_bytes()))
        }
    }
}

impl<T> From<Vec<T>> for Rc<[T]> {
    /// NOTE: This calls `shrink_to_fit` on `vec`, which may incur in a reallocation.
    fn from(vec: Vec<T>) -> Rc<[T]> {
        Rc::from(vec.into_boxed_slice())
    }
}

impl<T: ?Sized> Deref for Rc<T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe {
            mem::transmute(*self.data)
        }
    }
}

impl<T: ?Sized> Drop for Rc<T> {
    fn drop(&mut self) {
        let ptr = *self.count;

        if !ptr.is_null() && ptr as usize != mem::POST_DROP_USIZE {
            unsafe {
                self.dec_count();

                if self.count() == 0 {
                    drop(Box::from_raw(*self.count));
                    drop(Box::from_raw(*self.data));
                }
            }
        }
    }
}

impl<T: ?Sized> Hash for Rc<T> where T: Hash {
    fn hash<H>(&self, state: &mut H) where H: Hasher {
        Hash::hash(&**self, state)
    }
}

impl<T: ?Sized> PartialEq for Rc<T> where T: PartialEq {
    fn eq(&self, rhs: &Rc<T>) -> bool {
        PartialEq::eq(&**self, &**rhs)
    }
}

impl<T> !Send for Rc<T> {}
impl<T> !Sync for Rc<T> {}

#[cfg(test)]
mod test {
    use rand::{Rng, XorShiftRng, self};
    use quickcheck::TestResult;

    use Rc;

    #[test]
    fn closure_borrow() {
        let i = 0;
        let rc_fn = {
            let boxed_fn: Box<Fn() -> i32> = Box::new(|| { i });
            Rc::from(boxed_fn)
        };

        assert_eq!(rc_fn(), 0);
    }

    #[test]
    fn closure_move() {
        use std::collections::HashMap;

        let mut map = HashMap::new();
        map.insert("A".to_string(), Box::new(0));

        let boxed_fn: Box<Fn(&str) -> i32> = Box::new(move |k| **map.get(k).unwrap());
        let rc_fn = Rc::from(boxed_fn);

        assert_eq!(rc_fn("A"), 0);
    }

    /// `&str` -> `Rc<str>`, where `&str` is not necessarily aligned
    #[quickcheck]
    fn from_str(len: usize, offset: usize, copies: usize) -> TestResult {
        if offset > len {
            return TestResult::discard()
        }

        // create a random string
        let string = rand::thread_rng()
            .gen::<XorShiftRng>()
            .gen_ascii_chars()
            .take(len)
            .collect::<String>();

        // slice the random string
        let str: &str = &string[offset..];
        // create a ref counted string from the slice (this allocates)
        let rcstr = Rc::from(str);

        // create multiple references
        let references = (0..copies).map(|_| rcstr.clone()).collect::<Vec<_>>();

        // drop the original reference
        drop(rcstr);

        // check data integrity
        TestResult::from_bool(references.iter().all(|rcstr| &**rcstr == str))
    }

    /// `String` -> `Rc<str>`, where `String` may have `capacity >= length`
    #[quickcheck]
    fn from_string(cap: usize, len: usize, copies: usize) -> bool {
        // initialize empty string with some reserved capacity
        let mut string = String::with_capacity(cap);

        // push random ascii chars into the string
        for c in rand::thread_rng().gen::<XorShiftRng>().gen_ascii_chars().take(len) {
            string.push(c);
        }

        // create a ref counted string (consumes `string`)
        let original = string.clone();
        let rcstr = Rc::from(string);

        // create multiple owners
        let copies = (0..copies).map(|_| rcstr.clone()).collect::<Vec<_>>();

        // drop original owner
        drop(rcstr);

        // check data integrity
        copies.iter().all(|rcstr| &**rcstr == original)
    }

    /// `Box<Fn(..) -> ..>` -> `Rc<Fn(..) -> ..>`
    #[test]
    fn rc_fn() {
        let trait_object: Box<Fn() -> i32> = Box::new(|| { 0 });
        let rc_fn = Rc::from(trait_object);

        assert_eq!(rc_fn(), 0);
    }

    #[should_panic]
    #[test]
    fn unwind() {
        let str = "Hello, world!";
        let _rc_str_0 = Rc::from(str);
        let _rc_str_1 = Rc::from(str.to_string());
        let slice: &[_] = &[0, 1, 2];
        let _rc_slice_0 = Rc::from(slice);
        let _rc_slice_1 = Rc::from(slice.to_vec());
        let boxed_fn: Box<Fn()> = Box::new(|| {});
        let _rc_fn = Rc::from(boxed_fn);

        panic!();
    }
}
<commit_msg>Rustup to current nightly<commit_after>//! A reference-counted pointer that accepts DST: `Rc<str>`, `Rc<[T]>`, `Rc<Fn>`, etc

#![cfg_attr(test, plugin(quickcheck_macros))]
#![deny(missing_docs)]
#![deny(warnings)]
#![feature(alloc, nonzero, custom_attribute, filling_drop)]
#![feature(optin_builtin_traits, plugin, unsafe_no_drop_flag)]

#[cfg(test)] extern crate quickcheck;
#[cfg(test)] extern crate rand;

extern crate alloc;
extern crate core;

use core::nonzero::NonZero;
use std::borrow::Borrow;
use alloc::boxed;
use std::cell::Cell;
use std::hash::{Hash, Hasher};
use std::mem;
use std::ops::Deref;

/// A reference-counted pointer type over an immutable value.
///
/// # Examples
///
/// ```
/// # #![feature(convert)]
/// # extern crate rc;
/// # use rc::Rc;
/// # fn main() {
/// let boxed_fn: Box<Fn() -> i32> = Box::new(|| { 0 });
/// //boxed_fn.clone();  //~ error: does not implement `clone`
/// let original: Rc<Fn() -> i32> = Rc::from(boxed_fn);  // moves `boxed_fn`
/// let rc_fn = original.clone();  // increases refcount to 2
///
/// drop(original);  // decreases refcount to 1
///
/// // overloaded calls work with `Rc<Fn(..) -> ..>`s
/// assert_eq!(rc_fn(), 0);
///
/// // `rc_fn` dropped here, refcount reaches zero, `boxed_fn` is deallocated
/// # }
/// ```
///
/// # Layout
///
/// A single layer of indirection.
///
/// ``` text
///    Stack       |   Heap
///                |
///    Rc<str>     |
/// +------------+ |
/// | *mut str   |-|-> "Hello, world!"
/// | *mut usize |-|-> 3
/// +------------+ |
/// ```
///
/// ^ NOTE: `Cell`/`NonZero` wrappers omitted for brevity. String and reference count are not
/// (necessarily) stored in contiguous memory.
///
/// # Size
///
/// For sized types: 2 words, for DST: 3 words.
///
/// ```
/// # extern crate rc;
/// # use std::mem;
/// # use rc::Rc;
/// # fn main() {
/// assert_eq!(mem::size_of::<Rc<()>>(),    2 * mem::size_of::<usize>());
/// assert_eq!(mem::size_of::<Rc<[i32]>>(), 3 * mem::size_of::<usize>());
/// assert_eq!(mem::size_of::<Rc<str>>(),   3 * mem::size_of::<usize>());
/// # }
/// ```
#[unsafe_no_drop_flag]
pub struct Rc<T: ?Sized> {
    /// The number of references
    count: NonZero<*mut Cell<usize>>,
    /// A pointer to the heap allocated data
    data: NonZero<*mut T>,
}

impl<T> Rc<T> {
    /// Creates a new `Rc` pointer.
    ///
    /// NOTE: `value` will be allocated in the heap. If you have a heap allocated value like `Box`,
    /// `String` or `Vec`, use the `Rc::from()` method instead.
    pub fn new(value: T) -> Rc<T> {
        Rc::from(Box::new(value))
    }
}

impl<T: ?Sized> Rc<T> {
    /// Returns the number of references to this value.
    pub fn count(&self) -> usize {
        unsafe {
            (**self.count).get()
        }
    }

    fn dec_count(&self) {
        unsafe {
            (**self.count).set(self.count() - 1)
        }
    }

    fn inc_count(&self) {
        unsafe {
            (**self.count).set(self.count() + 1)
        }
    }
}

impl<T: ?Sized> Borrow<T> for Rc<T> {
    fn borrow(&self) -> &T {
        self
    }
}

impl<T: ?Sized> Clone for Rc<T> {
    fn clone(&self) -> Rc<T> {
        self.inc_count();

        Rc {
            count: self.count,
            data: self.data,
        }
    }
}

impl<T: ?Sized> Eq for Rc<T> where T: Eq {}

impl<'a, T> From<&'a [T]> for Rc<[T]> where T: Clone {
    /// NOTE: This requires allocating the `slice` first (`Vec::to_vec`).
    fn from(slice: &[T]) -> Rc<[T]> {
        Rc::from(slice.to_vec())
    }
}

impl<'a> From<&'a str> for Rc<str> {
    /// NOTE: This requires allocating the `string` first (`String::from`).
    fn from(string: &str) -> Rc<str> {
        Rc::from(String::from(string))
    }
}

impl<T: ?Sized> From<Box<T>> for Rc<T> {
    /// NOTE: this involves a single, small heap allocation for the reference count. `boxed_value`
    /// will *not* be reallocated.
    fn from(boxed_value: Box<T>) -> Rc<T> {
        unsafe {
            Rc {
                count: NonZero::new(boxed::Box::into_raw(Box::new(Cell::new(1)))),
                data: NonZero::new(boxed::Box::into_raw(boxed_value)),
            }
        }
    }
}

// TODO(rust-lang/rust#18283) use `Rc::from(string.into_boxed_str())` instead of `transmute`
impl From<String> for Rc<str> {
    /// NOTE: This calls `shrink_to_fit` on `string` (on the underlying `Vec<u8>`), which may incur
    /// in a reallocation.
    fn from(string: String) -> Rc<str> {
        // Create a `Rc<[u8]>` first, and then transmute that into a `Rc<str>`
        unsafe {
            mem::transmute(Rc::from(string.into_bytes()))
        }
    }
}

impl<T> From<Vec<T>> for Rc<[T]> {
    /// NOTE: This calls `shrink_to_fit` on `vec`, which may incur in a reallocation.
    fn from(vec: Vec<T>) -> Rc<[T]> {
        Rc::from(vec.into_boxed_slice())
    }
}

impl<T: ?Sized> Deref for Rc<T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe {
            mem::transmute(*self.data)
        }
    }
}

impl<T: ?Sized> Drop for Rc<T> {
    fn drop(&mut self) {
        let ptr = *self.count;

        if !ptr.is_null() && ptr as usize != mem::POST_DROP_USIZE {
            unsafe {
                self.dec_count();

                if self.count() == 0 {
                    drop(Box::from_raw(*self.count));
                    drop(Box::from_raw(*self.data));
                }
            }
        }
    }
}

impl<T: ?Sized> Hash for Rc<T> where T: Hash {
    fn hash<H>(&self, state: &mut H) where H: Hasher {
        Hash::hash(&**self, state)
    }
}

impl<T: ?Sized> PartialEq for Rc<T> where T: PartialEq {
    fn eq(&self, rhs: &Rc<T>) -> bool {
        PartialEq::eq(&**self, &**rhs)
    }
}

impl<T> !Send for Rc<T> {}
impl<T> !Sync for Rc<T> {}

#[cfg(test)]
mod test {
    use rand::{Rng, XorShiftRng, self};
    use quickcheck::TestResult;

    use Rc;

    #[test]
    fn closure_borrow() {
        let i = 0;
        let rc_fn = {
            let boxed_fn: Box<Fn() -> i32> = Box::new(|| { i });
            Rc::from(boxed_fn)
        };

        assert_eq!(rc_fn(), 0);
    }

    #[test]
    fn closure_move() {
        use std::collections::HashMap;

        let mut map = HashMap::new();
        map.insert("A".to_string(), Box::new(0));

        let boxed_fn: Box<Fn(&str) -> i32> = Box::new(move |k| **map.get(k).unwrap());
        let rc_fn = Rc::from(boxed_fn);

        assert_eq!(rc_fn("A"), 0);
    }

    /// `&str` -> `Rc<str>`, where `&str` is not necessarily aligned
    #[quickcheck]
    fn from_str(len: usize, offset: usize, copies: usize) -> TestResult {
        if offset > len {
            return TestResult::discard()
        }

        // create a random string
        let string = rand::thread_rng()
            .gen::<XorShiftRng>()
            .gen_ascii_chars()
            .take(len)
            .collect::<String>();

        // slice the random string
        let str: &str = &string[offset..];
        // create a ref counted string from the slice (this allocates)
        let rcstr = Rc::from(str);

        // create multiple references
        let references = (0..copies).map(|_| rcstr.clone()).collect::<Vec<_>>();

        // drop the original reference
        drop(rcstr);

        // check data integrity
        TestResult::from_bool(references.iter().all(|rcstr| &**rcstr == str))
    }

    /// `String` -> `Rc<str>`, where `String` may have `capacity >= length`
    #[quickcheck]
    fn from_string(cap: usize, len: usize, copies: usize) -> bool {
        // initialize empty string with some reserved capacity
        let mut string = String::with_capacity(cap);

        // push random ascii chars into the string
        for c in rand::thread_rng().gen::<XorShiftRng>().gen_ascii_chars().take(len) {
            string.push(c);
        }

        // create a ref counted string (consumes `string`)
        let original = string.clone();
        let rcstr = Rc::from(string);

        // create multiple owners
        let copies = (0..copies).map(|_| rcstr.clone()).collect::<Vec<_>>();

        // drop original owner
        drop(rcstr);

        // check data integrity
        copies.iter().all(|rcstr| &**rcstr == original)
    }

    /// `Box<Fn(..) -> ..>` -> `Rc<Fn(..) -> ..>`
    #[test]
    fn rc_fn() {
        let trait_object: Box<Fn() -> i32> = Box::new(|| { 0 });
        let rc_fn = Rc::from(trait_object);

        assert_eq!(rc_fn(), 0);
    }

    #[should_panic]
    #[test]
    fn unwind() {
        let str = "Hello, world!";
        let _rc_str_0 = Rc::from(str);
        let _rc_str_1 = Rc::from(str.to_string());
        let slice: &[_] = &[0, 1, 2];
        let _rc_slice_0 = Rc::from(slice);
        let _rc_slice_1 = Rc::from(slice.to_vec());
        let boxed_fn: Box<Fn()> = Box::new(|| {});
        let _rc_fn = Rc::from(boxed_fn);

        panic!();
    }
}
<|endoftext|>


<commit_before>#![crate_id = "staticfile"]
#![deny(missing_doc)]
#![feature(phase)]

//! Static file-serving middleware.

extern crate iron;
#[phase(plugin, link)]
extern crate log;

use std::path::BytesContainer;
use std::str::from_utf8;

use iron::{Request, Response, Middleware, Alloy};
use iron::mixin::{GetUrl, Serve};
use iron::middleware::{Status, Continue, Unwind};

/// The static file-serving `Middleware`.
#[deriving(Clone)]
pub struct Static {
    root_path: Path
}

impl Static {
    /// Create a new instance of `Static` with a given root path.
    ///
    /// This will attempt to serve static files from the given root path.
    /// The path may be relative or absolute. If `Path::new("")` is given,
    /// files will be served from the current directory.
    ///
    /// If a static file exists and can be read from, `enter` will serve it to
    /// the `Response` and `Unwind` the middleware stack with a status of `200`.
    ///
    /// In the case of any error, it will `Continue` through the stack.
    /// If a file should have been read but cannot, due to permissions or
    /// read errors, a different `Middleware` should handle it.
    ///
    /// If the path is '/', it will attempt to serve `index.html`.
    pub fn new(root_path: Path) -> Static {
        Static {
            root_path: root_path
        }
    }
}

impl Middleware for Static {
    fn enter(&mut self, req: &mut Request, res: &mut Response, _alloy: &mut Alloy) -> Status {
        match req.url() {
            Some(path) => {
                let mut relative_path = path.clone();
                if relative_path.eq(&"/".to_string()) {
                    relative_path = "index.html".to_string();
                }
                match res.serve_file(&self.root_path.join(Path::new(relative_path.to_string()))) {
                    Ok(()) => {
                        debug!("Serving static file at {}{}.",
                            from_utf8(self.root_path.container_as_bytes()).unwrap(), path);
                        Unwind
                    },
                    Err(_) => { Continue }
                }
            },
            None => {
                Continue
            }
        }
    }
}
<commit_msg>(fix) Handle requests as relative paths.<commit_after>#![crate_id = "staticfile"]
#![deny(missing_doc)]
#![feature(phase)]

//! Static file-serving middleware.

extern crate iron;
#[phase(plugin, link)]
extern crate log;

use iron::{Request, Response, Middleware, Alloy};
use iron::mixin::{GetUrl, Serve};
use iron::middleware::{Status, Continue, Unwind};

/// The static file-serving `Middleware`.
#[deriving(Clone)]
pub struct Static {
    root_path: Path
}

impl Static {
    /// Create a new instance of `Static` with a given root path.
    ///
    /// This will attempt to serve static files from the given root path.
    /// The path may be relative or absolute. If `Path::new("")` is given,
    /// files will be served from the current directory.
    ///
    /// If a static file exists and can be read from, `enter` will serve it to
    /// the `Response` and `Unwind` the middleware stack with a status of `200`.
    ///
    /// In the case of any error, it will `Continue` through the stack.
    /// If a file should have been read but cannot, due to permissions or
    /// read errors, a different `Middleware` should handle it.
    ///
    /// If the path is '/', it will attempt to serve `index.html`.
    pub fn new(root_path: Path) -> Static {
        Static {
            root_path: root_path
        }
    }
}

impl Middleware for Static {
    fn enter(&mut self, req: &mut Request, res: &mut Response, _alloy: &mut Alloy) -> Status {
        match req.url() {
            Some(path) => {
                // Check for requested file
                match res.serve_file(&self.root_path.join(
                    Path::new(
                        // Coerce to relative path, see http://is.gd/yz9p0B
                        "./".to_string().append(path.as_slice())))) {
                    Ok(()) => {
                        debug!("Serving static file at {}.",
                            &self.root_path.join("./".to_string().append(path.as_slice())).display());
                        return Unwind
                    },
                    Err(_) => ()
                }
                // Check for index.html
                // Do not serve index.html as directory
            },
            None => ()
        }
        Continue
    }
}
<|endoftext|>


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

use std::fmt::{self, Debug, Formatter};
use std::marker::PhantomData;
use std::mem;
use std::ops::Deref;
use std::ptr;
use std::sync::atomic::AtomicPtr;
use std::sync::atomic::Ordering;
use std::sync::Arc;

/// An Atom wraps an AtomicPtr, it allows for safe mutation of an atomic
/// into common Rust Types.
pub struct Atom

where
    P: IntoRawPtr + FromRawPtr,
{
    inner: AtomicPtr<()>,
    data: PhantomData
,
}

impl
 Debug for Atom

where
    P: IntoRawPtr + FromRawPtr,
{
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        write!(f, "atom({:?})", self.inner.load(Ordering::Relaxed))
    }
}

impl
 Atom

where
    P: IntoRawPtr + FromRawPtr,
{
    /// Create a empty Atom
    pub fn empty() -> Atom
 {
        Atom {
            inner: AtomicPtr::new(ptr::null_mut()),
            data: PhantomData,
        }
    }

    /// Create a new Atomic from Pointer P
    pub fn new(value: P) -> Atom
 {
        Atom {
            inner: AtomicPtr::new(value.into_raw()),
            data: PhantomData,
        }
    }

    /// Swap a new value into the Atom, This will try multiple
    /// times until it succeeds. The old value will be returned.
    pub fn swap(&self, v: P, order: Ordering) -> Option
 {
        let new = v.into_raw();
        let old = self.inner.swap(new, order);
        unsafe { Self::inner_from_raw(old) }
    }

    /// Take the value of the Atom replacing it with null pointer
    /// Returning the contents. If the contents was a `null` pointer the
    /// result will be `None`.
    pub fn take(&self, order: Ordering) -> Option
 {
        let old = self.inner.swap(ptr::null_mut(), order);
        unsafe { Self::inner_from_raw(old) }
    }

    /// This will do a `CAS` setting the value only if it is NULL
    /// this will return `None` if the value was written,
    /// otherwise a `Some(v)` will be returned, where the value was
    /// the same value that you passed into this function
    pub fn set_if_none(&self, v: P, order: Ordering) -> Option
 {
        let new = v.into_raw();
        let old = self.inner.compare_and_swap(ptr::null_mut(), new, order);
        if !old.is_null() {
            Some(unsafe { FromRawPtr::from_raw(new) })
        } else {
            None
        }
    }

    /// Take the current content, write it into P then do a CAS to extent this
    /// Atom with the previous contents. This can be used to create a LIFO
    ///
    /// Returns true if this set this migrated the Atom from null.
    pub fn replace_and_set_next(
        &self,
        mut value: P,
        load_order: Ordering,
        cas_order: Ordering,
    ) -> bool
    where
        P: GetNextMut<NextPtr = Option
>,
    {
        let next = value.get_next() as *mut Option
;
        let raw = value.into_raw();
        // If next was set to Some(P) we want to
        // assert that it was droppeds
        unsafe { ptr::drop_in_place(next) };
        loop {
            let pcurrent = self.inner.load(load_order);
            let current = unsafe { Self::inner_from_raw(pcurrent) };
            unsafe { ptr::write(next, current) };
            let last = self.inner.compare_and_swap(pcurrent, raw, cas_order);
            if last == pcurrent {
                return last.is_null();
            }
        }
    }

    /// Check to see if an atom is None
    ///
    /// This only means that the contents was None when it was measured
    pub fn is_none(&self, order: Ordering) -> bool {
        self.inner.load(order).is_null()
    }

    #[inline]
    fn inner_into_raw(val: Option
) -> *mut () {
        match val {
            Some(val) => val.into_raw(),
            None => ptr::null_mut(),
        }
    }

    #[inline]
    unsafe fn inner_from_raw(ptr: *mut ()) -> Option
 {
        if !ptr.is_null() {
            Some(FromRawPtr::from_raw(ptr))
        } else {
            None
        }
    }
}

impl
 Atom

where
    P: IntoRawPtr + FromRawPtr + Deref<Target = T>,
{
    /// Stores a value into the pointer if the current value is the same as the
    /// current value.
    ///
    /// The return value is always the previous value. If it is equal to
    /// current, then the value was updated.
    ///
    /// compare_and_swap also takes an Ordering argument which describes the
    /// memory ordering of this operation.
    pub fn compare_and_swap(
        &self,
        current: Option<&P>,
        new: Option
,
        order: Ordering,
    ) -> Result<Option
, (Option
, *mut P)> {
        let pcurrent = Self::inner_as_ptr(current);
        let pnew = Self::inner_into_raw(new);
        let pprev = self.inner.compare_and_swap(pcurrent, pnew, order);
        if pprev == pcurrent {
            Ok(unsafe { Self::inner_from_raw(pprev) })
        } else {
            Err((unsafe { Self::inner_from_raw(pnew) }, pprev as *mut P))
        }
    }

    /// Stores a value into the pointer if the current value is the same as the
    /// `current` value.
    ///
    /// The return value is a result indicating whether the new value was
    /// written and containing the previous value. On success this value is
    /// guaranteed to be equal to `current`.
    ///
    /// `compare_exchange` takes two `Ordering` arguments to describe the
    /// memory ordering of this operation. The first describes the required
    /// ordering if the operation succeeds while the second describes the
    /// required ordering when the operation fails. The failure ordering can't
    /// be `Release` or `AcqRel` and must be equivalent or weaker than the
    /// success ordering.
    pub fn compare_exchange(
        &self,
        current: Option<&P>,
        new: Option
,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Option
, (Option
, *mut P)> {
        let pnew = Self::inner_into_raw(new);
        self.inner
            .compare_exchange(Self::inner_as_ptr(current), pnew, success, failure)
            .map(|pprev| unsafe { Self::inner_from_raw(pprev) })
            .map_err(|pprev| (unsafe { Self::inner_from_raw(pnew) }, pprev as *mut P))
    }

    /// Stores a value into the pointer if the current value is the same as the
    /// `current` value.
    ///
    /// Unlike `compare_exchange`, this function is allowed to spuriously fail
    /// even when the comparison succeeds, which can result in more efficient
    /// code on some platforms. The return value is a result indicating whether
    /// the new value was written and containing the previous value.
    ///
    /// `compare_exchange_weak` takes two `Ordering` arguments to describe the
    /// memory ordering of this operation. The first describes the required
    /// ordering if the operation succeeds while the second describes the
    /// required ordering when the operation fails. The failure ordering can't
    /// be `Release` or `AcqRel` and must be equivalent or weaker than the
    /// success ordering.
    pub fn compare_exchange_weak(
        &self,
        current: Option<&P>,
        new: Option
,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Option
, (Option
, *mut P)> {
        let pnew = Self::inner_into_raw(new);
        self.inner
            .compare_exchange_weak(Self::inner_as_ptr(current), pnew, success, failure)
            .map(|pprev| unsafe { Self::inner_from_raw(pprev) })
            .map_err(|pprev| (unsafe { Self::inner_from_raw(pnew) }, pprev as *mut P))
    }

    #[inline]
    fn inner_as_ptr(val: Option<&P>) -> *mut () {
        match val {
            Some(val) => &**val as *const _ as *mut (),
            None => ptr::null_mut(),
        }
    }
}

impl
 Drop for Atom

where
    P: IntoRawPtr + FromRawPtr,
{
    fn drop(&mut self) {
        self.take(Ordering::Relaxed);
    }
}

unsafe impl
 Send for Atom

where
    P: IntoRawPtr + FromRawPtr,
{
}
unsafe impl
 Sync for Atom

where
    P: IntoRawPtr + FromRawPtr,
{
}

/// Convert from into a raw pointer
pub trait IntoRawPtr {
    fn into_raw(self) -> *mut ();
}

/// Convert from a raw ptr into a pointer
pub trait FromRawPtr {
    unsafe fn from_raw(ptr: *mut ()) -> Self;
}

impl<T> IntoRawPtr for Box<T> {
    #[inline]
    fn into_raw(self) -> *mut () {
        Box::into_raw(self) as *mut ()
    }
}

impl<T> FromRawPtr for Box<T> {
    #[inline]
    unsafe fn from_raw(ptr: *mut ()) -> Box<T> {
        Box::from_raw(ptr as *mut T)
    }
}

impl<T> IntoRawPtr for Arc<T> {
    #[inline]
    fn into_raw(self) -> *mut () {
        Arc::into_raw(self) as *mut T as *mut ()
    }
}

impl<T> FromRawPtr for Arc<T> {
    #[inline]
    unsafe fn from_raw(ptr: *mut ()) -> Arc<T> {
        Arc::from_raw(ptr as *const () as *const T)
    }
}

/// Transforms lifetime of the second pointer to match the first.
#[inline]
unsafe fn copy_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S, ptr: &T) -> &'a T {
    mem::transmute(ptr)
}

/// Transforms lifetime of the second pointer to match the first.
#[inline]
unsafe fn copy_mut_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S, ptr: &mut T) -> &'a mut T {
    mem::transmute(ptr)
}

/// This is a restricted version of the Atom. It allows for only
/// `set_if_none` to be called.
///
/// `swap` and `take` can be used only with a mutable reference. Meaning
/// that AtomSetOnce is not usable as a
#[derive(Debug)]
pub struct AtomSetOnce

where
    P: IntoRawPtr + FromRawPtr,
{
    inner: Atom
,
}

impl
 AtomSetOnce

where
    P: IntoRawPtr + FromRawPtr,
{
    /// Create an empty `AtomSetOnce`
    pub fn empty() -> AtomSetOnce
 {
        AtomSetOnce {
            inner: Atom::empty(),
        }
    }

    /// Create a new `AtomSetOnce` from Pointer P
    pub fn new(value: P) -> AtomSetOnce
 {
        AtomSetOnce {
            inner: Atom::new(value),
        }
    }

    /// This will do a `CAS` setting the value only if it is NULL
    /// this will return `OK(())` if the value was written,
    /// otherwise a `Err(P)` will be returned, where the value was
    /// the same value that you passed into this function
    pub fn set_if_none(&self, v: P, order: Ordering) -> Option
 {
        self.inner.set_if_none(v, order)
    }

    /// Convert an `AtomSetOnce` into an `Atom`
    pub fn into_atom(self) -> Atom
 {
        self.inner
    }

    /// Allow access to the atom if exclusive access is granted
    pub fn atom(&mut self) -> &mut Atom
 {
        &mut self.inner
    }

    /// Check to see if an atom is None
    ///
    /// This only means that the contents was None when it was measured
    pub fn is_none(&self, order: Ordering) -> bool {
        self.inner.is_none(order)
    }
}

impl<T, P> AtomSetOnce

where
    P: IntoRawPtr + FromRawPtr + Deref<Target = T>,
{
    /// If the Atom is set, get the value
    pub fn get<'a>(&'a self, order: Ordering) -> Option<&'a T> {
        let ptr = self.inner.inner.load(order);
        let val = unsafe { Atom::inner_from_raw(ptr) };
        val.map(|v: P| {
            // This is safe since ptr cannot be changed once it is set
            // which means that this is now a Arc or a Box.
            let out = unsafe { copy_lifetime(self, &*v) };
            mem::forget(v);
            out
        })
    }
}

impl<T> AtomSetOnce<Box<T>> {
    /// If the Atom is set, get the value
    pub fn get_mut<'a>(&'a mut self, order: Ordering) -> Option<&'a mut T> {
        let ptr = self.inner.inner.load(order);
        let val = unsafe { Atom::inner_from_raw(ptr) };
        val.map(move |mut v: Box<T>| {
            // This is safe since ptr cannot be changed once it is set
            // which means that this is now a Arc or a Box.
            let out = unsafe { copy_mut_lifetime(self, &mut *v) };
            mem::forget(v);
            out
        })
    }
}

impl<T> AtomSetOnce<T>
where
    T: Clone + IntoRawPtr + FromRawPtr,
{
    /// Duplicate the inner pointer if it is set
    pub fn dup<'a>(&self, order: Ordering) -> Option<T> {
        let ptr = self.inner.inner.load(order);
        let val = unsafe { Atom::inner_from_raw(ptr) };
        val.map(|v: T| {
            let out = v.clone();
            mem::forget(v);
            out
        })
    }
}

/// This is a utility Trait that fetches the next ptr from
/// an object.
pub trait GetNextMut {
    type NextPtr;
    fn get_next(&mut self) -> &mut Self::NextPtr;
}
<commit_msg>Improve compare_and_swap documentation<commit_after>//   Copyright 2015 Colin Sherratt
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

use std::fmt::{self, Debug, Formatter};
use std::marker::PhantomData;
use std::mem;
use std::ops::Deref;
use std::ptr;
use std::sync::atomic::AtomicPtr;
use std::sync::atomic::Ordering;
use std::sync::Arc;

/// An Atom wraps an AtomicPtr, it allows for safe mutation of an atomic
/// into common Rust Types.
pub struct Atom

where
    P: IntoRawPtr + FromRawPtr,
{
    inner: AtomicPtr<()>,
    data: PhantomData
,
}

impl
 Debug for Atom

where
    P: IntoRawPtr + FromRawPtr,
{
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        write!(f, "atom({:?})", self.inner.load(Ordering::Relaxed))
    }
}

impl
 Atom

where
    P: IntoRawPtr + FromRawPtr,
{
    /// Create a empty Atom
    pub fn empty() -> Atom
 {
        Atom {
            inner: AtomicPtr::new(ptr::null_mut()),
            data: PhantomData,
        }
    }

    /// Create a new Atomic from Pointer P
    pub fn new(value: P) -> Atom
 {
        Atom {
            inner: AtomicPtr::new(value.into_raw()),
            data: PhantomData,
        }
    }

    /// Swap a new value into the Atom, This will try multiple
    /// times until it succeeds. The old value will be returned.
    pub fn swap(&self, v: P, order: Ordering) -> Option
 {
        let new = v.into_raw();
        let old = self.inner.swap(new, order);
        unsafe { Self::inner_from_raw(old) }
    }

    /// Take the value of the Atom replacing it with null pointer
    /// Returning the contents. If the contents was a `null` pointer the
    /// result will be `None`.
    pub fn take(&self, order: Ordering) -> Option
 {
        let old = self.inner.swap(ptr::null_mut(), order);
        unsafe { Self::inner_from_raw(old) }
    }

    /// This will do a `CAS` setting the value only if it is NULL
    /// this will return `None` if the value was written,
    /// otherwise a `Some(v)` will be returned, where the value was
    /// the same value that you passed into this function
    pub fn set_if_none(&self, v: P, order: Ordering) -> Option
 {
        let new = v.into_raw();
        let old = self.inner.compare_and_swap(ptr::null_mut(), new, order);
        if !old.is_null() {
            Some(unsafe { FromRawPtr::from_raw(new) })
        } else {
            None
        }
    }

    /// Take the current content, write it into P then do a CAS to extent this
    /// Atom with the previous contents. This can be used to create a LIFO
    ///
    /// Returns true if this set this migrated the Atom from null.
    pub fn replace_and_set_next(
        &self,
        mut value: P,
        load_order: Ordering,
        cas_order: Ordering,
    ) -> bool
    where
        P: GetNextMut<NextPtr = Option
>,
    {
        let next = value.get_next() as *mut Option
;
        let raw = value.into_raw();
        // If next was set to Some(P) we want to
        // assert that it was droppeds
        unsafe { ptr::drop_in_place(next) };
        loop {
            let pcurrent = self.inner.load(load_order);
            let current = unsafe { Self::inner_from_raw(pcurrent) };
            unsafe { ptr::write(next, current) };
            let last = self.inner.compare_and_swap(pcurrent, raw, cas_order);
            if last == pcurrent {
                return last.is_null();
            }
        }
    }

    /// Check to see if an atom is None
    ///
    /// This only means that the contents was None when it was measured
    pub fn is_none(&self, order: Ordering) -> bool {
        self.inner.load(order).is_null()
    }

    #[inline]
    fn inner_into_raw(val: Option
) -> *mut () {
        match val {
            Some(val) => val.into_raw(),
            None => ptr::null_mut(),
        }
    }

    #[inline]
    unsafe fn inner_from_raw(ptr: *mut ()) -> Option
 {
        if !ptr.is_null() {
            Some(FromRawPtr::from_raw(ptr))
        } else {
            None
        }
    }
}

impl
 Atom

where
    P: IntoRawPtr + FromRawPtr + Deref<Target = T>,
{
    /// Stores `new` in the Atom if `current` has the same raw pointer
    /// representation as the currently stored value.
    ///
    /// On success, the Atom's previous value is returned. On failure, `new` is
    /// returned together with a raw pointer to the Atom's current unchanged
    /// value, which is **not safe to dereference**, especially if the Atom is
    /// accessed from multiple threads.
    ///
    /// `compare_and_swap` also takes an `Ordering` argument which describes
    /// the memory ordering of this operation.
    pub fn compare_and_swap(
        &self,
        current: Option<&P>,
        new: Option
,
        order: Ordering,
    ) -> Result<Option
, (Option
, *mut P)> {
        let pcurrent = Self::inner_as_ptr(current);
        let pnew = Self::inner_into_raw(new);
        let pprev = self.inner.compare_and_swap(pcurrent, pnew, order);
        if pprev == pcurrent {
            Ok(unsafe { Self::inner_from_raw(pprev) })
        } else {
            Err((unsafe { Self::inner_from_raw(pnew) }, pprev as *mut P))
        }
    }

    /// Stores a value into the pointer if the current value is the same as the
    /// `current` value.
    ///
    /// The return value is a result indicating whether the new value was
    /// written and containing the previous value. On success this value is
    /// guaranteed to be equal to `current`.
    ///
    /// `compare_exchange` takes two `Ordering` arguments to describe the
    /// memory ordering of this operation. The first describes the required
    /// ordering if the operation succeeds while the second describes the
    /// required ordering when the operation fails. The failure ordering can't
    /// be `Release` or `AcqRel` and must be equivalent or weaker than the
    /// success ordering.
    pub fn compare_exchange(
        &self,
        current: Option<&P>,
        new: Option
,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Option
, (Option
, *mut P)> {
        let pnew = Self::inner_into_raw(new);
        self.inner
            .compare_exchange(Self::inner_as_ptr(current), pnew, success, failure)
            .map(|pprev| unsafe { Self::inner_from_raw(pprev) })
            .map_err(|pprev| (unsafe { Self::inner_from_raw(pnew) }, pprev as *mut P))
    }

    /// Stores a value into the pointer if the current value is the same as the
    /// `current` value.
    ///
    /// Unlike `compare_exchange`, this function is allowed to spuriously fail
    /// even when the comparison succeeds, which can result in more efficient
    /// code on some platforms. The return value is a result indicating whether
    /// the new value was written and containing the previous value.
    ///
    /// `compare_exchange_weak` takes two `Ordering` arguments to describe the
    /// memory ordering of this operation. The first describes the required
    /// ordering if the operation succeeds while the second describes the
    /// required ordering when the operation fails. The failure ordering can't
    /// be `Release` or `AcqRel` and must be equivalent or weaker than the
    /// success ordering.
    pub fn compare_exchange_weak(
        &self,
        current: Option<&P>,
        new: Option
,
        success: Ordering,
        failure: Ordering,
    ) -> Result<Option
, (Option
, *mut P)> {
        let pnew = Self::inner_into_raw(new);
        self.inner
            .compare_exchange_weak(Self::inner_as_ptr(current), pnew, success, failure)
            .map(|pprev| unsafe { Self::inner_from_raw(pprev) })
            .map_err(|pprev| (unsafe { Self::inner_from_raw(pnew) }, pprev as *mut P))
    }

    #[inline]
    fn inner_as_ptr(val: Option<&P>) -> *mut () {
        match val {
            Some(val) => &**val as *const _ as *mut (),
            None => ptr::null_mut(),
        }
    }
}

impl
 Drop for Atom

where
    P: IntoRawPtr + FromRawPtr,
{
    fn drop(&mut self) {
        self.take(Ordering::Relaxed);
    }
}

unsafe impl
 Send for Atom

where
    P: IntoRawPtr + FromRawPtr,
{
}
unsafe impl
 Sync for Atom

where
    P: IntoRawPtr + FromRawPtr,
{
}

/// Convert from into a raw pointer
pub trait IntoRawPtr {
    fn into_raw(self) -> *mut ();
}

/// Convert from a raw ptr into a pointer
pub trait FromRawPtr {
    unsafe fn from_raw(ptr: *mut ()) -> Self;
}

impl<T> IntoRawPtr for Box<T> {
    #[inline]
    fn into_raw(self) -> *mut () {
        Box::into_raw(self) as *mut ()
    }
}

impl<T> FromRawPtr for Box<T> {
    #[inline]
    unsafe fn from_raw(ptr: *mut ()) -> Box<T> {
        Box::from_raw(ptr as *mut T)
    }
}

impl<T> IntoRawPtr for Arc<T> {
    #[inline]
    fn into_raw(self) -> *mut () {
        Arc::into_raw(self) as *mut T as *mut ()
    }
}

impl<T> FromRawPtr for Arc<T> {
    #[inline]
    unsafe fn from_raw(ptr: *mut ()) -> Arc<T> {
        Arc::from_raw(ptr as *const () as *const T)
    }
}

/// Transforms lifetime of the second pointer to match the first.
#[inline]
unsafe fn copy_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S, ptr: &T) -> &'a T {
    mem::transmute(ptr)
}

/// Transforms lifetime of the second pointer to match the first.
#[inline]
unsafe fn copy_mut_lifetime<'a, S: ?Sized, T: ?Sized + 'a>(_ptr: &'a S, ptr: &mut T) -> &'a mut T {
    mem::transmute(ptr)
}

/// This is a restricted version of the Atom. It allows for only
/// `set_if_none` to be called.
///
/// `swap` and `take` can be used only with a mutable reference. Meaning
/// that AtomSetOnce is not usable as a
#[derive(Debug)]
pub struct AtomSetOnce

where
    P: IntoRawPtr + FromRawPtr,
{
    inner: Atom
,
}

impl
 AtomSetOnce

where
    P: IntoRawPtr + FromRawPtr,
{
    /// Create an empty `AtomSetOnce`
    pub fn empty() -> AtomSetOnce
 {
        AtomSetOnce {
            inner: Atom::empty(),
        }
    }

    /// Create a new `AtomSetOnce` from Pointer P
    pub fn new(value: P) -> AtomSetOnce
 {
        AtomSetOnce {
            inner: Atom::new(value),
        }
    }

    /// This will do a `CAS` setting the value only if it is NULL
    /// this will return `OK(())` if the value was written,
    /// otherwise a `Err(P)` will be returned, where the value was
    /// the same value that you passed into this function
    pub fn set_if_none(&self, v: P, order: Ordering) -> Option
 {
        self.inner.set_if_none(v, order)
    }

    /// Convert an `AtomSetOnce` into an `Atom`
    pub fn into_atom(self) -> Atom
 {
        self.inner
    }

    /// Allow access to the atom if exclusive access is granted
    pub fn atom(&mut self) -> &mut Atom
 {
        &mut self.inner
    }

    /// Check to see if an atom is None
    ///
    /// This only means that the contents was None when it was measured
    pub fn is_none(&self, order: Ordering) -> bool {
        self.inner.is_none(order)
    }
}

impl<T, P> AtomSetOnce

where
    P: IntoRawPtr + FromRawPtr + Deref<Target = T>,
{
    /// If the Atom is set, get the value
    pub fn get<'a>(&'a self, order: Ordering) -> Option<&'a T> {
        let ptr = self.inner.inner.load(order);
        let val = unsafe { Atom::inner_from_raw(ptr) };
        val.map(|v: P| {
            // This is safe since ptr cannot be changed once it is set
            // which means that this is now a Arc or a Box.
            let out = unsafe { copy_lifetime(self, &*v) };
            mem::forget(v);
            out
        })
    }
}

impl<T> AtomSetOnce<Box<T>> {
    /// If the Atom is set, get the value
    pub fn get_mut<'a>(&'a mut self, order: Ordering) -> Option<&'a mut T> {
        let ptr = self.inner.inner.load(order);
        let val = unsafe { Atom::inner_from_raw(ptr) };
        val.map(move |mut v: Box<T>| {
            // This is safe since ptr cannot be changed once it is set
            // which means that this is now a Arc or a Box.
            let out = unsafe { copy_mut_lifetime(self, &mut *v) };
            mem::forget(v);
            out
        })
    }
}

impl<T> AtomSetOnce<T>
where
    T: Clone + IntoRawPtr + FromRawPtr,
{
    /// Duplicate the inner pointer if it is set
    pub fn dup<'a>(&self, order: Ordering) -> Option<T> {
        let ptr = self.inner.inner.load(order);
        let val = unsafe { Atom::inner_from_raw(ptr) };
        val.map(|v: T| {
            let out = v.clone();
            mem::forget(v);
            out
        })
    }
}

/// This is a utility Trait that fetches the next ptr from
/// an object.
pub trait GetNextMut {
    type NextPtr;
    fn get_next(&mut self) -> &mut Self::NextPtr;
}
<|endoftext|>