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

//! Implementation of cookie creation and matching as specified by
//! http://tools.ietf.org/html/rfc6265

use cookie_storage::CookieSource;
use pub_domains::PUB_DOMAINS;

use cookie_rs;
use time::{Tm, now, at, Timespec};
use url::Url;
use std::borrow::ToOwned;
use std::i64;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::time::Duration;
use std::str::FromStr;

/// A stored cookie that wraps the definition in cookie-rs. This is used to implement
/// various behaviours defined in the spec that rely on an associated request URL,
/// which cookie-rs and hyper's header parsing do not support.
#[derive(Clone, Debug)]
pub struct Cookie {
    pub cookie: cookie_rs::Cookie,
    pub host_only: bool,
    pub persistent: bool,
    pub creation_time: Tm,
    pub last_access: Tm,
    pub expiry_time: Tm,
}

impl Cookie {
    /// http://tools.ietf.org/html/rfc6265#section-5.3
    pub fn new_wrapped(mut cookie: cookie_rs::Cookie, request: &Url, source: CookieSource)
                       -> Option<Cookie> {
        // Step 3
        let (persistent, expiry_time) = match (&cookie.max_age, &cookie.expires) {
            (&Some(max_age), _) => (true, at(now().to_timespec() + Duration::seconds(max_age as i64))),
            (_, &Some(expires)) => (true, expires),
            _ => (false, at(Timespec::new(i64::MAX, 0)))
        };

        let url_host = request.host().map(|host| host.serialize()).unwrap_or("".to_owned());

        // Step 4
        let mut domain = cookie.domain.clone().unwrap_or("".to_owned());

        // Step 5
        match PUB_DOMAINS.iter().find(|&x| domain == *x) {
            Some(val) if *val == url_host => domain = "".to_string(),
            Some(_) => return None,
            None => {}
        }

        // Step 6
        let host_only = if !domain.is_empty() {
            if !Cookie::domain_match(&url_host, &domain) {
                return None;
            } else {
                cookie.domain = Some(domain);
                false
            }
        } else {
            cookie.domain = Some(url_host);
            true
        };

        // Step 7
        let mut path = cookie.path.unwrap_or("".to_owned());
        if path.is_empty() || path.char_at(0) != '/' {
            let url_path = request.serialize_path();
            let url_path = url_path.as_ref().map(|path| &**path);
            path = Cookie::default_path(url_path.unwrap_or(""));
        }
        cookie.path = Some(path);

        // Step 10
        if cookie.httponly && source != CookieSource::HTTP {
            return None;
        }

        Some(Cookie {
            cookie: cookie,
            host_only: host_only,
            persistent: persistent,
            creation_time: now(),
            last_access: now(),
            expiry_time: expiry_time,
        })
    }

    pub fn touch(&mut self) {
        self.last_access = now();
    }

    // http://tools.ietf.org/html/rfc6265#section-5.1.4
    fn default_path(request_path: &str) -> String {
        if request_path == "" || request_path.char_at(0) != '/' ||
           request_path.chars().filter(|&c| c == '/').count() == 1 {
            "/".to_owned()
        } else if request_path.ends_with("/") {
            request_path[..request_path.len() - 1].to_owned()
        } else {
            request_path.to_owned()
        }
    }

    // http://tools.ietf.org/html/rfc6265#section-5.1.4
    pub fn path_match(request_path: &str, cookie_path: &str) -> bool {
        request_path == cookie_path ||
        ( request_path.starts_with(cookie_path) &&
            ( request_path.ends_with("/") || request_path.char_at(cookie_path.len() - 1) == '/' )
        )
    }

    // http://tools.ietf.org/html/rfc6265#section-5.1.3
    pub fn domain_match(string: &str, domain_string: &str) -> bool {
        if string == domain_string {
            return true;
        }
        if string.ends_with(domain_string)
            && string.char_at(string.len()-domain_string.len()-1) == '.'
            && Ipv4Addr::from_str(string).is_err()
            && Ipv6Addr::from_str(string).is_err() {
            return true;
        }
        false
    }

    // http://tools.ietf.org/html/rfc6265#section-5.4 step 1
    pub fn appropriate_for_url(&self, url: &Url, source: CookieSource) -> bool {
        let domain = url.host().map(|host| host.serialize());
        if self.host_only {
            if self.cookie.domain != domain {
                return false;
            }
        } else {
            if let (Some(ref domain), &Some(ref cookie_domain)) = (domain, &self.cookie.domain) {
                if !Cookie::domain_match(domain, cookie_domain) {
                    return false;
                }
            }
        }

        if let (Some(ref path), &Some(ref cookie_path)) = (url.serialize_path(), &self.cookie.path) {
            if !Cookie::path_match(path, cookie_path) {
                return false;
            }
        }

        if self.cookie.secure && url.scheme != "https".to_string() {
            return false;
        }
        if self.cookie.httponly && source == CookieSource::NonHTTP {
            return false;
        }

        return true;
    }
}

#[test]
fn test_domain_match() {
    assert!(Cookie::domain_match("foo.com", "foo.com"));
    assert!(Cookie::domain_match("bar.foo.com", "foo.com"));
    assert!(Cookie::domain_match("baz.bar.foo.com", "foo.com"));

    assert!(!Cookie::domain_match("bar.foo.com", "bar.com"));
    assert!(!Cookie::domain_match("bar.com", "baz.bar.com"));
    assert!(!Cookie::domain_match("foo.com", "bar.com"));

    assert!(!Cookie::domain_match("bar.com", "bbar.com"));
    assert!(Cookie::domain_match("235.132.2.3", "235.132.2.3"));
    assert!(!Cookie::domain_match("235.132.2.3", "1.1.1.1"));
    assert!(!Cookie::domain_match("235.132.2.3", ".2.3"));
}

#[test]
fn test_default_path() {
    assert!(&*Cookie::default_path("/foo/bar/baz/") == "/foo/bar/baz");
    assert!(&*Cookie::default_path("/foo/") == "/foo");
    assert!(&*Cookie::default_path("/foo") == "/");
    assert!(&*Cookie::default_path("/") == "/");
    assert!(&*Cookie::default_path("") == "/");
    assert!(&*Cookie::default_path("foo") == "/");
}

#[test]
fn fn_cookie_constructor() {
    use cookie_storage::CookieSource;

    let url = &Url::parse("http://example.com/foo").unwrap();

    let gov_url = &Url::parse("http://gov.ac/foo").unwrap();
    // cookie name/value test
    assert!(cookie_rs::Cookie::parse(" baz ").is_err());
    assert!(cookie_rs::Cookie::parse(" = bar  ").is_err());
    assert!(cookie_rs::Cookie::parse(" baz = ").is_ok());

    // cookie domains test
    let cookie = cookie_rs::Cookie::parse(" baz = bar; Domain =  ").unwrap();
    assert!(Cookie::new_wrapped(cookie.clone(), url, CookieSource::HTTP).is_some());
    let cookie = Cookie::new_wrapped(cookie, url, CookieSource::HTTP).unwrap();
    assert!(&**cookie.cookie.domain.as_ref().unwrap() == "example.com");

    // cookie public domains test
    let cookie = cookie_rs::Cookie::parse(" baz = bar; Domain =  gov.ac").unwrap();
    assert!(Cookie::new_wrapped(cookie.clone(), url, CookieSource::HTTP).is_none());
    assert!(Cookie::new_wrapped(cookie, gov_url, CookieSource::HTTP).is_some());

    // cookie domain matching test
    let cookie = cookie_rs::Cookie::parse(" baz = bar ; Secure; Domain = bazample.com").unwrap();
    assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none());

    let cookie = cookie_rs::Cookie::parse(" baz = bar ; Secure; Path = /foo/bar/").unwrap();
    assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_some());

    let cookie = cookie_rs::Cookie::parse(" baz = bar ; HttpOnly").unwrap();
    assert!(Cookie::new_wrapped(cookie, url, CookieSource::NonHTTP).is_none());

    let cookie = cookie_rs::Cookie::parse(" baz = bar ; Secure; Path = /foo/bar/").unwrap();
    let cookie = Cookie::new_wrapped(cookie, url, CookieSource::HTTP).unwrap();
    assert!(cookie.cookie.value.as_slice() == "bar");
    assert!(cookie.cookie.name.as_slice() == "baz");
    assert!(cookie.cookie.secure);
    assert!(cookie.cookie.path.as_ref().unwrap().as_slice() == "/foo/bar/");
    assert!(cookie.cookie.domain.as_ref().unwrap().as_slice() == "example.com");
    assert!(cookie.host_only);

    let u = &Url::parse("http://example.com/foobar").unwrap();
    let cookie = cookie_rs::Cookie::parse("foobar=value;path=/").unwrap();
    assert!(Cookie::new_wrapped(cookie, u, CookieSource::HTTP).is_some());
}
<commit_msg>auto merge of #5403 : frewsxcv/servo/cookie-default-path, r=jdm<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Implementation of cookie creation and matching as specified by
//! http://tools.ietf.org/html/rfc6265

use cookie_storage::CookieSource;
use pub_domains::PUB_DOMAINS;

use cookie_rs;
use time::{Tm, now, at, Timespec};
use url::Url;
use std::borrow::ToOwned;
use std::i64;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::time::Duration;
use std::str::FromStr;

/// A stored cookie that wraps the definition in cookie-rs. This is used to implement
/// various behaviours defined in the spec that rely on an associated request URL,
/// which cookie-rs and hyper's header parsing do not support.
#[derive(Clone, Debug)]
pub struct Cookie {
    pub cookie: cookie_rs::Cookie,
    pub host_only: bool,
    pub persistent: bool,
    pub creation_time: Tm,
    pub last_access: Tm,
    pub expiry_time: Tm,
}

impl Cookie {
    /// http://tools.ietf.org/html/rfc6265#section-5.3
    pub fn new_wrapped(mut cookie: cookie_rs::Cookie, request: &Url, source: CookieSource)
                       -> Option<Cookie> {
        // Step 3
        let (persistent, expiry_time) = match (&cookie.max_age, &cookie.expires) {
            (&Some(max_age), _) => (true, at(now().to_timespec() + Duration::seconds(max_age as i64))),
            (_, &Some(expires)) => (true, expires),
            _ => (false, at(Timespec::new(i64::MAX, 0)))
        };

        let url_host = request.host().map(|host| host.serialize()).unwrap_or("".to_owned());

        // Step 4
        let mut domain = cookie.domain.clone().unwrap_or("".to_owned());

        // Step 5
        match PUB_DOMAINS.iter().find(|&x| domain == *x) {
            Some(val) if *val == url_host => domain = "".to_string(),
            Some(_) => return None,
            None => {}
        }

        // Step 6
        let host_only = if !domain.is_empty() {
            if !Cookie::domain_match(&url_host, &domain) {
                return None;
            } else {
                cookie.domain = Some(domain);
                false
            }
        } else {
            cookie.domain = Some(url_host);
            true
        };

        // Step 7
        let mut path = cookie.path.unwrap_or("".to_owned());
        if path.is_empty() || path.char_at(0) != '/' {
            let url_path = request.serialize_path();
            let url_path = url_path.as_ref().map(|path| &**path);
            path = Cookie::default_path(url_path.unwrap_or("")).to_owned();
        }
        cookie.path = Some(path);

        // Step 10
        if cookie.httponly && source != CookieSource::HTTP {
            return None;
        }

        Some(Cookie {
            cookie: cookie,
            host_only: host_only,
            persistent: persistent,
            creation_time: now(),
            last_access: now(),
            expiry_time: expiry_time,
        })
    }

