<commit_before>#[cfg(test)]

use std::path::Path;
use serde_json;
use book::bookconfig::*;

#[test]
fn it_parses_json_config() {
    let text = r#"
{
    "title": "mdBook Documentation",
    "description": "Create book from markdown files. Like Gitbook but implemented in Rust",
    "author": "Mathieu David"
}"#;

    // TODO don't require path argument, take pwd
    let mut config = BookConfig::new(Path::new("."));

    config.parse_from_json_string(&text.to_string());

    let mut expected = BookConfig::new(Path::new("."));
    expected.title = "mdBook Documentation".to_string();
    expected.author = "Mathieu David".to_string();
    expected.description = "Create book from markdown files. Like Gitbook but implemented in Rust".to_string();

    assert_eq!(format!("{:#?}", config), format!("{:#?}", expected));
}

#[test]
fn it_parses_toml_config() {
    let text = r#"
title = "mdBook Documentation"
description = "Create book from markdown files. Like Gitbook but implemented in Rust"
author = "Mathieu David"
"#;

    // TODO don't require path argument, take pwd
    let mut config = BookConfig::new(Path::new("."));

    config.parse_from_toml_string(&text.to_string());

    let mut expected = BookConfig::new(Path::new("."));
    expected.title = "mdBook Documentation".to_string();
    expected.author = "Mathieu David".to_string();
    expected.description = "Create book from markdown files. Like Gitbook but implemented in Rust".to_string();

    assert_eq!(format!("{:#?}", config), format!("{:#?}", expected));
}

#[test]
fn it_parses_json_nested_array_to_toml() {

    // Example from:
    // toml-0.2.1/tests/valid/arrays-nested.json

    let text = r#"
{
    "nest": {
        "type": "array",
        "value": [
            {"type": "array", "value": [
                {"type": "string", "value": "a"}
            ]},
            {"type": "array", "value": [
                {"type": "string", "value": "b"}
            ]}
        ]
    }
}"#;

    let c: serde_json::Value = serde_json::from_str(&text).unwrap();

    let result = json_object_to_btreemap(&c.as_object().unwrap());

    let expected = r#"{
    "nest": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "array"
                            ),
                            "value": Array(
                                [
                                    Table(
                                        {
                                            "type": String(
                                                "string"
                                            ),
                                            "value": String(
                                                "a"
                                            )
                                        }
                                    )
                                ]
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "array"
                            ),
                            "value": Array(
                                [
                                    Table(
                                        {
                                            "type": String(
                                                "string"
                                            ),
                                            "value": String(
                                                "b"
                                            )
                                        }
                                    )
                                ]
                            )
                        }
                    )
                ]
            )
        }
    )
}"#;

    assert_eq!(format!("{:#?}", result), expected);
}

#[test]
fn it_parses_json_arrays_to_toml() {

    // Example from:
    // toml-0.2.1/tests/valid/arrays.json

    let text = r#"
{
    "ints": {
        "type": "array",
        "value": [
            {"type": "integer", "value": "1"},
            {"type": "integer", "value": "2"},
            {"type": "integer", "value": "3"}
        ]
    },
    "floats": {
        "type": "array",
        "value": [
            {"type": "float", "value": "1.1"},
            {"type": "float", "value": "2.1"},
            {"type": "float", "value": "3.1"}
        ]
    },
    "strings": {
        "type": "array",
        "value": [
            {"type": "string", "value": "a"},
            {"type": "string", "value": "b"},
            {"type": "string", "value": "c"}
        ]
    },
    "dates": {
        "type": "array",
        "value": [
            {"type": "datetime", "value": "1987-07-05T17:45:00Z"},
            {"type": "datetime", "value": "1979-05-27T07:32:00Z"},
            {"type": "datetime", "value": "2006-06-01T11:00:00Z"}
        ]
    }
}"#;

    let c: serde_json::Value = serde_json::from_str(&text).unwrap();

    let result = json_object_to_btreemap(&c.as_object().unwrap());

    let expected = r#"{
    "dates": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "datetime"
                            ),
                            "value": String(
                                "1987-07-05T17:45:00Z"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "datetime"
                            ),
                            "value": String(
                                "1979-05-27T07:32:00Z"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "datetime"
                            ),
                            "value": String(
                                "2006-06-01T11:00:00Z"
                            )
                        }
                    )
                ]
            )
        }
    ),
    "floats": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "float"
                            ),
                            "value": String(
                                "1.1"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "float"
                            ),
                            "value": String(
                                "2.1"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "float"
                            ),
                            "value": String(
                                "3.1"
                            )
                        }
                    )
                ]
            )
        }
    ),
    "ints": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "integer"
                            ),
                            "value": String(
                                "1"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "integer"
                            ),
                            "value": String(
                                "2"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "integer"
                            ),
                            "value": String(
                                "3"
                            )
                        }
                    )
                ]
            )
        }
    ),
    "strings": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "string"
                            ),
                            "value": String(
                                "a"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "string"
                            ),
                            "value": String(
                                "b"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "string"
                            ),
                            "value": String(
                                "c"
                            )
                        }
                    )
                ]
            )
        }
    )
}"#;

    assert_eq!(format!("{:#?}", result), expected);
}
<commit_msg>Fix cfg attribute in bookconfig_test<commit_after>#![cfg(test)]

use std::path::Path;
use serde_json;
use book::bookconfig::*;

#[test]
fn it_parses_json_config() {
    let text = r#"
{
    "title": "mdBook Documentation",
    "description": "Create book from markdown files. Like Gitbook but implemented in Rust",
    "author": "Mathieu David"
}"#;

    // TODO don't require path argument, take pwd
    let mut config = BookConfig::new(Path::new("."));

    config.parse_from_json_string(&text.to_string());

    let mut expected = BookConfig::new(Path::new("."));
    expected.title = "mdBook Documentation".to_string();
    expected.author = "Mathieu David".to_string();
    expected.description = "Create book from markdown files. Like Gitbook but implemented in Rust".to_string();

    assert_eq!(format!("{:#?}", config), format!("{:#?}", expected));
}

#[test]
fn it_parses_toml_config() {
    let text = r#"
title = "mdBook Documentation"
description = "Create book from markdown files. Like Gitbook but implemented in Rust"
author = "Mathieu David"
"#;

    // TODO don't require path argument, take pwd
    let mut config = BookConfig::new(Path::new("."));

    config.parse_from_toml_string(&text.to_string());

    let mut expected = BookConfig::new(Path::new("."));
    expected.title = "mdBook Documentation".to_string();
    expected.author = "Mathieu David".to_string();
    expected.description = "Create book from markdown files. Like Gitbook but implemented in Rust".to_string();

    assert_eq!(format!("{:#?}", config), format!("{:#?}", expected));
}

#[test]
fn it_parses_json_nested_array_to_toml() {

    // Example from:
    // toml-0.2.1/tests/valid/arrays-nested.json

    let text = r#"
{
    "nest": {
        "type": "array",
        "value": [
            {"type": "array", "value": [
                {"type": "string", "value": "a"}
            ]},
            {"type": "array", "value": [
                {"type": "string", "value": "b"}
            ]}
        ]
    }
}"#;

    let c: serde_json::Value = serde_json::from_str(&text).unwrap();

    let result = json_object_to_btreemap(&c.as_object().unwrap());

    let expected = r#"{
    "nest": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "array"
                            ),
                            "value": Array(
                                [
                                    Table(
                                        {
                                            "type": String(
                                                "string"
                                            ),
                                            "value": String(
                                                "a"
                                            )
                                        }
                                    )
                                ]
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "array"
                            ),
                            "value": Array(
                                [
                                    Table(
                                        {
                                            "type": String(
                                                "string"
                                            ),
                                            "value": String(
                                                "b"
                                            )
                                        }
                                    )
                                ]
                            )
                        }
                    )
                ]
            )
        }
    )
}"#;

    assert_eq!(format!("{:#?}", result), expected);
}

#[test]
fn it_parses_json_arrays_to_toml() {

    // Example from:
    // toml-0.2.1/tests/valid/arrays.json

    let text = r#"
{
    "ints": {
        "type": "array",
        "value": [
            {"type": "integer", "value": "1"},
            {"type": "integer", "value": "2"},
            {"type": "integer", "value": "3"}
        ]
    },
    "floats": {
        "type": "array",
        "value": [
            {"type": "float", "value": "1.1"},
            {"type": "float", "value": "2.1"},
            {"type": "float", "value": "3.1"}
        ]
    },
    "strings": {
        "type": "array",
        "value": [
            {"type": "string", "value": "a"},
            {"type": "string", "value": "b"},
            {"type": "string", "value": "c"}
        ]
    },
    "dates": {
        "type": "array",
        "value": [
            {"type": "datetime", "value": "1987-07-05T17:45:00Z"},
            {"type": "datetime", "value": "1979-05-27T07:32:00Z"},
            {"type": "datetime", "value": "2006-06-01T11:00:00Z"}
        ]
    }
}"#;

    let c: serde_json::Value = serde_json::from_str(&text).unwrap();

    let result = json_object_to_btreemap(&c.as_object().unwrap());

    let expected = r#"{
    "dates": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "datetime"
                            ),
                            "value": String(
                                "1987-07-05T17:45:00Z"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "datetime"
                            ),
                            "value": String(
                                "1979-05-27T07:32:00Z"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "datetime"
                            ),
                            "value": String(
                                "2006-06-01T11:00:00Z"
                            )
                        }
                    )
                ]
            )
        }
    ),
    "floats": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "float"
                            ),
                            "value": String(
                                "1.1"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "float"
                            ),
                            "value": String(
                                "2.1"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "float"
                            ),
                            "value": String(
                                "3.1"
                            )
                        }
                    )
                ]
            )
        }
    ),
    "ints": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "integer"
                            ),
                            "value": String(
                                "1"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "integer"
                            ),
                            "value": String(
                                "2"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "integer"
                            ),
                            "value": String(
                                "3"
                            )
                        }
                    )
                ]
            )
        }
    ),
    "strings": Table(
        {
            "type": String(
                "array"
            ),
            "value": Array(
                [
                    Table(
                        {
                            "type": String(
                                "string"
                            ),
                            "value": String(
                                "a"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "string"
                            ),
                            "value": String(
                                "b"
                            )
                        }
                    ),
                    Table(
                        {
                            "type": String(
                                "string"
                            ),
                            "value": String(
                                "c"
                            )
                        }
                    )
                ]
            )
        }
    )
}"#;

    assert_eq!(format!("{:#?}", result), expected);
}
<|endoftext|>


<commit_before>// 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.

#![feature(unboxed_closures)]
#![feature(rustc_attrs)]

