<commit_before>pub fn scoping() {
    println!("***Scoping***");

    raii();
    ownership_and_moves();
    borrowing();

    println!("");
}

fn raii() {
    fn create_box() {
        // allocate an i32 on the heap
        let _box1 = Box::new(3_i32);

        // box gets destroyed here, memory gets freed
    }

    let _box2 = Box::new(5_i32);

    // a nested scope

    {
        let _box3 = Box::new(4_i32);

        // _box3 is destroyed here
    }

    // creating lots of boxes just for fun
    // they're not bound to anything so they get immediately destroyed
    for _ in 0_u32..1_000 {
        create_box();
    }

    // _box2 destroyed here
}

fn ownership_and_moves() {
    fn destroy_box(c: Box<i32>) {
        println!("Destroying a box that contains {}", c);

        // c is destroyed and memory freed
    }

    // a stack allocated integer
    let x = 5_u32;

    // x gets copied because u32 is a Copy type & it's on the stack
    let y = x;

    // both can be accessed
    println!("x is {}, and y is {}", x, y);

    // a is a ptr to heap allocated i32
    let a = Box::new(5_i32);

    println!("a contains: {}", a);

    // moving a into b
    let b = a;

    println!("b contains: {}", b);

    // a does not own it anymore, it can't be accessed
    // println!("a contains: {}", a);

    destroy_box(b);

    // Heap memory has been freed at this point, can't access b
    // println!("b now contains: {}", b);

    // mutability

    let immutable_box = Box::new(5_u32);

    println!("immutable box contains: {}", immutable_box);

    // mutability error
    // *immutable_box = 4;

    // move it into the mutable binding, changes mutability
    let mut mutable_box = immutable_box;

    println!("mutable_box contains: {}", mutable_box);

    *mutable_box = 4;

    println!("mutable_box now contains: {}", mutable_box);
}

fn borrowing() {
    // function takes ownership of a box and destroyes it
    fn eat_box_i32(boxed_i32: Box<i32>) {
        println!("Eating a box that contains: {}", boxed_i32);
    }

    // this function borrows an i32
    fn borrow_i32(borrowed_i32: &i32) {
        println!("This int is: {}", borrowed_i32);
    }

    // create a boxed i32 and stacked i32
    let boxed_i32 = Box::new(5_i32);
    let stacked_i32 = 6_i32;

    // borrow the contents of the box
    // does not take ownership -> contents can be borrowed again
    borrow_i32(&boxed_i32);
    borrow_i32(&stacked_i32);

    {
        // take a reference to the data inside the box
        let _ref_to_i32: &i32 = &boxed_i32;

        // can't destroy boxed_i32 while the inner value is borrowed
        // eat_box_i32(boxed_i32);
    } // ref_to_i32 goes out of scope - no longer borrowed

    // no more borrows
    // now it can give up its ownership and be destroyed
    eat_box_i32(boxed_i32);

    /* mutability */

    #[derive(Clone, Copy)]
    struct Book {
        author: &'static str,
        title: &'static str,
        year: u32,
    }

    fn borrow_book(book: &Book) {
        println!("I immmutably borrowed {} - {} edition", book.title, book.year);
    }

    fn new_edition(book: &mut Book) {
        book.year = 2017;
        println!("I mutably borrowed {} - {} edition", book.title, book.year);
    }

    let immutabook = Book {
        author: "George R. R. Martin",
        title: "A Game of Thrones",
        year: 1996,
    };

    // mutable copy of immutabook
    let mut mutabook = immutabook;

    borrow_book(&immutabook);

    borrow_book(&mutabook);

    new_edition(&mut mutabook);

    // can't borrow immutable object as mutable
    // new_edition(&mut immutabook);

    /* freezing */

    let mut _mutable_int = 7_i32;

    {
        let _large_int = &_mutable_int;

        // _mutable_int is frozen because it was borrowed!
        // _mutable_int = 50;
    }

    // it's okay here, not borrowed anymore
    _mutable_int = 3;

    struct Point {
        x: i32,
        y: i32,
        z: i32,
    }

    let mut point = Point {
        x: 0,
        y: 0,
        z: 0,
    };

    {
        let borrowed_point = &point;
        let another_borrow = &point;

        // data can be accessed by references and the original owner
        println!("Point is: ({},{},{})", borrowed_point.x, another_borrow.y, point.z);

        // can't borrow mutably - it's already borrowed as immutable
        // let mutable_borrow = &mut point;
    }

    {
        let mutable_borrow = &mut point;

        mutable_borrow.x = 5;
        mutable_borrow.y = 2;
        mutable_borrow.z = 1;

        // can't borrow as immutable - currently borrowed as mutable
        // let y = &point.y;

        // mutable references can be passed as immutable to println

        println!("Point is: ({},{},{})", mutable_borrow.x, mutable_borrow.y, mutable_borrow.z);
    }

    // immutable references to point are allowed again
    let borrowed_point = &point;
    println!("Point is: ({},{},{})", borrowed_point.x, borrowed_point.y, borrowed_point.z);

    /* the ref pattern */
    {
        #[derive(Clone, Copy)]
        struct Point {
            x: i32,
            y: i32,
        }

        let c = 'Q';

        // both have the same effect
        let ref ref_c1 = c;
        let ref_c2 = &c;

        println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);

        let point = Point { x: 0, y: 0 };

        let _copy_of_x = {
            // ref_to_x points to the x field of a point
            let Point { x: ref ref_to_x, y: _ } = point;

            // return a copy of the 'x' field
            *ref_to_x
        };

        // a mutable copy of 'point'
        let mut mutable_point = point;

        {
            let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;

            *mut_ref_to_y = 1;
        }

        println!("point is: ({},{})", point.x, point.y);
        println!("mutable point is: ({},{})", mutable_point.x, mutable_point.y);

        // a mutable tuple that includes a pointer
        let mut mutable_tuple = (Box::new(5_u32), 3_u32);

        {
            let (_, ref mut last) = mutable_tuple;
            *last = 2_u32;
        }

        println!("tuple is: {:?}", mutable_tuple);
    }
}
<commit_msg>[Rust] Rust by Example - Scoping - Lifetimes<commit_after>pub fn scoping() {
    println!("***Scoping***");

    raii();
    ownership_and_moves();
    borrowing();
    lifetimes();

    println!("");
}

fn raii() {
    fn create_box() {
        // allocate an i32 on the heap
        let _box1 = Box::new(3_i32);

        // box gets destroyed here, memory gets freed
    }

    let _box2 = Box::new(5_i32);

    // a nested scope

    {
        let _box3 = Box::new(4_i32);

        // _box3 is destroyed here
    }

    // creating lots of boxes just for fun
    // they're not bound to anything so they get immediately destroyed
    for _ in 0_u32..1_000 {
        create_box();
    }

    // _box2 destroyed here
}

fn ownership_and_moves() {
    fn destroy_box(c: Box<i32>) {
        println!("Destroying a box that contains {}", c);

        // c is destroyed and memory freed
    }

    // a stack allocated integer
    let x = 5_u32;

    // x gets copied because u32 is a Copy type & it's on the stack
    let y = x;

    // both can be accessed
    println!("x is {}, and y is {}", x, y);

    // a is a ptr to heap allocated i32
    let a = Box::new(5_i32);

    println!("a contains: {}", a);

    // moving a into b
    let b = a;

    println!("b contains: {}", b);

    // a does not own it anymore, it can't be accessed
    // println!("a contains: {}", a);

    destroy_box(b);

    // Heap memory has been freed at this point, can't access b
    // println!("b now contains: {}", b);

    // mutability

    let immutable_box = Box::new(5_u32);

    println!("immutable box contains: {}", immutable_box);

    // mutability error
    // *immutable_box = 4;

    // move it into the mutable binding, changes mutability
    let mut mutable_box = immutable_box;

    println!("mutable_box contains: {}", mutable_box);

    *mutable_box = 4;

    println!("mutable_box now contains: {}", mutable_box);
}

fn borrowing() {
    // function takes ownership of a box and destroyes it
    fn eat_box_i32(boxed_i32: Box<i32>) {
        println!("Eating a box that contains: {}", boxed_i32);
    }

    // this function borrows an i32
    fn borrow_i32(borrowed_i32: &i32) {
        println!("This int is: {}", borrowed_i32);
    }

    // create a boxed i32 and stacked i32
    let boxed_i32 = Box::new(5_i32);
    let stacked_i32 = 6_i32;

    // borrow the contents of the box
    // does not take ownership -> contents can be borrowed again
    borrow_i32(&boxed_i32);
    borrow_i32(&stacked_i32);

    {
        // take a reference to the data inside the box
        let _ref_to_i32: &i32 = &boxed_i32;

        // can't destroy boxed_i32 while the inner value is borrowed
        // eat_box_i32(boxed_i32);
    } // ref_to_i32 goes out of scope - no longer borrowed

    // no more borrows
    // now it can give up its ownership and be destroyed
    eat_box_i32(boxed_i32);

    /* mutability */

    #[derive(Clone, Copy)]
    struct Book {
        author: &'static str,
        title: &'static str,
        year: u32,
    }

    fn borrow_book(book: &Book) {
        println!("I immmutably borrowed {} - {} edition", book.title, book.year);
    }

    fn new_edition(book: &mut Book) {
        book.year = 2017;
        println!("I mutably borrowed {} - {} edition", book.title, book.year);
    }

    let immutabook = Book {
        author: "George R. R. Martin",
        title: "A Game of Thrones",
        year: 1996,
    };

    // mutable copy of immutabook
    let mut mutabook = immutabook;

    borrow_book(&immutabook);

    borrow_book(&mutabook);

    new_edition(&mut mutabook);

    // can't borrow immutable object as mutable
    // new_edition(&mut immutabook);

    /* freezing */

    let mut _mutable_int = 7_i32;

    {
        let _large_int = &_mutable_int;

        // _mutable_int is frozen because it was borrowed!
        // _mutable_int = 50;
    }

    // it's okay here, not borrowed anymore
    _mutable_int = 3;

    struct Point {
        x: i32,
        y: i32,
        z: i32,
    }

    let mut point = Point {
        x: 0,
        y: 0,
        z: 0,
    };

    {
        let borrowed_point = &point;
        let another_borrow = &point;

        // data can be accessed by references and the original owner
        println!("Point is: ({},{},{})", borrowed_point.x, another_borrow.y, point.z);

        // can't borrow mutably - it's already borrowed as immutable
        // let mutable_borrow = &mut point;
    }

    {
        let mutable_borrow = &mut point;

        mutable_borrow.x = 5;
        mutable_borrow.y = 2;
        mutable_borrow.z = 1;

        // can't borrow as immutable - currently borrowed as mutable
        // let y = &point.y;

        // mutable references can be passed as immutable to println

        println!("Point is: ({},{},{})", mutable_borrow.x, mutable_borrow.y, mutable_borrow.z);
    }

    // immutable references to point are allowed again
    let borrowed_point = &point;
    println!("Point is: ({},{},{})", borrowed_point.x, borrowed_point.y, borrowed_point.z);

    /* the ref pattern */
    {
        #[derive(Clone, Copy)]
        struct Point {
            x: i32,
            y: i32,
        }

        let c = 'Q';

        // both have the same effect
        let ref ref_c1 = c;
        let ref_c2 = &c;

        println!("ref_c1 equals ref_c2: {}", *ref_c1 == *ref_c2);

        let point = Point { x: 0, y: 0 };

        let _copy_of_x = {
            // ref_to_x points to the x field of a point
            let Point { x: ref ref_to_x, y: _ } = point;

            // return a copy of the 'x' field
            *ref_to_x
        };

        // a mutable copy of 'point'
        let mut mutable_point = point;

        {
            let Point { x: _, y: ref mut mut_ref_to_y } = mutable_point;

            *mut_ref_to_y = 1;
        }

        println!("point is: ({},{})", point.x, point.y);
        println!("mutable point is: ({},{})", mutable_point.x, mutable_point.y);

        // a mutable tuple that includes a pointer
        let mut mutable_tuple = (Box::new(5_u32), 3_u32);

        {
            let (_, ref mut last) = mutable_tuple;
            *last = 2_u32;
        }

        println!("tuple is: {:?}", mutable_tuple);
    }
}