    pub fn touch(&mut self) {
        self.last_access = now();
    }

    // http://tools.ietf.org/html/rfc6265#section-5.1.4
    fn default_path(request_path: &str) -> &str {
        // Step 2
        if request_path.is_empty() || !request_path.starts_with("/") {
            return "/";
        }

        // Step 3
        let rightmost_slash_idx = request_path.rfind("/").unwrap();
        if rightmost_slash_idx == 0 {
            // There's only one slash; it's the first character
            return "/";
        }

        // Step 4
        &request_path[..rightmost_slash_idx]
    }

    // http://tools.ietf.org/html/rfc6265#section-5.1.4
    pub fn path_match(request_path: &str, cookie_path: &str) -> bool {
        request_path == cookie_path ||
        ( request_path.starts_with(cookie_path) &&
            ( request_path.ends_with("/") || request_path.char_at(cookie_path.len() - 1) == '/' )
        )
    }

    // http://tools.ietf.org/html/rfc6265#section-5.1.3
    pub fn domain_match(string: &str, domain_string: &str) -> bool {
        if string == domain_string {
            return true;
        }
        if string.ends_with(domain_string)
            && string.char_at(string.len()-domain_string.len()-1) == '.'
            && Ipv4Addr::from_str(string).is_err()
            && Ipv6Addr::from_str(string).is_err() {
            return true;
        }
        false
    }

    // http://tools.ietf.org/html/rfc6265#section-5.4 step 1
    pub fn appropriate_for_url(&self, url: &Url, source: CookieSource) -> bool {
        let domain = url.host().map(|host| host.serialize());
        if self.host_only {
            if self.cookie.domain != domain {
                return false;
            }
        } else {
            if let (Some(ref domain), &Some(ref cookie_domain)) = (domain, &self.cookie.domain) {
                if !Cookie::domain_match(domain, cookie_domain) {
                    return false;
                }
            }
        }

        if let (Some(ref path), &Some(ref cookie_path)) = (url.serialize_path(), &self.cookie.path) {
            if !Cookie::path_match(path, cookie_path) {
                return false;
            }
        }

        if self.cookie.secure && url.scheme != "https".to_string() {
            return false;
        }
        if self.cookie.httponly && source == CookieSource::NonHTTP {
            return false;
        }

        return true;
    }
}

#[test]
fn test_domain_match() {
    assert!(Cookie::domain_match("foo.com", "foo.com"));
    assert!(Cookie::domain_match("bar.foo.com", "foo.com"));
    assert!(Cookie::domain_match("baz.bar.foo.com", "foo.com"));

    assert!(!Cookie::domain_match("bar.foo.com", "bar.com"));
    assert!(!Cookie::domain_match("bar.com", "baz.bar.com"));
    assert!(!Cookie::domain_match("foo.com", "bar.com"));

    assert!(!Cookie::domain_match("bar.com", "bbar.com"));
    assert!(Cookie::domain_match("235.132.2.3", "235.132.2.3"));
    assert!(!Cookie::domain_match("235.132.2.3", "1.1.1.1"));
    assert!(!Cookie::domain_match("235.132.2.3", ".2.3"));
}

#[test]
fn test_default_path() {
    assert!(&*Cookie::default_path("/foo/bar/baz/") == "/foo/bar/baz");
    assert!(&*Cookie::default_path("/foo/bar/baz") == "/foo/bar");
    assert!(&*Cookie::default_path("/foo/") == "/foo");
    assert!(&*Cookie::default_path("/foo") == "/");
    assert!(&*Cookie::default_path("/") == "/");
    assert!(&*Cookie::default_path("") == "/");
    assert!(&*Cookie::default_path("foo") == "/");
}

#[test]
fn fn_cookie_constructor() {
    use cookie_storage::CookieSource;

    let url = &Url::parse("http://example.com/foo").unwrap();

    let gov_url = &Url::parse("http://gov.ac/foo").unwrap();
    // cookie name/value test
    assert!(cookie_rs::Cookie::parse(" baz ").is_err());
    assert!(cookie_rs::Cookie::parse(" = bar  ").is_err());
    assert!(cookie_rs::Cookie::parse(" baz = ").is_ok());

    // cookie domains test
    let cookie = cookie_rs::Cookie::parse(" baz = bar; Domain =  ").unwrap();
    assert!(Cookie::new_wrapped(cookie.clone(), url, CookieSource::HTTP).is_some());
    let cookie = Cookie::new_wrapped(cookie, url, CookieSource::HTTP).unwrap();
    assert!(&**cookie.cookie.domain.as_ref().unwrap() == "example.com");

    // cookie public domains test
    let cookie = cookie_rs::Cookie::parse(" baz = bar; Domain =  gov.ac").unwrap();
    assert!(Cookie::new_wrapped(cookie.clone(), url, CookieSource::HTTP).is_none());
    assert!(Cookie::new_wrapped(cookie, gov_url, CookieSource::HTTP).is_some());

    // cookie domain matching test
    let cookie = cookie_rs::Cookie::parse(" baz = bar ; Secure; Domain = bazample.com").unwrap();
    assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none());

    let cookie = cookie_rs::Cookie::parse(" baz = bar ; Secure; Path = /foo/bar/").unwrap();
    assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_some());

    let cookie = cookie_rs::Cookie::parse(" baz = bar ; HttpOnly").unwrap();
    assert!(Cookie::new_wrapped(cookie, url, CookieSource::NonHTTP).is_none());

    let cookie = cookie_rs::Cookie::parse(" baz = bar ; Secure; Path = /foo/bar/").unwrap();
    let cookie = Cookie::new_wrapped(cookie, url, CookieSource::HTTP).unwrap();
    assert!(cookie.cookie.value.as_slice() == "bar");
    assert!(cookie.cookie.name.as_slice() == "baz");
    assert!(cookie.cookie.secure);
    assert!(cookie.cookie.path.as_ref().unwrap().as_slice() == "/foo/bar/");
    assert!(cookie.cookie.domain.as_ref().unwrap().as_slice() == "example.com");
    assert!(cookie.host_only);

    let u = &Url::parse("http://example.com/foobar").unwrap();
    let cookie = cookie_rs::Cookie::parse("foobar=value;path=/").unwrap();
    assert!(Cookie::new_wrapped(cookie, u, CookieSource::HTTP).is_some());
}
<|endoftext|>


<commit_before><commit_msg>Create an program to demonstrate random programs<commit_after>extern crate rand;
extern crate nadezhda;

use nadezhda::grammar::Program;

trait Length {
    fn length(&self) -> i32;
}

impl Length for Program {
    fn length(&self) -> i32 {
        1 + match *self {
            Program::Forward(ref contained_program) => {
                contained_program.length()
            },
            Program::Backward(ref contained_program) => {
                contained_program.length()
            },
            Program::Stop => 0

        }
    }
}

fn main() {
    let program: Program = rand::random();

    println!("length of program is {}", program.length());
}

<|endoftext|>


<commit_before><commit_msg>Add publish method to query names for `namesp`.<commit_after><|endoftext|>


<commit_before><commit_msg>Reimplement `namesp` structure with explicit ownership relations instead of `Rc`s.<commit_after><|endoftext|>


<commit_before><commit_msg>compact<commit_after><|endoftext|>


<commit_before>
//! Storing sounds, textures, animations etc.

// Extern crates.
use graphics::*;
use HashMap = collections::HashMap;
use gl;
use gl::types::GLuint;
use libc::c_void;
use std::os::self_exe_path;

// Local crate.
use png;

/// Represents a texture in Piston.
pub struct Texture {
    id: GLuint,
    width: u32,
    height: u32,
}

/// A place to store sounds, textures, animations etc.
///
/// The idea is to have one object which the app can use
/// to load assets for the game with a simple interface.
pub struct AssetStore {
    // The folder to load assets from.
    assets_folder: Option<String>,
    // List of OpenGL textures.
    textures: Vec<Texture>,
    // Contains names of loaded textures.
    texture_files: HashMap<String, uint>,
}

impl AssetStore {
    /// Creates a new `AssetStore` from an assets folder.
    pub fn from_folder(assets_folder: &str) -> AssetStore {
        AssetStore {
            assets_folder: Some(assets_folder.to_string()),
            textures: Vec::new(),
            texture_files: HashMap::new(),
        }
    }

    /// Creates an empty `AssetStore` with no assets.
    pub fn empty() -> AssetStore {
        AssetStore {
            assets_folder: None,
            textures: Vec::new(),
            texture_files: HashMap::new(),
        }
    }

    /// Gets OpenGL texture from texture id.
    pub fn get_texture(&self, texture_id: uint) -> GLuint {
        self.textures.get(texture_id).id
    }

    /// Loads image by relative file name to the asset root.
    pub fn load_image(&mut self, file: &str) -> Result<Image, String> {
        match self.texture_files.find_equiv(&file) {
            None => {},
            Some(&texture_id) => {
                let texture = self.textures.get(texture_id);
                return Ok(Image {
                    texture_id: texture_id,
                    texture_width: texture.width,
                    texture_height: texture.height,
                    source_rect: [0, 0, texture.width, texture.height],
                })
            },
        };

        let folder = self.assets_folder.as_ref().unwrap();
        let exe_path = self_exe_path();
        let exe_path = match exe_path {
            Some(path) => path,
            None => return Err("Could not get the path to executable".to_string()),
        };
        let path = exe_path.join(Path::new(folder.as_slice())).join(Path::new(file));
        let img = match png::load_png(&path) {
            Ok(img) => img,
            Err(msg) => return Err(format!("Could not load '{}': {}", file, msg)),
        };

        match img.color_type {
            png::RGBA8 => {},
            t => fail!("Unsupported color type {:?} in png", t),
        };

        let mut id: GLuint = 0;
        unsafe {
            gl::GenTextures(1, &mut id);
            gl::BindTexture(gl::TEXTURE_2D, id);
            gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
            gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
            gl::TexImage2D(
                gl::TEXTURE_2D,
                0,
                gl::RGBA as i32,
                img.width as i32,
                img.height as i32,
                0,
                gl::RGBA,
                gl::UNSIGNED_BYTE,
                img.pixels.as_ptr() as *c_void
            );
        }
        let texture = Texture {
            id: id,
            width: img.width,
            height: img.height,
        };
        self.textures.push(texture);
        let texture_id = self.textures.len() - 1;

        self.texture_files.insert(file.to_string(), texture_id);
        Ok(Image {
            texture_id: texture_id,
            texture_width: texture.width,
            texture_height: texture.height,
            source_rect: [0, 0, texture.width, texture.height],
        })
    }
}