// Test for projection cache. We should be able to project distinct
// lifetimes from `foo` as we reinstantiate it multiple times, but not
// if we do it just once. In this variant, the region `'a` is used in
// an invariant position, which affects the results.

// revisions: ok oneuse transmute krisskross

#![allow(dead_code, unused_variables)]

use std::marker::PhantomData;

struct Type<'a> {
    // Invariant
    data: PhantomData<fn(&'a u32) -> &'a u32>
}

fn foo<'a>() -> Type<'a> { loop { } }

fn bar<T>(t: T, x: T::Output) -> T::Output
    where T: FnOnce<()>
{
    t()
}

#[cfg(ok)] // two instantiations: OK
fn baz<'a,'b>(x: Type<'a>, y: Type<'b>) -> (Type<'a>, Type<'b>) {
    let a = bar(foo, x);
    let b = bar(foo, y);
    (a, b)
}

#[cfg(oneuse)] // one instantiation: BAD
fn baz<'a,'b>(x: Type<'a>, y: Type<'b>) -> (Type<'a>, Type<'b>) {
   let f = foo; // <-- No consistent type can be inferred for `f` here.
   let a = bar(f, x);
   let b = bar(f, y);
   (a, b) //[oneuse]~ ERROR E0623
}

#[cfg(transmute)] // one instantiations: BAD
fn baz<'a,'b>(x: Type<'a>) -> Type<'static> {
   // Cannot instantiate `foo` with any lifetime other than `'a`,
   // since it is provided as input.

   bar(foo, x) //[transmute]~ ERROR E0495
}

#[cfg(krisskross)] // two instantiations, mixing and matching: BAD
fn transmute<'a,'b>(x: Type<'a>, y: Type<'b>) -> (Type<'a>, Type<'b>) {
   let a = bar(foo, y);
   let b = bar(foo, x);
   (a, b) //[krisskross]~ ERROR E0623
   //[krisskross]~^ ERROR E0623
}

#[rustc_error]
fn main() { }
//[ok]~^ ERROR compilation successful
<commit_msg>Update fn-ret-invariant test assertion<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.

#![feature(unboxed_closures)]
#![feature(rustc_attrs)]

// Test for projection cache. We should be able to project distinct
// lifetimes from `foo` as we reinstantiate it multiple times, but not
// if we do it just once. In this variant, the region `'a` is used in
// an invariant position, which affects the results.

// revisions: ok oneuse transmute krisskross

#![allow(dead_code, unused_variables)]

use std::marker::PhantomData;

struct Type<'a> {
    // Invariant
    data: PhantomData<fn(&'a u32) -> &'a u32>
}

fn foo<'a>() -> Type<'a> { loop { } }

fn bar<T>(t: T, x: T::Output) -> T::Output
    where T: FnOnce<()>
{
    t()
}

#[cfg(ok)] // two instantiations: OK
fn baz<'a,'b>(x: Type<'a>, y: Type<'b>) -> (Type<'a>, Type<'b>) {
    let a = bar(foo, x);
    let b = bar(foo, y);
    (a, b)
}

#[cfg(oneuse)] // one instantiation: BAD
fn baz<'a,'b>(x: Type<'a>, y: Type<'b>) -> (Type<'a>, Type<'b>) {
   let f = foo; // <-- No consistent type can be inferred for `f` here.
   let a = bar(f, x);
   let b = bar(f, y);
   (a, b) //[oneuse]~ ERROR E0623
}

#[cfg(transmute)] // one instantiations: BAD
fn baz<'a,'b>(x: Type<'a>) -> Type<'static> {
   // Cannot instantiate `foo` with any lifetime other than `'a`,
   // since it is provided as input.

   bar(foo, x) //[transmute]~ ERROR E0495
}

#[cfg(krisskross)] // two instantiations, mixing and matching: BAD
fn transmute<'a,'b>(x: Type<'a>, y: Type<'b>) -> (Type<'a>, Type<'b>) {
   let a = bar(foo, y);
   let b = bar(foo, x); //[krisskross]~ ERROR E0623
   (a, b) //[krisskross]~ ERROR E0623
}

#[rustc_error]
fn main() { }
//[ok]~^ ERROR compilation successful
<|endoftext|>


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

use device as d;
use device::Resources;

struct Entry<R: Resources> {
    last_used: u16,
    bound: Option<(d::tex::Kind, R::Texture, Option<(R::Sampler, d::tex::SamplerInfo)>)>,
}

pub struct TextureCache<R: Resources> {
    count: u16,
    textures: Vec<Entry<R>>
}

fn age(now: u16, age: u16) -> u16 {
    use std::num::Wrapping;
    (Wrapping(now) - Wrapping(age)).0
}

impl<R> TextureCache<R> where R: Resources {
    /// Create a TextureCache with `x` slots
    pub fn new(slots: usize) -> TextureCache<R> {
        return TextureCache{
            count: 0,
            textures: (0..slots).map(|_| Entry {
                last_used: 0,
                bound: None
            }).collect()
        }
    }

    /// Returns the number of slots, If a draw call needs
    /// to bind more then this number of slots it will cause
    /// undefined behavior.
    pub fn number_of_slots(&self) -> usize {
        self.textures.len()
    }

    /// Bind a texture, this will look up the texture to see if
    /// it has been bound to a slot, if it has it will return that
    /// slot rather then sending a bind command, iff not it will
    /// release a free slot and bind the texture to it. If there is
    /// no free slots, and there is no bound texture we will throw
    /// away the oldest entries first to make room for the new ones
    pub fn bind_texture<C>(&mut self,
                           kind: d::tex::Kind,
                           tex: R::Texture,
                           samp: Option<(R::Sampler, d::tex::SamplerInfo)>,
                           cb: &mut C) -> d::TextureSlot
        where C: d::draw::CommandBuffer<R>
    {
        self.count += 1;
        let count = self.count;

        let bind = (kind, tex, samp);
        for (i, ent) in self.textures.iter_mut().enumerate() {
            if let Some(ref bound) = ent.bound {
                if bound.0 == bind.0 && bound.1 == bind.1 && bound.2 == bind.2 {
                    // Update the LRU with the current count
                    ent.last_used = count;
                    return i as d::TextureSlot;
                }
            }
        }

        // No texture was found that was bound to the texture slot
        let mut oldest = 0;
        for i in (0..self.textures.len()) {
            if self.textures[i].bound.is_none() {
                oldest = i;
                break;
            }
            if age(count, self.textures[i].last_used) > age(count, self.textures[oldest].last_used) {
                oldest = i;
            }
        }

        cb.bind_texture(oldest as d::TextureSlot, bind.0, bind.1, bind.2);

        self.textures[oldest].last_used = count;
        self.textures[oldest].bound = Some(bind);
        return oldest as d::TextureSlot;
    }

    /// Clear the texture cache
    pub fn clear(&mut self) {
        self.count = 0;
        for ent in self.textures.iter_mut() {
            ent.last_used = 0;
            ent.bound = None;
        }
    }
}

#[test]
fn test_age() {
    assert_eq!(age(100, 0), 100);
    assert_eq!(age(0, 0), 0);
    assert_eq!(age(0, 0xFFFF), 1);
    assert_eq!(age(0, 0xFFFE), 2);
}
<commit_msg>Fixed warning about unecessary parenthesis<commit_after>// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use device as d;
use device::Resources;

struct Entry<R: Resources> {
    last_used: u16,
    bound: Option<(d::tex::Kind, R::Texture, Option<(R::Sampler, d::tex::SamplerInfo)>)>,
}

pub struct TextureCache<R: Resources> {
    count: u16,
    textures: Vec<Entry<R>>
}

fn age(now: u16, age: u16) -> u16 {
    use std::num::Wrapping;
    (Wrapping(now) - Wrapping(age)).0
}

impl<R> TextureCache<R> where R: Resources {
    /// Create a TextureCache with `x` slots
    pub fn new(slots: usize) -> TextureCache<R> {
        return TextureCache{
            count: 0,
            textures: (0..slots).map(|_| Entry {
                last_used: 0,
                bound: None
            }).collect()
        }
    }

    /// Returns the number of slots, If a draw call needs
    /// to bind more then this number of slots it will cause
    /// undefined behavior.
    pub fn number_of_slots(&self) -> usize {
        self.textures.len()
    }

    /// Bind a texture, this will look up the texture to see if
    /// it has been bound to a slot, if it has it will return that
    /// slot rather then sending a bind command, iff not it will
    /// release a free slot and bind the texture to it. If there is
    /// no free slots, and there is no bound texture we will throw
    /// away the oldest entries first to make room for the new ones
    pub fn bind_texture<C>(&mut self,
                           kind: d::tex::Kind,
                           tex: R::Texture,
                           samp: Option<(R::Sampler, d::tex::SamplerInfo)>,
                           cb: &mut C) -> d::TextureSlot
        where C: d::draw::CommandBuffer<R>
    {
        self.count += 1;
        let count = self.count;

        let bind = (kind, tex, samp);
        for (i, ent) in self.textures.iter_mut().enumerate() {
            if let Some(ref bound) = ent.bound {
                if bound.0 == bind.0 && bound.1 == bind.1 && bound.2 == bind.2 {
                    // Update the LRU with the current count
                    ent.last_used = count;
                    return i as d::TextureSlot;
                }
            }
        }

        // No texture was found that was bound to the texture slot
        let mut oldest = 0;
        for i in 0..self.textures.len() {
            if self.textures[i].bound.is_none() {
                oldest = i;
                break;
            }
            if age(count, self.textures[i].last_used) > age(count, self.textures[oldest].last_used) {
                oldest = i;
            }
        }

        cb.bind_texture(oldest as d::TextureSlot, bind.0, bind.1, bind.2);

        self.textures[oldest].last_used = count;
        self.textures[oldest].bound = Some(bind);
        return oldest as d::TextureSlot;
    }

    /// Clear the texture cache
    pub fn clear(&mut self) {
        self.count = 0;
        for ent in self.textures.iter_mut() {
            ent.last_used = 0;
            ent.bound = None;
        }
    }
}

#[test]
fn test_age() {
    assert_eq!(age(100, 0), 100);
    assert_eq!(age(0, 0), 0);
    assert_eq!(age(0, 0xFFFF), 1);
    assert_eq!(age(0, 0xFFFE), 2);
}
<|endoftext|>


<commit_before>use std::time::Instant;
use std::io;
use futures::Future;
use tokio_service::Service;
use eventstore_tcp::{EventStoreClient, Builder};
use {Config, Command, print_elapsed};

pub struct Ping {
    started: Option<Instant>,
}

impl Ping {
    pub fn new() -> Self {
        Ping { started: None }
    }
}

impl Command for Ping {
    fn init(&mut self) {
        self.started = Some(Instant::now());
    }

    fn execute(&self, config: &Config, client: EventStoreClient) -> Box<Future<Item = (), Error = io::Error>> {
        use eventstore_tcp::AdaptedMessage;

        let verbose = config.verbose;
        let started = self.started.unwrap();
        let ping = client.call(Builder::ping().build_package(config.credentials.clone(), None));

        Box::new(ping.map(move |resp| (resp, started))
            .and_then(move |(pong, started)| {
                let received = Instant::now();
                match pong.message.try_adapt().unwrap() {
                    AdaptedMessage::Pong => Ok((started, received)),
                    msg => Err(io::Error::new(io::ErrorKind::Other, format!("Unexpected response: {:?}", msg)))
                }
            }).and_then(move |(started, received)| {
                print_elapsed("pong received in", started.elapsed());
                Ok(())
            }))
    }
}

<commit_msg>testclient/ping: cleanup warnings<commit_after>use std::time::Instant;
use std::io;
use futures::Future;
use tokio_service::Service;
use eventstore_tcp::{EventStoreClient, Builder};
use {Config, Command, print_elapsed};

pub struct Ping {
    started: Option<Instant>,
}

impl Ping {
    pub fn new() -> Self {
        Ping { started: None }
    }
}

impl Command for Ping {
    fn init(&mut self) {
        self.started = Some(Instant::now());
    }

    fn execute(&self, config: &Config, client: EventStoreClient) -> Box<Future<Item = (), Error = io::Error>> {
        use eventstore_tcp::AdaptedMessage;

        let started = self.started.unwrap();
        let ping = client.call(Builder::ping().build_package(config.credentials.clone(), None));

        Box::new(ping.map(move |resp| (resp, started))
            .and_then(move |(pong, started)| {
                match pong.message.try_adapt().unwrap() {
                    AdaptedMessage::Pong => Ok(started),
                    msg => Err(io::Error::new(io::ErrorKind::Other, format!("Unexpected response: {:?}", msg)))
                }
            }).and_then(move |started| {
                print_elapsed("pong received in", started.elapsed());
                Ok(())
            }))
    }
}

<|endoftext|>


<commit_before><commit_msg>Add check to handle zerosize linear gradients<commit_after><|endoftext|>


<commit_before><commit_msg>Respect FilterMode when drawing images<commit_after><|endoftext|>


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

// Checks that all rvalues in a crate have statically known size. check_crate
// is the public starting point.

use middle::expr_use_visitor as euv;
use middle::mem_categorization as mc;
use middle::ty;
use util::ppaux::ty_to_string;

use syntax::ast;
use syntax::codemap::Span;
use syntax::visit;

pub fn check_crate(tcx: &ty::ctxt,
                   krate: &ast::Crate) {
    let mut rvcx = RvalueContext { tcx: tcx };
    visit::walk_crate(&mut rvcx, krate);
}

struct RvalueContext<'a, 'tcx: 'a> {
    tcx: &'a ty::ctxt<'tcx>
}

impl<'a, 'tcx, 'v> visit::Visitor<'v> for RvalueContext<'a, 'tcx> {
    fn visit_fn(&mut self,
                _: visit::FnKind<'v>,
                fd: &'v ast::FnDecl,
                b: &'v ast::Block,
                _: Span,
                _: ast::NodeId) {
        let mut euv = euv::ExprUseVisitor::new(self, self.tcx);
        euv.walk_fn(fd, b);
    }
}

impl<'a, 'tcx> euv::Delegate for RvalueContext<'a, 'tcx> {
    fn consume(&mut self,
               _: ast::NodeId,
               span: Span,
               cmt: mc::cmt,
               _: euv::ConsumeMode) {
        debug!("consume; cmt: {:?}; type: {}", *cmt, ty_to_string(self.tcx, cmt.ty));
        if !ty::type_is_sized(self.tcx, cmt.ty) {
            span_err!(self.tcx.sess, span, E0161,
                "cannot move a value of type {0}: the size of {0} cannot be statically determined",
                ty_to_string(self.tcx, cmt.ty));
        }
    }

    fn consume_pat(&mut self,
                   _consume_pat: &ast::Pat,
                   _cmt: mc::cmt,
                   _mode: euv::ConsumeMode) {
    }

    fn borrow(&mut self,
              _borrow_id: ast::NodeId,
              _borrow_span: Span,
              _cmt: mc::cmt,
              _loan_region: ty::Region,
              _bk: ty::BorrowKind,
              _loan_cause: euv::LoanCause) {
    }

    fn decl_without_init(&mut self,
                         _id: ast::NodeId,
                         _span: Span) {
    }

    fn mutate(&mut self,
              _assignment_id: ast::NodeId,
              _assignment_span: Span,
              _assignee_cmt: mc::cmt,
              _mode: euv::MutateMode) {
    }
}
<commit_msg>Properly visit nested functions and closures in check_rvalues<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Checks that all rvalues in a crate have statically known size. check_crate
// is the public starting point.

use middle::expr_use_visitor as euv;
use middle::mem_categorization as mc;
use middle::ty;
use util::ppaux::ty_to_string;

use syntax::ast;
use syntax::codemap::Span;
use syntax::visit;

pub fn check_crate(tcx: &ty::ctxt,
                   krate: &ast::Crate) {
    let mut rvcx = RvalueContext { tcx: tcx };
    visit::walk_crate(&mut rvcx, krate);
}

struct RvalueContext<'a, 'tcx: 'a> {
    tcx: &'a ty::ctxt<'tcx>
}