fn lifetimes() {
    /* explicit annotation */
    {
        // fn takes two references to i32 which have different lifetimes
        // 'a and 'b. These two lifetimes must both be at least as long
        // as the function print_refs
        fn print_refs<'a, 'b>(x: &'a i32, y: &'b i32) {
            println!("x is {} and y is {}", x, y);
        }

        // a function which takes no arguments
        // but has a lifetime parameter a
        fn failed_borrow<'a>() {
            let _x = 12;

            // _x does not live long enough
            // let y: &'a i32 = &_x;
            // attempting to use the lifetime 'a as an explicit type annotation
            // inside the function will fail because the lifetime &_x is shorter
            // than that of y
        }

        let (four, nine) = (4, 9);
        // passes borrows into a function
        print_refs(&four, &nine);
        // any input which is borrowed must outlive the borrower
        // the lifetime of four and nine must be longer
        // than that of print_refs

        failed_borrow();
        // it contains no references to force 'a to be
        // longer than the lifetime of the function but 'a is longer
        // because the lifetime is not constrained, it defaults to static
    }

    /* functions */
    {
        // input with lifetime 'a must live at least as long as the function
        fn print_one<'a>(x: &'a i32) {
            println!("print_one: x is {}", x);
        }

        // mutable references are possible with lifetimes as well
        fn add_one<'a>(x: &'a mut i32) {
            *x += 1;
        }

        // multiple elements with different lifetimes
        // in this case it would be fine for both to have the same lifetime 'a
        fn print_multi<'a, 'b>(x: &'a i32, y: &'b i32) {
            println!("print_multi: x is {}, y is {}", x, y);
        }

        // returning references that have been passed in is acceptable
        // the correct lifetime must be returned
        fn pass_x<'a, 'b>(x: &'a i32, _: &'b i32) -> &'a i32 {
            x
        }

        let (x, y) = (7, 9);
        print_one(&x);
        print_multi(&x, &y);

        let z = pass_x(&x, &y);
        print_one(z);

        let mut t = 3;
        add_one(&mut t);
        print_one(&t);
    }

    /* methods */
    {
        struct Owner(i32);

        impl Owner {
            fn add_one<'a>(&'a mut self) {
                self.0 += 1
            }

            fn print<'a>(&'a self) {
                println!("print: {}", self.0);
            }
        }

        let mut owner = Owner(18);
        owner.add_one();
        owner.print();
    }

    /* structs */
    {
        // a reference to i32 must outlive the struct
        #[derive(Debug)]
        struct Borrowed<'a>(&'a i32);

        // both references must outlive the structure
        #[derive(Debug)]
        struct NamedBorrowed<'a> {
            x: &'a i32,
            y: &'a i32,
        }

        // an enum which is either an i32 or a reference to one
        #[derive(Debug)]
        enum Either<'a> {
            Num(i32),
            Ref(&'a i32),
        }

        let x = 18;
        let y = 15;

        let single = Borrowed(&x);
        let double = NamedBorrowed {
            x: &x,
            y: &y,
        };
        let reference = Either::Ref(&x);
        let number = Either::Num(y);

        println!("x is borrowed in {:?}", single);
        println!("x and y are borrowed in {:?}", double);
        println!("x is borrowed in {:?}", reference);
        println!("y is *not* borrowed in {:?}", number);
    }

    /* bounds */
    {
        use std::fmt::Debug;

        #[derive(Debug)]
        struct Ref<'a, T: 'a>(&'a T);
        // Ref contains a reference to generic type T that has an unknown lifetime 'a
        // T is bounded such that any references in T must outlive 'a
        // the lifetime of Ref may not exceed 'a

        fn print<T>(t: T) where T: Debug {
            println!("print: t is {:?}", t);
        }

        // a reference to T is taken where T implements Debug
        // all references in T outlive 'a
        // 'a must outlive the function
        fn print_ref<'a, T>(t: &'a T) where T: Debug + 'a {
            println!("print_ref: t is {:?}", t);
        }

        let x = 7;
        let ref_x = Ref(&x);

        print_ref(&ref_x);
        print(ref_x);
    }

    /* coercion */
    {
        // Rust infers a lifetime that is as short as possible
        // two references are then coerced to that lifetime
        fn multiply<'a>(first: &'a i32, second: &'a i32) -> i32 {
            first * second
        }

        // <'a: 'b, 'b> - lifetime 'a is at least as long as 'b
        // we take in an &'a i32 and return a &'b i32 as a result of coercion
        fn choose_first<'a: 'b, 'b>(first: &'a i32, _: &'b i32) -> &'b i32 {
            first
        }

        let first = 2; // longer lifetime

        {
            let second = 3; // shorter lifetime
            println!("the product is {}", multiply(&first, &second));

            println!("{} is the first", choose_first(&first, &second));
        }
    }

    /* static */
    {
        // a constant with a 'static lifetime
        static NUM: i32 = 18;

        // returns a reference to NUM where its static
        // lifetime is coerced to that of the input argument
        fn coerce_static<'a>(_: &'a i32) -> &'a i32 {
            &NUM
        }

        {
            let static_string = "I'm in read-only memory";
            println!("static_string: {}", static_string);

            // when the reference goes out of scope, str can no longer be used
            // but the data remains in the binary
        }

        {
            let lifetime_num = 9;

            // coerce NUM to the lifetime of lifetime_num
            let coerced_static = coerce_static(&lifetime_num);

            println!("coerced static: {}", coerced_static);
        }

        println!("NUM: {} stays accessible!", NUM);
    }

    /* elision */
    {
        fn elided_input(x: &i32) {
            println!("elided_input: {}", x);
        }

        fn annotated_input<'a>(x: &'a i32) {
            println!("annotated_input: {}", x);
        }

        fn elided_pass(x: &i32) -> &i32 {
            x
        }

        fn annotated_pass<'a>(x: &'a i32) -> &'a i32 {
            x
        }

        let x = 3;

        elided_input(&x);
        annotated_input(&x);

        println!("elided_pass: {}", elided_pass(&x));
        println!("annotated pass: {}", annotated_pass(&x));
    }
}
<|endoftext|>


<commit_before>#![cfg(any(
    target_os = "windows",
    target_os = "macos",
    target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"
))]

use event::Event;
use event_loop::{EventLoop, EventLoopWindowTarget, ControlFlow};

/// Additional methods on `EventLoop` that are specific to desktop platforms.
pub trait EventLoopExtDesktop {
    /// A type provided by the user that can be passed through `Event::UserEvent`.
    type UserEvent;

    /// Initializes the `winit` event loop.
    ///
    /// Unlike `run`, this function accepts non-`'static` (i.e. non-`move`) closures and returns
    /// control flow to the caller when `control_flow` is set to `ControlFlow::Exit`.
    fn run_return<F>(&mut self, event_handler: F)
        where F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>, &mut ControlFlow);
}

impl<T> EventLoopExtDesktop for EventLoop<T> {
    type UserEvent = T;

    fn run_return<F>(&mut self, event_handler: F)
        where F: FnMut(Event<T>, &EventLoopWindowTarget<T>, &mut ControlFlow)
    {
        self.event_loop.run_return(event_handler)
    }
}
<commit_msg>Document the caveats of run_return (#914)<commit_after>#![cfg(any(
    target_os = "windows",
    target_os = "macos",
    target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"
))]

use event::Event;
use event_loop::{EventLoop, EventLoopWindowTarget, ControlFlow};

/// Additional methods on `EventLoop` that are specific to desktop platforms.
pub trait EventLoopExtDesktop {
    /// A type provided by the user that can be passed through `Event::UserEvent`.
    type UserEvent;

    /// Initializes the `winit` event loop.
    ///
    /// Unlike `run`, this function accepts non-`'static` (i.e. non-`move`) closures and returns
    /// control flow to the caller when `control_flow` is set to `ControlFlow::Exit`.
    ///
    /// # Caveats
    /// Despite its apperance at first glance, this is *not* a perfect replacement for
    /// `poll_events`. For example, this function will not return on Windows or macOS while a
    /// window is getting resized, resulting in all application logic outside of the
    /// `event_handler` closure not running until the resize operation ends. Other OS operations
    /// may also result in such freezes. This behavior is caused by fundamental limitations in the
    /// underyling OS APIs, which cannot be hidden by Winit without severe stability reprecussions.
    ///
    /// You are strongly encouraged to use `run`, unless the use of this is absolutely necessary.
    fn run_return<F>(&mut self, event_handler: F)
        where F: FnMut(Event<Self::UserEvent>, &EventLoopWindowTarget<Self::UserEvent>, &mut ControlFlow);
}

impl<T> EventLoopExtDesktop for EventLoop<T> {
    type UserEvent = T;

    fn run_return<F>(&mut self, event_handler: F)
        where F: FnMut(Event<T>, &EventLoopWindowTarget<T>, &mut ControlFlow)
    {
        self.event_loop.run_return(event_handler)
    }
}
<|endoftext|>


<commit_before>use std::marker::PhantomData;
use par_exec::{Executor, ExecutorJobError, JobExecuteError};

use super::PopulationFit;
use super::super::individual::{Individual, IndividualManager};
use super::super::super::set::{Set, SetManager};
use super::super::super::set::union;

pub trait RetrieveFitsManager {
    type FitsM;