<commit_msg>Remove alias in asset_store<commit_after>
//! Storing sounds, textures, animations etc.

// Extern crates.
use graphics::*;
use collections::HashMap;
use gl;
use gl::types::GLuint;
use libc::c_void;
use std::os::self_exe_path;

// Local crate.
use png;

/// Represents a texture in Piston.
pub struct Texture {
    id: GLuint,
    width: u32,
    height: u32,
}

/// A place to store sounds, textures, animations etc.
///
/// The idea is to have one object which the app can use
/// to load assets for the game with a simple interface.
pub struct AssetStore {
    // The folder to load assets from.
    assets_folder: Option<String>,
    // List of OpenGL textures.
    textures: Vec<Texture>,
    // Contains names of loaded textures.
    texture_files: HashMap<String, uint>,
}

impl AssetStore {
    /// Creates a new `AssetStore` from an assets folder.
    pub fn from_folder(assets_folder: &str) -> AssetStore {
        AssetStore {
            assets_folder: Some(assets_folder.to_string()),
            textures: Vec::new(),
            texture_files: HashMap::new(),
        }
    }

    /// Creates an empty `AssetStore` with no assets.
    pub fn empty() -> AssetStore {
        AssetStore {
            assets_folder: None,
            textures: Vec::new(),
            texture_files: HashMap::new(),
        }
    }

    /// Gets OpenGL texture from texture id.
    pub fn get_texture(&self, texture_id: uint) -> GLuint {
        self.textures.get(texture_id).id
    }

    /// Loads image by relative file name to the asset root.
    pub fn load_image(&mut self, file: &str) -> Result<Image, String> {
        match self.texture_files.find_equiv(&file) {
            None => {},
            Some(&texture_id) => {
                let texture = self.textures.get(texture_id);
                return Ok(Image {
                    texture_id: texture_id,
                    texture_width: texture.width,
                    texture_height: texture.height,
                    source_rect: [0, 0, texture.width, texture.height],
                })
            },
        };

        let folder = self.assets_folder.as_ref().unwrap();
        let exe_path = self_exe_path();
        let exe_path = match exe_path {
            Some(path) => path,
            None => return Err("Could not get the path to executable".to_string()),
        };
        let path = exe_path.join(Path::new(folder.as_slice())).join(Path::new(file));
        let img = match png::load_png(&path) {
            Ok(img) => img,
            Err(msg) => return Err(format!("Could not load '{}': {}", file, msg)),
        };

        match img.color_type {
            png::RGBA8 => {},
            t => fail!("Unsupported color type {:?} in png", t),
        };

        let mut id: GLuint = 0;
        unsafe {
            gl::GenTextures(1, &mut id);
            gl::BindTexture(gl::TEXTURE_2D, id);
            gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32);
            gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32);
            gl::TexImage2D(
                gl::TEXTURE_2D,
                0,
                gl::RGBA as i32,
                img.width as i32,
                img.height as i32,
                0,
                gl::RGBA,
                gl::UNSIGNED_BYTE,
                img.pixels.as_ptr() as *c_void
            );
        }
        let texture = Texture {
            id: id,
            width: img.width,
            height: img.height,
        };
        self.textures.push(texture);
        let texture_id = self.textures.len() - 1;

        self.texture_files.insert(file.to_string(), texture_id);
        Ok(Image {
            texture_id: texture_id,
            texture_width: texture.width,
            texture_height: texture.height,
            source_rect: [0, 0, texture.width, texture.height],
        })
    }
}

<|endoftext|>


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

#![cfg(not(test))]

#[macro_use]
extern crate log;
extern crate rustfmt;
extern crate toml;
extern crate env_logger;
extern crate getopts;

use rustfmt::{WriteMode, run, run_from_stdin};
use rustfmt::config::Config;

use std::env;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};

use getopts::Options;

/// Rustfmt operations.
enum Operation {
    /// Format a file and its child modules.
    Format(PathBuf, WriteMode),
    /// Print the help message.
    Help,
    /// Invalid program input, including reason.
    InvalidInput(String),
    /// No file specified, read from stdin
    Stdin(String, WriteMode),
}

/// Try to find a project file in the input file directory and its parents.
fn lookup_project_file(input_file: &Path) -> io::Result<PathBuf> {
    let mut current = if input_file.is_relative() {
        try!(env::current_dir()).join(input_file)
    } else {
        input_file.to_path_buf()
    };

    // FIXME: We should canonize path to properly handle its parents,
    // but `canonicalize` function is unstable now (recently added API)
    // current = try!(fs::canonicalize(current));

    loop {
        // If the current directory has no parent, we're done searching.
        if !current.pop() {
            return Err(io::Error::new(io::ErrorKind::NotFound, "Config not found"));
        }
        let config_file = current.join("rustfmt.toml");
        if fs::metadata(&config_file).is_ok() {
            return Ok(config_file);
        }
    }
}

/// Try to find a project file. If it's found, read it.
fn lookup_and_read_project_file(input_file: &Path) -> io::Result<(PathBuf, String)> {
    let path = try!(lookup_project_file(input_file));
    let mut file = try!(File::open(&path));
    let mut toml = String::new();
    try!(file.read_to_string(&mut toml));
    Ok((path, toml))
}

fn execute() -> i32 {
    let mut opts = Options::new();
    opts.optflag("h", "help", "show this message");
    opts.optopt("",
                "write-mode",
                "mode to write in (not usable when piping from stdin)",
                "[replace|overwrite|display|diff|coverage]");

    let operation = determine_operation(&opts, env::args().skip(1));

    match operation {
        Operation::InvalidInput(reason) => {
            print_usage(&opts, &reason);
            1
        }
        Operation::Help => {
            print_usage(&opts, "");
            0
        }
        Operation::Stdin(input, write_mode) => {
            // try to read config from local directory
            let config = match lookup_and_read_project_file(&Path::new(".")) {
                Ok((path, toml)) => {
                    Config::from_toml(&toml)
                }
                Err(_) => Default::default(),
            };

            run_from_stdin(input, write_mode, &config);
            0
        }
        Operation::Format(file, write_mode) => {
            let config = match lookup_and_read_project_file(&file) {
                Ok((path, toml)) => {
                    println!("Using rustfmt config file: {}", path.display());
                    Config::from_toml(&toml)
                }
                Err(_) => Default::default(),
            };

            run(&file, write_mode, &config);
            0
        }
    }
}

fn main() {
    let _ = env_logger::init();
    let exit_code = execute();

    // Make sure standard output is flushed before we exit.
    std::io::stdout().flush().unwrap();

    // Exit with given exit code.
    //
    // NOTE: This immediately terminates the process without doing any cleanup,
    // so make sure to finish all necessary cleanup before this is called.
    std::process::exit(exit_code);
}

fn print_usage(opts: &Options, reason: &str) {
    let reason = format!("{}\nusage: {} [options] <file>",
                         reason,
                         env::current_exe().unwrap().display());
    println!("{}", opts.usage(&reason));
    Config::print_docs();
}

fn determine_operation<I>(opts: &Options, args: I) -> Operation
    where I: Iterator<Item = String>
{
    let matches = match opts.parse(args) {
        Ok(m) => m,
        Err(e) => return Operation::InvalidInput(e.to_string()),
    };

    if matches.opt_present("h") {
        return Operation::Help;
    }

    // if no file argument is supplied, read from stdin
    if matches.free.len() == 0 {

        let mut buffer = String::new();
        match io::stdin().read_to_string(&mut buffer) {
            Ok(..) => (),
            Err(e) => return Operation::InvalidInput(e.to_string()),
        }

        // WriteMode is always plain for Stdin
        return Operation::Stdin(buffer, WriteMode::Plain);
    }

    let write_mode = match matches.opt_str("write-mode") {
        Some(mode) => {
            match mode.parse() {
                Ok(mode) => mode,
                Err(..) => return Operation::InvalidInput("Unrecognized write mode".into()),
            }
        }
        None => WriteMode::Replace,
    };

    Operation::Format(PathBuf::from(&matches.free[0]), write_mode)
}
<commit_msg>fix unused variable `path` warning<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![cfg(not(test))]

#[macro_use]
extern crate log;
extern crate rustfmt;
extern crate toml;
extern crate env_logger;
extern crate getopts;

use rustfmt::{WriteMode, run, run_from_stdin};
use rustfmt::config::Config;

use std::env;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};

use getopts::Options;

/// Rustfmt operations.
enum Operation {
    /// Format a file and its child modules.
    Format(PathBuf, WriteMode),
    /// Print the help message.
    Help,
    /// Invalid program input, including reason.
    InvalidInput(String),
    /// No file specified, read from stdin
    Stdin(String, WriteMode),
}

/// Try to find a project file in the input file directory and its parents.
fn lookup_project_file(input_file: &Path) -> io::Result<PathBuf> {
    let mut current = if input_file.is_relative() {
        try!(env::current_dir()).join(input_file)
    } else {
        input_file.to_path_buf()
    };

    // FIXME: We should canonize path to properly handle its parents,
    // but `canonicalize` function is unstable now (recently added API)
    // current = try!(fs::canonicalize(current));

    loop {
        // If the current directory has no parent, we're done searching.
        if !current.pop() {
            return Err(io::Error::new(io::ErrorKind::NotFound, "Config not found"));
        }
        let config_file = current.join("rustfmt.toml");
        if fs::metadata(&config_file).is_ok() {
            return Ok(config_file);
        }
    }
}

/// Try to find a project file. If it's found, read it.
fn lookup_and_read_project_file(input_file: &Path) -> io::Result<(PathBuf, String)> {
    let path = try!(lookup_project_file(input_file));
    let mut file = try!(File::open(&path));
    let mut toml = String::new();
    try!(file.read_to_string(&mut toml));
    Ok((path, toml))
}

fn execute() -> i32 {
    let mut opts = Options::new();
    opts.optflag("h", "help", "show this message");
    opts.optopt("",
                "write-mode",
                "mode to write in (not usable when piping from stdin)",
                "[replace|overwrite|display|diff|coverage]");

    let operation = determine_operation(&opts, env::args().skip(1));

    match operation {
        Operation::InvalidInput(reason) => {
            print_usage(&opts, &reason);
            1
        }
        Operation::Help => {
            print_usage(&opts, "");
            0
        }
        Operation::Stdin(input, write_mode) => {
            // try to read config from local directory
            let config = match lookup_and_read_project_file(&Path::new(".")) {
                Ok((_, toml)) => {
                    Config::from_toml(&toml)
                }
                Err(_) => Default::default(),
            };

            run_from_stdin(input, write_mode, &config);
            0
        }
        Operation::Format(file, write_mode) => {
            let config = match lookup_and_read_project_file(&file) {
                Ok((path, toml)) => {
                    println!("Using rustfmt config file: {}", path.display());
                    Config::from_toml(&toml)
                }
                Err(_) => Default::default(),
            };

            run(&file, write_mode, &config);
            0
        }
    }
}