impl<'a, 'tcx, 'v> visit::Visitor<'v> for RvalueContext<'a, 'tcx> {
    fn visit_fn(&mut self,
                fk: visit::FnKind<'v>,
                fd: &'v ast::FnDecl,
                b: &'v ast::Block,
                s: Span,
                _: ast::NodeId) {
        {
            let mut euv = euv::ExprUseVisitor::new(self, self.tcx);
            euv.walk_fn(fd, b);
        }
        visit::walk_fn(self, fk, fd, b, s)
    }
}

impl<'a, 'tcx> euv::Delegate for RvalueContext<'a, 'tcx> {
    fn consume(&mut self,
               _: ast::NodeId,
               span: Span,
               cmt: mc::cmt,
               _: euv::ConsumeMode) {
        debug!("consume; cmt: {:?}; type: {}", *cmt, ty_to_string(self.tcx, cmt.ty));
        if !ty::type_is_sized(self.tcx, cmt.ty) {
            span_err!(self.tcx.sess, span, E0161,
                "cannot move a value of type {0}: the size of {0} cannot be statically determined",
                ty_to_string(self.tcx, cmt.ty));
        }
    }

    fn consume_pat(&mut self,
                   _consume_pat: &ast::Pat,
                   _cmt: mc::cmt,
                   _mode: euv::ConsumeMode) {
    }

    fn borrow(&mut self,
              _borrow_id: ast::NodeId,
              _borrow_span: Span,
              _cmt: mc::cmt,
              _loan_region: ty::Region,
              _bk: ty::BorrowKind,
              _loan_cause: euv::LoanCause) {
    }

    fn decl_without_init(&mut self,
                         _id: ast::NodeId,
                         _span: Span) {
    }

    fn mutate(&mut self,
              _assignment_id: ast::NodeId,
              _assignment_span: Span,
              _assignee_cmt: mc::cmt,
              _mode: euv::MutateMode) {
    }
}
<|endoftext|>


<commit_before>#[doc(hidden)];

// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];

use libc::{c_char, c_void, intptr_t, uintptr_t};
use ptr::{mut_null, null, to_unsafe_ptr};
use repr::BoxRepr;
use sys::TypeDesc;
use cast::transmute;

export annihilate;

/**
 * Runtime structures
 *
 * NB: These must match the representation in the C++ runtime.
 */

type DropGlue = fn(**TypeDesc, *c_void);
type FreeGlue = fn(**TypeDesc, *c_void);

type TaskID = uintptr_t;

struct StackSegment { priv opaque: () }
struct Scheduler { priv opaque: () }
struct SchedulerLoop { priv opaque: () }
struct Kernel { priv opaque: () }
struct Env { priv opaque: () }
struct AllocHeader { priv opaque: () }
struct MemoryRegion { priv opaque: () }

#[cfg(target_arch="x86")]
struct Registers {
    data: [u32 * 13]
}

#[cfg(target_arch="x86_64")]
struct Registers {
    data: [u64 * 22]
}

struct Context {
    regs: Registers,
    next: *Context,
    pad: u64
}

struct BoxedRegion {
    env: *Env,
    backing_region: *MemoryRegion,
    live_allocs: *BoxRepr
}

struct Task {
    // Public fields
    refcount: intptr_t,
    id: TaskID,
    ctx: Context,
    stack_segment: *StackSegment,
    runtime_sp: uintptr_t,
    scheduler: *Scheduler,
    scheduler_loop: *SchedulerLoop,

    // Fields known only to the runtime
    kernel: *Kernel,
    name: *c_char,
    list_index: *i32,
    rendezvous_ptr: *uintptr_t,
    boxed_region: BoxedRegion
}

/*
 * Box annihilation
 *
 * This runs at task death to free all boxes.
 */

/// Destroys all managed memory (i.e. @ boxes) held by the current task.
#[cfg(notest)]
#[lang="annihilate"]
pub unsafe fn annihilate() {
    use rt::rt_free;
    use io::WriterUtil;

    let task: *Task = transmute(rustrt::rust_get_task());

    // Pass 1: Make all boxes immortal.
    let box = (*task).boxed_region.live_allocs;
    let mut box: *mut BoxRepr = transmute(copy box);
    while box != mut_null() {
        debug!("making box immortal: %x", box as uint);
        (*box).header.ref_count = 0x77777777;
        box = transmute(copy (*box).header.next);
    }

    // Pass 2: Drop all boxes.
    let box = (*task).boxed_region.live_allocs;
    let mut box: *mut BoxRepr = transmute(copy box);
    while box != mut_null() {
        debug!("calling drop glue for box: %x", box as uint);
        let tydesc: *TypeDesc = transmute(copy (*box).header.type_desc);
        let drop_glue: DropGlue = transmute(((*tydesc).drop_glue, 0));
        drop_glue(to_unsafe_ptr(&tydesc), transmute(&(*box).data));

        box = transmute(copy (*box).header.next);
    }

    // Pass 3: Free all boxes.
    loop {
        let box = (*task).boxed_region.live_allocs;
        if box == null() { break; }
        let mut box: *mut BoxRepr = transmute(copy box);
        assert (*box).header.prev == null();

        debug!("freeing box: %x", box as uint);
        rt_free(transmute(box));
    }
}