    fn retrieve(&mut self) -> &mut Self::FitsM;
}

pub trait RetrieveIndividualManager {
    type IM;

    fn retrieve(&mut self) -> &mut Self::IM;
}

pub trait Policy {
    type LocalContext: RetrieveFitsManager<FitsM = Self::FitsM> + RetrieveIndividualManager<IM = Self::IndivM>;
    type Exec: Executor<LC = Self::LocalContext>;

    type Indiv: Individual;
    type Fit;
    type IndivME: Send + 'static;
    type IndivM: IndividualManager<I = Self::Indiv, FI = Self::Fit, E = Self::IndivME>;

    type PopE: Send + 'static;
    type Pop: Set<T = Self::Indiv, E = Self::PopE>;

    type FitsE: Send + 'static;
    type Fits: Set<T = (Self::Fit, usize), E = Self::FitsE> + Send + 'static;
    type FitsME: Send + 'static;
    type FitsM: SetManager<S = Self::Fits, E = Self::FitsME>;
}
<commit_msg>basic implementation skeleton<commit_after>use std::marker::PhantomData;
use par_exec::{Executor, ExecutorJobError, JobExecuteError};

use super::PopulationFit;
use super::super::individual::{Individual, IndividualManager};
use super::super::super::set::{Set, SetManager};
use super::super::super::set::union;

pub trait RetrieveFitsManager {
    type FitsM;

    fn retrieve(&mut self) -> &mut Self::FitsM;
}

pub trait RetrieveIndividualManager {
    type IM;

    fn retrieve(&mut self) -> &mut Self::IM;
}

pub trait Policy {
    type LocalContext: RetrieveFitsManager<FitsM = Self::FitsM> + RetrieveIndividualManager<IM = Self::IndivM>;
    type Exec: Executor<LC = Self::LocalContext>;

    type Indiv: Individual;
    type Fit;
    type IndivME: Send + 'static;
    type IndivM: IndividualManager<I = Self::Indiv, FI = Self::Fit, E = Self::IndivME>;

    type PopE: Send + 'static;
    type Pop: Set<T = Self::Indiv, E = Self::PopE>;

    type FitsE: Send + 'static;
    type Fits: Set<T = (Self::Fit, usize), E = Self::FitsE> + Send + 'static;
    type FitsME: Send + 'static;
    type FitsM: SetManager<S = Self::Fits, E = Self::FitsME>;
}

pub struct StandardPopulationFit<P> where P: Policy {
    _marker: PhantomData<P>,
}

impl<P> StandardPopulationFit<P> where P: Policy {
    pub fn new() -> StandardPopulationFit<P> {
        StandardPopulationFit {
            _marker: PhantomData,
        }
    }
}

#[derive(Debug)]
pub enum FitnessError<PE, FE, FME, IME> {
    Population(PE),
    FitsSet(FE),
    FitsSetManager(FME),
    IndividualManager(IME),
}

#[derive(Debug)]
pub enum Error<ExecE, PopE, FitsE, FitsME, IndivME> {
    NoOutputFitnessValues,
    Executor(ExecutorJobError<ExecE, JobExecuteError<FitnessError<PopE, FitsE, FitsME, IndivME>, union::Error<FitsE, FitsME>>>),
}

pub type ErrorP<P> where P: Policy = Error<<P::Exec as Executor>::E, P::PopE, P::FitsE, P::FitsME, P::IndivME>;

impl<P> PopulationFit for StandardPopulationFit<P> where P: Policy {
    type Exec = P::Exec;
    type Indiv = P::Indiv;
    type Pop = P::Pop;
    type Fit = P::Fit;
    type Fits = P::Fits;
    type Err = ErrorP<P>;

    fn fit(&self, _population: &Self::Pop, _exec: &mut Self::Exec) -> Result<Self::Fits, Self::Err> {
        Err(Error::NoOutputFitnessValues::<<Self::Exec as Executor>::E, P::PopE, P::FitsE, P::FitsME, P::IndivME>)
    }
}
<|endoftext|>


<commit_before>// This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.

//! Generators.
//!
//! Generators allow repeatedly suspending the execution of a function,
//! returning a value to the caller, and resuming the suspended function
//! afterwards.

use core::marker::PhantomData;
use core::{ptr, mem};
use core::cell::Cell;

use stack;
use debug;
use arch::{self, StackPointer};

#[derive(Debug, Clone, Copy)]
pub enum State {
  /// Generator can be resumed. This is the initial state.
  Runnable,
  /// Generator cannot be resumed. This is the state of the generator after
  /// the generator function has returned or panicked.
  Unavailable
}

/// Generator wraps a function and allows suspending its execution more than once, returning
/// a value each time.
///
/// The first time `resume(input0)` is called, the function is called as `f(yielder, input0)`.
/// It runs until it suspends its execution through `yielder.suspend(output0)`, after which
/// `resume(input0)` returns `output0`. The function can be resumed again using `resume(input1)`,
/// after which `yielder.suspend(output0)` returns `input1`, and so on. Once the function returns,
/// the `resume()` call will return `None`, and it will return `None` every time it is called
/// after that.
///
/// If the generator function panics, the panic is propagated through the `resume()` call as usual.
///
/// After the generator function returns or panics, it is safe to reclaim the generator stack
/// using `unwrap()`.
///
/// `state()` can be used to determine whether the generator function has returned;
/// the state is `State::Runnable` after creation and suspension, and `State::Unavailable`
/// once the generator function returns or panics.
///
/// When the input type is `()`, a generator implements the Iterator trait.
///
/// # Example
///
/// ```
/// use fringe::{OsStack, Generator};
///
/// let stack = OsStack::new(0).unwrap();
/// let mut add_one = Generator::new(stack, move |yielder, mut input| {
///   loop {
///     if input == 0 { break }
///     input = yielder.suspend(input + 1)
///   }
/// });
/// println!("{:?}", add_one.resume(2)); // prints Some(3)
/// println!("{:?}", add_one.resume(3)); // prints Some(4)
/// println!("{:?}", add_one.resume(0)); // prints None
/// ```
///
/// # Iterator example
///
/// ```
/// use fringe::{OsStack, Generator};
///
/// let stack = OsStack::new(0).unwrap();
/// let mut nat = Generator::new(stack, move |yielder, ()| {
///   for i in 1.. { yielder.suspend(i) }
/// });
/// println!("{:?}", nat.next()); // prints Some(0)
/// println!("{:?}", nat.next()); // prints Some(1)
/// println!("{:?}", nat.next()); // prints Some(2)
/// ```
#[derive(Debug)]
pub struct Generator<'a, Input: Send + 'a, Output: Send + 'a, Stack: stack::Stack> {
  state:     State,
  stack:     Stack,
  stack_id:  debug::StackId,
  stack_ptr: arch::StackPointer,
  phantom:   PhantomData<(&'a (), *mut Input, *const Output)>
}

unsafe impl<'a, Input, Output, Stack> Send for Generator<'a, Input, Output, Stack>
  where Input: Send + 'a, Output: Send + 'a, Stack: stack::Stack + Send {}

impl<'a, Input, Output, Stack> Generator<'a, Input, Output, Stack>
    where Input: Send + 'a, Output: Send + 'a, Stack: stack::Stack {
  /// Creates a new generator.
  ///
  /// See also the [contract](../trait.GuardedStack.html) that needs to be fulfilled by `stack`.
  pub fn new<F>(stack: Stack, f: F) -> Generator<'a, Input, Output, Stack>
      where Stack: stack::GuardedStack,
            F: FnOnce(&Yielder<Input, Output>, Input) + Send + 'a {
    unsafe { Generator::unsafe_new(stack, f) }
  }

  /// Same as `new`, but does not require `stack` to have a guard page.
  ///
  /// This function is unsafe because the generator function can easily violate
  /// memory safety by overflowing the stack. It is useful in environments where
  /// guarded stacks do not exist, e.g. in absence of an MMU.
  ///
  /// See also the [contract](../trait.Stack.html) that needs to be fulfilled by `stack`.
  pub unsafe fn unsafe_new<F>(stack: Stack, f: F) -> Generator<'a, Input, Output, Stack>
      where F: FnOnce(&Yielder<Input, Output>, Input) + Send + 'a {
    unsafe extern "C" fn generator_wrapper<Input, Output, Stack, F>(env: usize, stack_ptr: StackPointer) -> !
        where Input: Send, Output: Send, Stack: stack::Stack,
              F: FnOnce(&Yielder<Input, Output>, Input) {
      // Retrieve our environment from the callee and return control to it.
      let f = ptr::read(env as *const F);
      let (data, stack_ptr) = arch::swap(0, stack_ptr, None);
      // See the second half of Yielder::suspend_bare.
      let input = ptr::read(data as *const Input);
      // Run the body of the generator.
      let yielder = Yielder::new(stack_ptr);
      f(&yielder, input);
      // Past this point, the generator has dropped everything it has held.
      loop { yielder.suspend_bare(None); }
    }

    let stack_id  = debug::StackId::register(&stack);
    let stack_ptr = arch::init(&stack, generator_wrapper::<Input, Output, Stack, F>);

    // Transfer environment to the callee.
    let stack_ptr = arch::swap(&f as *const F as usize, stack_ptr, Some(&stack)).1;
    mem::forget(f);

    Generator {
      state:     State::Runnable,
      stack:     stack,
      stack_id:  stack_id,
      stack_ptr: stack_ptr,
      phantom:   PhantomData
    }
  }

  /// Resumes the generator and return the next value it yields.
  /// If the generator function has returned, returns `None`.
  #[inline]
  pub fn resume(&mut self, input: Input) -> Option<Output> {
    match self.state {
      State::Runnable => {
        // Set the state to Unavailable. Since we have exclusive access to the generator,
        // the only case where this matters is the generator function panics, after which
        // it must not be invocable again.
        self.state = State::Unavailable;

        // Switch to the generator function, and retrieve the yielded value.
        let val = unsafe {
          let (data_out, stack_ptr) = arch::swap(&input as *const Input as usize, self.stack_ptr, Some(&self.stack));
          self.stack_ptr = stack_ptr;
          mem::forget(input);
          ptr::read(data_out as *const Option<Output>)
        };

        // Unless the generator function has returned, it can be switched to again, so
        // set the state to Runnable.
        if val.is_some() { self.state = State::Runnable }

        val
      }
      State::Unavailable => None
    }
  }

  /// Returns the state of the generator.
  #[inline]
  pub fn state(&self) -> State { self.state }

  /// Extracts the stack from a generator when the generator function has returned.
  /// If the generator function has not returned
  /// (i.e. `self.state() == State::Runnable`), panics.
  pub fn unwrap(self) -> Stack {
    match self.state {
      State::Runnable    => panic!("Argh! Bastard! Don't touch that!"),
      State::Unavailable => self.stack
    }
  }
}