fn main() {
    let _ = env_logger::init();
    let exit_code = execute();

    // Make sure standard output is flushed before we exit.
    std::io::stdout().flush().unwrap();

    // Exit with given exit code.
    //
    // NOTE: This immediately terminates the process without doing any cleanup,
    // so make sure to finish all necessary cleanup before this is called.
    std::process::exit(exit_code);
}

fn print_usage(opts: &Options, reason: &str) {
    let reason = format!("{}\nusage: {} [options] <file>",
                         reason,
                         env::current_exe().unwrap().display());
    println!("{}", opts.usage(&reason));
    Config::print_docs();
}

fn determine_operation<I>(opts: &Options, args: I) -> Operation
    where I: Iterator<Item = String>
{
    let matches = match opts.parse(args) {
        Ok(m) => m,
        Err(e) => return Operation::InvalidInput(e.to_string()),
    };

    if matches.opt_present("h") {
        return Operation::Help;
    }

    // if no file argument is supplied, read from stdin
    if matches.free.len() == 0 {

        let mut buffer = String::new();
        match io::stdin().read_to_string(&mut buffer) {
            Ok(..) => (),
            Err(e) => return Operation::InvalidInput(e.to_string()),
        }

        // WriteMode is always plain for Stdin
        return Operation::Stdin(buffer, WriteMode::Plain);
    }

    let write_mode = match matches.opt_str("write-mode") {
        Some(mode) => {
            match mode.parse() {
                Ok(mode) => mode,
                Err(..) => return Operation::InvalidInput("Unrecognized write mode".into()),
            }
        }
        None => WriteMode::Replace,
    };

    Operation::Format(PathBuf::from(&matches.free[0]), write_mode)
}
<|endoftext|>


<commit_before><commit_msg>simplify endpoint format selection<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test for #2324<commit_after>// nested function calls with cast.
fn main() {
    self.ptr
        .set(intrinsics::arith_offset(self.ptr.get() as *mut u8, 1) as *mut T);
    self.ptr
        .set(intrinsics::arith_offset(self.ptr.get(), mem::size_of::<T>() as isize) as *mut u8);
}
<|endoftext|>


<commit_before><commit_msg>Add more system calls.<commit_after>use core::cell::RefCell;
use core::cell::Cell;
use hil::{AppId,Driver,Callback,AppSlice,Shared,NUM_PROCS};
use hil::spi_master::{SpiMaster,SpiCallback};
use core::cmp;

/* SPI operations are handled by coping into a kernel buffer for
 * writes and copying out of a kernel buffer for reads.
 *
 * If the application buffer is larger than the kernel buffer,
 * the driver issues multiple HAL operations. The len field
 * of an application keeps track of the length of the desired
 * operation, while the index variable keeps track of the
 * index an ongoing operation is at in the buffers. */

struct App {
    callback:  Option<Callback>,
    app_read:  Option<AppSlice<Shared, u8>>,
    app_write: Option<AppSlice<Shared, u8>>,
    len:       Cell<usize>,
    index:     Cell<usize>,
}

pub struct Spi<'a, S: SpiMaster + 'a> {
    spi_master:   &'a mut S,
    busy:         Cell<bool>,
    apps:         [RefCell<Option<App>>; NUM_PROCS],
    kernel_read:  RefCell<Option<&'static mut [u8]>>,
    kernel_write: RefCell<Option<&'static mut [u8]>>,
    kernel_len:   Cell<usize>
}

impl<'a, S: SpiMaster> Spi<'a, S> {
    pub fn new(spi_master: &'a mut S) -> Spi<S> {
        Spi {
            spi_master: spi_master,
            busy: Cell::new(false),
            apps: [RefCell::new(None)],
            kernel_len: Cell::new(0),
            kernel_read : RefCell::new(None),
            kernel_write : RefCell::new(None),
        }
    }

    pub fn config_buffers(&mut self,
                          read: &'static mut [u8],
                          write: &'static mut [u8]) {
        let len = cmp::min(read.len(), write.len());
        self.kernel_len.set(len);
        self.kernel_read = RefCell::new(Some(read));
        self.kernel_write = RefCell::new(Some(write));
    }

    // Assumes checks for busy/etc. already done
    // Updates app.index to be index + length of op
    fn do_next_read_write(&self, app: &mut App) {
        let start = app.index.get();
        let len = cmp::min(app.len.get() - start, self.kernel_len.get());
        let end = start + len;
        app.index.set(end);
        let mut kwrite = self.kernel_write.borrow_mut();
        let mut kread  = self.kernel_read.borrow_mut();
        {
            use core::slice::bytes::copy_memory;
            let src = app.app_write.as_mut().unwrap();
            let mut kwbuf = kwrite.as_mut().unwrap();
            copy_memory(&src.as_ref()[start .. end], kwbuf);
        }
        let reading = app.app_read.is_some();
        if reading {
            self.spi_master.read_write_bytes(kwrite.take(), kread.take(), len);
        } else {
            self.spi_master.read_write_bytes(kwrite.take(), None, len);
        }
    }
}

impl<'a, S: SpiMaster> Driver for Spi<'a, S> {
    fn allow(&self, appid: AppId,
             allow_num: usize, slice: AppSlice<Shared, u8>) -> isize {
        let app = appid.idx();
        match allow_num {
            0 => {
                let mut appc = self.apps[app].borrow_mut();
                if appc.is_none() {
                    *appc = Some(App {
                        callback: None,
                        app_read: Some(slice),
                        app_write: None,
                        len: Cell::new(0),
                        index: Cell::new(0),
                    })
                } else {
                    appc.as_mut().map(|app| {
                        app.app_read = Some(slice);
                    });
                }
                0
            },
            1 => {
                let mut appc = self.apps[app].borrow_mut();
                if appc.is_none() {
                    *appc = Some(App {
                        callback: None,
                        app_read: None,
                        app_write: Some(slice),
                        len: Cell::new(0),
                        index: Cell::new(0),
                    })
                } else {
                    appc.as_mut().map(|app| app.app_write = Some(slice));
                }
                0
            }
            _ => -1
        }
    }

    #[inline(never)]
    fn subscribe(&self, subscribe_num: usize, callback: Callback) -> isize {
        match subscribe_num {
            0 /* read_write */ => {
                let mut app = self.apps[0].borrow_mut();
                if app.is_none() {
                    *app = Some(App {
                        callback: Some(callback),
                        app_read: None,
                        app_write: None,
                        len: Cell::new(0),
                        index: Cell::new(0),
                    });
                } else {
                    app.as_mut().map(|a| a.callback = Some(callback));
                }
                0
            },
            _ => -1
        }
    }
    /*
     * 0: read/write a single byte (blocking)
     * 1: read/write buffers
     *   - requires write buffer registered with allow
     *   - read buffer optional
     * 2: set chip select
     *   - valid values are 0-3
     *   - invalid value will result in no chip select
     * 3: get chip select
     *   - returns current selected peripheral
     *   - If none selected, returns 255
     * x: lock spi
     *   - if you perform an operation without the lock,
     *     it implicitly acquires the lock before the
     *     operation and releases it after
     *   - while an app holds the lock no other app can issue
     *     operations on SPI (they are buffered)
     * x+1: unlock spi
     *   - does nothing if lock not held
     */

    fn command(&self, cmd_num: usize, arg1: usize) -> isize {
        match cmd_num {
            0 /* read_write_byte */ => {
                self.spi_master.read_write_byte(arg1 as u8) as isize
            },
            1 /* read_write_bytes */ => {
                if self.busy.get() {
                    return -1;
                }
                let mut app = self.apps[0].borrow_mut();
                if app.is_none() {
                    return -1;
                }
                app.as_mut().map(|mut a| {
                    // If no write buffer, return
                    if a.app_write.is_none() {
                        return -1;
                    }
                    let mut mlen = 0;
                    // If write buffer too small, return
                    a.app_write.as_mut().map(|w| {
                        mlen = w.len();
                    });
                    a.app_read.as_mut().map(|r| {
                        mlen = cmp::min(mlen, r.len());
                    });
                    if mlen < arg1 {
                        return -1;
                    }
                    a.len.set(arg1);
                    a.index.set(0);
                    self.busy.set(true);
                    self.do_next_read_write(&mut a as &mut App);
                    0
                });
                -1
            }
            2 /* set chip select */ => {
                let cs = arg1 as u8;
                if cs <= 3 {
                    self.spi_master.set_chip_select(cs);
                    0
                } else {
                    -1
                }
            }
            3 /* get chip select */ => {
                self.spi_master.get_chip_select() as isize
            }
            _ => -1
        }
    }
}

#[allow(dead_code)]
fn each_some<'a, T, I, F>(lst: I, f: F)
        where T: 'a, I: Iterator<Item=&'a RefCell<Option<T>>>, F: Fn(&mut T) {
    for item in lst {
        item.borrow_mut().as_mut().map(|i| f(i));
    }
}

impl<'a, S: SpiMaster> SpiCallback for Spi<'a, S> {
    fn read_write_done(&self,
                       writebuf: Option<&'static mut [u8]>,
                       readbuf:  Option<&'static mut [u8]>,
                       length: usize) {
        self.apps[0].borrow_mut().as_mut().map(|app| {
            if app.app_read.is_some() {
                use core::slice::bytes::copy_memory;
                let src = readbuf.as_ref().unwrap();
                let dest = app.app_read.as_mut().unwrap();
                let start = app.index.get() - length;
                let end = start + length;
                copy_memory(&src[0 .. length], &mut dest.as_mut()[start .. end]);
            }

            *self.kernel_read.borrow_mut() =  readbuf;
            *self.kernel_write.borrow_mut() = writebuf;

            if app.index.get() == app.len.get() {
                self.busy.set(false);
                app.len.set(0);
                app.index.set(0);
                app.callback.take().map(|mut cb| {
                    cb.schedule(app.len.get(), 0, 0);
                });
            } else {
                self.do_next_read_write(app);
            }
        });
    }
}

<|endoftext|>


<commit_before><commit_msg>fetch/git: add basic version check to disable unsupported features<commit_after><|endoftext|>


<commit_before><commit_msg>fixed update_branch bug where checkout was only current branch<commit_after><|endoftext|>


<commit_before><commit_msg>Add meh solution to problem 68<commit_after>#![feature(collections)]
#[macro_use] extern crate libeuler;