/// Bindings to the runtime
extern mod rustrt {
    #[legacy_exports];
    #[rust_stack]
    /*priv*/ fn rust_get_task() -> *c_void;
}

<commit_msg>libcore: Fix 32 bit Rust task structure offsets for unwinding<commit_after>#[doc(hidden)];

// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];

use libc::{c_char, c_void, intptr_t, uintptr_t};
use ptr::{mut_null, null, to_unsafe_ptr};
use repr::BoxRepr;
use sys::TypeDesc;
use cast::transmute;

export annihilate;

/**
 * Runtime structures
 *
 * NB: These must match the representation in the C++ runtime.
 */

type DropGlue = fn(**TypeDesc, *c_void);
type FreeGlue = fn(**TypeDesc, *c_void);

type TaskID = uintptr_t;

struct StackSegment { priv opaque: () }
struct Scheduler { priv opaque: () }
struct SchedulerLoop { priv opaque: () }
struct Kernel { priv opaque: () }
struct Env { priv opaque: () }
struct AllocHeader { priv opaque: () }
struct MemoryRegion { priv opaque: () }

#[cfg(target_arch="x86")]
struct Registers {
    data: [u32 * 16]
}

#[cfg(target_arch="x86")]
struct Context {
    regs: Registers,
    next: *Context,
    pad: [u32 * 3]
}

#[cfg(target_arch="x86_64")]
struct Registers {
    data: [u64 * 22]
}

#[cfg(target_arch="x86_64")]
struct Context {
    regs: Registers,
    next: *Context,
    pad: uintptr_t
}

struct BoxedRegion {
    env: *Env,
    backing_region: *MemoryRegion,
    live_allocs: *BoxRepr
}

#[cfg(target_arch="x86")]
struct Task {
    // Public fields
    refcount: intptr_t,                 // 0
    id: TaskID,                         // 4
    pad: [u32 * 2],                     // 8
    ctx: Context,                       // 16
    stack_segment: *StackSegment,       // 96
    runtime_sp: uintptr_t,              // 100
    scheduler: *Scheduler,              // 104
    scheduler_loop: *SchedulerLoop,     // 108

    // Fields known only to the runtime
    kernel: *Kernel,                    // 112
    name: *c_char,                      // 116
    list_index: i32,                    // 120
    rendezvous_ptr: *uintptr_t,         // 124
    boxed_region: BoxedRegion           // 128
}

#[cfg(target_arch="x86_64")]
struct Task {
    // Public fields
    refcount: intptr_t,
    id: TaskID,
    ctx: Context,
    stack_segment: *StackSegment,
    runtime_sp: uintptr_t,
    scheduler: *Scheduler,
    scheduler_loop: *SchedulerLoop,

    // Fields known only to the runtime
    kernel: *Kernel,
    name: *c_char,
    list_index: i32,
    rendezvous_ptr: *uintptr_t,
    boxed_region: BoxedRegion
}

/*
 * Box annihilation
 *
 * This runs at task death to free all boxes.
 */

/// Destroys all managed memory (i.e. @ boxes) held by the current task.
#[cfg(notest)]
#[lang="annihilate"]
pub unsafe fn annihilate() {
    use rt::rt_free;
    use io::WriterUtil;

    let task: *Task = transmute(rustrt::rust_get_task());

    // Pass 1: Make all boxes immortal.
    let box = (*task).boxed_region.live_allocs;
    let mut box: *mut BoxRepr = transmute(copy box);
    while box != mut_null() {
        debug!("making box immortal: %x", box as uint);
        (*box).header.ref_count = 0x77777777;
        box = transmute(copy (*box).header.next);
    }

    // Pass 2: Drop all boxes.
    let box = (*task).boxed_region.live_allocs;
    let mut box: *mut BoxRepr = transmute(copy box);
    while box != mut_null() {
        debug!("calling drop glue for box: %x", box as uint);
        let tydesc: *TypeDesc = transmute(copy (*box).header.type_desc);
        let drop_glue: DropGlue = transmute(((*tydesc).drop_glue, 0));
        drop_glue(to_unsafe_ptr(&tydesc), transmute(&(*box).data));

        box = transmute(copy (*box).header.next);
    }

    // Pass 3: Free all boxes.
    loop {
        let box = (*task).boxed_region.live_allocs;
        if box == null() { break; }
        let mut box: *mut BoxRepr = transmute(copy box);
        assert (*box).header.prev == null();

        debug!("freeing box: %x", box as uint);
        rt_free(transmute(box));
    }
}

/// Bindings to the runtime
extern mod rustrt {
    #[legacy_exports];
    #[rust_stack]
    /*priv*/ fn rust_get_task() -> *c_void;
}

<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2460<commit_after>// https://leetcode.com/problems/apply-operations-to-an-array/
pub fn apply_operations(nums: Vec<i32>) -> Vec<i32> {
    todo!()
}

fn main() {
    println!("{:?}", apply_operations(vec![1, 2, 2, 1, 1, 0])); // [1,4,2,0,0,0]
    println!("{:?}", apply_operations(vec![0, 1])); // [1,0]
}
<|endoftext|>


<commit_before><commit_msg>make handling of sigma neater<commit_after><|endoftext|>


<commit_before><commit_msg>rustup, fix writer.rs<commit_after><|endoftext|>


<commit_before><commit_msg>add benchmark tests for nightly<commit_after>// -*- coding: utf-8 -*-
// vi: set sts=4 ts=4 sw=4 et ft=rust:
#![feature(test)]

extern crate test;
extern crate varsun;

use test::Bencher;

fn mapfn(name: &str) -> Option<String> {
    match name {
        "foo" => Some("foo!!".to_string()),
        "bar" => Some("!bar!".to_string()),
        "baz" => Some("-baz-".to_string()),
        _     => Some("(　・ω・)?".to_string()),
    }
}

#[bench]
fn posix_basic(b: &mut Bencher) {
    let src = "${foo}";
    b.iter(|| {
        varsun::posix::substitute(src, mapfn);
    });
}

#[bench]
fn mswin_basic(b: &mut Bencher) {
    let src = "%foo%";
    b.iter(|| {
        varsun::mswin::substitute(src, mapfn);
    });
}
<|endoftext|>


<commit_before><commit_msg>Fix for new all_annotations() interface<commit_after><|endoftext|>


<commit_before><commit_msg>Conditionsals over closures<commit_after><|endoftext|>


<commit_before><commit_msg>strings cannot be indexed<commit_after><|endoftext|>


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

//! Unicode-intensive string manipulations.
//!
//! This module provides functionality to `str` that requires the Unicode
//! methods provided by the unicode parts of the CharExt trait.

use core::char;
use core::iter::{Filter, FusedIterator};
use core::str::Split;

/// An iterator over the non-whitespace substrings of a string,
/// separated by any amount of whitespace.
///
/// This struct is created by the [`split_whitespace`] method on [`str`].
/// See its documentation for more.
///
/// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
/// [`str`]: ../../std/primitive.str.html
#[stable(feature = "split_whitespace", since = "1.1.0")]
#[derive(Clone)]
pub struct SplitWhitespace<'a> {
    inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
}

/// Methods for Unicode string slices
#[allow(missing_docs)] // docs in liballoc
pub trait UnicodeStr {
    fn split_whitespace<'a>(&'a self) -> SplitWhitespace<'a>;
    fn is_whitespace(&self) -> bool;
    fn is_alphanumeric(&self) -> bool;
    fn trim(&self) -> &str;
    fn trim_left(&self) -> &str;
    fn trim_right(&self) -> &str;
}

impl UnicodeStr for str {
    #[inline]
    fn split_whitespace(&self) -> SplitWhitespace {
        SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
    }

    #[inline]
    fn is_whitespace(&self) -> bool {
        self.chars().all(|c| c.is_whitespace())
    }

    #[inline]
    fn is_alphanumeric(&self) -> bool {
        self.chars().all(|c| c.is_alphanumeric())
    }

    #[inline]
    fn trim(&self) -> &str {
        self.trim_matches(|c: char| c.is_whitespace())
    }

    #[inline]
    fn trim_left(&self) -> &str {
        self.trim_left_matches(|c: char| c.is_whitespace())
    }

    #[inline]
    fn trim_right(&self) -> &str {
        self.trim_right_matches(|c: char| c.is_whitespace())
    }
}

/// Iterator adaptor for encoding `char`s to UTF-16.
#[derive(Clone)]
pub struct Utf16Encoder<I> {
    chars: I,
    extra: u16,
}

impl<I> Utf16Encoder<I> {
    /// Create a UTF-16 encoder from any `char` iterator.
    pub fn new(chars: I) -> Utf16Encoder<I>
        where I: Iterator<Item = char>
    {
        Utf16Encoder {
            chars,
            extra: 0,
        }
    }
}

impl<I> Iterator for Utf16Encoder<I>
    where I: Iterator<Item = char>
{
    type Item = u16;

    #[inline]
    fn next(&mut self) -> Option<u16> {
        if self.extra != 0 {
            let tmp = self.extra;
            self.extra = 0;
            return Some(tmp);
        }

        let mut buf = [0; 2];
        self.chars.next().map(|ch| {
            let n = CharExt::encode_utf16(ch, &mut buf).len();
            if n == 2 {
                self.extra = buf[1];
            }
            buf[0]
        })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (low, high) = self.chars.size_hint();
        // every char gets either one u16 or two u16,
        // so this iterator is between 1 or 2 times as
        // long as the underlying iterator.
        (low, high.and_then(|n| n.checked_mul(2)))
    }
}

#[unstable(feature = "fused", issue = "35602")]
impl<I> FusedIterator for Utf16Encoder<I>
    where I: FusedIterator<Item = char> {}

#[derive(Clone)]
struct IsWhitespace;

impl FnOnce<(char, )> for IsWhitespace {
    type Output = bool;

    #[inline]
    extern "rust-call" fn call_once(mut self, arg: (char, )) -> bool {
        self.call_mut(arg)
    }
}

impl FnMut<(char, )> for IsWhitespace {
    #[inline]
    extern "rust-call" fn call_mut(&mut self, arg: (char, )) -> bool {
        arg.0.is_whitespace()
    }
}

#[derive(Clone)]
struct IsNotEmpty;

impl<'a, 'b> FnOnce<(&'a &'b str, )> for IsNotEmpty {
    type Output = bool;

    #[inline]
    extern "rust-call" fn call_once(mut self, arg: (&&str, )) -> bool {
        self.call_mut(arg)
    }
}