/// Yielder is an interface provided to every generator through which it
/// returns a value.
#[derive(Debug)]
pub struct Yielder<Input: Send, Output: Send> {
  stack_ptr: Cell<StackPointer>,
  phantom: PhantomData<(*const Input, *mut Output)>
}

impl<Input, Output> Yielder<Input, Output>
    where Input: Send, Output: Send {
  fn new(stack_ptr: StackPointer) -> Yielder<Input, Output> {
    Yielder {
      stack_ptr: Cell::new(stack_ptr),
      phantom: PhantomData
    }
  }

  #[inline(always)]
  fn suspend_bare(&self, val: Option<Output>) -> Input {
    unsafe {
      let (data, stack_ptr) = arch::swap(&val as *const Option<Output> as usize, self.stack_ptr.get(), None);
      self.stack_ptr.set(stack_ptr);
      mem::forget(val);
      ptr::read(data as *const Input)
    }
  }

  /// Suspends the generator and returns `Some(item)` from the `resume()`
  /// invocation that resumed the generator.
  #[inline(always)]
  pub fn suspend(&self, item: Output) -> Input {
    self.suspend_bare(Some(item))
  }
}

impl<'a, Output, Stack> Iterator for Generator<'a, (), Output, Stack>
    where Output: Send + 'a, Stack: stack::Stack {
  type Item = Output;

  fn next(&mut self) -> Option<Self::Item> { self.resume(()) }
}
<commit_msg>Allow Generator to have !Send inputs and outputs<commit_after>// This file is part of libfringe, a low-level green threading library.
// Copyright (c) whitequark <whitequark@whitequark.org>
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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.

//! Generators.
//!
//! Generators allow repeatedly suspending the execution of a function,
//! returning a value to the caller, and resuming the suspended function
//! afterwards.

use core::marker::PhantomData;
use core::{ptr, mem};
use core::cell::Cell;

use stack;
use debug;
use arch::{self, StackPointer};

#[derive(Debug, Clone, Copy)]
pub enum State {
  /// Generator can be resumed. This is the initial state.
  Runnable,
  /// Generator cannot be resumed. This is the state of the generator after
  /// the generator function has returned or panicked.
  Unavailable
}

/// Generator wraps a function and allows suspending its execution more than once, returning
/// a value each time.
///
/// The first time `resume(input0)` is called, the function is called as `f(yielder, input0)`.
/// It runs until it suspends its execution through `yielder.suspend(output0)`, after which
/// `resume(input0)` returns `output0`. The function can be resumed again using `resume(input1)`,
/// after which `yielder.suspend(output0)` returns `input1`, and so on. Once the function returns,
/// the `resume()` call will return `None`, and it will return `None` every time it is called
/// after that.
///
/// If the generator function panics, the panic is propagated through the `resume()` call as usual.
///
/// After the generator function returns or panics, it is safe to reclaim the generator stack
/// using `unwrap()`.
///
/// `state()` can be used to determine whether the generator function has returned;
/// the state is `State::Runnable` after creation and suspension, and `State::Unavailable`
/// once the generator function returns or panics.
///
/// When the input type is `()`, a generator implements the Iterator trait.
///
/// # Example
///
/// ```
/// use fringe::{OsStack, Generator};
///
/// let stack = OsStack::new(0).unwrap();
/// let mut add_one = Generator::new(stack, move |yielder, mut input| {
///   loop {
///     if input == 0 { break }
///     input = yielder.suspend(input + 1)
///   }
/// });
/// println!("{:?}", add_one.resume(2)); // prints Some(3)
/// println!("{:?}", add_one.resume(3)); // prints Some(4)
/// println!("{:?}", add_one.resume(0)); // prints None
/// ```
///
/// # Iterator example
///
/// ```
/// use fringe::{OsStack, Generator};
///
/// let stack = OsStack::new(0).unwrap();
/// let mut nat = Generator::new(stack, move |yielder, ()| {
///   for i in 1.. { yielder.suspend(i) }
/// });
/// println!("{:?}", nat.next()); // prints Some(0)
/// println!("{:?}", nat.next()); // prints Some(1)
/// println!("{:?}", nat.next()); // prints Some(2)
/// ```
#[derive(Debug)]
pub struct Generator<'a, Input: 'a, Output: 'a, Stack: stack::Stack> {
  state:     State,
  stack:     Stack,
  stack_id:  debug::StackId,
  stack_ptr: arch::StackPointer,
  phantom:   PhantomData<(&'a (), *mut Input, *const Output)>
}

unsafe impl<'a, Input, Output, Stack> Send for Generator<'a, Input, Output, Stack>
  where Input: Send + 'a, Output: Send + 'a, Stack: stack::Stack + Send {}

impl<'a, Input, Output, Stack> Generator<'a, Input, Output, Stack>
    where Input: 'a, Output: 'a, Stack: stack::Stack {
  /// Creates a new generator.
  ///
  /// See also the [contract](../trait.GuardedStack.html) that needs to be fulfilled by `stack`.
  pub fn new<F>(stack: Stack, f: F) -> Generator<'a, Input, Output, Stack>
      where Stack: stack::GuardedStack,
            F: FnOnce(&Yielder<Input, Output>, Input) + Send + 'a {
    unsafe { Generator::unsafe_new(stack, f) }
  }

  /// Same as `new`, but does not require `stack` to have a guard page.
  ///
  /// This function is unsafe because the generator function can easily violate
  /// memory safety by overflowing the stack. It is useful in environments where
  /// guarded stacks do not exist, e.g. in absence of an MMU.
  ///
  /// See also the [contract](../trait.Stack.html) that needs to be fulfilled by `stack`.
  pub unsafe fn unsafe_new<F>(stack: Stack, f: F) -> Generator<'a, Input, Output, Stack>
      where F: FnOnce(&Yielder<Input, Output>, Input) + Send + 'a {
    unsafe extern "C" fn generator_wrapper<Input, Output, Stack, F>(env: usize, stack_ptr: StackPointer) -> !
        where Stack: stack::Stack, F: FnOnce(&Yielder<Input, Output>, Input) {
      // Retrieve our environment from the callee and return control to it.
      let f = ptr::read(env as *const F);
      let (data, stack_ptr) = arch::swap(0, stack_ptr, None);
      // See the second half of Yielder::suspend_bare.
      let input = ptr::read(data as *const Input);
      // Run the body of the generator.
      let yielder = Yielder::new(stack_ptr);
      f(&yielder, input);
      // Past this point, the generator has dropped everything it has held.
      loop { yielder.suspend_bare(None); }
    }

    let stack_id  = debug::StackId::register(&stack);
    let stack_ptr = arch::init(&stack, generator_wrapper::<Input, Output, Stack, F>);

    // Transfer environment to the callee.
    let stack_ptr = arch::swap(&f as *const F as usize, stack_ptr, Some(&stack)).1;
    mem::forget(f);

    Generator {
      state:     State::Runnable,
      stack:     stack,
      stack_id:  stack_id,
      stack_ptr: stack_ptr,
      phantom:   PhantomData
    }
  }

  /// Resumes the generator and return the next value it yields.
  /// If the generator function has returned, returns `None`.
  #[inline]
  pub fn resume(&mut self, input: Input) -> Option<Output> {
    match self.state {
      State::Runnable => {
        // Set the state to Unavailable. Since we have exclusive access to the generator,
        // the only case where this matters is the generator function panics, after which
        // it must not be invocable again.
        self.state = State::Unavailable;

        // Switch to the generator function, and retrieve the yielded value.
        let val = unsafe {
          let (data_out, stack_ptr) = arch::swap(&input as *const Input as usize, self.stack_ptr, Some(&self.stack));
          self.stack_ptr = stack_ptr;
          mem::forget(input);
          ptr::read(data_out as *const Option<Output>)
        };

        // Unless the generator function has returned, it can be switched to again, so
        // set the state to Runnable.
        if val.is_some() { self.state = State::Runnable }

        val
      }
      State::Unavailable => None
    }
  }

  /// Returns the state of the generator.
  #[inline]
  pub fn state(&self) -> State { self.state }

  /// Extracts the stack from a generator when the generator function has returned.
  /// If the generator function has not returned
  /// (i.e. `self.state() == State::Runnable`), panics.
  pub fn unwrap(self) -> Stack {
    match self.state {
      State::Runnable    => panic!("Argh! Bastard! Don't touch that!"),
      State::Unavailable => self.stack
    }
  }
}

/// Yielder is an interface provided to every generator through which it
/// returns a value.
#[derive(Debug)]
pub struct Yielder<Input, Output> {
  stack_ptr: Cell<StackPointer>,
  phantom: PhantomData<(*const Input, *mut Output)>
}

impl<Input, Output> Yielder<Input, Output> {
  fn new(stack_ptr: StackPointer) -> Yielder<Input, Output> {
    Yielder {
      stack_ptr: Cell::new(stack_ptr),
      phantom: PhantomData
    }
  }

  #[inline(always)]
  fn suspend_bare(&self, val: Option<Output>) -> Input {
    unsafe {
      let (data, stack_ptr) = arch::swap(&val as *const Option<Output> as usize, self.stack_ptr.get(), None);
      self.stack_ptr.set(stack_ptr);
      mem::forget(val);
      ptr::read(data as *const Input)
    }
  }

  /// Suspends the generator and returns `Some(item)` from the `resume()`
  /// invocation that resumed the generator.
  #[inline(always)]
  pub fn suspend(&self, item: Output) -> Input {
    self.suspend_bare(Some(item))
  }
}

impl<'a, Output, Stack> Iterator for Generator<'a, (), Output, Stack>
    where Output: 'a, Stack: stack::Stack {
  type Item = Output;

  fn next(&mut self) -> Option<Self::Item> { self.resume(()) }
}
<|endoftext|>