use std::usize;
/// Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each line adding
/// to nine.
///
/// Working clockwise, and starting from the group of three with the numerically lowest external
/// node (4,3,2 in this example), each solution can be described uniquely. For example, the above
/// solution can be described by the set: 4,3,2; 6,2,1; 5,1,3.
///
/// It is possible to complete the ring with four different totals: 9, 10, 11, and 12. There are
/// eight solutions in total.
/// Total   Solution Set
/// 9   4,2,3; 5,3,1; 6,1,2
/// 9   4,3,2; 6,2,1; 5,1,3
/// 10  2,3,5; 4,5,1; 6,1,3
/// 10  2,5,3; 6,3,1; 4,1,5
/// 11  1,4,6; 3,6,2; 5,2,4
/// 11  1,6,4; 5,4,2; 3,2,6
/// 12  1,5,6; 2,6,4; 3,4,5
/// 12  1,6,5; 3,5,4; 2,4,6
///
/// By concatenating each group it is possible to form 9-digit strings; the maximum string for a
/// 3-gon ring is 432621513.
///
/// Using the numbers 1 to 10, and depending on arrangements, it is possible to form 16- and
/// 17-digit strings. What is the maximum 16-digit string for a "magic" 5-gon ring?
fn main() {
    solutions! {
        inputs: (size: usize = 5)

        sol naive {
            let mut n: Vec<_> = (0..(size*2)).map(|d| d + 1).collect();
            let mut minlen = usize::MAX;
            let mut max = 0;

            // [r1, r2, r3, r4, r5, e1, e2, e3, e4, e5]
            while n.next_permutation() {
                let ring = &n[0..5];

                if ring.iter().any(|&i| i == 10) {
                    continue;
                }

                let sides: Vec<_> = (0..size)
                    .map(|ix| (n[ix + size], n[ix], n[(ix + 1) % size]))
                    .collect();

                let minside = sides.iter().map(|&(a, _, _)| a).min().unwrap();

                if sides[0].0 != minside {
                    continue;
                }

                let (sameness, total) = sides.iter()
                    .map(|&(a, b, c)| a+b+c)
                    .fold((true, None), |(c, prev), v| {
                        let t = c && (prev.is_none() || prev.unwrap() == v);

                        (t, Some(v))
                    });

                if sameness {
                    println!("{:?} {:?} {}", total, sides, sameness);

                    let d = sides.iter()
                        .map(|&(a, b, c)| format!("{}{}{}", a, b, c))
                        .collect::<Vec<_>>().concat();

                    println!("{} {} / {} {}", d, d.len(), max, minlen);

                    let v: i64 = d.parse().unwrap();
                    if d.len() < minlen || (d.len() == minlen && v > max) {
                        max = v;
                        minlen = d.len();
                    }
                }
            }

            max
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>add an example of parsing floats with CompleteStr<commit_after>#[macro_use]
extern crate nom;

use nom::digit;
use nom::types::CompleteStr;

use std::str;
use std::str::FromStr;

#[macro_export]
macro_rules! complete_named (
  ($name:ident, $submac:ident!( $($args:tt)* )) => (
    fn $name<'a>( i: CompleteStr<'a> ) -> nom::IResult<CompleteStr<'a>, CompleteStr<'a>, u32> {
      $submac!(i, $($args)*)
    }
  );
  ($name:ident<$o:ty>, $submac:ident!( $($args:tt)* )) => (
    fn $name<'a>( i: CompleteStr<'a> ) -> nom::IResult<CompleteStr<'a>, $o, u32> {
      $submac!(i, $($args)*)
    }
  );
);

complete_named!(unsigned_float <f32>,
  flat_map!(
    recognize!(
      alt!(
        delimited!(digit, tag!("."), opt!(digit)) |
        delimited!(opt!(digit), tag!("."), digit)
      )
    ),
    parse_to!(f32)
  )
);

complete_named!(float <f32>, map!(
  pair!(
    opt!(alt!(tag!("+") | tag!("-"))),
    unsigned_float
  ),
  |(sign, value): (Option<CompleteStr>, f32)| {
    sign.and_then(|s| s.0.chars().next()).and_then(|c| if c == '-' { Some(-1f32) } else { None }).unwrap_or(1f32) * value
  }
));

#[test]
fn unsigned_float_test() {
  assert_eq!(unsigned_float(CompleteStr("123.456")), Ok((CompleteStr(""), 123.456)));
  assert_eq!(unsigned_float(CompleteStr("0.123")),   Ok((CompleteStr(""), 0.123)));
  assert_eq!(unsigned_float(CompleteStr("123.0")),   Ok((CompleteStr(""), 123.0)));
  assert_eq!(unsigned_float(CompleteStr("123.")),    Ok((CompleteStr(""), 123.0)));
  assert_eq!(unsigned_float(CompleteStr(".123")),    Ok((CompleteStr(""), 0.123)));
}

#[test]
fn float_test() {
  assert_eq!(float(CompleteStr("123.456")),  Ok((CompleteStr(""), 123.456)));
  assert_eq!(float(CompleteStr("+123.456")), Ok((CompleteStr(""), 123.456)));
  assert_eq!(float(CompleteStr("-123.456")), Ok((CompleteStr(""), -123.456)));
}
<|endoftext|>


<commit_before><commit_msg>Minor<commit_after><|endoftext|>


<commit_before>use super::SDTHeader;

#[repr(packed)]
#[derive(Clone, Copy, Debug, Default)]
pub struct DSDT {
    pub header: SDTHeader,
    pub data: &'static [u8]

}

impl DSDT {
    pub fn new(header: *const SDTHeader) -> Option<Self> {
        if unsafe { (*header).valid("DSDT") } {
            Some(DSDT {
                header: unsafe { *header },
                data: unsafe { (*header).data() }
            })
        } else {
            None
        }
    }
}
<commit_msg>Simplify `DSDT::new()` with fewer `unsafe` blocks<commit_after>use super::SDTHeader;

#[repr(packed)]
#[derive(Clone, Copy, Debug, Default)]
pub struct DSDT {
    pub header: SDTHeader,
    pub data: &'static [u8]

}

impl DSDT {
    pub fn new(header: *const SDTHeader) -> Option<Self> {
        let header = unsafe { *header };
        if header.valid("DSDT") {
            Some(DSDT {
                header: header,
                data: header.data(),
            })
        } else {
            None
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Log tuning.<commit_after><|endoftext|>


<commit_before><commit_msg>Work on function type inference.<commit_after><|endoftext|>


<commit_before>// Must derive `Debug` so `println!` can be used.
// `allow` required to silence warnings because only
// one variant is used.
#[allow(dead_code)]
#[derive(Debug)]
enum Color {
    // These 3 are specified solely by their name.
    Red,
    Blue,
    Green,
    // This requires 3 `i32`s and a name.
    RGB(i32, i32, i32),
}

fn main() {
    let color = Color::RGB(122, 17, 40);
    // TODO ^ Try different variants for `color`

    println!("What color is it?");
    // An `enum` can be destructured using a `match`.
    match color {
        Color::Red   => println!("The color is Red!"),
        Color::Blue  => println!("The color is Blue!"),
        Color::Green => println!("The color is Green!"),
        Color::RGB(r, g, b) => {
            println!("Red: {:?}, green: {:?}, and blue: {:?}!:", r, g, b);
        },
        // Don't need another arm because all variants have been examined
    }
}
<commit_msg>flow control/match/destructuring/enums: fix typo<commit_after>// Must derive `Debug` so `println!` can be used.
// `allow` required to silence warnings because only
// one variant is used.
#[allow(dead_code)]
#[derive(Debug)]
enum Color {
    // These 3 are specified solely by their name.
    Red,
    Blue,
    Green,
    // This requires 3 `i32`s and a name.
    RGB(i32, i32, i32),
}

fn main() {
    let color = Color::RGB(122, 17, 40);
    // TODO ^ Try different variants for `color`

    println!("What color is it?");
    // An `enum` can be destructured using a `match`.
    match color {
        Color::Red   => println!("The color is Red!"),
        Color::Blue  => println!("The color is Blue!"),
        Color::Green => println!("The color is Green!"),
        Color::RGB(r, g, b) => {
            println!("Red: {:?}, green: {:?}, and blue: {:?}!", r, g, b);
        },
        // Don't need another arm because all variants have been examined
    }
}
<|endoftext|>


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

// pp-exact

#[cfg = r#"just parse this"#]
extern mod blah = r##"blah"##;

fn main() { unsafe { asm!(r###"blah"###); } }
<|endoftext|>


<commit_before>use std::{fmt, mem, ptr, isize};
use std::num::Int;
use std::ops::{Index, IndexMut};
use alloc::heap;
use os::token::Token;

/// A preallocated chunk of memory for storing objects of the same type.
pub struct Slab<T> {
    // Chunk of memory
    mem: *mut Entry<T>,
    // Number of elements currently in the slab
    len: isize,
    // The total number of elements that the slab can hold
    cap: isize,
    // The token offset
    off: usize,
    // Offset of the next available slot in the slab. Set to the slab's
    // capacity when the slab is full.
    nxt: isize,
    // The total number of slots that were initialized
    init: isize,
}

const MAX: usize = isize::MAX as usize;

// When Entry.nxt is set to this, the entry is in use
const IN_USE: isize = -1;

unsafe impl<T> Send for Slab<T> where T: Send {}

impl<T> Slab<T> {
    pub fn new(cap: usize) -> Slab<T> {
        Slab::new_starting_at(Token(0), cap)
    }

    pub fn new_starting_at(offset: Token, cap: usize) -> Slab<T> {
        assert!(cap <= MAX, "capacity too large");
        // TODO:
        // - Rename to with_capacity
        // - Use a power of 2 capacity
        // - Ensure that mem size is less than usize::MAX

        let size = cap.checked_mul(mem::size_of::<Entry<T>>())
            .expect("capacity overflow");

        let ptr = unsafe { heap::allocate(size, mem::min_align_of::<Entry<T>>()) };

        Slab {
            mem: ptr as *mut Entry<T>,
            cap: cap as isize,
            len: 0,
            off: offset.as_usize(),
            nxt: 0,
            init: 0,
        }
    }

    #[inline]
    pub fn count(&self) -> usize {
        self.len as usize
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    #[inline]
    pub fn remaining(&self) -> usize {
        (self.cap - self.len) as usize
    }

    #[inline]
    pub fn has_remaining(&self) -> bool {
        self.remaining() > 0
    }

    #[inline]
    pub fn contains(&self, idx: Token) -> bool {
        if idx.as_usize() < self.off {
            return false;
        }

        let idx = self.token_to_idx(idx);

        if idx <= MAX {
            let idx = idx as isize;

            if idx < self.init {
                return self.entry(idx).in_use();
            }
        }

        false
    }

    pub fn get(&self, idx: Token) -> Option<&T> {
        assert!(self.contains(idx), "slab does not contain token `{:?}`", idx);

        let idx = self.token_to_idx(idx);

        if idx <= MAX {
            let idx = idx as isize;

            if idx < self.init {
                let entry = self.entry(idx);

                if entry.in_use() {
                    return Some(&entry.val);
                }
            }
        }

        None
    }

    pub fn get_mut(&mut self, idx: Token) -> Option<&mut T> {
        let idx = self.token_to_idx(idx);

        if idx <= MAX {
            let idx = idx as isize;

            if idx < self.init {
                let mut entry = self.mut_entry(idx);

                if entry.in_use() {
                    return Some(&mut entry.val);
                }
            }
        }

        None
    }

    pub fn insert(&mut self, val: T) -> Result<Token, T> {
        let idx = self.nxt;

        if idx == self.init {
            // Using an uninitialized entry
            if idx == self.cap {
                // No more capacity
                debug!("slab out of capacity; cap={}", self.cap);
                return Err(val);
            }

            self.mut_entry(idx).put(val, true);

            self.init += 1;
            self.len = self.init;
            self.nxt = self.init;

            debug!("inserting into new slot; idx={}", idx);
        }
        else {
            self.len += 1;
            self.nxt = self.mut_entry(idx).put(val, false);

            debug!("inserting into reused slot; idx={}", idx);
        }

        Ok(self.idx_to_token(idx))
    }

    /// Releases the given slot
    pub fn remove(&mut self, idx: Token) -> Option<T> {
        debug!("removing value; idx={:?}", idx);

        // Cast to usize
        let idx = self.token_to_idx(idx);

        if idx > MAX {
            return None;
        }

        let idx = idx as isize;

        // Ensure index is within capacity of slab
        if idx >= self.init {
            return None;
        }

        let nxt = self.nxt;

        match self.mut_entry(idx).remove(nxt) {
            Some(v) => {
                self.nxt = idx;
                self.len -= 1;
                Some(v)
            }
            None => None
        }
    }

    pub fn iter(&self) -> SlabIter<T> {
        SlabIter {
            slab: self,
            cur_idx: 0,
            yielded: 0
        }
    }

    pub fn iter_mut(&mut self) -> SlabMutIter<T> {
        SlabMutIter {
            slab: self,
            cur_idx: 0,
            yielded: 0
        }
    }

    #[inline]
    fn entry(&self, idx: isize) -> &Entry<T> {
        unsafe { &*self.mem.offset(idx) }
    }

    #[inline]
    fn mut_entry(&mut self, idx: isize) -> &mut Entry<T> {
        unsafe { &mut *self.mem.offset(idx) }
    }

    #[inline]
    fn validate_idx(&self, idx: usize) -> isize {
        if idx <= MAX {
            let idx = idx as isize;

            if idx < self.init {
                return idx;
            }
        }

        panic!("invalid index {} -- greater than capacity {}", idx, self.cap);
    }

    fn token_to_idx(&self, token: Token) -> usize {
        token.as_usize() - self.off
    }

    fn idx_to_token(&self, idx: isize) -> Token {
        Token(idx as usize + self.off)
    }
}

impl<T> Index<Token> for Slab<T> {
    type Output = T;

    fn index<'a>(&'a self, idx: &Token) -> &'a T {
        let idx = self.token_to_idx(*idx);
        let idx = self.validate_idx(idx);

        let e = self.entry(idx);

        if !e.in_use() {
            panic!("invalid index; idx={}", idx);
        }

        &e.val
    }
}

impl<T> IndexMut<Token> for Slab<T> {
    fn index_mut<'a>(&'a mut self, idx: &Token) -> &'a mut T {
        let idx = self.token_to_idx(*idx);
        let idx = self.validate_idx(idx);

        let e = self.mut_entry(idx);

        if !e.in_use() {
            panic!("invalid index; idx={}", idx);
        }

        &mut e.val
    }
}

impl<T> fmt::Debug for Slab<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Slab {{ len: {}, cap: {} }}", self.len, self.cap)
    }
}

#[unsafe_destructor]
impl<T> Drop for Slab<T> {
    fn drop(&mut self) {
        // TODO: check whether or not this is needed with intrinsics::needs_drop
        let mut i = 0;

        while i < self.init {
            self.mut_entry(i).release();
            i += 1;
        }

        let cap = self.cap as usize;
        let size = cap.checked_mul(mem::size_of::<Entry<T>>()).unwrap();
        unsafe { heap::deallocate(self.mem as *mut u8, size, mem::min_align_of::<Entry<T>>()) };
    }
}

// Holds the values in the slab.
struct Entry<T> {
    nxt: isize,
    val: T
}

impl<T> Entry<T> {
    #[inline]
    fn put(&mut self, val: T, init: bool) -> isize {
        assert!(init || self.nxt != IN_USE);

        let ret = self.nxt;

        unsafe { ptr::write(&mut self.val as *mut T, val); }
        self.nxt = IN_USE;

        // Could be uninitialized memory, but the caller (Slab) should guard
        // not use the return value in those cases.
        ret
    }