impl<'a, 'b> FnMut<(&'a &'b str, )> for IsNotEmpty {
    #[inline]
    extern "rust-call" fn call_mut(&mut self, arg: (&&str, )) -> bool {
        !arg.0.is_empty()
    }
}

#[stable(feature = "split_whitespace", since = "1.1.0")]
impl<'a> Iterator for SplitWhitespace<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        self.inner.next()
    }
}

#[stable(feature = "split_whitespace", since = "1.1.0")]
impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
    fn next_back(&mut self) -> Option<&'a str> {
        self.inner.next_back()
    }
}

#[unstable(feature = "fused", issue = "35602")]
impl<'a> FusedIterator for SplitWhitespace<'a> {}
<commit_msg>Rollup merge of #44303 - clarcharr:debugs, r=alexcrichton<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Unicode-intensive string manipulations.
//!
//! This module provides functionality to `str` that requires the Unicode
//! methods provided by the unicode parts of the CharExt trait.

use core::char;
use core::iter::{Filter, FusedIterator};
use core::str::Split;

/// An iterator over the non-whitespace substrings of a string,
/// separated by any amount of whitespace.
///
/// This struct is created by the [`split_whitespace`] method on [`str`].
/// See its documentation for more.
///
/// [`split_whitespace`]: ../../std/primitive.str.html#method.split_whitespace
/// [`str`]: ../../std/primitive.str.html
#[stable(feature = "split_whitespace", since = "1.1.0")]
#[derive(Clone, Debug)]
pub struct SplitWhitespace<'a> {
    inner: Filter<Split<'a, IsWhitespace>, IsNotEmpty>,
}

/// Methods for Unicode string slices
#[allow(missing_docs)] // docs in liballoc
pub trait UnicodeStr {
    fn split_whitespace<'a>(&'a self) -> SplitWhitespace<'a>;
    fn is_whitespace(&self) -> bool;
    fn is_alphanumeric(&self) -> bool;
    fn trim(&self) -> &str;
    fn trim_left(&self) -> &str;
    fn trim_right(&self) -> &str;
}

impl UnicodeStr for str {
    #[inline]
    fn split_whitespace(&self) -> SplitWhitespace {
        SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
    }

    #[inline]
    fn is_whitespace(&self) -> bool {
        self.chars().all(|c| c.is_whitespace())
    }

    #[inline]
    fn is_alphanumeric(&self) -> bool {
        self.chars().all(|c| c.is_alphanumeric())
    }

    #[inline]
    fn trim(&self) -> &str {
        self.trim_matches(|c: char| c.is_whitespace())
    }

    #[inline]
    fn trim_left(&self) -> &str {
        self.trim_left_matches(|c: char| c.is_whitespace())
    }

    #[inline]
    fn trim_right(&self) -> &str {
        self.trim_right_matches(|c: char| c.is_whitespace())
    }
}

/// Iterator adaptor for encoding `char`s to UTF-16.
#[derive(Clone)]
pub struct Utf16Encoder<I> {
    chars: I,
    extra: u16,
}

impl<I> Utf16Encoder<I> {
    /// Create a UTF-16 encoder from any `char` iterator.
    pub fn new(chars: I) -> Utf16Encoder<I>
        where I: Iterator<Item = char>
    {
        Utf16Encoder {
            chars,
            extra: 0,
        }
    }
}

impl<I> Iterator for Utf16Encoder<I>
    where I: Iterator<Item = char>
{
    type Item = u16;

    #[inline]
    fn next(&mut self) -> Option<u16> {
        if self.extra != 0 {
            let tmp = self.extra;
            self.extra = 0;
            return Some(tmp);
        }

        let mut buf = [0; 2];
        self.chars.next().map(|ch| {
            let n = CharExt::encode_utf16(ch, &mut buf).len();
            if n == 2 {
                self.extra = buf[1];
            }
            buf[0]
        })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (low, high) = self.chars.size_hint();
        // every char gets either one u16 or two u16,
        // so this iterator is between 1 or 2 times as
        // long as the underlying iterator.
        (low, high.and_then(|n| n.checked_mul(2)))
    }
}

#[unstable(feature = "fused", issue = "35602")]
impl<I> FusedIterator for Utf16Encoder<I>
    where I: FusedIterator<Item = char> {}

#[derive(Clone)]
struct IsWhitespace;

impl FnOnce<(char, )> for IsWhitespace {
    type Output = bool;

    #[inline]
    extern "rust-call" fn call_once(mut self, arg: (char, )) -> bool {
        self.call_mut(arg)
    }
}

impl FnMut<(char, )> for IsWhitespace {
    #[inline]
    extern "rust-call" fn call_mut(&mut self, arg: (char, )) -> bool {
        arg.0.is_whitespace()
    }
}

#[derive(Clone)]
struct IsNotEmpty;

impl<'a, 'b> FnOnce<(&'a &'b str, )> for IsNotEmpty {
    type Output = bool;

    #[inline]
    extern "rust-call" fn call_once(mut self, arg: (&&str, )) -> bool {
        self.call_mut(arg)
    }
}

impl<'a, 'b> FnMut<(&'a &'b str, )> for IsNotEmpty {
    #[inline]
    extern "rust-call" fn call_mut(&mut self, arg: (&&str, )) -> bool {
        !arg.0.is_empty()
    }
}

#[stable(feature = "split_whitespace", since = "1.1.0")]
impl<'a> Iterator for SplitWhitespace<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        self.inner.next()
    }
}

#[stable(feature = "split_whitespace", since = "1.1.0")]
impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
    fn next_back(&mut self) -> Option<&'a str> {
        self.inner.next_back()
    }
}

#[unstable(feature = "fused", issue = "35602")]
impl<'a> FusedIterator for SplitWhitespace<'a> {}
<|endoftext|>


<commit_before><commit_msg>Daemon read config and support for custom autobackup<commit_after><|endoftext|>


<commit_before><commit_msg>Removed double blank line<commit_after><|endoftext|>


<commit_before>// Copyright 2016 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.

use std::env;
use std::process::Command;
use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::Write;

struct Test {
    repo: &'static str,
    name: &'static str,
    sha: &'static str,
    lock: Option<&'static str>,
}

const TEST_REPOS: &'static [Test] = &[
    Test {
        name: "cargo",
        repo: "https://github.com/rust-lang/cargo",
        sha: "b7be4f2ef2cf743492edc6dfb55d087ed88f2d76",
        lock: None,
    },
    Test {
        name: "iron",
        repo: "https://github.com/iron/iron",
        sha: "16c858ec2901e2992fe5e529780f59fa8ed12903",
        lock: Some(include_str!("lockfiles/iron-Cargo.lock")),
    },
    Test {
        name: "ripgrep",
        repo: "https://github.com/BurntSushi/ripgrep",
        sha: "b65bb37b14655e1a89c7cd19c8b011ef3e312791",
        lock: None,
    },
    Test {
        name: "tokei",
        repo: "https://github.com/Aaronepower/tokei",
        sha: "5e11c4852fe4aa086b0e4fe5885822fbe57ba928",
        lock: None,
    },
    Test {
        name: "treeify",
        repo: "https://github.com/dzamlo/treeify",
        sha: "999001b223152441198f117a68fb81f57bc086dd",
        lock: None,
    },
];

fn main() {
    // One of the projects being tested here is Cargo, and when being tested
    // Cargo will at some point call `nmake.exe` on Windows MSVC. Unfortunately
    // `nmake` will read these two environment variables below and try to
    // intepret them. We're likely being run, however, from MSYS `make` which
    // uses the same variables.
    //
    // As a result, to prevent confusion and errors, we remove these variables
    // from our environment to prevent passing MSYS make flags to nmake, causing
    // it to blow up.
    if cfg!(target_env = "msvc") {
        env::remove_var("MAKE");
        env::remove_var("MAKEFLAGS");
    }

    let args = env::args().collect::<Vec<_>>();
    let ref cargo = args[1];
    let out_dir = Path::new(&args[2]);
    let ref cargo = Path::new(cargo);

    for test in TEST_REPOS.iter().rev() {
        test_repo(cargo, out_dir, test);
    }
}

fn test_repo(cargo: &Path, out_dir: &Path, test: &Test) {
    println!("testing {}", test.repo);
    let dir = clone_repo(test, out_dir);
    if let Some(lockfile) = test.lock {
        File::create(&dir.join("Cargo.lock"))
            .expect("")
            .write_all(lockfile.as_bytes())
            .expect("");
    }
    if !run_cargo_test(cargo, &dir) {
        panic!("tests failed for {}", test.repo);
    }
}

fn clone_repo(test: &Test, out_dir: &Path) -> PathBuf {
    let out_dir = out_dir.join(test.name);

    if !out_dir.join(".git").is_dir() {
        let status = Command::new("git")
                         .arg("init")
                         .arg(&out_dir)
                         .status()
                         .expect("");
        assert!(status.success());
    }

    // Try progressively deeper fetch depths to find the commit
    let mut found = false;
    for depth in &[0, 1, 10, 100, 1000, 100000] {
        if *depth > 0 {
            let status = Command::new("git")
                             .arg("fetch")
                             .arg(test.repo)
                             .arg("master")
                             .arg(&format!("--depth={}", depth))
                             .current_dir(&out_dir)
                             .status()
                             .expect("");
            assert!(status.success());
        }

        let status = Command::new("git")
                         .arg("reset")
                         .arg(test.sha)
                         .arg("--hard")
                         .current_dir(&out_dir)
                         .status()
                         .expect("");

        if status.success() {
            found = true;
            break;
        }
    }

    if !found {
        panic!("unable to find commit {}", test.sha)
    }
    let status = Command::new("git")
                     .arg("clean")
                     .arg("-fdx")
                     .current_dir(&out_dir)
                     .status()
                     .unwrap();
    assert!(status.success());

    out_dir
}

fn run_cargo_test(cargo_path: &Path, crate_path: &Path) -> bool {
    let status = Command::new(cargo_path)
        .arg("test")
        // Disable rust-lang/cargo's cross-compile tests
        .env("CFG_DISABLE_CROSS_TESTS", "1")
        .current_dir(crate_path)
        .status()
        .expect("");

    status.success()
}
<commit_msg>cargotest: Add xsv to tested crates<commit_after>// Copyright 2016 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.

use std::env;
use std::process::Command;
use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::Write;

struct Test {
    repo: &'static str,
    name: &'static str,
    sha: &'static str,
    lock: Option<&'static str>,
}