<commit_before>//! Half-edge graph representation of meshes.
//!
//! This module provides a flexible representation of meshes as a [half-edge
//! graph](https://en.wikipedia.org/wiki/doubly_connected_edge_list) exposed as
//! the [`Mesh`] type. Meshes can store arbitrary geometric data associated
//! with any topological structure, including vertices, half-edges, and faces.
//!
//! These structures can be difficult to construct from individual components;
//! the `generate` module can be used to produce primitive meshes that can be
//! converted into a graph.
//!
//! # Representation
//!
//! Meshes store topological data using keyed storage. That is, structures
//! representing vertices, edges, and faces, are stored using associative
//! collections. Keys are exposed as strongly typed and opaque values, which
//! can be used to refer to a topological structure, e.g., [`VertexKey`].
//! Importantly, raw references are not used, which eases the construction and
//! manipulation of the graph in both user and library code by avoiding certain
//! borrowing rules.
//!
//! # Topological Views
//!
//! Meshes expose views over their topological structures (vertices, edges, and
//! faces). Views are accessed via keys or iteration and behave like
//! references, and are exposed as `...Ref`, `...Mut`, and `Orphan...Mut` types
//! (immutable, mutable, and orphan views, respectively) summarized below:
//!
//! | Type      | Name           | Traversal | Arity | Geometry  | Topology  |
//! |-----------|----------------|-----------|-------|-----------|-----------|
//! | Immutable | `...Ref`       | Yes       | Many  | Immutable | Immutable |
//! | Mutable   | `...Mut`       | Neighbors | One   | Mutable   | Mutable   |
//! | Orphan    | `Orphan...Mut` | No        | Many  | Mutable   | N/A       |
//!
//! Note that it is not possible to get mutable views from another mutable view
//! via a traversal, because a mutation may alter the topology and invalidate
//! the originating view. This also means that mutable operations will always
//! consume `self`. In general, an immutable traversal of topology can be used
//! to collect keys that are later used to query and mutate the target
//! topology.
//!
//! All views provide access to their associated geometry. Mutable views, like
//! [`FaceMut`], provide topological operations, like triangulation and
//! extrusion.
//!
//! # Examples
//!
//! Creating an empty mesh with no geometric data:
//!
//! ```rust
//! # use plexus::graph::Mesh;
//! let mut mesh = Mesh::<()>::new();
//! ```
//!
//! Generating a mesh from a primitive:
//!
//! ```rust
//! # extern crate nalgebra;
//! # extern crate plexus;
//! use nalgebra::Point3;
//! use plexus::generate::sphere::UVSphere;
//! use plexus::graph::Mesh;
//! use plexus::prelude::*;
//!
//! # fn main() {
//! let mut mesh = UVSphere::<f32>::with_unit_radius(16, 16)
//!     .polygons_with_position()
//!     .map_vertices(|vertex| vertex.into_hash())
//!     .collect::<Mesh<Point3<f32>>>();
//! # }
//! ```
//!
//! Generating a mesh from raw position and index buffers:
//!
//! ```rust
//! # extern crate nalgebra;
//! # extern crate plexus;
//! use nalgebra::Point3;
//! use plexus::generate::LruIndexer;
//! use plexus::generate::sphere::UVSphere;
//! use plexus::graph::Mesh;
//! use plexus::prelude::*;
//!
//! # fn main() {
//! let (indeces, positions) = UVSphere::<f32>::with_unit_radius(16, 16)
//!     .polygons_with_position()
//!     .triangulate()
//!     .index_vertices(LruIndexer::with_capacity(256));
//! let mut mesh = Mesh::<Point3<f32>>::from_raw_buffers(indeces, positions, 3);
//! # }
//! ```

mod geometry;
mod mesh;
mod storage;
mod topology;

pub use self::mesh::Mesh;
pub use self::storage::{EdgeKey, FaceKey, VertexKey};
pub use self::topology::{EdgeKeyTopology, EdgeMut, EdgeRef, FaceKeyTopology, FaceMut, FaceRef,
                         OrphanEdgeMut, OrphanFaceMut, OrphanVertexMut, VertexMut, VertexRef};

trait VecExt<T>
where
    T: Copy,
{
    fn duplet_circuit_windows(&self) -> DupletCircuitWindows<T>;
}

impl<T> VecExt<T> for Vec<T>
where
    T: Copy,
{
    fn duplet_circuit_windows(&self) -> DupletCircuitWindows<T> {
        DupletCircuitWindows::new(self)
    }
}

struct DupletCircuitWindows<'a, T>
where
    T: 'a + Copy,
{
    input: &'a Vec<T>,
    index: usize,
}

impl<'a, T> DupletCircuitWindows<'a, T>
where
    T: 'a + Copy,
{
    fn new(input: &'a Vec<T>) -> Self {
        DupletCircuitWindows {
            input: input,
            index: 0,
        }
    }
}

impl<'a, T> Iterator for DupletCircuitWindows<'a, T>
where
    T: 'a + Copy,
{
    type Item = (T, T);

    fn next(&mut self) -> Option<Self::Item> {
        let index = self.index;
        let n = self.input.len();
        if index >= n {
            None
        }
        else {
            self.index += 1;
            Some((self.input[index], self.input[(index + 1) % n]))
        }
    }
}
<commit_msg>Add an example for manipulating a face in a mesh.<commit_after>//! Half-edge graph representation of meshes.
//!
//! This module provides a flexible representation of meshes as a [half-edge
//! graph](https://en.wikipedia.org/wiki/doubly_connected_edge_list) exposed as
//! the [`Mesh`] type. Meshes can store arbitrary geometric data associated
//! with any topological structure, including vertices, half-edges, and faces.
//!
//! These structures can be difficult to construct from individual components;
//! the `generate` module can be used to produce primitive meshes that can be
//! converted into a graph.
//!
//! # Representation
//!
//! Meshes store topological data using keyed storage. That is, structures
//! representing vertices, edges, and faces, are stored using associative
//! collections. Keys are exposed as strongly typed and opaque values, which
//! can be used to refer to a topological structure, e.g., [`VertexKey`].
//! Importantly, raw references are not used, which eases the construction and
//! manipulation of the graph in both user and library code by avoiding certain
//! borrowing rules.
//!
//! # Topological Views
//!
//! Meshes expose views over their topological structures (vertices, edges, and
//! faces). Views are accessed via keys or iteration and behave like
//! references, and are exposed as `...Ref`, `...Mut`, and `Orphan...Mut` types
//! (immutable, mutable, and orphan views, respectively) summarized below:
//!
//! | Type      | Name           | Traversal | Arity | Geometry  | Topology  |
//! |-----------|----------------|-----------|-------|-----------|-----------|
//! | Immutable | `...Ref`       | Yes       | Many  | Immutable | Immutable |
//! | Mutable   | `...Mut`       | Neighbors | One   | Mutable   | Mutable   |
//! | Orphan    | `Orphan...Mut` | No        | Many  | Mutable   | N/A       |
//!
//! Note that it is not possible to get mutable views from another mutable view
//! via a traversal, because a mutation may alter the topology and invalidate
//! the originating view. This also means that mutable operations will always
//! consume `self`. In general, an immutable traversal of topology can be used
//! to collect keys that are later used to query and mutate the target
//! topology.
//!
//! All views provide access to their associated geometry. Mutable views, like
//! [`FaceMut`], provide topological operations, like triangulation and
//! extrusion.
//!
//! # Circulators
//!
//! Topological views allow for traversals of a mesh's topology. One useful
//! type of traversal uses a circulator, which is a type of iterator that
//! examines the neighbors of a topological structure. For example, the face
//! circulator of a vertex yields all faces that share that vertex in order.
//!
//! # Examples
//!
//! Creating an empty mesh with no geometric data:
//!
//! ```rust
//! use plexus::graph::Mesh;
//!
//! let mut mesh = Mesh::<()>::new();
//! ```
//!
//! Generating a mesh from a primitive:
//!
//! ```rust
//! # extern crate nalgebra;
//! # extern crate plexus;
//! use nalgebra::Point3;
//! use plexus::generate::sphere::UVSphere;
//! use plexus::graph::Mesh;
//! use plexus::prelude::*;
//!
//! # fn main() {
//! let mut mesh = UVSphere::<f32>::with_unit_radius(16, 16)
//!     .polygons_with_position()
//!     .map_vertices(|vertex| vertex.into_hash())
//!     .collect::<Mesh<Point3<f32>>>();
//! # }
//! ```
//!
//! Generating a mesh from raw position and index buffers:
//!
//! ```rust
//! # extern crate nalgebra;
//! # extern crate plexus;
//! use nalgebra::Point3;
//! use plexus::generate::LruIndexer;
//! use plexus::generate::sphere::UVSphere;
//! use plexus::graph::Mesh;
//! use plexus::prelude::*;
//!
//! # fn main() {
//! let (indeces, positions) = UVSphere::<f32>::with_unit_radius(16, 16)
//!     .polygons_with_position()
//!     .triangulate()
//!     .index_vertices(LruIndexer::with_capacity(256));
//! let mut mesh = Mesh::<Point3<f32>>::from_raw_buffers(indeces, positions, 3);
//! # }
//!
//! ```
//!
//! Manipulating a face in a mesh:
//!
//! ```rust
//! # extern crate nalgebra;
//! # extern crate plexus;
//! use nalgebra::Point3;
//! use plexus::generate::sphere::UVSphere;
//! use plexus::graph::Mesh;
//! use plexus::prelude::*;
//!
//! # fn main() {
//! let mut mesh = UVSphere::<f32>::with_unit_radius(16, 16)
//!     .polygons_with_position()
//!     .map_vertices(|vertex| vertex.into_hash())
//!     .collect::<Mesh<Point3<f32>>>();
//! let key = mesh.faces().nth(0).unwrap().key(); // Get the key of the first face.
//! mesh.face_mut(key).unwrap().extrude(1.0).unwrap(); // Extrude the face.
//! # }
//! ```

mod geometry;
mod mesh;
mod storage;
mod topology;

pub use self::mesh::Mesh;
pub use self::storage::{EdgeKey, FaceKey, VertexKey};
pub use self::topology::{EdgeKeyTopology, EdgeMut, EdgeRef, FaceKeyTopology, FaceMut, FaceRef,
                         OrphanEdgeMut, OrphanFaceMut, OrphanVertexMut, VertexMut, VertexRef};

trait VecExt<T>
where
    T: Copy,
{
    fn duplet_circuit_windows(&self) -> DupletCircuitWindows<T>;
}

impl<T> VecExt<T> for Vec<T>
where
    T: Copy,
{
    fn duplet_circuit_windows(&self) -> DupletCircuitWindows<T> {
        DupletCircuitWindows::new(self)
    }
}

struct DupletCircuitWindows<'a, T>
where
    T: 'a + Copy,
{
    input: &'a Vec<T>,
    index: usize,
}

impl<'a, T> DupletCircuitWindows<'a, T>
where
    T: 'a + Copy,
{
    fn new(input: &'a Vec<T>) -> Self {
        DupletCircuitWindows {
            input: input,
            index: 0,
        }
    }
}

impl<'a, T> Iterator for DupletCircuitWindows<'a, T>
where
    T: 'a + Copy,
{
    type Item = (T, T);

    fn next(&mut self) -> Option<Self::Item> {
        let index = self.index;
        let n = self.input.len();
        if index >= n {
            None
        }
        else {
            self.index += 1;
            Some((self.input[index], self.input[(index + 1) % n]))
        }
    }
}
<|endoftext|>


<commit_before>use libc::{uint64_t, int64_t, c_double, c_int};
use std::mem;