    fn remove(&mut self, nxt: isize) -> Option<T> {
        if self.in_use() {
            self.nxt = nxt;
            Some(unsafe { ptr::read(&self.val as *const T) })
        } else {
            None
        }
    }

    fn release(&mut self) {
        if self.in_use() {
            let _ = Some(unsafe { ptr::read(&self.val as *const T) });
        }
    }

    #[inline]
    fn in_use(&self) -> bool {
        self.nxt == IN_USE
    }
}

pub struct SlabIter<'a, T: 'a> {
    slab: &'a Slab<T>,
    cur_idx: isize,
    yielded: isize
}

impl <'a, T> Iterator for SlabIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<&'a T> {
        while self.yielded < self.slab.len {
            let entry = self.slab.entry(self.cur_idx);
            self.cur_idx += 1;
            if entry.in_use() {
                self.yielded += 1;
                return Some(&entry.val);
            }
        }
        None
    }
}

pub struct SlabMutIter<'a, T: 'a> {
    slab: &'a mut Slab<T>,
    cur_idx: isize,
    yielded: isize
}

impl <'a, T> Iterator for SlabMutIter<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<&'a mut T> {
        while self.yielded < self.slab.len {
            let entry = unsafe { &mut *self.slab.mem.offset(self.cur_idx) };
            self.cur_idx += 1;
            if entry.in_use() {
                self.yielded += 1;
                return Some(&mut entry.val);
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::Slab;
    use {Token};

    #[test]
    fn test_insertion() {
        let mut slab = Slab::new(1);
        let token = slab.insert(10).ok().expect("Failed to insert");
        assert_eq!(slab[token], 10);
    }

    #[test]
    fn test_repeated_insertion() {
        let mut slab = Slab::new(10);

        for i in range(0, 10) {
            let token = slab.insert(i + 10).ok().expect("Failed to insert");
            assert_eq!(slab[token], i + 10);
        }

        slab.insert(20).err().expect("Inserted when full");
    }

    #[test]
    fn test_repeated_insertion_and_removal() {
        let mut slab = Slab::new(10);
        let mut tokens = vec![];

        for i in range(0, 10) {
            let token = slab.insert(i + 10).ok().expect("Failed to insert");
            tokens.push(token);
            assert_eq!(slab[token], i + 10);
        }

        for &i in tokens.iter() {
            slab.remove(i);
        }

        slab.insert(20).ok().expect("Failed to insert in newly empty slab");
    }

    #[test]
    fn test_insertion_when_full() {
        let mut slab = Slab::new(1);
        slab.insert(10).ok().expect("Failed to insert");
        slab.insert(10).err().expect("Inserted into a full slab");
    }

    #[test]
    fn test_removal_is_successful() {
        let mut slab = Slab::new(1);
        let t1 = slab.insert(10).ok().expect("Failed to insert");
        slab.remove(t1);
        let t2 = slab.insert(20).ok().expect("Failed to insert");
        assert_eq!(slab[t2], 20);
    }

    #[test]
    fn test_mut_retrieval() {
        let mut slab = Slab::new(1);
        let t1 = slab.insert("foo".to_string()).ok().expect("Failed to insert");

        slab[t1].push_str("bar");

        assert_eq!(slab[t1].as_slice(), "foobar");
    }

    #[test]
    #[should_fail]
    fn test_reusing_slots_1() {
        let mut slab = Slab::new(16);

        let t0 = slab.insert(123).unwrap();
        let t1 = slab.insert(456).unwrap();

        assert!(slab.count() == 2);
        assert!(slab.remaining() == 14);

        slab.remove(t0);

        assert!(slab.count() == 1, "actual={}", slab.count());
        assert!(slab.remaining() == 15);

        slab.remove(t1);

        assert!(slab.count() == 0);
        assert!(slab.remaining() == 16);

        let _ = slab[t1];
    }

    #[test]
    fn test_reusing_slots_2() {
        let mut slab = Slab::new(16);

        let t0 = slab.insert(123).unwrap();

        assert!(slab[t0] == 123);
        assert!(slab.remove(t0) == Some(123));

        let t0 = slab.insert(456).unwrap();

        assert!(slab[t0] == 456);

        let t1 = slab.insert(789).unwrap();

        assert!(slab[t0] == 456);
        assert!(slab[t1] == 789);

        assert!(slab.remove(t0).unwrap() == 456);
        assert!(slab.remove(t1).unwrap() == 789);

        assert!(slab.count() == 0);
    }

    #[test]
    #[should_fail]
    fn test_accessing_out_of_bounds() {
        let slab = Slab::<usize>::new(16);
        slab[Token(0)];
    }

    #[test]
    fn test_contains() {
        let mut slab = Slab::new_starting_at(Token(5),16);
        assert!(!slab.contains(Token(0)));

        let tok = slab.insert(111).unwrap();
        assert!(slab.contains(tok));
    }

    #[test]
    fn test_iter() {
        let mut slab: Slab<u32> = Slab::new_starting_at(Token(0), 4);
        for i in range(0, 4) {
            slab.insert(i).unwrap();
        }
        assert_eq!(slab.iter().map(|r| *r).collect(), vec![0, 1, 2, 3]);
        slab.remove(Token(1));
        assert_eq!(slab.iter().map(|r| *r).collect(), vec![0, 2, 3]);
    }

    #[test]
    fn test_iter_mut() {
        let mut slab: Slab<u32> = Slab::new_starting_at(Token(0), 4);
        for i in range(0, 4) {
            slab.insert(i).unwrap();
        }
        for e in slab.iter_mut() {
            *e = *e + 1;
        }

        assert_eq!(slab.iter().map(|r| *r).collect(), vec![1, 2, 3, 4]);
        slab.remove(Token(2));
        for e in slab.iter_mut() {
            *e = *e + 1;
        }
        assert_eq!(slab.iter().map(|r| *r).collect(), vec![2, 3, 5]);
    }
}
<commit_msg>Fix deprecation warning in tests<commit_after>use std::{fmt, mem, ptr, isize};
use std::num::Int;
use std::ops::{Index, IndexMut};
use alloc::heap;
use os::token::Token;

/// A preallocated chunk of memory for storing objects of the same type.
pub struct Slab<T> {
    // Chunk of memory
    mem: *mut Entry<T>,
    // Number of elements currently in the slab
    len: isize,
    // The total number of elements that the slab can hold
    cap: isize,
    // The token offset
    off: usize,
    // Offset of the next available slot in the slab. Set to the slab's
    // capacity when the slab is full.
    nxt: isize,
    // The total number of slots that were initialized
    init: isize,
}

const MAX: usize = isize::MAX as usize;

// When Entry.nxt is set to this, the entry is in use
const IN_USE: isize = -1;

unsafe impl<T> Send for Slab<T> where T: Send {}

impl<T> Slab<T> {
    pub fn new(cap: usize) -> Slab<T> {
        Slab::new_starting_at(Token(0), cap)
    }

    pub fn new_starting_at(offset: Token, cap: usize) -> Slab<T> {
        assert!(cap <= MAX, "capacity too large");
        // TODO:
        // - Rename to with_capacity
        // - Use a power of 2 capacity
        // - Ensure that mem size is less than usize::MAX

        let size = cap.checked_mul(mem::size_of::<Entry<T>>())
            .expect("capacity overflow");

        let ptr = unsafe { heap::allocate(size, mem::min_align_of::<Entry<T>>()) };

        Slab {
            mem: ptr as *mut Entry<T>,
            cap: cap as isize,
            len: 0,
            off: offset.as_usize(),
            nxt: 0,
            init: 0,
        }
    }

    #[inline]
    pub fn count(&self) -> usize {
        self.len as usize
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    #[inline]
    pub fn remaining(&self) -> usize {
        (self.cap - self.len) as usize
    }

    #[inline]
    pub fn has_remaining(&self) -> bool {
        self.remaining() > 0
    }

    #[inline]
    pub fn contains(&self, idx: Token) -> bool {
        if idx.as_usize() < self.off {
            return false;
        }

        let idx = self.token_to_idx(idx);

        if idx <= MAX {
            let idx = idx as isize;

            if idx < self.init {
                return self.entry(idx).in_use();
            }
        }

        false
    }

    pub fn get(&self, idx: Token) -> Option<&T> {
        assert!(self.contains(idx), "slab does not contain token `{:?}`", idx);

        let idx = self.token_to_idx(idx);

        if idx <= MAX {
            let idx = idx as isize;

            if idx < self.init {
                let entry = self.entry(idx);

                if entry.in_use() {
                    return Some(&entry.val);
                }
            }
        }

        None
    }

    pub fn get_mut(&mut self, idx: Token) -> Option<&mut T> {
        let idx = self.token_to_idx(idx);

        if idx <= MAX {
            let idx = idx as isize;

            if idx < self.init {
                let mut entry = self.mut_entry(idx);

                if entry.in_use() {
                    return Some(&mut entry.val);
                }
            }
        }

        None
    }

    pub fn insert(&mut self, val: T) -> Result<Token, T> {
        let idx = self.nxt;

        if idx == self.init {
            // Using an uninitialized entry
            if idx == self.cap {
                // No more capacity
                debug!("slab out of capacity; cap={}", self.cap);
                return Err(val);
            }

            self.mut_entry(idx).put(val, true);

            self.init += 1;
            self.len = self.init;
            self.nxt = self.init;

            debug!("inserting into new slot; idx={}", idx);
        }
        else {
            self.len += 1;
            self.nxt = self.mut_entry(idx).put(val, false);

            debug!("inserting into reused slot; idx={}", idx);
        }

        Ok(self.idx_to_token(idx))
    }

    /// Releases the given slot
    pub fn remove(&mut self, idx: Token) -> Option<T> {
        debug!("removing value; idx={:?}", idx);

        // Cast to usize
        let idx = self.token_to_idx(idx);

        if idx > MAX {
            return None;
        }

        let idx = idx as isize;

        // Ensure index is within capacity of slab
        if idx >= self.init {
            return None;
        }

        let nxt = self.nxt;

        match self.mut_entry(idx).remove(nxt) {
            Some(v) => {
                self.nxt = idx;
                self.len -= 1;
                Some(v)
            }
            None => None
        }
    }

    pub fn iter(&self) -> SlabIter<T> {
        SlabIter {
            slab: self,
            cur_idx: 0,
            yielded: 0
        }
    }

    pub fn iter_mut(&mut self) -> SlabMutIter<T> {
        SlabMutIter {
            slab: self,
            cur_idx: 0,
            yielded: 0
        }
    }

    #[inline]
    fn entry(&self, idx: isize) -> &Entry<T> {
        unsafe { &*self.mem.offset(idx) }
    }

    #[inline]
    fn mut_entry(&mut self, idx: isize) -> &mut Entry<T> {
        unsafe { &mut *self.mem.offset(idx) }
    }

    #[inline]
    fn validate_idx(&self, idx: usize) -> isize {
        if idx <= MAX {
            let idx = idx as isize;

            if idx < self.init {
                return idx;
            }
        }

        panic!("invalid index {} -- greater than capacity {}", idx, self.cap);
    }

    fn token_to_idx(&self, token: Token) -> usize {
        token.as_usize() - self.off
    }

    fn idx_to_token(&self, idx: isize) -> Token {
        Token(idx as usize + self.off)
    }
}

impl<T> Index<Token> for Slab<T> {
    type Output = T;

    fn index<'a>(&'a self, idx: &Token) -> &'a T {
        let idx = self.token_to_idx(*idx);
        let idx = self.validate_idx(idx);

        let e = self.entry(idx);

        if !e.in_use() {
            panic!("invalid index; idx={}", idx);
        }

        &e.val
    }
}

impl<T> IndexMut<Token> for Slab<T> {
    fn index_mut<'a>(&'a mut self, idx: &Token) -> &'a mut T {
        let idx = self.token_to_idx(*idx);
        let idx = self.validate_idx(idx);