const TEST_REPOS: &'static [Test] = &[
    Test {
        name: "cargo",
        repo: "https://github.com/rust-lang/cargo",
        sha: "b7be4f2ef2cf743492edc6dfb55d087ed88f2d76",
        lock: None,
    },
    Test {
        name: "iron",
        repo: "https://github.com/iron/iron",
        sha: "16c858ec2901e2992fe5e529780f59fa8ed12903",
        lock: Some(include_str!("lockfiles/iron-Cargo.lock")),
    },
    Test {
        name: "ripgrep",
        repo: "https://github.com/BurntSushi/ripgrep",
        sha: "b65bb37b14655e1a89c7cd19c8b011ef3e312791",
        lock: None,
    },
    Test {
        name: "tokei",
        repo: "https://github.com/Aaronepower/tokei",
        sha: "5e11c4852fe4aa086b0e4fe5885822fbe57ba928",
        lock: None,
    },
    Test {
        name: "treeify",
        repo: "https://github.com/dzamlo/treeify",
        sha: "999001b223152441198f117a68fb81f57bc086dd",
        lock: None,
    },
    Test {
        name: "xsv",
        repo: "https://github.com/BurntSushi/xsv",
        sha: "a9a7163f2a2953cea426fee1216bec914fe2f56a",
        lock: None,
    },
];

fn main() {
    // One of the projects being tested here is Cargo, and when being tested
    // Cargo will at some point call `nmake.exe` on Windows MSVC. Unfortunately
    // `nmake` will read these two environment variables below and try to
    // intepret them. We're likely being run, however, from MSYS `make` which
    // uses the same variables.
    //
    // As a result, to prevent confusion and errors, we remove these variables
    // from our environment to prevent passing MSYS make flags to nmake, causing
    // it to blow up.
    if cfg!(target_env = "msvc") {
        env::remove_var("MAKE");
        env::remove_var("MAKEFLAGS");
    }

    let args = env::args().collect::<Vec<_>>();
    let ref cargo = args[1];
    let out_dir = Path::new(&args[2]);
    let ref cargo = Path::new(cargo);

    for test in TEST_REPOS.iter().rev() {
        test_repo(cargo, out_dir, test);
    }
}

fn test_repo(cargo: &Path, out_dir: &Path, test: &Test) {
    println!("testing {}", test.repo);
    let dir = clone_repo(test, out_dir);
    if let Some(lockfile) = test.lock {
        File::create(&dir.join("Cargo.lock"))
            .expect("")
            .write_all(lockfile.as_bytes())
            .expect("");
    }
    if !run_cargo_test(cargo, &dir) {
        panic!("tests failed for {}", test.repo);
    }
}

fn clone_repo(test: &Test, out_dir: &Path) -> PathBuf {
    let out_dir = out_dir.join(test.name);

    if !out_dir.join(".git").is_dir() {
        let status = Command::new("git")
                         .arg("init")
                         .arg(&out_dir)
                         .status()
                         .expect("");
        assert!(status.success());
    }

    // Try progressively deeper fetch depths to find the commit
    let mut found = false;
    for depth in &[0, 1, 10, 100, 1000, 100000] {
        if *depth > 0 {
            let status = Command::new("git")
                             .arg("fetch")
                             .arg(test.repo)
                             .arg("master")
                             .arg(&format!("--depth={}", depth))
                             .current_dir(&out_dir)
                             .status()
                             .expect("");
            assert!(status.success());
        }

        let status = Command::new("git")
                         .arg("reset")
                         .arg(test.sha)
                         .arg("--hard")
                         .current_dir(&out_dir)
                         .status()
                         .expect("");

        if status.success() {
            found = true;
            break;
        }
    }

    if !found {
        panic!("unable to find commit {}", test.sha)
    }
    let status = Command::new("git")
                     .arg("clean")
                     .arg("-fdx")
                     .current_dir(&out_dir)
                     .status()
                     .unwrap();
    assert!(status.success());

    out_dir
}

fn run_cargo_test(cargo_path: &Path, crate_path: &Path) -> bool {
    let status = Command::new(cargo_path)
        .arg("test")
        // Disable rust-lang/cargo's cross-compile tests
        .env("CFG_DISABLE_CROSS_TESTS", "1")
        .current_dir(crate_path)
        .status()
        .expect("");

    status.success()
}
<|endoftext|>


<commit_before><commit_msg>Add a regression test for FromIterator of OscArray<commit_after>extern crate rosc;

use rosc::{OscArray, OscType};

#[test]
fn test_osc_array_from_iter() {
    use std::iter::FromIterator;
    let iter = (0..3).map(|i| OscType::Int(i));
    let osc_arr = OscArray::from_iter(iter);
    assert_eq!(
        osc_arr,
        OscArray {
            content: vec![OscType::Int(0), OscType::Int(1), OscType::Int(2)]
        }
    );
}
<|endoftext|>


<commit_before><commit_msg>server: dispatch idle test<commit_after>extern crate wayland_client as wayc;
extern crate wayland_server as ways;

mod helpers;

use helpers::TestServer;

#[test]
fn skel() {
    // Server setup
    //
    let mut server = TestServer::new();

    let idle = server
        .event_loop
        .add_idle_event_source(|_, idata| *idata = true, false);

    server.event_loop.dispatch(Some(1)).unwrap();

    let done = idle.remove();
    assert!(done);
}
<|endoftext|>


<commit_before><commit_msg>Integration tests fail<commit_after><|endoftext|>


<commit_before><commit_msg>add fn example<commit_after>// Unlike C/C++, there's no restriction on the order of function definitions
fn main() {
    // We can use this function here, and define it somewhere later
    fizzbuzz_to(100);
}

// Function that returns a boolean value
fn is_divisible_by(lhs: u32, rhs: u32) -> bool {
    // Corner case, early return
    if rhs == 0 {
        return false;
    }

    // This is an expression, the `return` keyword is not necessary here
    lhs % rhs == 0
}

// Functions that "don't" return a value, actually return the unit type `()`
fn fizzbuzz(n: u32) -> () {
    if is_divisible_by(n, 15) {
        println!("fizzbuzz");
    } else if is_divisible_by(n, 3) {
        println!("fizz");
    } else if is_divisible_by(n, 5) {
        println!("buzz");
    } else {
        println!("{}", n);
    }
}

// When a function returns `()`, the return type can be omitted from the
// signature
fn fizzbuzz_to(n: u32) {
    for n in 1..n + 1 {
        fizzbuzz(n);
    }
}
<|endoftext|>


<commit_before><commit_msg>More solutions<commit_after>// https://leetcode.com/problems/generate-parentheses/

pub struct Solution;

impl Solution {
    pub fn generate_parenthesis(n: i32) -> Vec<String> {
        let mut result: Vec<String> = Vec::new();
        let mut curr_stack = Vec::new();
        Self::gen_parens_recursive(&mut curr_stack, 0, n, &mut result);

        return result;
    }