pub type HeartbeatWindowCompleteFn = extern fn(*const Heartbeat, *const HeartbeatRecord, uint64_t);

#[link(name = "hbs-pow")]
extern {
    fn heartbeat_init(hb: *mut Heartbeat,
                      window_size: uint64_t,
                      window_buffer: *mut HeartbeatRecord,
                      hwc_callback: Option<HeartbeatWindowCompleteFn>) -> c_int;

    fn heartbeat(hb: *mut Heartbeat,
                 user_tag: uint64_t,
                 work: uint64_t,
                 start_time: int64_t,
                 end_time: int64_t);

    fn heartbeat_pow(hb: *mut Heartbeat,
                     user_tag: uint64_t,
                     work: uint64_t,
                     start_time: int64_t,
                     end_time: int64_t,
                     start_energy: uint64_t,
                     end_energy: uint64_t);

    fn hb_get_user_tag(hb: *const Heartbeat) -> uint64_t;

    fn hb_get_window_rate(hb: *const Heartbeat) -> c_double;

    fn hb_get_window_power(hb: *const Heartbeat) -> c_double;
}

#[derive(Clone, Copy)]
#[repr(C)]
struct HeartbeatTimeData {
    total_time: int64_t,
    window_time: int64_t,
}

#[derive(Clone, Copy)]
#[repr(C)]
struct HeartbeatWorkData {
    total_work: uint64_t,
    window_work: uint64_t,
}

#[derive(Clone, Copy)]
#[repr(C)]
struct HeartbeatEnergyData {
    total_energy: uint64_t,
    window_energy: uint64_t,
}

#[derive(Clone, Copy)]
#[repr(C)]
pub struct HeartbeatRecord {
    pub id: uint64_t,
    pub user_tag: uint64_t,

    pub work: uint64_t,
    pub start_time: int64_t,
    pub end_time: int64_t,
    pub global_perf: c_double,
    pub window_perf: c_double,
    pub instant_perf: c_double,

    pub start_energy: uint64_t,
    pub end_energy: uint64_t,
    pub global_pwr: c_double,
    pub window_pwr: c_double,
    pub instant_pwr: c_double,
}

#[allow(raw_pointer_derive)]
#[derive(Clone, Copy)]
#[repr(C)]
/// A `Heartbeat` is used for tracking performance/power of recurring jobs.
pub struct Heartbeat {
    counter: uint64_t,
    buffer_index: uint64_t,
    read_index: uint64_t,
    window_size: uint64_t,
    window_buffer: *mut HeartbeatRecord,
    hwc_callback: HeartbeatWindowCompleteFn,

    td: HeartbeatTimeData,
    wd: HeartbeatWorkData,
    ed: HeartbeatEnergyData,
}

pub struct HeartbeatSimple {
    pub hb: Heartbeat,
    pub hbr: Vec<HeartbeatRecord>,
}

impl HeartbeatSimple {
    /// Allocate and initialize a new `Heartbeat`.
    pub fn new(window_size: usize,
               hwc_callback: Option<HeartbeatWindowCompleteFn>) -> Result<HeartbeatSimple, &'static str> {
        unsafe {
            let mut hb = HeartbeatSimple {
                hb: mem::uninitialized(),
                hbr: Vec::with_capacity(window_size)
            };
            match heartbeat_init(&mut hb.hb, window_size as u64, hb.hbr.as_mut_ptr(), hwc_callback) {
                0 => Ok(hb),
                _ => Err("Failed to initialize heartbeat")
            }
        }
    }

    /// Issue a heartbeat.
    pub fn heartbeat(&mut self,
                     tag: u64,
                     work: u64,
                     start_time: i64,
                     end_time: i64) {
        unsafe {
            heartbeat(&mut self.hb, tag, work, start_time, end_time)
        }
    }

    /// Issue a heartbeat with energy data.
    pub fn heartbeat_pow(&mut self,
                         tag: u64,
                         work: u64,
                         start_time: i64,
                         end_time: i64,
                         start_energy: u64,
                         end_energy: u64) {
        unsafe {
            heartbeat_pow(&mut self.hb, tag, work, start_time, end_time, start_energy, end_energy)
        }
    }

    /// Utility function to get the most recent user-specified tag
    pub fn get_tag(&self) -> u64 {
        unsafe {
            hb_get_user_tag(&self.hb)
        }
    }

    /// Utility function to get the current window performance.
    pub fn get_window_perf(&self) -> f64 {
        unsafe {
            hb_get_window_rate(&self.hb)
        }
    }

    /// Utility function to get the current window power.
    pub fn get_window_pwr(&self) -> f64 {
        unsafe {
            hb_get_window_power(&self.hb)
        }
    }
}

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

    #[test]
    fn test_simple() {
        let mut hb = HeartbeatSimple::new(20, None).unwrap();
        hb.heartbeat(1, 1, 0, 1000000000);
        assert!(hb.get_tag() == 1);
        assert!(hb.get_window_perf() == 1.0);
        hb.heartbeat_pow(2, 1, 1000000000, 2000000000, 0, 2000000);
        assert!(hb.get_window_pwr() == 1.0)
    }
}
<commit_msg>Add basic callback functionality for window completion<commit_after>use libc::{uint64_t, int64_t, c_double, c_int};
use std::mem;

pub type HeartbeatWindowCompleteFn = extern fn(*const Heartbeat, *const HeartbeatRecord, uint64_t);

#[link(name = "hbs-pow")]
extern {
    fn heartbeat_init(hb: *mut Heartbeat,
                      window_size: uint64_t,
                      window_buffer: *mut HeartbeatRecord,
                      hwc_callback: Option<HeartbeatWindowCompleteFn>) -> c_int;

    fn heartbeat(hb: *mut Heartbeat,
                 user_tag: uint64_t,
                 work: uint64_t,
                 start_time: int64_t,
                 end_time: int64_t);

    fn heartbeat_pow(hb: *mut Heartbeat,
                     user_tag: uint64_t,
                     work: uint64_t,
                     start_time: int64_t,
                     end_time: int64_t,
                     start_energy: uint64_t,
                     end_energy: uint64_t);

    pub fn heartbeat_log_window_buffer(hb: *const Heartbeat,
                                       fd: c_int,
                                       print_header: c_int) -> c_int;

    fn hb_get_user_tag(hb: *const Heartbeat) -> uint64_t;

    fn hb_get_window_rate(hb: *const Heartbeat) -> c_double;

    fn hb_get_window_power(hb: *const Heartbeat) -> c_double;
}

#[derive(Clone, Copy)]
#[repr(C)]
struct HeartbeatTimeData {
    total_time: int64_t,
    window_time: int64_t,
}

#[derive(Clone, Copy)]
#[repr(C)]
struct HeartbeatWorkData {
    total_work: uint64_t,
    window_work: uint64_t,
}

#[derive(Clone, Copy)]
#[repr(C)]
struct HeartbeatEnergyData {
    total_energy: uint64_t,
    window_energy: uint64_t,
}

#[derive(Clone, Copy)]
#[repr(C)]
pub struct HeartbeatRecord {
    pub id: uint64_t,
    pub user_tag: uint64_t,

    pub work: uint64_t,
    pub start_time: int64_t,
    pub end_time: int64_t,
    pub global_perf: c_double,
    pub window_perf: c_double,
    pub instant_perf: c_double,

    pub start_energy: uint64_t,
    pub end_energy: uint64_t,
    pub global_pwr: c_double,
    pub window_pwr: c_double,
    pub instant_pwr: c_double,
}

#[allow(raw_pointer_derive)]
#[derive(Clone, Copy)]
#[repr(C)]
/// A `Heartbeat` is used for tracking performance/power of recurring jobs.
pub struct Heartbeat {
    counter: uint64_t,
    buffer_index: uint64_t,
    read_index: uint64_t,
    window_size: uint64_t,
    window_buffer: *mut HeartbeatRecord,
    hwc_callback: HeartbeatWindowCompleteFn,

    td: HeartbeatTimeData,
    wd: HeartbeatWorkData,
    ed: HeartbeatEnergyData,
}

pub struct HeartbeatSimple {
    pub hb: Heartbeat,
    pub hbr: Vec<HeartbeatRecord>,
}

impl HeartbeatSimple {
    /// Allocate and initialize a new `Heartbeat`.
    pub fn new(window_size: usize,
               hwc_callback: Option<HeartbeatWindowCompleteFn>) -> Result<HeartbeatSimple, &'static str> {
        unsafe {
            let mut hb = HeartbeatSimple {
                hb: mem::uninitialized(),
                hbr: Vec::with_capacity(window_size)
            };
            match heartbeat_init(&mut hb.hb, window_size as u64, hb.hbr.as_mut_ptr(), hwc_callback) {
                0 => Ok(hb),
                _ => Err("Failed to initialize heartbeat")
            }
        }
    }

    /// Issue a heartbeat.
    pub fn heartbeat(&mut self,
                     tag: u64,
                     work: u64,
                     start_time: i64,
                     end_time: i64) {
        unsafe {
            heartbeat(&mut self.hb, tag, work, start_time, end_time)
        }
    }

    /// Issue a heartbeat with energy data.
    pub fn heartbeat_pow(&mut self,
                         tag: u64,
                         work: u64,
                         start_time: i64,
                         end_time: i64,
                         start_energy: u64,
                         end_energy: u64) {
        unsafe {
            heartbeat_pow(&mut self.hb, tag, work, start_time, end_time, start_energy, end_energy)
        }
    }

    /// Utility function to get the most recent user-specified tag
    pub fn get_tag(&self) -> u64 {
        unsafe {
            hb_get_user_tag(&self.hb)
        }
    }

    /// Utility function to get the current window performance.
    pub fn get_window_perf(&self) -> f64 {
        unsafe {
            hb_get_window_rate(&self.hb)
        }
    }

    /// Utility function to get the current window power.
    pub fn get_window_pwr(&self) -> f64 {
        unsafe {
            hb_get_window_power(&self.hb)
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use libc::uint64_t;

    extern fn heartbeat_window_complete_callback(hb: *const Heartbeat,
                                                 _hbr: *const HeartbeatRecord,
                                                 _size: uint64_t) {
    const STDOUT: i32 = 1;
    unsafe {
        heartbeat_log_window_buffer(hb, STDOUT, 0);
    }
}

    #[test]
    fn test_simple() {
        const TIME_INC: i64 = 1000000000;
        const ENERGY_INC: u64 = 1000000;
        let mut hb = HeartbeatSimple::new(5, Some(heartbeat_window_complete_callback)).unwrap();
        let mut start_time: i64 = 0;
        let mut end_time: i64 = TIME_INC;
        let mut start_energy: u64 = 0;
        let mut end_energy: u64 = ENERGY_INC;
        let mut tag: u64 = 0;
        for _ in 0..10 {
            hb.heartbeat_pow(tag, 1, start_time, end_time, start_energy, end_energy);
            assert!(hb.get_tag() == tag);
            assert!(hb.get_window_perf() == 1.0);
            assert!(hb.get_window_pwr() == 1.0);
            tag += 1;
            start_time = end_time;
            end_time += TIME_INC;
            start_energy = end_energy;
            end_energy += ENERGY_INC;
        }
    }
}
<|endoftext|>


<commit_before>use std::fmt::Display;
use std::convert;
use std::ops;
use std::str;

#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub enum Sign {
    Negative = -1,
    Zero = 0,
    Positive = 1,
}