        let e = self.mut_entry(idx);

        if !e.in_use() {
            panic!("invalid index; idx={}", idx);
        }

        &mut e.val
    }
}

impl<T> fmt::Debug for Slab<T> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Slab {{ len: {}, cap: {} }}", self.len, self.cap)
    }
}

#[unsafe_destructor]
impl<T> Drop for Slab<T> {
    fn drop(&mut self) {
        // TODO: check whether or not this is needed with intrinsics::needs_drop
        let mut i = 0;

        while i < self.init {
            self.mut_entry(i).release();
            i += 1;
        }

        let cap = self.cap as usize;
        let size = cap.checked_mul(mem::size_of::<Entry<T>>()).unwrap();
        unsafe { heap::deallocate(self.mem as *mut u8, size, mem::min_align_of::<Entry<T>>()) };
    }
}

// Holds the values in the slab.
struct Entry<T> {
    nxt: isize,
    val: T
}

impl<T> Entry<T> {
    #[inline]
    fn put(&mut self, val: T, init: bool) -> isize {
        assert!(init || self.nxt != IN_USE);

        let ret = self.nxt;

        unsafe { ptr::write(&mut self.val as *mut T, val); }
        self.nxt = IN_USE;

        // Could be uninitialized memory, but the caller (Slab) should guard
        // not use the return value in those cases.
        ret
    }

    fn remove(&mut self, nxt: isize) -> Option<T> {
        if self.in_use() {
            self.nxt = nxt;
            Some(unsafe { ptr::read(&self.val as *const T) })
        } else {
            None
        }
    }

    fn release(&mut self) {
        if self.in_use() {
            let _ = Some(unsafe { ptr::read(&self.val as *const T) });
        }
    }

    #[inline]
    fn in_use(&self) -> bool {
        self.nxt == IN_USE
    }
}

pub struct SlabIter<'a, T: 'a> {
    slab: &'a Slab<T>,
    cur_idx: isize,
    yielded: isize
}

impl <'a, T> Iterator for SlabIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<&'a T> {
        while self.yielded < self.slab.len {
            let entry = self.slab.entry(self.cur_idx);
            self.cur_idx += 1;
            if entry.in_use() {
                self.yielded += 1;
                return Some(&entry.val);
            }
        }
        None
    }
}

pub struct SlabMutIter<'a, T: 'a> {
    slab: &'a mut Slab<T>,
    cur_idx: isize,
    yielded: isize
}

impl <'a, T> Iterator for SlabMutIter<'a, T> {
    type Item = &'a mut T;