    fn gen_parens_recursive(
        stack: &mut Vec<char>,
        opens: i32,
        remaining: i32,
        result: &mut Vec<String>,
    ) {
        if opens == 0 && remaining == 0 {
            result.push(stack.iter().collect());
            return;
        }

        if remaining > 0 {
            stack.push('(');
            Self::gen_parens_recursive(stack, opens + 1, remaining - 1, result);
            stack.pop();
        }

        if opens > 0 {
            stack.push(')');
            Self::gen_parens_recursive(stack, opens - 1, remaining, result);
            stack.pop();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use test_util::assert_eq_ignore_order;

    #[test]
    fn test_1() {
        assert_eq_ignore_order(
            Solution::generate_parenthesis(3),
            ["((()))", "(()())", "(())()", "()(())", "()()()"]
                .iter()
                .map(|s| s.to_string())
                .collect(),
        );
    }
}
<|endoftext|>


<commit_before><commit_msg>Add tutorial-tasks-02_3-arc.rs<commit_after>#[crate_id="tutorial-tasks-02_3-arc.rs"];
//! Rust Tasks and Communication Tutorial - 2.3 Sharing immutable data without copy: Arc
//!
//! http://static.rust-lang.org/doc/master/guide-tasks.html#sharing-immutable-data-without-copy:-arc

extern crate rand;
extern crate sync;

use std::vec_ng::Vec;
use sync::Arc;

fn pnorm(nums: &Vec<f64>, p: uint) -> f64 {
	nums.iter().fold(0.0, |a,b| a+(*b).powf(&(p as f64)) ).powf(&(1.0 / (p as f64)))
}

fn main() {
	let numbers = Vec::from_fn(1000000u, |_| rand::random::<f64>());
	let numbers_arc = Arc::new(numbers);

	for num in range(1u, 10) {
		let (tx, rx) = channel();
		tx.send(numbers_arc.clone());

		spawn(proc() {
			let local_arc : Arc<Vec<f64>> = rx.recv();
			let task_numbers = local_arc.get();
			println!("{}-norm = {}", num, pnorm(task_numbers, num));
		});
	}
}
<|endoftext|>


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

//! Semantic version parsing and comparison.
//!
//! Semantic versioning (see http://semver.org/) is a set of rules for
//! assigning version numbers intended to convey meaning about what has
//! changed, and how much. A version number has five parts:
//!
//!  * Major number, updated for incompatible API changes
//!  * Minor number, updated for backwards-compatible API additions
//!  * Patch number, updated for backwards-compatible bugfixes
//!  * Pre-release information (optional), preceded by a hyphen (`-`)
//!  * Build metadata (optional), preceded by a plus sign (`+`)
//!
//! The three mandatory components are required to be decimal numbers. The
//! pre-release information and build metadata are required to be a
//! period-separated list of identifiers containing only alphanumeric
//! characters and hyphens.
//!
//! An example version number with all five components is
//! `0.8.1-rc.3.0+20130922.linux`.

#[crate_id = "semver#0.10-pre"];
#[crate_type = "rlib"];
#[crate_type = "dylib"];
#[license = "MIT/ASL2"];

use std::char;
use std::cmp;
use std::option::{Option, Some, None};
use std::to_str::ToStr;

/// An identifier in the pre-release or build metadata. If the identifier can
/// be parsed as a decimal value, it will be represented with `Numeric`.
#[deriving(Clone, Eq)]
#[allow(missing_doc)]
pub enum Identifier {
    Numeric(uint),
    AlphaNumeric(~str)
}

impl cmp::Ord for Identifier {
    #[inline]
    fn lt(&self, other: &Identifier) -> bool {
        match (self, other) {
            (&Numeric(a), &Numeric(b)) => a < b,
            (&Numeric(_), _) => true,
            (&AlphaNumeric(ref a), &AlphaNumeric(ref b)) => *a < *b,
            (&AlphaNumeric(_), _) => false
        }
    }
}

impl ToStr for Identifier {
    #[inline]
    fn to_str(&self) -> ~str {
        match self {
            &Numeric(n) => n.to_str(),
            &AlphaNumeric(ref s) => s.to_str()
        }
    }
}

/// Represents a version number conforming to the semantic versioning scheme.
#[deriving(Clone, Eq)]
pub struct Version {
    /// The major version, to be incremented on incompatible changes.
    priv major: uint,
    /// The minor version, to be incremented when functionality is added in a
    /// backwards-compatible manner.
    priv minor: uint,
    /// The patch version, to be incremented when backwards-compatible bug
    /// fixes are made.
    priv patch: uint,
    /// The pre-release version identifier, if one exists.
    priv pre: ~[Identifier],
    /// The build metadata, ignored when determining version precedence.
    priv build: ~[Identifier],
}

impl ToStr for Version {
    #[inline]
    fn to_str(&self) -> ~str {
        let s = format!("{}.{}.{}", self.major, self.minor, self.patch);
        let s = if self.pre.is_empty() {
            s
        } else {
            format!("{}-{}", s, self.pre.map(|i| i.to_str()).connect("."))
        };
        if self.build.is_empty() {
            s
        } else {
            format!("{}+{}", s, self.build.map(|i| i.to_str()).connect("."))
        }
    }
}

impl cmp::Ord for Version {
    #[inline]
    fn lt(&self, other: &Version) -> bool {

        self.major < other.major ||

            (self.major == other.major &&
             self.minor < other.minor) ||

            (self.major == other.major &&
             self.minor == other.minor &&
             self.patch < other.patch) ||

            (self.major == other.major &&
             self.minor == other.minor &&
             self.patch == other.patch &&
             // NB: semver spec says 0.0.0-pre < 0.0.0
             // but the version of ord defined for vec
             // says that [] < [pre], so we alter it
             // here.
             (match (self.pre.len(), other.pre.len()) {
                 (0, 0) => false,
                 (0, _) => false,
                 (_, 0) => true,
                 (_, _) => self.pre < other.pre
             }))
    }

    #[inline]
    fn le(&self, other: &Version) -> bool {
        ! (other < self)
    }
    #[inline]
    fn gt(&self, other: &Version) -> bool {
        other < self
    }
    #[inline]
    fn ge(&self, other: &Version) -> bool {
        ! (self < other)
    }
}

fn take_nonempty_prefix<T:Iterator<char>>(rdr: &mut T, pred: |char| -> bool)
                        -> (~str, Option<char>) {
    let mut buf = ~"";
    let mut ch = rdr.next();
    loop {
        match ch {
            None => break,
            Some(c) if !pred(c) => break,
            Some(c) => {
                buf.push_char(c);
                ch = rdr.next();
            }
        }
    }
    debug!("extracted nonempty prefix: {}", buf);
    (buf, ch)
}

fn take_num<T: Iterator<char>>(rdr: &mut T) -> Option<(uint, Option<char>)> {
    let (s, ch) = take_nonempty_prefix(rdr, char::is_digit);
    match from_str::<uint>(s) {
        None => None,
        Some(i) => Some((i, ch))
    }
}

fn take_ident<T: Iterator<char>>(rdr: &mut T) -> Option<(Identifier, Option<char>)> {
    let (s,ch) = take_nonempty_prefix(rdr, char::is_alphanumeric);
    if s.chars().all(char::is_digit) {
        match from_str::<uint>(s) {
            None => None,
            Some(i) => Some((Numeric(i), ch))
        }
    } else {
        Some((AlphaNumeric(s), ch))
    }
}

fn expect(ch: Option<char>, c: char) -> Option<()> {
    if ch != Some(c) {
        None
    } else {
        Some(())
    }
}

fn parse_iter<T: Iterator<char>>(rdr: &mut T) -> Option<Version> {
    let maybe_vers = take_num(rdr).and_then(|(major, ch)| {
        expect(ch, '.').and_then(|_| Some(major))
    }).and_then(|major| {
        take_num(rdr).and_then(|(minor, ch)| {
            expect(ch, '.').and_then(|_| Some((major, minor)))
        })
    }).and_then(|(major, minor)| {
        take_num(rdr).and_then(|(patch, ch)| {
           Some((major, minor, patch, ch))
        })
    });

    let (major, minor, patch, ch) = match maybe_vers {
        Some((a, b, c, d)) => (a, b, c, d),
        None => return None
    };

    let mut pre = ~[];
    let mut build = ~[];

    let mut ch = ch;
    if ch == Some('-') {
        loop {
            let (id, c) = match take_ident(rdr) {
                Some((id, c)) => (id, c),
                None => return None
            };
            pre.push(id);
            ch = c;
            if ch != Some('.') { break; }
        }
    }

    if ch == Some('+') {
        loop {
            let (id, c) = match take_ident(rdr) {
                Some((id, c)) => (id, c),
                None => return None
            };
            build.push(id);
            ch = c;
            if ch != Some('.') { break; }
        }
    }

    Some(Version {
        major: major,
        minor: minor,
        patch: patch,
        pre: pre,
        build: build,
    })
}

/// Parse a string into a semver object.
pub fn parse(s: &str) -> Option<Version> {
    if !s.is_ascii() {
        return None;
    }
    let s = s.trim();
    let v = parse_iter(&mut s.chars());
    match v {
        Some(v) => {
            if v.to_str().equiv(&s) {
                Some(v)
            } else {
                None
            }
        }
        None => None
    }
}

#[test]
fn test_parse() {
    assert_eq!(parse(""), None);
    assert_eq!(parse("  "), None);
    assert_eq!(parse("1"), None);
    assert_eq!(parse("1.2"), None);
    assert_eq!(parse("1.2"), None);
    assert_eq!(parse("1"), None);
    assert_eq!(parse("1.2"), None);
    assert_eq!(parse("1.2.3-"), None);
    assert_eq!(parse("a.b.c"), None);
    assert_eq!(parse("1.2.3 abc"), None);

    assert!(parse("1.2.3") == Some(Version {
        major: 1u,
        minor: 2u,
        patch: 3u,
        pre: ~[],
        build: ~[],
    }));
    assert!(parse("  1.2.3  ") == Some(Version {
        major: 1u,
        minor: 2u,
        patch: 3u,
        pre: ~[],
        build: ~[],
    }));
    assert!(parse("1.2.3-alpha1") == Some(Version {
        major: 1u,
        minor: 2u,
        patch: 3u,
        pre: ~[AlphaNumeric(~"alpha1")],
        build: ~[]
    }));
    assert!(parse("  1.2.3-alpha1  ") == Some(Version {
        major: 1u,
        minor: 2u,
        patch: 3u,
        pre: ~[AlphaNumeric(~"alpha1")],
        build: ~[]
    }));
    assert!(parse("1.2.3+build5") == Some(Version {
        major: 1u,
        minor: 2u,
        patch: 3u,
        pre: ~[],
        build: ~[AlphaNumeric(~"build5")]
    }));
    assert!(parse("  1.2.3+build5  ") == Some(Version {
        major: 1u,
        minor: 2u,
        patch: 3u,
        pre: ~[],
        build: ~[AlphaNumeric(~"build5")]
    }));
    assert!(parse("1.2.3-alpha1+build5") == Some(Version {
        major: 1u,
        minor: 2u,
        patch: 3u,
        pre: ~[AlphaNumeric(~"alpha1")],
        build: ~[AlphaNumeric(~"build5")]
    }));
    assert!(parse("  1.2.3-alpha1+build5  ") == Some(Version {
        major: 1u,
        minor: 2u,
        patch: 3u,
        pre: ~[AlphaNumeric(~"alpha1")],
        build: ~[AlphaNumeric(~"build5")]
    }));
    assert!(parse("1.2.3-1.alpha1.9+build5.7.3aedf  ") == Some(Version {
        major: 1u,
        minor: 2u,
        patch: 3u,
        pre: ~[Numeric(1),AlphaNumeric(~"alpha1"),Numeric(9)],
        build: ~[AlphaNumeric(~"build5"),
                 Numeric(7),
                 AlphaNumeric(~"3aedf")]
    }));

}

#[test]
fn test_eq() {
    assert_eq!(parse("1.2.3"), parse("1.2.3"));
    assert_eq!(parse("1.2.3-alpha1"), parse("1.2.3-alpha1"));
    assert_eq!(parse("1.2.3+build.42"), parse("1.2.3+build.42"));
    assert_eq!(parse("1.2.3-alpha1+42"), parse("1.2.3-alpha1+42"));
}

#[test]
fn test_ne() {
    assert!(parse("0.0.0")       != parse("0.0.1"));
    assert!(parse("0.0.0")       != parse("0.1.0"));
    assert!(parse("0.0.0")       != parse("1.0.0"));
    assert!(parse("1.2.3-alpha") != parse("1.2.3-beta"));
    assert!(parse("1.2.3+23")    != parse("1.2.3+42"));
}

#[test]
fn test_lt() {
    assert!(parse("0.0.0")        < parse("1.2.3-alpha2"));
    assert!(parse("1.0.0")        < parse("1.2.3-alpha2"));
    assert!(parse("1.2.0")        < parse("1.2.3-alpha2"));
    assert!(parse("1.2.3-alpha1") < parse("1.2.3"));
    assert!(parse("1.2.3-alpha1") < parse("1.2.3-alpha2"));
    assert!(!(parse("1.2.3-alpha2") < parse("1.2.3-alpha2")));
    assert!(!(parse("1.2.3+23")     < parse("1.2.3+42")));
}

#[test]
fn test_le() {
    assert!(parse("0.0.0")        <= parse("1.2.3-alpha2"));
    assert!(parse("1.0.0")        <= parse("1.2.3-alpha2"));
    assert!(parse("1.2.0")        <= parse("1.2.3-alpha2"));
    assert!(parse("1.2.3-alpha1") <= parse("1.2.3-alpha2"));
    assert!(parse("1.2.3-alpha2") <= parse("1.2.3-alpha2"));
    assert!(parse("1.2.3+23")     <= parse("1.2.3+42"));
}

#[test]
fn test_gt() {
    assert!(parse("1.2.3-alpha2") > parse("0.0.0"));
    assert!(parse("1.2.3-alpha2") > parse("1.0.0"));
    assert!(parse("1.2.3-alpha2") > parse("1.2.0"));
    assert!(parse("1.2.3-alpha2") > parse("1.2.3-alpha1"));
    assert!(parse("1.2.3")        > parse("1.2.3-alpha2"));
    assert!(!(parse("1.2.3-alpha2") > parse("1.2.3-alpha2")));
    assert!(!(parse("1.2.3+23")     > parse("1.2.3+42")));
}

#[test]
fn test_ge() {
    assert!(parse("1.2.3-alpha2") >= parse("0.0.0"));
    assert!(parse("1.2.3-alpha2") >= parse("1.0.0"));
    assert!(parse("1.2.3-alpha2") >= parse("1.2.0"));
    assert!(parse("1.2.3-alpha2") >= parse("1.2.3-alpha1"));
    assert!(parse("1.2.3-alpha2") >= parse("1.2.3-alpha2"));
    assert!(parse("1.2.3+23")     >= parse("1.2.3+42"));
}

#[test]
fn test_spec_order() {

    let vs = ["1.0.0-alpha",
              "1.0.0-alpha.1",
              "1.0.0-alpha.beta",
              "1.0.0-beta",
              "1.0.0-beta.2",
              "1.0.0-beta.11",
              "1.0.0-rc.1",
              "1.0.0"];
    let mut i = 1;
    while i < vs.len() {
        let a = parse(vs[i-1]).unwrap();
        let b = parse(vs[i]).unwrap();
        assert!(a < b);
        i += 1;
    }
}
<|endoftext|>


<commit_before><commit_msg>Added plane example. Mostly a rehash of sphere, but still...more examples!<commit_after>extern crate tray_rust;
extern crate rand;
extern crate image;

use rand::StdRng;

use tray_rust::linalg::{AnimatedTransform, Transform, Point, Vector};
use tray_rust::film::{Colorf, RenderTarget, Camera, ImageSample};
use tray_rust::film::filter::MitchellNetravali;
use tray_rust::geometry::{Plane, Instance};
use tray_rust::material::Matte;
use tray_rust::sampler::{BlockQueue, LowDiscrepancy, Sampler};

fn main() {
    let width = 800usize;
    let height = 600usize;
    let filter =
        Box::new(MitchellNetravali::new(2.0, 2.0, 0.333333333333333333, 0.333333333333333333));
    let rt = RenderTarget::new((width, height), (20, 20), filter);
    let transform =
        AnimatedTransform::unanimated(&Transform::look_at(&Point::new(0.0, 0.0, -10.0),
                                                          &Point::new(0.0, 0.0, 0.0),
                                                          &Vector::new(0.0, 1.0, 0.0)));
    let camera = Camera::new(transform, 40.0, rt.dimensions(), 0.5, 0);
    let plane = Plane {};
    let geometry_lock = std::sync::Arc::new(plane);
    let white_wall = Matte::new(&Colorf::new(0.740063, 0.742313, 0.733934), 1.0);
    let material_lock = std::sync::Arc::new(white_wall);
    let position_transform =
        AnimatedTransform::unanimated(&Transform::translate(&Vector::new(0.0, 2.0, 0.0)));
    let instance = Instance::receiver(geometry_lock,
                                      material_lock,
                                      position_transform,
                                      "single_plane".to_string());

    let dim = rt.dimensions();
    // A block queue is how work is distributed among threads, it's a list of tiles
    // of the image that have yet to be rendered. Each thread will pull a block from
    // this queue and render it.
    let block_queue = BlockQueue::new((dim.0 as u32, dim.1 as u32), (8, 8), (0, 0));
    let block_dim = block_queue.block_dim();
    // A sample is responsible for choosing randomly placed locations within a pixel to
    // get a good sampling of the image. Using a poor quality sampler will resuly in a
    // noiser and more aliased image that converges slower. The LowDiscrepency sampler
    // is a good choice for quality.
    let mut sampler = LowDiscrepancy::new(block_dim, 2);
    let mut sample_pos = Vec::with_capacity(sampler.max_spp());
    let mut block_samples = Vec::with_capacity(sampler.max_spp() *
                                               (block_dim.0 * block_dim.1) as usize);
    let mut rng = match StdRng::new() {
        Ok(r) => r,
        Err(e) => {
            println!("Failed to get StdRng, {}", e);
            return;
        }
    };
    // Grab a block from the queue and start working on it, submitting samples
    // to the render target thread after each pixel
    for b in block_queue.iter() {
        sampler.select_block(b);
        // While the sampler has samples left to take for this pixel, take some samples
        while sampler.has_samples() {
            // Get samples for a pixel and render them
            sampler.get_samples(&mut sample_pos, &mut rng);
            for s in &sample_pos[..] {
                let mut ray = camera.generate_ray(s, 0.0);
                if let Some(_) = instance.intersect(&mut ray) {
                    block_samples.push(ImageSample::new(s.0, s.1, Colorf::broadcast(1.0)));
                } else {
                    // For correct filtering we also MUST set a background color of some kind
                    // if we miss, otherwise the pixel weights will be wrong and we'll see object
                    // fringes and artifacts at object boundaries w/ nothing. Try removing this
                    // line and rendering again.
                    block_samples.push(ImageSample::new(s.0, s.1, Colorf::black()));
                }
            }
        }
        // We write all samples at once so we don't need to lock the render target tiles as often
        rt.write(&block_samples, sampler.get_region());
        block_samples.clear();
    }

    // Get the sRGB8 render buffer from the floating point framebuffer and save it
    let img = rt.get_render();
    match image::save_buffer("plane.png",
                             &img[..],
                             dim.0 as u32,
                             dim.1 as u32,
                             image::RGB(8)) {
        Ok(_) => {}
        Err(e) => println!("Error saving image, {}", e),
    };
}
<|endoftext|>


<commit_before><commit_msg>Can find&print the lowest detached session number!<commit_after>extern mod std;

use std::run;
use std::str;
use std::option::*;
use std::trie::*;

fn session_is_attached(line: &str) -> bool {
    line.ends_with("(attached)")
}

fn session_number(line: &str) -> Option<uint> {
    line.split_iter(':').next().and_then(|s| from_str(s))
}

fn detached_sessions(output: ~str) -> TrieSet {
    let mut set = TrieSet::new();
    for line in output.line_iter(){
        if !session_is_attached(line) {
            match session_number(line) {
                Some(n) => { set.insert(n); }
                None => ()
            }
        }
    }
    set
}

fn main() {
    let proc = run::process_output("/usr/local/bin/tmux", &[~"list-sessions"]);
    if proc.status != 0 {
        fail!(fmt!("Tmux exited with an error status: %d", proc.status));
    }
    let output = str::from_utf8(proc.output);
    let sessions = detached_sessions(output);
    match sessions.iter().next() {
        Some(n) => { println(fmt!("Can attach to %u", n)); }
        _ => { println("Have no sessions to attach to"); }
    }
}

#[test]
fn test_session_is_attached() {
    assert!(session_is_attached("11: 1 windows (created Sat Sep 14 17:11:29 2013) [130x65] (attached)"));
    assert!(!session_is_attached("20: 1 windows (created Sat Sep 14 17:11:29 2013) [130x65]"));
}

#[test]
fn test_session_number_with_numbers(){
    match(session_number("11: 1 windows (created Sat Sep 14 17:11:29 2013) [130x65] (attached)")) {
        Some(11) => (),
        Some(n) => fail!(fmt!("Should have returned 11, got %u!", n)),
        None => fail!("Should have returned something, got nothing"),
    }
}

#[test]
fn test_session_number_with_strings(){
    match(session_number("oink: 1 windows (created Sat Sep 14 17:11:29 2013) [130x65] (attached)")) {
        Some(n) => fail!(fmt!("Should have returned None, got %u!", n)),
        None => ()
    }
}

#[test]
fn test_detached_sessions() {
    let set = detached_sessions(~"3: foo (attached)\n2: bar\n4: abz (attached)\nfoo: baz");
    assert!(!set.contains(&2));
    assert!(set.contains(&3));
    assert!(set.contains(&4));
    assert!(!set.contains(&1));
}
<|endoftext|>


<commit_before><commit_msg>Modified example client to use cmdline args<commit_after><|endoftext|>


<commit_before><commit_msg>Add a Vulkan example<commit_after>// Copyright 2013 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// 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.
#![cfg(feature = "vulkan")]

extern crate glfw;
extern crate vk_sys;

use std::os::raw::c_void;
use std::mem;
use std::ptr;

use vk_sys::{
    self as vk,
    EntryPoints,
    InstancePointers,
    InstanceCreateInfo,
    Instance as VkInstance,
    Result as VkResult
};

use glfw::Context;

fn main() {
    let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();

    glfw.window_hint(glfw::WindowHint::Visible(true));

    let (mut window, _) = glfw.create_window(640, 480, "Defaults", glfw::WindowMode::Windowed)
                              .expect("Failed to create GLFW window.");

    window.make_current();

    assert!(glfw.vulkan_supported());

    let required_extensions = glfw.get_required_instance_extensions().unwrap_or(vec![]);

    //VK_KHR_surface will always be available if the previous operations were successful
    assert!(required_extensions.contains(&"VK_KHR_surface".to_string()));

    println!("Vulkan required extensions: {:?}", required_extensions);

    //Load up all the entry points using 0 as the VkInstance,
    //since you can't have an instance before you get vkCreateInstance...
    let mut entry_points: EntryPoints = EntryPoints::load(|func| {
        window.get_instance_proc_address(0, func.to_str().unwrap()) as *const c_void
    });

    let instance: VkInstance = unsafe { create_instance(&mut entry_points) };

    let mut instance_ptrs: InstancePointers = InstancePointers::load(|func| {
        window.get_instance_proc_address(instance, func.to_str().unwrap()) as *const c_void
    });

    //Load other pointers and do other Vulkan stuff here

    unsafe {
        destroy_instance(instance, &mut instance_ptrs);
    }

    println!("Vulkan instance successfully created and destroyed.");
}

unsafe fn create_instance(entry_points: &mut EntryPoints) -> VkInstance {
    let mut instance: VkInstance = mem::uninitialized();

    //This is literally the bare minimum required to create a blank instance
    //You'll want to fill in this with real data yourself
    let info: InstanceCreateInfo = InstanceCreateInfo {
        sType: vk::STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
        pNext: ptr::null(),
        flags: 0,
        pApplicationInfo: ptr::null(),
        enabledLayerCount: 0,
        ppEnabledLayerNames: ptr::null(),
        //These two should use the extensions returned by window.get_required_instance_extensions
        enabledExtensionCount: 0,
        ppEnabledExtensionNames: ptr::null()
    };

    let res: VkResult = entry_points.CreateInstance(&info as *const InstanceCreateInfo,
                                                    ptr::null(),
                                                    &mut instance as *mut VkInstance);

    assert_eq!(res, vk::SUCCESS);

    instance
}

unsafe fn destroy_instance(instance: VkInstance, instance_ptrs: &mut InstancePointers) {
    instance_ptrs.DestroyInstance(instance, ptr::null());
}<|endoftext|>


<commit_before><commit_msg>Optimize async variant<commit_after><|endoftext|>


<commit_before><commit_msg>87 opcode<commit_after><|endoftext|>