pub trait From<T> {
    fn from_lo(T, precision: usize) -> Self;
    fn from_hi(T, precision: usize) -> Self;
}

pub trait FromStr: Sized {
    type Err;
    fn from_str_lo(&str, precision: usize) -> Result<Self, Self::Err>;
    fn from_str_hi(&str, precision: usize) -> Result<Self, Self::Err>;
}

pub trait Into<T> {
    fn into_lo(self) -> T;
    fn into_hi(self) -> T;
}

pub trait MinMax<RHS = Self> {
    type Output;
    fn min(self, rhs: Self) -> Self;
    fn max(self, rhs: Self) -> Self;
}

pub trait Abs {
    type Output;
    fn abs(self) -> Self::Output;
}

pub trait Add<RHS = Self> {
    type Output;
    fn add_lo(self, rhs: RHS) -> Self::Output;
    fn add_hi(self, rhs: RHS) -> Self::Output;
}

pub trait Sub<RHS = Self> {
    type Output;
    fn sub_lo(self, rhs: RHS) -> Self::Output;
    fn sub_hi(self, rhs: RHS) -> Self::Output;
}

pub trait Mul<RHS = Self> {
    type Output;
    fn mul_lo(self, rhs: RHS) -> Self::Output;
    fn mul_hi(self, rhs: RHS) -> Self::Output;
}

pub trait Div<RHS = Self> {
    type Output;
    fn div_lo(self, rhs: RHS) -> Self::Output;
    fn div_hi(self, rhs: RHS) -> Self::Output;
}

pub trait Transc {
    type Output;
    fn log_lo(self) -> Self::Output;
    fn log_hi(self) -> Self::Output;
    fn exp_lo(self) -> Self::Output;
    fn exp_hi(self) -> Self::Output;
}

pub trait Float: convert::From<f64> + str::FromStr +
                 Clone + Display + Into<f64> + PartialOrd +
                 From<f64> + FromStr +
                 ops::Neg + Abs + Add + Sub + Mul + Div + MinMax
{
    fn zero(precision: usize) -> Self;
    fn neg_zero(precision: usize) -> Self;
    fn one(precision: usize) -> Self;
    fn infinity(precision: usize) -> Self;
    fn neg_infinity(precision: usize) -> Self;
    fn nan(precision: usize) -> Self;

    fn sign(&self) -> Sign;
    fn precision(&self) -> usize;

    fn is_finite(&self) -> bool;
    fn is_infinite(&self) -> bool;
    fn is_infinity(&self) -> bool;
    fn is_neg_infinity(&self) -> bool;
    fn is_nan(&self) -> bool;
}
<commit_msg>Ensure all Outputs are Self.<commit_after>use std::fmt::Display;
use std::convert;
use std::ops;
use std::str;

#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub enum Sign {
    Negative = -1,
    Zero = 0,
    Positive = 1,
}

pub trait From<T> {
    fn from_lo(T, precision: usize) -> Self;
    fn from_hi(T, precision: usize) -> Self;
}

pub trait FromStr: Sized {
    type Err;
    fn from_str_lo(&str, precision: usize) -> Result<Self, Self::Err>;
    fn from_str_hi(&str, precision: usize) -> Result<Self, Self::Err>;
}

pub trait Into<T> {
    fn into_lo(self) -> T;
    fn into_hi(self) -> T;
}

pub trait MinMax<RHS = Self> {
    type Output;
    fn min(self, rhs: Self) -> Self;
    fn max(self, rhs: Self) -> Self;
}

pub trait Abs {
    type Output;
    fn abs(self) -> Self::Output;
}

pub trait Add<RHS = Self> {
    type Output;
    fn add_lo(self, rhs: RHS) -> Self::Output;
    fn add_hi(self, rhs: RHS) -> Self::Output;
}

pub trait Sub<RHS = Self> {
    type Output;
    fn sub_lo(self, rhs: RHS) -> Self::Output;
    fn sub_hi(self, rhs: RHS) -> Self::Output;
}

pub trait Mul<RHS = Self> {
    type Output;
    fn mul_lo(self, rhs: RHS) -> Self::Output;
    fn mul_hi(self, rhs: RHS) -> Self::Output;
}

pub trait Div<RHS = Self> {
    type Output;
    fn div_lo(self, rhs: RHS) -> Self::Output;
    fn div_hi(self, rhs: RHS) -> Self::Output;
}

pub trait Transc {
    type Output;
    fn log_lo(self) -> Self::Output;
    fn log_hi(self) -> Self::Output;
    fn exp_lo(self) -> Self::Output;
    fn exp_hi(self) -> Self::Output;
}

pub trait Float: convert::From<f64> + str::FromStr +
                 Clone + Display + Into<f64> + PartialOrd +
                 From<f64> + FromStr +
                 ops::Neg<Output=Self> + Abs<Output=Self> +
                 Add<Output=Self> + Sub<Output=Self> + Mul<Output=Self> + Div<Output=Self> +
                 MinMax<Output=Self>
{
    fn zero(precision: usize) -> Self;
    fn neg_zero(precision: usize) -> Self;
    fn one(precision: usize) -> Self;
    fn infinity(precision: usize) -> Self;
    fn neg_infinity(precision: usize) -> Self;
    fn nan(precision: usize) -> Self;

    fn sign(&self) -> Sign;
    fn precision(&self) -> usize;

    fn is_finite(&self) -> bool;
    fn is_infinite(&self) -> bool;
    fn is_infinity(&self) -> bool;
    fn is_neg_infinity(&self) -> bool;
    fn is_nan(&self) -> bool;
}
<|endoftext|>


<commit_before>// Copyright:: Copyright (c) 2015-2016 The Habitat Maintainers
//
// The terms of the Evaluation Agreement (Habitat) between Chef Software Inc.
// and the party accessing this file ("Licensee") apply to Licensee's use of
// the Software until such time that the Software is made available under an
// open source license such as the Apache 2.0 License.

use std::path::PathBuf;

pub const PACKAGE_HOME: &'static str = "/opt/bldr/pkgs";
pub const SERVICE_HOME: &'static str = "/opt/bldr/svc";
pub const PACKAGE_CACHE: &'static str = "/opt/bldr/cache/pkgs";
pub const GPG_CACHE: &'static str = "/opt/bldr/cache/gpg";
pub const KEY_CACHE: &'static str = "/opt/bldr/cache/keys";

pub fn service_path(service_name: &str) -> PathBuf {
    PathBuf::from(SERVICE_HOME).join(service_name)
}
<commit_msg>Reduce the number of `/opt/bldr` path occurences.<commit_after>// Copyright:: Copyright (c) 2015-2016 The Habitat Maintainers
//
// The terms of the Evaluation Agreement (Habitat) between Chef Software Inc.
// and the party accessing this file ("Licensee") apply to Licensee's use of
// the Software until such time that the Software is made available under an
// open source license such as the Apache 2.0 License.

use std::path::PathBuf;

pub const ROOT: &'static str = "/opt/bldr";
pub const PACKAGE_HOME: &'static str = "/opt/bldr/pkgs";
pub const SERVICE_HOME: &'static str = "/opt/bldr/svc";
pub const SOURCE_CACHE: &'static str = "/opt/bldr/cache/src";
pub const PACKAGE_CACHE: &'static str = "/opt/bldr/cache/pkgs";
pub const GPG_CACHE: &'static str = "/opt/bldr/cache/gpg";
pub const KEY_CACHE: &'static str = "/opt/bldr/cache/keys";

pub fn service_path(service_name: &str) -> PathBuf {
    PathBuf::from(SERVICE_HOME).join(service_name)
}
<|endoftext|>


<commit_before>//! HTTP Request and response header handling.

use std::ascii::AsciiExt;
use std::str::from_utf8;
use std::slice;

use httparse;
use httparse::Status;

use error::Result;
use super::machine::TryParse;

/// Limit for the number of header lines.
pub const MAX_HEADERS: usize = 124;

/// HTTP request or response headers.
#[derive(Debug)]
pub struct Headers {
    data: Vec<(String, Box<[u8]>)>,
}

impl Headers {

    /// Get first header with the given name, if any.
    pub fn find_first(&self, name: &str) -> Option<&[u8]> {
        self.find(name).next()
    }

    /// Iterate over all headers with the given name.
    pub fn find<'headers, 'name>(&'headers self, name: &'name str) -> HeadersIter<'name, 'headers> {
        HeadersIter {
            name: name,
            iter: self.data.iter()
        }
    }

    /// Check if the given header has the given value.
    pub fn header_is(&self, name: &str, value: &str) -> bool {
        self.find_first(name)
            .map(|v| v == value.as_bytes())
            .unwrap_or(false)
    }

    /// Check if the given header has the given value (case-insensitive).
    pub fn header_is_ignore_case(&self, name: &str, value: &str) -> bool {
        self.find_first(name).ok_or(())
            .and_then(|val_raw| from_utf8(val_raw).map_err(|_| ()))
            .map(|val| val.eq_ignore_ascii_case(value))
            .unwrap_or(false)
    }

    /// Allows to iterate over available headers.
    pub fn iter(&self) -> slice::Iter<(String, Box<[u8]>)> {
        self.data.iter()
    }

}

/// The iterator over headers.
pub struct HeadersIter<'name, 'headers> {
    name: &'name str,
    iter: slice::Iter<'headers, (String, Box<[u8]>)>,
}

impl<'name, 'headers> Iterator for HeadersIter<'name, 'headers> {
    type Item = &'headers [u8];
    fn next(&mut self) -> Option<Self::Item> {
        while let Some(&(ref name, ref value)) = self.iter.next() {
            if name.eq_ignore_ascii_case(self.name) {
                return Some(value)
            }
        }
        None
    }
}

/// Trait to convert raw objects into HTTP parseables.
pub trait FromHttparse<T>: Sized {
    /// Convert raw object into parsed HTTP headers.
    fn from_httparse(raw: T) -> Result<Self>;
}