    fn next(&mut self) -> Option<&'a mut T> {
        while self.yielded < self.slab.len {
            let entry = unsafe { &mut *self.slab.mem.offset(self.cur_idx) };
            self.cur_idx += 1;
            if entry.in_use() {
                self.yielded += 1;
                return Some(&mut entry.val);
            }
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use super::Slab;
    use {Token};

    #[test]
    fn test_insertion() {
        let mut slab = Slab::new(1);
        let token = slab.insert(10).ok().expect("Failed to insert");
        assert_eq!(slab[token], 10);
    }

    #[test]
    fn test_repeated_insertion() {
        let mut slab = Slab::new(10);

        for i in range(0, 10) {
            let token = slab.insert(i + 10).ok().expect("Failed to insert");
            assert_eq!(slab[token], i + 10);
        }

        slab.insert(20).err().expect("Inserted when full");
    }

    #[test]
    fn test_repeated_insertion_and_removal() {
        let mut slab = Slab::new(10);
        let mut tokens = vec![];

        for i in range(0, 10) {
            let token = slab.insert(i + 10).ok().expect("Failed to insert");
            tokens.push(token);
            assert_eq!(slab[token], i + 10);
        }

        for &i in tokens.iter() {
            slab.remove(i);
        }

        slab.insert(20).ok().expect("Failed to insert in newly empty slab");
    }

    #[test]
    fn test_insertion_when_full() {
        let mut slab = Slab::new(1);
        slab.insert(10).ok().expect("Failed to insert");
        slab.insert(10).err().expect("Inserted into a full slab");
    }

    #[test]
    fn test_removal_is_successful() {
        let mut slab = Slab::new(1);
        let t1 = slab.insert(10).ok().expect("Failed to insert");
        slab.remove(t1);
        let t2 = slab.insert(20).ok().expect("Failed to insert");
        assert_eq!(slab[t2], 20);
    }

    #[test]
    fn test_mut_retrieval() {
        let mut slab = Slab::new(1);
        let t1 = slab.insert("foo".to_string()).ok().expect("Failed to insert");

        slab[t1].push_str("bar");

        assert_eq!(slab[t1].as_slice(), "foobar");
    }

    #[test]
    #[should_panic]
    fn test_reusing_slots_1() {
        let mut slab = Slab::new(16);

        let t0 = slab.insert(123).unwrap();
        let t1 = slab.insert(456).unwrap();

        assert!(slab.count() == 2);
        assert!(slab.remaining() == 14);

        slab.remove(t0);

        assert!(slab.count() == 1, "actual={}", slab.count());
        assert!(slab.remaining() == 15);

        slab.remove(t1);

        assert!(slab.count() == 0);
        assert!(slab.remaining() == 16);

        let _ = slab[t1];
    }

    #[test]
    fn test_reusing_slots_2() {
        let mut slab = Slab::new(16);

        let t0 = slab.insert(123).unwrap();

        assert!(slab[t0] == 123);
        assert!(slab.remove(t0) == Some(123));

        let t0 = slab.insert(456).unwrap();

        assert!(slab[t0] == 456);

        let t1 = slab.insert(789).unwrap();

        assert!(slab[t0] == 456);
        assert!(slab[t1] == 789);

        assert!(slab.remove(t0).unwrap() == 456);
        assert!(slab.remove(t1).unwrap() == 789);

        assert!(slab.count() == 0);
    }

    #[test]
    #[should_panic]
    fn test_accessing_out_of_bounds() {
        let slab = Slab::<usize>::new(16);
        slab[Token(0)];
    }

    #[test]
    fn test_contains() {
        let mut slab = Slab::new_starting_at(Token(5),16);
        assert!(!slab.contains(Token(0)));

        let tok = slab.insert(111).unwrap();
        assert!(slab.contains(tok));
    }

    #[test]
    fn test_iter() {
        let mut slab: Slab<u32> = Slab::new_starting_at(Token(0), 4);
        for i in range(0, 4) {
            slab.insert(i).unwrap();
        }
        assert_eq!(slab.iter().map(|r| *r).collect(), vec![0, 1, 2, 3]);
        slab.remove(Token(1));
        assert_eq!(slab.iter().map(|r| *r).collect(), vec![0, 2, 3]);
    }

    #[test]
    fn test_iter_mut() {
        let mut slab: Slab<u32> = Slab::new_starting_at(Token(0), 4);
        for i in range(0, 4) {
            slab.insert(i).unwrap();
        }
        for e in slab.iter_mut() {
            *e = *e + 1;
        }

        assert_eq!(slab.iter().map(|r| *r).collect(), vec![1, 2, 3, 4]);
        slab.remove(Token(2));
        for e in slab.iter_mut() {
            *e = *e + 1;
        }
        assert_eq!(slab.iter().map(|r| *r).collect(), vec![2, 3, 5]);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add rust trait alias example<commit_after><|endoftext|>


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


<commit_before><commit_msg>Example for match_if_let<commit_after>#![feature(phase)]

#[phase(plugin)]
extern crate rust_clippy;

fn main(){
    let x = Some(1u);
    match x {
        Some(y) => println!("{}", y),
        _ => ()
    }
    // Not linted
    match x {
        Some(y) => println!("{}", y),
        None => ()
    }
    let z = (1u,1u);
    match z {
        (2...3, 7...9) => println!("{}", z),
        _ => {}
    }
}<|endoftext|>


<commit_before><commit_msg>More VIP state cleanup<commit_after><|endoftext|>


<commit_before>use std::iter::Peekable;
use std::num::ParseIntError;
use std::collections::HashMap;

use xml::reader::events::*;
use xml::reader::Events;
use hyper::client::response::*;

/// generic Error for XML parsing
#[derive(Debug)]
pub struct XmlParseError(pub String);

impl XmlParseError {
	pub fn new(msg: &str) -> XmlParseError {
		XmlParseError(msg.to_string())
	}
}

/// syntactic sugar for the XML event stack we pass around
pub type XmlStack<'a> = Peekable<Events<'a, Response>>;

impl From<ParseIntError> for XmlParseError{
        fn from(_e:ParseIntError) -> XmlParseError { XmlParseError::new("ParseIntError") }
}

/// parse Some(String) if the next tag has the right name, otherwise None
pub fn optional_string_field(field_name: &str, stack: &mut XmlStack) -> Result<Option<String>, XmlParseError> {
	if try!(peek_at_name(stack)) == field_name {
		let val = try!(string_field(field_name, stack));
		Ok(Some(val))
	} else {
		Ok(None)
	}
}

/// return a string field with the right name or throw a parse error
pub fn string_field(name: &str, stack: &mut XmlStack) -> Result<String, XmlParseError> {
	try!(start_element(name, stack));
	let value = try!(characters(stack));
	try!(end_element(name, stack));
	Ok(value)
}

/// return some XML Characters
pub fn characters(stack: &mut XmlStack ) -> Result<String, XmlParseError> {
	if let Some(XmlEvent::Characters(data)) = stack.next() {
		Ok(data.to_string())
	} else {
		Err(XmlParseError::new("Expected characters"))
	}

}

/// get the name of the current element in the stack.  throw a parse error if it's not a StartElement
pub fn peek_at_name(stack: &mut XmlStack) -> Result<String, XmlParseError> {
	let current = stack.peek();
	if let Some(&XmlEvent::StartElement{ref name, ..}) = current {
		Ok(name.local_name.to_string())
	} else {
		Ok("".to_string())
	}
}

/// consume a StartElement with a specific name or throw an XmlParseError
pub fn start_element(element_name: &str, stack: &mut XmlStack)  -> Result<HashMap<String, String>, XmlParseError> {
	let next = stack.next();
	if let Some(XmlEvent::StartElement { name, attributes, .. }) = next {
		if name.local_name != element_name {
			Err(XmlParseError::new(&format!("Expected {} got {}", element_name, name.local_name)))
		} else {
			let mut attr_map = HashMap::new();
			for attr in attributes {
				attr_map.insert(attr.name.local_name, attr.value);
			}
			Ok(attr_map)
		}
	}else {

    //  	println!("{:#?}", next);
		Err(XmlParseError::new(&format!("Expected StartElement {}", element_name)))
	}
}

/// consume an EndElement with a specific name or throw an XmlParseError
pub fn end_element(element_name: &str, stack: &mut XmlStack)  -> Result<(), XmlParseError> {
	let next = stack.next();
	if let Some(XmlEvent::EndElement { name, .. }) = next {
		if name.local_name != element_name {
			Err(XmlParseError::new(&format!("Expected {} got {}", element_name, name.local_name)))
		} else {
			Ok(())
		}
	}else {
		Err(XmlParseError::new(&format!("Expected EndElement {} got {:?}", element_name, next)))
	}
}

<commit_msg>Starts refactoring of xmlstack to be more testable.<commit_after>use std::iter::Peekable;
use std::num::ParseIntError;
use std::collections::HashMap;
use std::io::{self, Read};
use xml::reader::events::*;
use xml::reader::Events;
use hyper::client::response::*;

/// generic Error for XML parsing
#[derive(Debug)]
pub struct XmlParseError(pub String);

impl XmlParseError {
	pub fn new(msg: &str) -> XmlParseError {
		XmlParseError(msg.to_string())
	}
}

/// syntactic sugar for the XML event stack we pass around
pub type XmlStack<'a> = Peekable<Events<'a, Response>>;

// Wraps the Hyper Response type
pub struct XmlResponseFromAws<'b> {
	response: Response, // Hyper response type
	xml_stack: Peekable<Events<'b, Response>> // refactor to use XmlStack type?
}

impl <'b> Read for XmlResponseFromAws<'b> {
	// implement read.  See https://github.com/hyperium/hyper/blob/master/src/client/response.rs
	fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
		return self.response.read(buf);
	}
}

// TODO: move to tests/xmlutils.rs
pub struct XmlResponseFromFile {
	file_location: String
}

impl Read for XmlResponseFromFile {
	#[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
		// Get a Result reader from our specified file
        panic!("Not implemented.");
    }
}
// /move to tests/xmlutils.rs

impl From<ParseIntError> for XmlParseError{
        fn from(_e:ParseIntError) -> XmlParseError { XmlParseError::new("ParseIntError") }
}

/// parse Some(String) if the next tag has the right name, otherwise None
pub fn optional_string_field(field_name: &str, stack: &mut XmlStack) -> Result<Option<String>, XmlParseError> {
	if try!(peek_at_name(stack)) == field_name {
		let val = try!(string_field(field_name, stack));
		Ok(Some(val))
	} else {
		Ok(None)
	}
}

/// return a string field with the right name or throw a parse error
pub fn string_field(name: &str, stack: &mut XmlStack) -> Result<String, XmlParseError> {
	try!(start_element(name, stack));
	let value = try!(characters(stack));
	try!(end_element(name, stack));
	Ok(value)
}

/// return some XML Characters
pub fn characters(stack: &mut XmlStack ) -> Result<String, XmlParseError> {
	if let Some(XmlEvent::Characters(data)) = stack.next() {
		Ok(data.to_string())
	} else {
		Err(XmlParseError::new("Expected characters"))
	}

}

/// get the name of the current element in the stack.  throw a parse error if it's not a StartElement
pub fn peek_at_name(stack: &mut XmlStack) -> Result<String, XmlParseError> {
	let current = stack.peek();
	if let Some(&XmlEvent::StartElement{ref name, ..}) = current {
		Ok(name.local_name.to_string())
	} else {
		Ok("".to_string())
	}
}

/// consume a StartElement with a specific name or throw an XmlParseError
pub fn start_element(element_name: &str, stack: &mut XmlStack)  -> Result<HashMap<String, String>, XmlParseError> {
	let next = stack.next();
	if let Some(XmlEvent::StartElement { name, attributes, .. }) = next {
		if name.local_name != element_name {
			Err(XmlParseError::new(&format!("Expected {} got {}", element_name, name.local_name)))
		} else {
			let mut attr_map = HashMap::new();
			for attr in attributes {
				attr_map.insert(attr.name.local_name, attr.value);
			}
			Ok(attr_map)
		}
	}else {

    //  	println!("{:#?}", next);
		Err(XmlParseError::new(&format!("Expected StartElement {}", element_name)))
	}
}

/// consume an EndElement with a specific name or throw an XmlParseError
pub fn end_element(element_name: &str, stack: &mut XmlStack)  -> Result<(), XmlParseError> {
	let next = stack.next();
	if let Some(XmlEvent::EndElement { name, .. }) = next {
		if name.local_name != element_name {
			Err(XmlParseError::new(&format!("Expected {} got {}", element_name, name.local_name)))
		} else {
			Ok(())
		}
	}else {
		Err(XmlParseError::new(&format!("Expected EndElement {} got {:?}", element_name, next)))
	}
}
<|endoftext|>


<commit_before><commit_msg>vga: Testing something again.<commit_after><|endoftext|>


<commit_before><commit_msg>Add smoke test<commit_after>extern crate rudy;

#[test]
fn smoke_test() {
    use rudy::rudymap::RudyMap;

    let mut map: RudyMap<u32, u32> = RudyMap::new();
    let n = 10_000;

    for i in 0..n {
        assert!(map.insert(i, i).is_none());
    }

    for i in 0..n {
        assert_eq!(map.remove(i), Some(i));
    }
}
<|endoftext|>


<commit_before><commit_msg>Add functionality to flush the internal cache<commit_after><|endoftext|>


<commit_before><commit_msg>Add quicksort algorithm<commit_after><|endoftext|>