impl TryParse for Headers {
    fn try_parse(buf: &[u8]) -> Result<Option<(usize, Self)>> {
        let mut hbuffer = [httparse::EMPTY_HEADER; MAX_HEADERS];
        Ok(match httparse::parse_headers(buf, &mut hbuffer)? {
            Status::Partial => None,
            Status::Complete((size, hdr)) => Some((size, Headers::from_httparse(hdr)?)),
        })
    }
}

impl<'b: 'h, 'h> FromHttparse<&'b [httparse::Header<'h>]> for Headers {
    fn from_httparse(raw: &'b [httparse::Header<'h>]) -> Result<Self> {
        Ok(Headers {
            data: raw.iter()
                     .map(|h| (h.name.into(), Vec::from(h.value).into_boxed_slice()))
                     .collect(),
        })
    }
}

#[cfg(test)]
mod tests {

    use super::Headers;
    use super::super::machine::TryParse;

    #[test]
    fn headers() {
        const DATA: &'static [u8] =
            b"Host: foo.com\r\n\
             Connection: Upgrade\r\n\
             Upgrade: websocket\r\n\
             \r\n";
        let (_, hdr) = Headers::try_parse(DATA).unwrap().unwrap();
        assert_eq!(hdr.find_first("Host"), Some(&b"foo.com"[..]));
        assert_eq!(hdr.find_first("Upgrade"), Some(&b"websocket"[..]));
        assert_eq!(hdr.find_first("Connection"), Some(&b"Upgrade"[..]));

        assert!(hdr.header_is("upgrade", "websocket"));
        assert!(!hdr.header_is("upgrade", "Websocket"));
        assert!(hdr.header_is_ignore_case("upgrade", "Websocket"));
    }

    #[test]
    fn headers_iter() {
        const DATA: &'static [u8] =
            b"Host: foo.com\r\n\
              Sec-WebSocket-Extensions: permessage-deflate\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-ExtenSIONS: permessage-unknown\r\n\
              Upgrade: websocket\r\n\
              \r\n";
        let (_, hdr) = Headers::try_parse(DATA).unwrap().unwrap();
        let mut iter = hdr.find("Sec-WebSocket-Extensions");
        assert_eq!(iter.next(), Some(&b"permessage-deflate"[..]));
        assert_eq!(iter.next(), Some(&b"permessage-unknown"[..]));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn headers_incomplete() {
        const DATA: &'static [u8] =
            b"Host: foo.com\r\n\
              Connection: Upgrade\r\n\
              Upgrade: websocket\r\n";
        let hdr = Headers::try_parse(DATA).unwrap();
        assert!(hdr.is_none());
    }

}
<commit_msg>Update for Rust 1.23<commit_after>//! HTTP Request and response header handling.

use std::str::from_utf8;
use std::slice;

use httparse;
use httparse::Status;

use error::Result;
use super::machine::TryParse;

/// Limit for the number of header lines.
pub const MAX_HEADERS: usize = 124;

/// HTTP request or response headers.
#[derive(Debug)]
pub struct Headers {
    data: Vec<(String, Box<[u8]>)>,
}

impl Headers {

    /// Get first header with the given name, if any.
    pub fn find_first(&self, name: &str) -> Option<&[u8]> {
        self.find(name).next()
    }

    /// Iterate over all headers with the given name.
    pub fn find<'headers, 'name>(&'headers self, name: &'name str) -> HeadersIter<'name, 'headers> {
        HeadersIter {
            name: name,
            iter: self.data.iter()
        }
    }

    /// Check if the given header has the given value.
    pub fn header_is(&self, name: &str, value: &str) -> bool {
        self.find_first(name)
            .map(|v| v == value.as_bytes())
            .unwrap_or(false)
    }

    /// Check if the given header has the given value (case-insensitive).
    pub fn header_is_ignore_case(&self, name: &str, value: &str) -> bool {
        self.find_first(name).ok_or(())
            .and_then(|val_raw| from_utf8(val_raw).map_err(|_| ()))
            .map(|val| val.eq_ignore_ascii_case(value))
            .unwrap_or(false)
    }

    /// Allows to iterate over available headers.
    pub fn iter(&self) -> slice::Iter<(String, Box<[u8]>)> {
        self.data.iter()
    }

}

/// The iterator over headers.
pub struct HeadersIter<'name, 'headers> {
    name: &'name str,
    iter: slice::Iter<'headers, (String, Box<[u8]>)>,
}

impl<'name, 'headers> Iterator for HeadersIter<'name, 'headers> {
    type Item = &'headers [u8];
    fn next(&mut self) -> Option<Self::Item> {
        while let Some(&(ref name, ref value)) = self.iter.next() {
            if name.eq_ignore_ascii_case(self.name) {
                return Some(value)
            }
        }
        None
    }
}

/// Trait to convert raw objects into HTTP parseables.
pub trait FromHttparse<T>: Sized {
    /// Convert raw object into parsed HTTP headers.
    fn from_httparse(raw: T) -> Result<Self>;
}

impl TryParse for Headers {
    fn try_parse(buf: &[u8]) -> Result<Option<(usize, Self)>> {
        let mut hbuffer = [httparse::EMPTY_HEADER; MAX_HEADERS];
        Ok(match httparse::parse_headers(buf, &mut hbuffer)? {
            Status::Partial => None,
            Status::Complete((size, hdr)) => Some((size, Headers::from_httparse(hdr)?)),
        })
    }
}

impl<'b: 'h, 'h> FromHttparse<&'b [httparse::Header<'h>]> for Headers {
    fn from_httparse(raw: &'b [httparse::Header<'h>]) -> Result<Self> {
        Ok(Headers {
            data: raw.iter()
                     .map(|h| (h.name.into(), Vec::from(h.value).into_boxed_slice()))
                     .collect(),
        })
    }
}

#[cfg(test)]
mod tests {

    use super::Headers;
    use super::super::machine::TryParse;

    #[test]
    fn headers() {
        const DATA: &'static [u8] =
            b"Host: foo.com\r\n\
             Connection: Upgrade\r\n\
             Upgrade: websocket\r\n\
             \r\n";
        let (_, hdr) = Headers::try_parse(DATA).unwrap().unwrap();
        assert_eq!(hdr.find_first("Host"), Some(&b"foo.com"[..]));
        assert_eq!(hdr.find_first("Upgrade"), Some(&b"websocket"[..]));
        assert_eq!(hdr.find_first("Connection"), Some(&b"Upgrade"[..]));

        assert!(hdr.header_is("upgrade", "websocket"));
        assert!(!hdr.header_is("upgrade", "Websocket"));
        assert!(hdr.header_is_ignore_case("upgrade", "Websocket"));
    }

    #[test]
    fn headers_iter() {
        const DATA: &'static [u8] =
            b"Host: foo.com\r\n\
              Sec-WebSocket-Extensions: permessage-deflate\r\n\
              Connection: Upgrade\r\n\
              Sec-WebSocket-ExtenSIONS: permessage-unknown\r\n\
              Upgrade: websocket\r\n\
              \r\n";
        let (_, hdr) = Headers::try_parse(DATA).unwrap().unwrap();
        let mut iter = hdr.find("Sec-WebSocket-Extensions");
        assert_eq!(iter.next(), Some(&b"permessage-deflate"[..]));
        assert_eq!(iter.next(), Some(&b"permessage-unknown"[..]));
        assert_eq!(iter.next(), None);
    }

    #[test]
    fn headers_incomplete() {
        const DATA: &'static [u8] =
            b"Host: foo.com\r\n\
              Connection: Upgrade\r\n\
              Upgrade: websocket\r\n";
        let hdr = Headers::try_parse(DATA).unwrap();
        assert!(hdr.is_none());
    }

}
<|endoftext|>


<commit_before>use std::io;
use std::io::Read;
use command::Command;

type Cell = u8;

pub struct VM {
    pub cells: [Cell; 30_000],
    pub data_pointer: usize,
}

impl VM {
    pub fn new() -> VM {
        VM { cells: [0; 30_000], data_pointer: 0 }
    }

    pub fn output(&self) {
        print!("{}", self.cells[self.data_pointer] as char);
    }

    pub fn input(&mut self) {
        match io::stdin().bytes().next() {
            Some(res) => match res {
                Ok(value) => self.cells[self.data_pointer] = value,
                Err(error) => panic!(error),
            },
            None => {}
        }
        println!("");
    }

    pub fn increment(&mut self) {
        self.cells[self.data_pointer] = self.cells[self.data_pointer].checked_add(1).unwrap_or(0);
    }

    pub fn decrement(&mut self) {
        self.cells[self.data_pointer] = self.cells[self.data_pointer]
            .checked_sub(1)
            .unwrap_or(Cell::max_value());
    }

    pub fn right_shift(&mut self) {
        self.data_pointer += 1;
    }

    pub fn left_shift(&mut self) {
        self.data_pointer -= 1;
    }

    pub fn apply(&mut self, command: Command) {
        match command {
            Command::Output => self.output(),
            Command::Input => self.input(),
            Command::Increment => self.increment(),
            Command::Decrement => self.decrement(),
            Command::RightShift => self.right_shift(),
            Command::LeftShift => self.left_shift(),
            _ => {},
        }
    }
}
<commit_msg>Add unit test for VM::new()<commit_after>use std::io;
use std::io::Read;
use command::Command;

type Cell = u8;

pub struct VM {
    pub cells: [Cell; 30_000],
    pub data_pointer: usize,
}

impl VM {
    pub fn new() -> VM {
        VM { cells: [0; 30_000], data_pointer: 0 }
    }

    pub fn output(&self) {
        print!("{}", self.cells[self.data_pointer] as char);
    }

    pub fn input(&mut self) {
        match io::stdin().bytes().next() {
            Some(res) => match res {
                Ok(value) => self.cells[self.data_pointer] = value,
                Err(error) => panic!(error),
            },
            None => {}
        }
        println!("");
    }

    pub fn increment(&mut self) {
        self.cells[self.data_pointer] = self.cells[self.data_pointer].checked_add(1).unwrap_or(0);
    }

    pub fn decrement(&mut self) {
        self.cells[self.data_pointer] = self.cells[self.data_pointer]
            .checked_sub(1)
            .unwrap_or(Cell::max_value());
    }

    pub fn right_shift(&mut self) {
        self.data_pointer += 1;
    }

    pub fn left_shift(&mut self) {
        self.data_pointer -= 1;
    }

    pub fn apply(&mut self, command: Command) {
        match command {
            Command::Output => self.output(),
            Command::Input => self.input(),
            Command::Increment => self.increment(),
            Command::Decrement => self.decrement(),
            Command::RightShift => self.right_shift(),
            Command::LeftShift => self.left_shift(),
            _ => {},
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn test_new() {
        let vm = VM::new();
        assert!(vm.cells[0] == 0);
        assert!(vm.cells[30_000 - 1] == 0);
        assert!(vm.cells[0] == 0);
    }
}
<|endoftext|>