<commit_before>use libimagstore::store::Entry;
use libimagstore::storeid::StoreId;

pub trait IsInDiary {

    fn is_in_diary(&self, name: &str) -> bool;

}

impl IsInDiary for Entry {

    fn is_in_diary(&self, name: &str) -> bool {
        self.get_location().clone().is_in_diary(name)
    }

}

impl IsInDiary for StoreId {

    fn is_in_diary(&self, name: &str) -> bool {
        self.is_in_collection(&["diary", name])
    }

}

<commit_msg>Use new StoreId::is_in_collection() interface<commit_after>use libimagstore::store::Entry;
use libimagstore::storeid::StoreId;

pub trait IsInDiary {

    fn is_in_diary(&self, name: &str) -> bool;

}

impl IsInDiary for Entry {

    fn is_in_diary(&self, name: &str) -> bool {
        self.get_location().clone().is_in_diary(name)
    }

}

impl IsInDiary for StoreId {

    fn is_in_diary(&self, name: &str) -> bool {
        use std::path::PathBuf;
        self.is_in_collection(&PathBuf::from(format!("diary/{}", name)))
    }

}

<|endoftext|>


<commit_before><commit_msg>style refactors from code review<commit_after><|endoftext|>


<commit_before><commit_msg>Create 3_generic_vector_function.rs<commit_after>/* Writing a function which calculates min value of any type of vector

Method 1: Inside function, find out the value of type during runtime and perform operation based on its type.
          But user might have provided a type which you didn't handle in the function. Which is a runtime logic error

Method 2: During compilation, function only accepts types which has a implemented methods that it requires. In this case 'min'.
          How do we make sure that 'type' implemented a function? -> Trait
          Let's say we want to make the 'vec_min' funtion take ints, floats and strings.
          Create trait bound on 'vec_min' with 'Minimum' trait. Minimum trait lists 'min' method. Now 'vec_min' will only accept types that implemented 'min' method
          Since we want 'vec_min' to take int, float and string, implement 'Minimum' train on these.
          If user passes any type that doesn't implement minimum method, it will fail at compile time instead of runtime.

NOTE: Flow has completely changed with method 2. Instead of 'vec_min' finding out the 'type' of argument and chaning the implementaion based on type,
      type itself is providing stuff that 'vec_min' requires. This way 'vec_min' will remain clean and in future if you want to extend it with new types,
      just make that type implement the 'min' method (Minimum trait). This is extremely useful if 'vec_min' is inside a library whose sources you dont want to change.
*/

/*

pub trait Minimum : Copy {
    fn min(self, b: Self) -> Self;
}

fn vec_min<T: Minimum>(vec: Vec<T>) -> Option<T>{
    println!("finding minimum");
}
*/

fn main() {
    println!("Hello World");
}
<|endoftext|>


<commit_before><commit_msg>Add `response::Profile` and fix `Response`<commit_after><|endoftext|>


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

//! An implementation of SipHash 2-4.

use prelude::v1::*;

use ptr;
use super::Hasher;

/// An implementation of SipHash 2-4.
///
/// See: http://131002.net/siphash/
///
/// Consider this as a main "general-purpose" hash for all hashtables: it
/// runs at good speed (competitive with spooky and city) and permits
/// strong _keyed_ hashing. Key your hashtables from a strong RNG,
/// such as `rand::Rng`.
///
/// Although the SipHash algorithm is considered to be cryptographically
/// strong, this implementation has not been reviewed for such purposes.
/// As such, all cryptographic uses of this implementation are strongly
/// discouraged.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SipHasher {
    k0: u64,
    k1: u64,
    length: usize, // how many bytes we've processed
    // v0, v2 and v1, v3 show up in pairs in the algorithm,
    // and simd implementations of SipHash will use vectors
    // of v02 and v13. By placing them in this order in the struct,
    // the compiler can pick up on just a few simd optimizations by itself.
    v0: u64,      // hash state
    v2: u64,
    v1: u64,
    v3: u64,
    tail: u64, // unprocessed bytes le
    ntail: usize,  // how many bytes in tail are valid
}

// sadly, these macro definitions can't appear later,
// because they're needed in the following defs;
// this design could be improved.

macro_rules! u8to64_le {
    ($buf:expr, $i:expr) =>
    ($buf[0+$i] as u64 |
     ($buf[1+$i] as u64) << 8 |
     ($buf[2+$i] as u64) << 16 |
     ($buf[3+$i] as u64) << 24 |
     ($buf[4+$i] as u64) << 32 |
     ($buf[5+$i] as u64) << 40 |
     ($buf[6+$i] as u64) << 48 |
     ($buf[7+$i] as u64) << 56);
    ($buf:expr, $i:expr, $len:expr) =>
    ({
        let mut t = 0;
        let mut out = 0;
        while t < $len {
            out |= ($buf[t+$i] as u64) << t*8;
            t += 1;
        }
        out
    });
}

/// Load a full u64 word from a byte stream, in LE order. Use
/// `copy_nonoverlapping` to let the compiler generate the most efficient way
/// to load u64 from a possibly unaligned address.
///
/// Unsafe because: unchecked indexing at i..i+8
#[inline]
unsafe fn load_u64_le(buf: &[u8], i: usize) -> u64 {
    debug_assert!(i + 8 <= buf.len());
    let mut data = 0u64;
    ptr::copy_nonoverlapping(buf.get_unchecked(i),
                             &mut data as *mut _ as *mut u8, 8);
    data.to_le()
}

macro_rules! rotl {
    ($x:expr, $b:expr) =>
    (($x << $b) | ($x >> (64_i32.wrapping_sub($b))))
}

macro_rules! compress {
    ($v0:expr, $v1:expr, $v2:expr, $v3:expr) =>
    ({
        $v0 = $v0.wrapping_add($v1); $v1 = rotl!($v1, 13); $v1 ^= $v0;
        $v0 = rotl!($v0, 32);
        $v2 = $v2.wrapping_add($v3); $v3 = rotl!($v3, 16); $v3 ^= $v2;
        $v0 = $v0.wrapping_add($v3); $v3 = rotl!($v3, 21); $v3 ^= $v0;
        $v2 = $v2.wrapping_add($v1); $v1 = rotl!($v1, 17); $v1 ^= $v2;
        $v2 = rotl!($v2, 32);
    })
}

impl SipHasher {
    /// Creates a new `SipHasher` with the two initial keys set to 0.
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new() -> SipHasher {
        SipHasher::new_with_keys(0, 0)
    }

    /// Creates a `SipHasher` that is keyed off the provided keys.
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
        let mut state = SipHasher {
            k0: key0,
            k1: key1,
            length: 0,
            v0: 0,
            v1: 0,
            v2: 0,
            v3: 0,
            tail: 0,
            ntail: 0,
        };
        state.reset();
        state
    }

    #[inline]
    fn reset(&mut self) {
        self.length = 0;
        self.v0 = self.k0 ^ 0x736f6d6570736575;
        self.v1 = self.k1 ^ 0x646f72616e646f6d;
        self.v2 = self.k0 ^ 0x6c7967656e657261;
        self.v3 = self.k1 ^ 0x7465646279746573;
        self.ntail = 0;
    }

    #[inline]
    fn write(&mut self, msg: &[u8]) {
        let length = msg.len();
        self.length += length;

        let mut needed = 0;

        if self.ntail != 0 {
            needed = 8 - self.ntail;
            if length < needed {
                self.tail |= u8to64_le!(msg, 0, length) << 8*self.ntail;
                self.ntail += length;
                return
            }

            let m = self.tail | u8to64_le!(msg, 0, needed) << 8*self.ntail;

            self.v3 ^= m;
            compress!(self.v0, self.v1, self.v2, self.v3);
            compress!(self.v0, self.v1, self.v2, self.v3);
            self.v0 ^= m;

            self.ntail = 0;
        }

        // Buffered tail is now flushed, process new input.
        let len = length - needed;
        let left = len & 0x7;

        let mut i = needed;
        while i < len - left {
            let mi = unsafe { load_u64_le(msg, i) };

            self.v3 ^= mi;
            compress!(self.v0, self.v1, self.v2, self.v3);
            compress!(self.v0, self.v1, self.v2, self.v3);
            self.v0 ^= mi;

            i += 8;
        }

        self.tail = u8to64_le!(msg, i, left);
        self.ntail = left;
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Hasher for SipHasher {
    #[inline]
    fn write(&mut self, msg: &[u8]) {
        self.write(msg)
    }

    #[inline]
    fn finish(&self) -> u64 {
        let mut v0 = self.v0;
        let mut v1 = self.v1;
        let mut v2 = self.v2;
        let mut v3 = self.v3;

        let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;

        v3 ^= b;
        compress!(v0, v1, v2, v3);
        compress!(v0, v1, v2, v3);
        v0 ^= b;

        v2 ^= 0xff;
        compress!(v0, v1, v2, v3);
        compress!(v0, v1, v2, v3);
        compress!(v0, v1, v2, v3);
        compress!(v0, v1, v2, v3);

        v0 ^ v1 ^ v2 ^ v3
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for SipHasher {
    #[inline]
    fn clone(&self) -> SipHasher {
        SipHasher {
            k0: self.k0,
            k1: self.k1,
            length: self.length,
            v0: self.v0,
            v1: self.v1,
            v2: self.v2,
            v3: self.v3,
            tail: self.tail,
            ntail: self.ntail,
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Default for SipHasher {
    fn default() -> SipHasher {
        SipHasher::new()
    }
}
<commit_msg>Stop a private method on `SipHasher` from shadowing `Hasher::write`<commit_after>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! An implementation of SipHash 2-4.

use prelude::v1::*;

use ptr;
use super::Hasher;

/// An implementation of SipHash 2-4.
///
/// See: http://131002.net/siphash/
///
/// Consider this as a main "general-purpose" hash for all hashtables: it
/// runs at good speed (competitive with spooky and city) and permits
/// strong _keyed_ hashing. Key your hashtables from a strong RNG,
/// such as `rand::Rng`.
///
/// Although the SipHash algorithm is considered to be cryptographically
/// strong, this implementation has not been reviewed for such purposes.
/// As such, all cryptographic uses of this implementation are strongly
/// discouraged.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct SipHasher {
    k0: u64,
    k1: u64,
    length: usize, // how many bytes we've processed
    // v0, v2 and v1, v3 show up in pairs in the algorithm,
    // and simd implementations of SipHash will use vectors
    // of v02 and v13. By placing them in this order in the struct,
    // the compiler can pick up on just a few simd optimizations by itself.
    v0: u64,      // hash state
    v2: u64,
    v1: u64,
    v3: u64,
    tail: u64, // unprocessed bytes le
    ntail: usize,  // how many bytes in tail are valid
}

// sadly, these macro definitions can't appear later,
// because they're needed in the following defs;
// this design could be improved.

macro_rules! u8to64_le {
    ($buf:expr, $i:expr) =>
    ($buf[0+$i] as u64 |
     ($buf[1+$i] as u64) << 8 |
     ($buf[2+$i] as u64) << 16 |
     ($buf[3+$i] as u64) << 24 |
     ($buf[4+$i] as u64) << 32 |
     ($buf[5+$i] as u64) << 40 |
     ($buf[6+$i] as u64) << 48 |
     ($buf[7+$i] as u64) << 56);
    ($buf:expr, $i:expr, $len:expr) =>
    ({
        let mut t = 0;
        let mut out = 0;
        while t < $len {
            out |= ($buf[t+$i] as u64) << t*8;
            t += 1;
        }
        out
    });
}

/// Load a full u64 word from a byte stream, in LE order. Use
/// `copy_nonoverlapping` to let the compiler generate the most efficient way
/// to load u64 from a possibly unaligned address.
///
/// Unsafe because: unchecked indexing at i..i+8
#[inline]
unsafe fn load_u64_le(buf: &[u8], i: usize) -> u64 {
    debug_assert!(i + 8 <= buf.len());
    let mut data = 0u64;
    ptr::copy_nonoverlapping(buf.get_unchecked(i),
                             &mut data as *mut _ as *mut u8, 8);
    data.to_le()
}

macro_rules! rotl {
    ($x:expr, $b:expr) =>
    (($x << $b) | ($x >> (64_i32.wrapping_sub($b))))
}

macro_rules! compress {
    ($v0:expr, $v1:expr, $v2:expr, $v3:expr) =>
    ({
        $v0 = $v0.wrapping_add($v1); $v1 = rotl!($v1, 13); $v1 ^= $v0;
        $v0 = rotl!($v0, 32);
        $v2 = $v2.wrapping_add($v3); $v3 = rotl!($v3, 16); $v3 ^= $v2;
        $v0 = $v0.wrapping_add($v3); $v3 = rotl!($v3, 21); $v3 ^= $v0;
        $v2 = $v2.wrapping_add($v1); $v1 = rotl!($v1, 17); $v1 ^= $v2;
        $v2 = rotl!($v2, 32);
    })
}

impl SipHasher {
    /// Creates a new `SipHasher` with the two initial keys set to 0.
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new() -> SipHasher {
        SipHasher::new_with_keys(0, 0)
    }

    /// Creates a `SipHasher` that is keyed off the provided keys.
    #[inline]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
        let mut state = SipHasher {
            k0: key0,
            k1: key1,
            length: 0,
            v0: 0,
            v1: 0,
            v2: 0,
            v3: 0,
            tail: 0,
            ntail: 0,
        };
        state.reset();
        state
    }

    #[inline]
    fn reset(&mut self) {
        self.length = 0;
        self.v0 = self.k0 ^ 0x736f6d6570736575;
        self.v1 = self.k1 ^ 0x646f72616e646f6d;
        self.v2 = self.k0 ^ 0x6c7967656e657261;
        self.v3 = self.k1 ^ 0x7465646279746573;
        self.ntail = 0;
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Hasher for SipHasher {
    #[inline]
    fn write(&mut self, msg: &[u8]) {
        let length = msg.len();
        self.length += length;

        let mut needed = 0;

        if self.ntail != 0 {
            needed = 8 - self.ntail;
            if length < needed {
                self.tail |= u8to64_le!(msg, 0, length) << 8*self.ntail;
                self.ntail += length;
                return
            }

            let m = self.tail | u8to64_le!(msg, 0, needed) << 8*self.ntail;

            self.v3 ^= m;
            compress!(self.v0, self.v1, self.v2, self.v3);
            compress!(self.v0, self.v1, self.v2, self.v3);
            self.v0 ^= m;

            self.ntail = 0;
        }

        // Buffered tail is now flushed, process new input.
        let len = length - needed;
        let left = len & 0x7;

        let mut i = needed;
        while i < len - left {
            let mi = unsafe { load_u64_le(msg, i) };

            self.v3 ^= mi;
            compress!(self.v0, self.v1, self.v2, self.v3);
            compress!(self.v0, self.v1, self.v2, self.v3);
            self.v0 ^= mi;

            i += 8;
        }

        self.tail = u8to64_le!(msg, i, left);
        self.ntail = left;
    }

    #[inline]
    fn finish(&self) -> u64 {
        let mut v0 = self.v0;
        let mut v1 = self.v1;
        let mut v2 = self.v2;
        let mut v3 = self.v3;

        let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail;

        v3 ^= b;
        compress!(v0, v1, v2, v3);
        compress!(v0, v1, v2, v3);
        v0 ^= b;

        v2 ^= 0xff;
        compress!(v0, v1, v2, v3);
        compress!(v0, v1, v2, v3);
        compress!(v0, v1, v2, v3);
        compress!(v0, v1, v2, v3);

        v0 ^ v1 ^ v2 ^ v3
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Clone for SipHasher {
    #[inline]
    fn clone(&self) -> SipHasher {
        SipHasher {
            k0: self.k0,
            k1: self.k1,
            length: self.length,
            v0: self.v0,
            v1: self.v1,
            v2: self.v2,
            v3: self.v3,
            tail: self.tail,
            ntail: self.ntail,
        }
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl Default for SipHasher {
    fn default() -> SipHasher {
        SipHasher::new()
    }
}
<|endoftext|>


<commit_before><commit_msg>Add deserialization example<commit_after>extern crate ron;
extern crate serde;
#[macro_use]
extern crate serde_derive;

use std::collections::HashMap;

use ron::de::from_str;

#[derive(Debug, Deserialize)]
struct Config {
    boolean: bool,
    float: f32,
    map: HashMap<u8, char>,
    nested: Nested,
    tuple: (u32, u32),
}

#[derive(Debug, Deserialize)]
struct Nested {
    a: String,
    b: char,
}

const CONFIG: &str = "(
    boolean: true,
    float: 8.2,
    map: {
        1: '1',
        2: '4',
        3: '9',
        4: '1',
        5: '2',
        6: '3',
    },
    nested: Nested(
        a: \"Decode me!\",
        b: 'z',
    ),
    tuple: (3, 7),
)";

fn main() {
    let config: Config = from_str(CONFIG).expect("Failed to deserialize");

    println!("Config: {:?}", &config);
}
<|endoftext|>


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

// We won't use the usual `main` function. We are going to use a different "entry point".
#![no_main]

// We won't use the standard library because it requires OS abstractions like threads and files and
// those are not available in this platform.
#![no_std]
#![feature(alloc)]
#![feature(collections)]

#[macro_use]
extern crate cc3200;
extern crate alloc;
extern crate freertos_rs;
extern crate freertos_alloc;

extern crate smallhttp;

#[macro_use]
extern crate log;

#[macro_use]
extern crate collections;

use cc3200::cc3200::{Board, Update};
use cc3200::simplelink::{SimpleLink, SimpleLinkError};
use cc3200::io::{File, Read, Write};

use freertos_rs::{Task};

static VERSION: &'static str = "1.0";

#[derive(Debug)]
pub enum Error {
    SLE(SimpleLinkError),
}

impl From<SimpleLinkError> for Error {
    fn from(err: SimpleLinkError) -> Error {
        Error::SLE(err)
    }
}

macro_rules! ignore {
    ($e:expr) => ({
        match $e {
            _ => { }
        }
    })
}

fn update_demo() -> Result<(), Error> {

    SimpleLink::start_spawn_task()?;
    SimpleLink::init_app_variables();
    SimpleLink::start()?;

    let imagename = "/sys/mcuimg.bin";
    let filename = "/update/mcuimg.bin";

    // 1) Get file info for update binary

    let info = File::get_info(filename)?;

    println!("Found update {} of {} bytes.", filename, info.file_length);

    // 2) Open image file for writing

    let mut image = File::create(imagename, info.file_length as usize, false)?;

    // 3) Copy update to image

    {
        let mut file = File::open(filename)?;

        let mut len = 0 as usize;

        loop {
            let mut buf: [u8; 256] = [0; 256];

            let buflen = match file.read(&mut buf) {
                Ok(res) => {
                    res
                },
                Err(_) => {
                    break; // assume EOF
                },
            };

            len += image.write(&buf[0..buflen])?;
        }

        println!("Wrote {} bytes to {}.", len, imagename);
    }

    // 4) Commit

    Update::commit();

    println!("Press RESET to run updated image...");

    Ok(())
}

// Conceptually, this is our program "entry point". It's the first thing the microcontroller will
// execute when it (re)boots. (As far as the linker is concerned the entry point must be named
// `start` (by default; it can have a different name). That's why this function is `pub`lic, named
// `start` and is marked as `#[no_mangle]`.)
//
// Returning from this function is undefined because there is nothing to return to! To statically
// forbid returning from this function, we mark it as divergent, hence the `fn() -> !` signature.
#[no_mangle]
pub fn start() -> ! {

    Board::init();

    println!("Welcome to CC3200 Update example {}", VERSION);

    let _client = {
        Task::new()
            .name("client")
            .stack_size(2048) // 32-bit words
            .start(|| {
                match update_demo() {
                    Ok(())  => { println!("update_demo succeeded"); },
                    Err(e)  => { println!("update_demo failed: {:?}", e); },
                };
                loop {}
            })
            .unwrap()
    };

    Board::start_scheduler();

    // The only reason start_scheduler should fail is if there wasn't enough
    // heap to initialize the IDLE and timer tasks

    loop {}
}
<|endoftext|>


<commit_before><commit_msg>Look at implementing collision physics<commit_after>#![cfg_attr(feature = "nightly", feature(test))]
#![cfg(feature = "nightly")]
extern crate test;

extern crate korome;

#[cfg(all(feature = "nightly", test))]
mod tests {
    use test::{Bencher, black_box};
    use super::*;

    const M1: f32 = 10.;
    const M2: f32 = 20.;

    const V1: Vect = Vector2(10., 10.);
    const V2: Vect = Vector2(0., 10.);

    const P: Vect = Vector2(10., 0.);

    #[bench]
    fn bench_normal(bench: &mut Bencher){
        bench
            .iter(|| black_box(
                calc_velocity_after_collision(M1, M2, V1, V2, P)
            ))
    }

    #[bench]
    fn bench_alt(bench: &mut Bencher){
        bench
            .iter(|| black_box(
                call_alt(M1, M2, V1, V2, P.direction())
            ))
    }
    #[bench]
    fn bench_polar(bench: &mut Bencher){
        let a = (V1.length(), V2.length(), V1.direction(), V2.direction(), P.direction());
        bench
            .iter(|| black_box(
                calc_velocity_after_collision_alt(M1, M2, a.0, a.1, a.2, a.3, a.4)
            ))
    }
    #[bench]
    fn bench_cartesian(bench: &mut Bencher){
        let a = (V1.length(), V2.length(), V1.direction(), V2.direction());
        bench
            .iter(|| black_box(
                calc_velocity_after_collision(M1, M2, a.0 * Vector2::unit_vector(a.2), a.1 * Vector2::unit_vector(a.3), P)
            ))
    }
}

pub use korome::Vector2;

pub type Vect = Vector2<f32>;

pub fn calc_velocity_after_collision(m1: f32, m2: f32, v1: Vect, v2: Vect, dist: Vect) -> Vect{
    v1 - (2. * m2)/(m1 + m2) * (v1 - v2).dot(dist) / dist.length().powi(2) * dist
}

use std::f32::consts::FRAC_PI_2;

#[inline]
pub fn call_alt(m1: f32, m2: f32, v1: Vect, v2: Vect, dir: f32) -> Vect{
    calc_velocity_after_collision_alt(m1, m2, v1.length(), v2.length(), v1.direction(), v2.direction(), dir)
}

pub fn calc_velocity_after_collision_alt(m1: f32, m2: f32, v1: f32, v2: f32, a1: f32, a2: f32, phi: f32) -> Vect{
    let (r1_sin, r1_cos) = (a1 - phi).sin_cos();
    let r2_cos = (a2 - phi).cos();

    let sum1 = (v1 * r1_cos * (m1-m2) + 2. * m2 * v2 * r2_cos) / (m1 + m2);
    let sum2 = v1 * r1_sin;

    let (sin1, cos1) = phi.sin_cos();
    let (sin2, cos2) = (phi + FRAC_PI_2).sin_cos();

    Vector2(
        sum1 * cos1 + sum2 * cos2,
        sum1 * sin1 + sum2 * sin2
    )
}

use std::io::{Write, stdin, stdout};

fn main() {
    let (m1, m2, v1, v2, dist);

    m1 = ask_for_value("Mass 1");
    m2 = ask_for_value("Mass 2");
    v1 = Vector2(ask_for_value("v1.x"), ask_for_value("v1.y"));
    v2 = Vector2(ask_for_value("v2.x"), ask_for_value("v2.y"));
    dist = Vector2::<f32>(ask_for_value("p1.x"), ask_for_value("p1.y")) - Vector2(ask_for_value("p2.x"), ask_for_value("p2.y"));

    println!("= {:?}", calc_velocity_after_collision(m1, m2, v1, v2, dist));
    println!("= {:?}", call_alt(m1, m2, v1, v2, dist.direction()));
}

use std::str::FromStr;
use std::fmt::Debug;

fn ask_for_value<T: FromStr>(prompt: &str) -> T
where <T as FromStr>::Err: Debug {
    let mut line = String::new();

    print!("{}: ", prompt);stdout().flush().unwrap();
    stdin().read_line(&mut line).unwrap();
    line.trim().parse::<T>().unwrap()
}
<|endoftext|>


<commit_before><commit_msg>Implemented CRC32<commit_after>extern crate crc;

use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use std::io::Read;
use std::path::Path;

use self::crc::{crc32, Hasher32};

fn verify(path: &Path)
{
    let mut buffer = File::open(path).unwrap();
    let mut digest = crc32::Digest::new(crc32::IEEE);

    for line in buffer.bytes() {
            digest.write(&[line.unwrap()]);
    }
}

<|endoftext|>


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

extern crate winit;
extern crate vk_sys as vk;
extern crate gfx_core;
extern crate gfx_device_vulkan;

#[cfg(unix)]
extern crate xcb;
#[cfg(target_os = "windows")]
extern crate kernel32;

use std::ffi::CStr;
use std::ptr;
use std::os::raw;
use gfx_core::format;

#[cfg(target_os = "windows")]
use winit::os::windows::WindowExt;

pub type TargetHandle<T> = gfx_core::handle::RenderTargetView<gfx_device_vulkan::Resources, T>;

pub struct SwapTarget<T> {
    _image: vk::Image,
    target: TargetHandle<T>,
    _fence: vk::Fence,
}

pub struct Window<T> {
    window: winit::Window,
    _debug_callback: Option<vk::DebugReportCallbackEXT>,
    swapchain: vk::SwapchainKHR,
    targets: Vec<SwapTarget<T>>,
    queue: gfx_device_vulkan::GraphicsQueue,
}

pub struct Frame<'a, T: 'a> {
    window: &'a mut Window<T>,
    target_id: u32,
}

impl<'a, T: Clone> Frame<'a, T> {
    pub fn get_target(&self) -> TargetHandle<T> {
        self.window.targets[self.target_id as usize].target.clone()
    }
    pub fn get_queue(&mut self) -> &mut gfx_device_vulkan::GraphicsQueue {
        &mut self.window.queue
    }
}

impl<'a, T> Drop for Frame<'a, T> {
    fn drop(&mut self) {
        let mut result = vk::SUCCESS;
        let info = vk::PresentInfoKHR {
            sType: vk::STRUCTURE_TYPE_PRESENT_INFO_KHR,
            pNext: ptr::null(),
            waitSemaphoreCount: 0,
            pWaitSemaphores: ptr::null(),
            swapchainCount: 1,
            pSwapchains: &self.window.swapchain,
            pImageIndices: &self.target_id,
            pResults: &mut result,
        };
        let (_dev, vk) = self.window.queue.get_share().get_device();
        unsafe {
            vk.QueuePresentKHR(self.window.queue.get_queue(), &info);
        }
        assert_eq!(vk::SUCCESS, result);
    }
}

impl<T: Clone> Window<T> {
    pub fn start_frame(&mut self) -> Frame<T> {
        //TODO: handle window resize (requires swapchain recreation)
        let index = unsafe {
            let (dev, vk) = self.queue.get_share().get_device();
            let mut i = 0;
            assert_eq!(vk::SUCCESS, vk.AcquireNextImageKHR(dev, self.swapchain, 60, 0, 0, &mut i));
            i
        };
        Frame {
            window: self,
            target_id: index,
        }
    }

    pub fn get_any_target(&self) -> TargetHandle<T> {
        self.targets[0].target.clone()
    }

    pub fn get_window(&mut self) -> &mut winit::Window {
        &mut self.window
    }
}

const LAYERS: &'static [&'static str] = &[
];
const LAYERS_DEBUG: &'static [&'static str] = &[
    "VK_LAYER_LUNARG_standard_validation",
];
const EXTENSIONS: &'static [&'static str] = &[
    "VK_KHR_surface",
    "VK_KHR_xcb_surface",
];
const EXTENSIONS_DEBUG: &'static [&'static str] = &[
    "VK_KHR_surface",
    "VK_KHR_xcb_surface",
    "VK_EXT_debug_report",
];
const DEV_EXTENSIONS: &'static [&'static str] = &[
    "VK_KHR_swapchain",
];

extern "system" fn callback(flags: vk::DebugReportFlagsEXT,
                            _ob_type: vk::DebugReportObjectTypeEXT, _object: u64, _location: usize,
                            _msg_code: i32, layer_prefix_c: *const raw::c_char,
                            description_c: *const raw::c_char, _user_data: *mut raw::c_void) -> u32
{
    let layer_prefix = unsafe { CStr::from_ptr(layer_prefix_c) }.to_str().unwrap();
    let description  = unsafe { CStr::from_ptr(description_c)  }.to_str().unwrap();
    println!("Vk flags {:x} in layer {}: {}", flags, layer_prefix, description);
    vk::FALSE
}

pub fn init<T: gfx_core::format::RenderFormat>(title: &str, width: u32, height: u32)
                -> (Window<T>, gfx_device_vulkan::Factory) {
    let window = winit::WindowBuilder::new()
        .with_dimensions(width, height)
        .with_title(title.to_string()).build().unwrap();

    let debug = false;
    let (mut device, mut factory, backend) = gfx_device_vulkan::create(title, 1,
        if debug {LAYERS_DEBUG} else {LAYERS},
        if debug {EXTENSIONS_DEBUG} else {EXTENSIONS},
        DEV_EXTENSIONS);

    let debug_callback = if debug {
        let info = vk::DebugReportCallbackCreateInfoEXT {
            sType: vk::STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT,
            pNext: ptr::null(),
            flags: vk::DEBUG_REPORT_INFORMATION_BIT_EXT | vk::DEBUG_REPORT_WARNING_BIT_EXT |
                   vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | vk::DEBUG_REPORT_ERROR_BIT_EXT |
                   vk::DEBUG_REPORT_DEBUG_BIT_EXT,
            pfnCallback: callback,
            pUserData: ptr::null_mut(),
        };
        let (inst, vk) = backend.get_instance();
        let mut out = 0;
        assert_eq!(vk::SUCCESS, unsafe {
            vk.CreateDebugReportCallbackEXT(inst, &info, ptr::null(), &mut out)
        });
        Some(out)
    }else {
        None
    };

    let surface = create_surface(backend.clone(), &window);

    let (dev, vk) = backend.get_device();
    let mut images: [vk::Image; 2] = [0; 2];
    let mut num = images.len() as u32;
    let format = <T as format::Formatted>::get_format();

    let swapchain_info = vk::SwapchainCreateInfoKHR {
        sType: vk::STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
        pNext: ptr::null(),
        flags: 0,
        surface: surface,
        minImageCount: num,
        imageFormat: gfx_device_vulkan::data::map_format(format.0, format.1).unwrap(),
        imageColorSpace: vk::COLOR_SPACE_SRGB_NONLINEAR_KHR,
        imageExtent: vk::Extent2D { width: width, height: height },
        imageArrayLayers: 1,
        imageUsage: vk::IMAGE_USAGE_COLOR_ATTACHMENT_BIT | vk::IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
        imageSharingMode: vk::SHARING_MODE_EXCLUSIVE,
        queueFamilyIndexCount: 1,
        pQueueFamilyIndices: &0,
        preTransform: vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
        compositeAlpha: vk::COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
        presentMode: vk::PRESENT_MODE_FIFO_RELAXED_KHR,
        clipped: vk::TRUE,
        oldSwapchain: 0,
    };

    let mut swapchain = 0;
    assert_eq!(vk::SUCCESS, unsafe {
        vk.CreateSwapchainKHR(dev, &swapchain_info, ptr::null(), &mut swapchain)
    });

    assert_eq!(vk::SUCCESS, unsafe {
        vk.GetSwapchainImagesKHR(dev, swapchain, &mut num, images.as_mut_ptr())
    });

    let mut cbuf = factory.create_command_buffer();

    let targets = images[.. num as usize].iter().map(|image| {
        use gfx_core::factory::Typed;
        cbuf.image_barrier(*image, vk::IMAGE_ASPECT_COLOR_BIT, vk::IMAGE_LAYOUT_UNDEFINED, vk::IMAGE_LAYOUT_PRESENT_SRC_KHR);
        let raw_view = factory.view_swapchain_image(*image, format, (width, height)).unwrap();
        SwapTarget {
            _image: *image,
            target: Typed::new(raw_view),
            _fence: factory.create_fence(true),
        }
    }).collect();

    {
        use gfx_core::Device;
        device.submit(&mut cbuf);
    }

    let win = Window {
        window: window,
        _debug_callback: debug_callback,
        swapchain: swapchain,
        targets: targets,
        queue: device,
    };
    (win, factory)
}

#[cfg(target_os = "windows")]
fn create_surface(backend: gfx_device_vulkan::SharePointer, window: &winit::Window) -> vk::SurfaceKHR {
    let (inst, vk) = backend.get_instance();
    let info = vk::Win32SurfaceCreateInfoKHR {
        sType: vk::STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR,
        pNext: ptr::null(),
        flags: 0,
        hinstance: unsafe { kernel32::GetModuleHandleW(ptr::null()) } as *mut _,
        hwnd: window.get_hwnd() as *mut _,
    };
    let mut out = 0;
    assert_eq!(vk::SUCCESS, unsafe {
        vk.CreateWin32SurfaceKHR(inst, &info, ptr::null(), &mut out)
    });
    out
}

#[cfg(unix)]
fn create_surface(backend: gfx_device_vulkan::SharePointer, win: &winit::Window) -> vk::SurfaceKHR {
    let (inst, vk) = backend.get_instance();
    let info = vk::XcbSurfaceCreateInfoKHR {
        sType: vk::STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR,
        pNext: ptr::null(),
        flags: 0,
        connection: window.get_xcb_connection() as *const _,
        window: window.get_xlib_window() as *const _,
    };
    let mut out = 0;
    assert_eq!(vk::SUCCESS, unsafe {
        vk.CreateXcbSurfaceKHR(inst, &info, ptr::null(), &mut out)
    });
    out
}
<commit_msg>Vulkan: Fix linux build<commit_after>// Copyright 2016 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.

extern crate winit;
extern crate vk_sys as vk;
extern crate gfx_core;
extern crate gfx_device_vulkan;

#[cfg(unix)]
extern crate xcb;
#[cfg(target_os = "windows")]
extern crate kernel32;

use std::ffi::CStr;
use std::ptr;
use std::os::raw;
use gfx_core::format;

#[cfg(unix)]
use winit::os::unix::WindowExt;
#[cfg(target_os = "windows")]
use winit::os::windows::WindowExt;

pub type TargetHandle<T> = gfx_core::handle::RenderTargetView<gfx_device_vulkan::Resources, T>;

pub struct SwapTarget<T> {
    _image: vk::Image,
    target: TargetHandle<T>,
    _fence: vk::Fence,
}

pub struct Window<T> {
    window: winit::Window,
    _debug_callback: Option<vk::DebugReportCallbackEXT>,
    swapchain: vk::SwapchainKHR,
    targets: Vec<SwapTarget<T>>,
    queue: gfx_device_vulkan::GraphicsQueue,
}

pub struct Frame<'a, T: 'a> {
    window: &'a mut Window<T>,
    target_id: u32,
}

impl<'a, T: Clone> Frame<'a, T> {
    pub fn get_target(&self) -> TargetHandle<T> {
        self.window.targets[self.target_id as usize].target.clone()
    }
    pub fn get_queue(&mut self) -> &mut gfx_device_vulkan::GraphicsQueue {
        &mut self.window.queue
    }
}

impl<'a, T> Drop for Frame<'a, T> {
    fn drop(&mut self) {
        let mut result = vk::SUCCESS;
        let info = vk::PresentInfoKHR {
            sType: vk::STRUCTURE_TYPE_PRESENT_INFO_KHR,
            pNext: ptr::null(),
            waitSemaphoreCount: 0,
            pWaitSemaphores: ptr::null(),
            swapchainCount: 1,
            pSwapchains: &self.window.swapchain,
            pImageIndices: &self.target_id,
            pResults: &mut result,
        };
        let (_dev, vk) = self.window.queue.get_share().get_device();
        unsafe {
            vk.QueuePresentKHR(self.window.queue.get_queue(), &info);
        }
        assert_eq!(vk::SUCCESS, result);
    }
}

impl<T: Clone> Window<T> {
    pub fn start_frame(&mut self) -> Frame<T> {
        //TODO: handle window resize (requires swapchain recreation)
        let index = unsafe {
            let (dev, vk) = self.queue.get_share().get_device();
            let mut i = 0;
            assert_eq!(vk::SUCCESS, vk.AcquireNextImageKHR(dev, self.swapchain, 60, 0, 0, &mut i));
            i
        };
        Frame {
            window: self,
            target_id: index,
        }
    }

    pub fn get_any_target(&self) -> TargetHandle<T> {
        self.targets[0].target.clone()
    }

    pub fn get_window(&mut self) -> &mut winit::Window {
        &mut self.window
    }
}

const LAYERS: &'static [&'static str] = &[
];
const LAYERS_DEBUG: &'static [&'static str] = &[
    "VK_LAYER_LUNARG_standard_validation",
];
const EXTENSIONS: &'static [&'static str] = &[
    "VK_KHR_surface",
    "VK_KHR_xcb_surface",
];
const EXTENSIONS_DEBUG: &'static [&'static str] = &[
    "VK_KHR_surface",
    "VK_KHR_xcb_surface",
    "VK_EXT_debug_report",
];
const DEV_EXTENSIONS: &'static [&'static str] = &[
    "VK_KHR_swapchain",
];

extern "system" fn callback(flags: vk::DebugReportFlagsEXT,
                            _ob_type: vk::DebugReportObjectTypeEXT, _object: u64, _location: usize,
                            _msg_code: i32, layer_prefix_c: *const raw::c_char,
                            description_c: *const raw::c_char, _user_data: *mut raw::c_void) -> u32
{
    let layer_prefix = unsafe { CStr::from_ptr(layer_prefix_c) }.to_str().unwrap();
    let description  = unsafe { CStr::from_ptr(description_c)  }.to_str().unwrap();
    println!("Vk flags {:x} in layer {}: {}", flags, layer_prefix, description);
    vk::FALSE
}

pub fn init<T: gfx_core::format::RenderFormat>(title: &str, width: u32, height: u32)
                -> (Window<T>, gfx_device_vulkan::Factory) {
    let window = winit::WindowBuilder::new()
        .with_dimensions(width, height)
        .with_title(title.to_string()).build().unwrap();

    let debug = false;
    let (mut device, mut factory, backend) = gfx_device_vulkan::create(title, 1,
        if debug {LAYERS_DEBUG} else {LAYERS},
        if debug {EXTENSIONS_DEBUG} else {EXTENSIONS},
        DEV_EXTENSIONS);

    let debug_callback = if debug {
        let info = vk::DebugReportCallbackCreateInfoEXT {
            sType: vk::STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT,
            pNext: ptr::null(),
            flags: vk::DEBUG_REPORT_INFORMATION_BIT_EXT | vk::DEBUG_REPORT_WARNING_BIT_EXT |
                   vk::DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT | vk::DEBUG_REPORT_ERROR_BIT_EXT |
                   vk::DEBUG_REPORT_DEBUG_BIT_EXT,
            pfnCallback: callback,
            pUserData: ptr::null_mut(),
        };
        let (inst, vk) = backend.get_instance();
        let mut out = 0;
        assert_eq!(vk::SUCCESS, unsafe {
            vk.CreateDebugReportCallbackEXT(inst, &info, ptr::null(), &mut out)
        });
        Some(out)
    }else {
        None
    };

    let surface = create_surface(backend.clone(), &window);

    let (dev, vk) = backend.get_device();
    let mut images: [vk::Image; 2] = [0; 2];
    let mut num = images.len() as u32;
    let format = <T as format::Formatted>::get_format();

    let swapchain_info = vk::SwapchainCreateInfoKHR {
        sType: vk::STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,
        pNext: ptr::null(),
        flags: 0,
        surface: surface,
        minImageCount: num,
        imageFormat: gfx_device_vulkan::data::map_format(format.0, format.1).unwrap(),
        imageColorSpace: vk::COLOR_SPACE_SRGB_NONLINEAR_KHR,
        imageExtent: vk::Extent2D { width: width, height: height },
        imageArrayLayers: 1,
        imageUsage: vk::IMAGE_USAGE_COLOR_ATTACHMENT_BIT | vk::IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
        imageSharingMode: vk::SHARING_MODE_EXCLUSIVE,
        queueFamilyIndexCount: 1,
        pQueueFamilyIndices: &0,
        preTransform: vk::SURFACE_TRANSFORM_IDENTITY_BIT_KHR,
        compositeAlpha: vk::COMPOSITE_ALPHA_OPAQUE_BIT_KHR,
        presentMode: vk::PRESENT_MODE_FIFO_RELAXED_KHR,
        clipped: vk::TRUE,
        oldSwapchain: 0,
    };

    let mut swapchain = 0;
    assert_eq!(vk::SUCCESS, unsafe {
        vk.CreateSwapchainKHR(dev, &swapchain_info, ptr::null(), &mut swapchain)
    });

    assert_eq!(vk::SUCCESS, unsafe {
        vk.GetSwapchainImagesKHR(dev, swapchain, &mut num, images.as_mut_ptr())
    });

    let mut cbuf = factory.create_command_buffer();

    let targets = images[.. num as usize].iter().map(|image| {
        use gfx_core::factory::Typed;
        cbuf.image_barrier(*image, vk::IMAGE_ASPECT_COLOR_BIT, vk::IMAGE_LAYOUT_UNDEFINED, vk::IMAGE_LAYOUT_PRESENT_SRC_KHR);
        let raw_view = factory.view_swapchain_image(*image, format, (width, height)).unwrap();
        SwapTarget {
            _image: *image,
            target: Typed::new(raw_view),
            _fence: factory.create_fence(true),
        }
    }).collect();

    {
        use gfx_core::Device;
        device.submit(&mut cbuf);
    }

    let win = Window {
        window: window,
        _debug_callback: debug_callback,
        swapchain: swapchain,
        targets: targets,
        queue: device,
    };
    (win, factory)
}

#[cfg(target_os = "windows")]
fn create_surface(backend: gfx_device_vulkan::SharePointer, window: &winit::Window) -> vk::SurfaceKHR {
    let (inst, vk) = backend.get_instance();
    let info = vk::Win32SurfaceCreateInfoKHR {
        sType: vk::STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR,
        pNext: ptr::null(),
        flags: 0,
        hinstance: unsafe { kernel32::GetModuleHandleW(ptr::null()) } as *mut _,
        hwnd: window.get_hwnd() as *mut _,
    };
    let mut out = 0;
    assert_eq!(vk::SUCCESS, unsafe {
        vk.CreateWin32SurfaceKHR(inst, &info, ptr::null(), &mut out)
    });
    out
}

#[cfg(unix)]
fn create_surface(backend: gfx_device_vulkan::SharePointer, window: &winit::Window) -> vk::SurfaceKHR {
    let (inst, vk) = backend.get_instance();
    let info = vk::XcbSurfaceCreateInfoKHR {
        sType: vk::STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR,
        pNext: ptr::null(),
        flags: 0,
        connection: window.get_xcb_connection().unwrap() as *const _,
        window: window.get_xlib_window().unwrap() as *const _,
    };
    let mut out = 0;
    assert_eq!(vk::SUCCESS, unsafe {
        vk.CreateXcbSurfaceKHR(inst, &info, ptr::null(), &mut out)
    });
    out
}
<|endoftext|>


<commit_before><commit_msg>Implement Rectangle.can_hold<commit_after><|endoftext|>


<commit_before><commit_msg>Add store cache flushing after each 100st entry<commit_after><|endoftext|>


<commit_before><commit_msg>Added a basic example<commit_after>#![feature(core)]

extern crate iron;
extern crate postgres;
extern crate "iron-postgres-middleware" as pg_middleware;

use iron::prelude::*;
use iron::status;
use pg_middleware::{PostgresMiddleware, PostgresReqExt};

fn main() {
    let mut chain = Chain::new(name_list);

    let pg_middleware = PostgresMiddleware::new("postgres://postgres@localhost/example");

    {
        let conn = pg_middleware.pool.get().unwrap();
        conn.execute(
            "CREATE TABLE IF NOT EXISTS names (
                id SERIAL PRIMARY KEY,
                name VARCHAR(255) NOT NULL
            )",
        &[]).unwrap();
        conn.execute("INSERT INTO names(name) VALUES ($1)", &[&"Joe Smith".to_string()]).unwrap();
    }

    chain.link_before(pg_middleware);

    Iron::new(chain).listen("localhost:3000").unwrap();
}

fn name_list(req: &mut Request) -> IronResult<Response> {
    let conn = req.db_conn();
    let stmt = conn.prepare("SELECT id, name FROM names").unwrap();
    let rows = stmt.query(&[]).unwrap();

    let mut resp_str = "Names:\n".to_string();

    for row in rows {
        let id: i32 = row.get(0);
        let name: String = row.get(1);
        let name_format = format!("{}: {}\n", id, name);
        resp_str.push_str(name_format.as_slice());
    }

    Ok(Response::with((status::Ok, resp_str)))
}
<|endoftext|>


<commit_before><commit_msg>Add tests<commit_after><|endoftext|>


<commit_before>/**

An implementation of the Graph500 Bread First Search problem in Rust.

*/

use std;
import std::time;
import std::map;
import std::map::hashmap;
import std::deque;
import std::deque::t;
import std::arc;
import std::par;
import io::writer_util;
import comm::*;
import int::abs;

type node_id = i64;
type graph = [[node_id]];
type bfs_result = [node_id];

iface queue<T: send> {
    fn add_back(T);
    fn pop_front() -> T;
    fn size() -> uint;
}

#[doc="Creates a queue based on ports and channels.

This is admittedly not ideal, but it will help us work around the deque
bugs for the time being."]
fn create_queue<T: send>() -> queue<T> {
    type repr<T: send> = {
        p : port<T>,
        c : chan<T>,
        mut s : uint,
    };

    let p = port();
    let c = chan(p);

    impl<T: copy send> of queue<T> for repr<T> {
        fn add_back(x : T) {
            let x = x;
            send(self.c, x);
            self.s += 1u;
        }

        fn pop_front() -> T {
            self.s -= 1u;
            recv(self.p)
        }

        fn size() -> uint { self.s }
    }

    let Q : repr<T> = { p : p, c : c, mut s : 0u };
    Q as queue::<T>
}

fn make_edges(scale: uint, edgefactor: uint) -> [(node_id, node_id)] {
    let r = rand::rng();

    fn choose_edge(i: node_id, j: node_id, scale: uint, r: rand::rng)
        -> (node_id, node_id) {

        let A = 0.57;
        let B = 0.19;
        let C = 0.19;

        if scale == 0u {
            (i, j)
        }
        else {
            let i = i * 2i64;
            let j = j * 2i64;
            let scale = scale - 1u;

            let x = r.gen_float();

            if x < A {
                choose_edge(i, j, scale, r)
            }
            else {
                let x = x - A;
                if x < B {
                    choose_edge(i + 1i64, j, scale, r)
                }
                else {
                    let x = x - B;
                    if x < C {
                        choose_edge(i, j + 1i64, scale, r)
                    }
                    else {
                        choose_edge(i + 1i64, j + 1i64, scale, r)
                    }
                }
            }
        }
    }

    vec::from_fn((1u << scale) * edgefactor) {|_i|
        choose_edge(0i64, 0i64, scale, r)
    }
}

fn make_graph(N: uint, edges: [(node_id, node_id)]) -> graph {
    let graph = vec::from_fn(N) {|_i|
        map::hashmap::<node_id, ()>({|x| x as uint }, {|x, y| x == y })
    };

    vec::each(edges) {|e|
        let (i, j) = e;
        map::set_add(graph[i], j);
        map::set_add(graph[j], i);
        true
    }

    graph.map() {|v|
        map::vec_from_set(v)
    }
}

fn gen_search_keys(graph: graph, n: uint) -> [node_id] {
    let keys = map::hashmap::<node_id, ()>({|x| x as uint }, {|x, y| x == y });
    let r = rand::rng();

    while keys.size() < n {
        let k = r.gen_uint_range(0u, graph.len());

        if graph[k].len() > 0u && vec::any(graph[k]) {|i|
            i != k as node_id
        } {
            map::set_add(keys, k as node_id);
        }
    }
    map::vec_from_set(keys)
}

#[doc="Returns a vector of all the parents in the BFS tree rooted at key.

Nodes that are unreachable have a parent of -1."]
fn bfs(graph: graph, key: node_id) -> bfs_result {
    let marks : [mut node_id]
        = vec::to_mut(vec::from_elem(vec::len(graph), -1i64));

    let Q = create_queue();

    Q.add_back(key);
    marks[key] = key;

    while Q.size() > 0u {
        let t = Q.pop_front();

        graph[t].each() {|k|
            if marks[k] == -1i64 {
                marks[k] = t;
                Q.add_back(k);
            }
            true
        };
    }

    vec::from_mut(marks)
}

#[doc="Another version of the bfs function.

This one uses the same algorithm as the parallel one, just without
using the parallel vector operators."]
fn bfs2(graph: graph, key: node_id) -> bfs_result {
    // This works by doing functional updates of a color vector.

    enum color {
        white,
        // node_id marks which node turned this gray/black.
        // the node id later becomes the parent.
        gray(node_id),
        black(node_id)
    };

    let mut colors = vec::from_fn(graph.len()) {|i|
        if i as node_id == key {
            gray(key)
        }
        else {
            white
        }
    };

    fn is_gray(c: color) -> bool {
        alt c {
          gray(_) { true }
          _ { false }
        }
    }

    let mut i = 0u;
    while vec::any(colors, is_gray) {
        // Do the BFS.
        log(info, #fmt("PBFS iteration %?", i));
        i += 1u;
        colors = colors.mapi() {|i, c|
            let c : color = c;
            alt c {
              white {
                let i = i as node_id;

                let neighbors = graph[i];

                let mut color = white;

                neighbors.each() {|k|
                    if is_gray(colors[k]) {
                        color = gray(k);
                        false
                    }
                    else { true }
                };

                color
              }
              gray(parent) { black(parent) }
              black(parent) { black(parent) }
            }
        }
    }

    // Convert the results.
    vec::map(colors) {|c|
        alt c {
          white { -1i64 }
          black(parent) { parent }
          _ { fail "Found remaining gray nodes in BFS" }
        }
    }
}

#[doc="A parallel version of the bfs function."]
fn pbfs(graph: graph, key: node_id) -> bfs_result {
    // This works by doing functional updates of a color vector.

    enum color {
        white,
        // node_id marks which node turned this gray/black.
        // the node id later becomes the parent.
        gray(node_id),
        black(node_id)
    };

    let mut colors = vec::from_fn(graph.len()) {|i|
        if i as node_id == key {
            gray(key)
        }
        else {
            white
        }
    };

    #[inline(always)]
    fn is_gray(c: color) -> bool {
        alt c {
          gray(_) { true }
          _ { false }
        }
    }

    let (res, graph) = arc::shared_arc(copy graph);

    let mut i = 0u;
    while par::any(colors, is_gray) {
        // Do the BFS.
        log(info, #fmt("PBFS iteration %?", i));
        i += 1u;
        let old_len = colors.len();

        let (res, color) = arc::shared_arc(copy colors);

        colors = par::mapi(colors) {|i, c|
            let c : color = c;
            let colors = &arc::get_arc(color);
            let colors : [color] = *arc::get(colors);
            let graph = &arc::get_arc(graph);
            let graph : graph = *arc::get(graph);
            alt c {
              white {
                let i = i as node_id;

                let neighbors = graph[i];

                let mut color = white;

                neighbors.each() {|k|
                    if is_gray(colors[k]) {
                        color = gray(k);
                        false
                    }
                    else { true }
                    };
                color
              }
              gray(parent) { black(parent) }
              black(parent) { black(parent) }
            }
        };
        assert(colors.len() == old_len);
    }

    // Convert the results.
    par::map(colors) {|c|
        alt c {
          white { -1i64 }
          black(parent) { parent }
          _ { fail "Found remaining gray nodes in BFS" }
        }
    }
}

#[doc="Performs at least some of the validation in the Graph500 spec."]
fn validate(edges: [(node_id, node_id)],
            root: node_id, tree: bfs_result) -> bool {
    // There are 5 things to test. Below is code for each of them.

    // 1. The BFS tree is a tree and does not contain cycles.
    //
    // We do this by iterating over the tree, and tracing each of the
    // parent chains back to the root. While we do this, we also
    // compute the levels for each node.

    log(info, "Verifying tree structure...");

    let mut status = true;
    let level = tree.map() {|parent|
        let mut parent = parent;
        let mut path = [];

        if parent == -1i64 {
            // This node was not in the tree.
            -1
        }
        else {
            while parent != root {
                if vec::contains(path, parent) {
                    status = false;
                }

                path += [parent];
                parent = tree[parent];
            }

            // The length of the path back to the root is the current
            // level.
            path.len() as int
        }
    };

    if !status { ret status }

    // 2. Each tree edge connects vertices whose BFS levels differ by
    //    exactly one.

    log(info, "Verifying tree edges...");

    let status = tree.alli() {|k, parent|
        if parent != root && parent != -1i64 {
            level[parent] == level[k] - 1
        }
        else {
            true
        }
    };

    if !status { ret status }

    // 3. Every edge in the input list has vertices with levels that
    //    differ by at most one or that both are not in the BFS tree.

    log(info, "Verifying graph edges...");

    let status = edges.all() {|e|
        let (u, v) = e;

        abs(level[u] - level[v]) <= 1
    };

    if !status { ret status }

    // 4. The BFS tree spans an entire connected component's vertices.

    // This is harder. We'll skip it for now...

    // 5. A node and its parent are joined by an edge of the original
    //    graph.

    log(info, "Verifying tree and graph edges...");

    let status = par::alli(tree) {|u, v|
        let u = u as node_id;
        if v == -1i64 || u == root {
            true
        }
        else {
            edges.contains((u, v)) || edges.contains((v, u))
        }
    };

    if !status { ret status }

    // If we get through here, all the tests passed!
    true
}

fn main(args: [str]) {
    let args = if os::getenv("RUST_BENCH").is_some() {
        ["", "15", "48"]
    } else if args.len() <= 1u {
        ["", "10", "16"]
    } else {
        args
    };

    let scale = uint::from_str(args[1]).get();
    let num_keys = uint::from_str(args[2]).get();
    let do_validate = false;
    let do_sequential = true;

    let start = time::precise_time_s();
    let edges = make_edges(scale, 16u);
    let stop = time::precise_time_s();

    io::stdout().write_line(#fmt("Generated %? edges in %? seconds.",
                                 vec::len(edges), stop - start));

    let start = time::precise_time_s();
    let graph = make_graph(1u << scale, edges);
    let stop = time::precise_time_s();

    let mut total_edges = 0u;
    vec::each(graph) {|edges| total_edges += edges.len(); true };

    io::stdout().write_line(#fmt("Generated graph with %? edges in %? seconds.",
                                 total_edges / 2u,
                                 stop - start));

    let mut total_seq = 0.0;
    let mut total_par = 0.0;

    gen_search_keys(graph, num_keys).map() {|root|
        io::stdout().write_line("");
        io::stdout().write_line(#fmt("Search key: %?", root));

        if do_sequential {
            let start = time::precise_time_s();
            let bfs_tree = bfs(graph, root);
            let stop = time::precise_time_s();

            //total_seq += stop - start;

            io::stdout().write_line(
                #fmt("Sequential BFS completed in %? seconds.",
                     stop - start));

            if do_validate {
                let start = time::precise_time_s();
                assert(validate(edges, root, bfs_tree));
                let stop = time::precise_time_s();

                io::stdout().write_line(
                    #fmt("Validation completed in %? seconds.",
                         stop - start));
            }

            let start = time::precise_time_s();
            let bfs_tree = bfs2(graph, root);
            let stop = time::precise_time_s();

            total_seq += stop - start;

            io::stdout().write_line(
                #fmt("Alternate Sequential BFS completed in %? seconds.",
                     stop - start));

            if do_validate {
                let start = time::precise_time_s();
                assert(validate(edges, root, bfs_tree));
                let stop = time::precise_time_s();

                io::stdout().write_line(
                    #fmt("Validation completed in %? seconds.",
                         stop - start));
            }
        }

        let start = time::precise_time_s();
        let bfs_tree = pbfs(graph, root);
        let stop = time::precise_time_s();

        total_par += stop - start;

        io::stdout().write_line(#fmt("Parallel BFS completed in %? seconds.",
                                     stop - start));

        if do_validate {
            let start = time::precise_time_s();
            assert(validate(edges, root, bfs_tree));
            let stop = time::precise_time_s();

            io::stdout().write_line(#fmt("Validation completed in %? seconds.",
                                         stop - start));
        }
    };

    io::stdout().write_line("");
    io::stdout().write_line(
        #fmt("Total sequential: %? \t Total Parallel: %? \t Speedup: %?x",
             total_seq, total_par, total_seq / total_par));
}
<commit_msg>Use std::deque now that the bugs are fixed. Also, avoid a few copies.<commit_after>/**

An implementation of the Graph500 Bread First Search problem in Rust.

*/

use std;
import std::time;
import std::map;
import std::map::hashmap;
import std::deque;
import std::deque::t;
import std::arc;
import std::par;
import io::writer_util;
import comm::*;
import int::abs;

type node_id = i64;
type graph = [[node_id]];
type bfs_result = [node_id];

fn make_edges(scale: uint, edgefactor: uint) -> [(node_id, node_id)] {
    let r = rand::rng();

    fn choose_edge(i: node_id, j: node_id, scale: uint, r: rand::rng)
        -> (node_id, node_id) {

        let A = 0.57;
        let B = 0.19;
        let C = 0.19;

        if scale == 0u {
            (i, j)
        }
        else {
            let i = i * 2i64;
            let j = j * 2i64;
            let scale = scale - 1u;

            let x = r.gen_float();

            if x < A {
                choose_edge(i, j, scale, r)
            }
            else {
                let x = x - A;
                if x < B {
                    choose_edge(i + 1i64, j, scale, r)
                }
                else {
                    let x = x - B;
                    if x < C {
                        choose_edge(i, j + 1i64, scale, r)
                    }
                    else {
                        choose_edge(i + 1i64, j + 1i64, scale, r)
                    }
                }
            }
        }
    }

    vec::from_fn((1u << scale) * edgefactor) {|_i|
        choose_edge(0i64, 0i64, scale, r)
    }
}

fn make_graph(N: uint, edges: [(node_id, node_id)]) -> graph {
    let graph = vec::from_fn(N) {|_i|
        map::hashmap::<node_id, ()>({|x| x as uint }, {|x, y| x == y })
    };

    vec::each(edges) {|e|
        let (i, j) = e;
        map::set_add(graph[i], j);
        map::set_add(graph[j], i);
        true
    }

    graph.map() {|v|
        map::vec_from_set(v)
    }
}

fn gen_search_keys(graph: graph, n: uint) -> [node_id] {
    let keys = map::hashmap::<node_id, ()>({|x| x as uint }, {|x, y| x == y });
    let r = rand::rng();

    while keys.size() < n {
        let k = r.gen_uint_range(0u, graph.len());

        if graph[k].len() > 0u && vec::any(graph[k]) {|i|
            i != k as node_id
        } {
            map::set_add(keys, k as node_id);
        }
    }
    map::vec_from_set(keys)
}

#[doc="Returns a vector of all the parents in the BFS tree rooted at key.

Nodes that are unreachable have a parent of -1."]
fn bfs(graph: graph, key: node_id) -> bfs_result {
    let marks : [mut node_id]
        = vec::to_mut(vec::from_elem(vec::len(graph), -1i64));

    let Q = deque::create();

    Q.add_back(key);
    marks[key] = key;

    while Q.size() > 0u {
        let t = Q.pop_front();

        graph[t].each() {|k|
            if marks[k] == -1i64 {
                marks[k] = t;
                Q.add_back(k);
            }
            true
        };
    }

    vec::from_mut(marks)
}

#[doc="Another version of the bfs function.

This one uses the same algorithm as the parallel one, just without
using the parallel vector operators."]
fn bfs2(graph: graph, key: node_id) -> bfs_result {
    // This works by doing functional updates of a color vector.

    enum color {
        white,
        // node_id marks which node turned this gray/black.
        // the node id later becomes the parent.
        gray(node_id),
        black(node_id)
    };

    let mut colors = vec::from_fn(graph.len()) {|i|
        if i as node_id == key {
            gray(key)
        }
        else {
            white
        }
    };

    fn is_gray(c: color) -> bool {
        alt c {
          gray(_) { true }
          _ { false }
        }
    }

    let mut i = 0u;
    while vec::any(colors, is_gray) {
        // Do the BFS.
        log(info, #fmt("PBFS iteration %?", i));
        i += 1u;
        colors = colors.mapi() {|i, c|
            let c : color = c;
            alt c {
              white {
                let i = i as node_id;

                let neighbors = graph[i];

                let mut color = white;

                neighbors.each() {|k|
                    if is_gray(colors[k]) {
                        color = gray(k);
                        false
                    }
                    else { true }
                };

                color
              }
              gray(parent) { black(parent) }
              black(parent) { black(parent) }
            }
        }
    }

    // Convert the results.
    vec::map(colors) {|c|
        alt c {
          white { -1i64 }
          black(parent) { parent }
          _ { fail "Found remaining gray nodes in BFS" }
        }
    }
}

#[doc="A parallel version of the bfs function."]
fn pbfs(graph: graph, key: node_id) -> bfs_result {
    // This works by doing functional updates of a color vector.

    enum color {
        white,
        // node_id marks which node turned this gray/black.
        // the node id later becomes the parent.
        gray(node_id),
        black(node_id)
    };

    let mut colors = vec::from_fn(graph.len()) {|i|
        if i as node_id == key {
            gray(key)
        }
        else {
            white
        }
    };

    #[inline(always)]
    fn is_gray(c: color) -> bool {
        alt c {
          gray(_) { true }
          _ { false }
        }
    }

    let (_res, graph) = arc::shared_arc(copy graph);

    let mut i = 0u;
    while par::any(colors, is_gray) {
        // Do the BFS.
        log(info, #fmt("PBFS iteration %?", i));
        i += 1u;
        let old_len = colors.len();

        let (_res, color) = arc::shared_arc(copy colors);

        colors = par::mapi(colors) {|i, c|
            let c : color = c;
            let colors = &arc::get_arc(color);
            let colors = arc::get(colors);
            let graph = &arc::get_arc(graph);
            let graph = arc::get(graph);
            alt c {
              white {
                let i = i as node_id;

                let neighbors = (*graph)[i];

                let mut color = white;

                neighbors.each() {|k|
                    if is_gray((*colors)[k]) {
                        color = gray(k);
                        false
                    }
                    else { true }
                    };
                color
              }
              gray(parent) { black(parent) }
              black(parent) { black(parent) }
            }
        };
        assert(colors.len() == old_len);
    }

    // Convert the results.
    par::map(colors) {|c|
        alt c {
          white { -1i64 }
          black(parent) { parent }
          _ { fail "Found remaining gray nodes in BFS" }
        }
    }
}

#[doc="Performs at least some of the validation in the Graph500 spec."]
fn validate(edges: [(node_id, node_id)],
            root: node_id, tree: bfs_result) -> bool {
    // There are 5 things to test. Below is code for each of them.

    // 1. The BFS tree is a tree and does not contain cycles.
    //
    // We do this by iterating over the tree, and tracing each of the
    // parent chains back to the root. While we do this, we also
    // compute the levels for each node.

    log(info, "Verifying tree structure...");

    let mut status = true;
    let level = tree.map() {|parent|
        let mut parent = parent;
        let mut path = [];

        if parent == -1i64 {
            // This node was not in the tree.
            -1
        }
        else {
            while parent != root {
                if vec::contains(path, parent) {
                    status = false;
                }

                path += [parent];
                parent = tree[parent];
            }

            // The length of the path back to the root is the current
            // level.
            path.len() as int
        }
    };

    if !status { ret status }

    // 2. Each tree edge connects vertices whose BFS levels differ by
    //    exactly one.

    log(info, "Verifying tree edges...");

    let status = tree.alli() {|k, parent|
        if parent != root && parent != -1i64 {
            level[parent] == level[k] - 1
        }
        else {
            true
        }
    };

    if !status { ret status }

    // 3. Every edge in the input list has vertices with levels that
    //    differ by at most one or that both are not in the BFS tree.

    log(info, "Verifying graph edges...");

    let status = edges.all() {|e|
        let (u, v) = e;

        abs(level[u] - level[v]) <= 1
    };

    if !status { ret status }

    // 4. The BFS tree spans an entire connected component's vertices.

    // This is harder. We'll skip it for now...

    // 5. A node and its parent are joined by an edge of the original
    //    graph.

    log(info, "Verifying tree and graph edges...");

    let status = par::alli(tree) {|u, v|
        let u = u as node_id;
        if v == -1i64 || u == root {
            true
        }
        else {
            edges.contains((u, v)) || edges.contains((v, u))
        }
    };

    if !status { ret status }

    // If we get through here, all the tests passed!
    true
}

fn main(args: [str]) {
    let args = if os::getenv("RUST_BENCH").is_some() {
        ["", "15", "48"]
    } else if args.len() <= 1u {
        ["", "10", "16"]
    } else {
        args
    };

    let scale = uint::from_str(args[1]).get();
    let num_keys = uint::from_str(args[2]).get();
    let do_validate = false;
    let do_sequential = true;

    let start = time::precise_time_s();
    let edges = make_edges(scale, 16u);
    let stop = time::precise_time_s();

    io::stdout().write_line(#fmt("Generated %? edges in %? seconds.",
                                 vec::len(edges), stop - start));

    let start = time::precise_time_s();
    let graph = make_graph(1u << scale, edges);
    let stop = time::precise_time_s();

    let mut total_edges = 0u;
    vec::each(graph) {|edges| total_edges += edges.len(); true };

    io::stdout().write_line(#fmt("Generated graph with %? edges in %? seconds.",
                                 total_edges / 2u,
                                 stop - start));

    let mut total_seq = 0.0;
    let mut total_par = 0.0;

    gen_search_keys(graph, num_keys).map() {|root|
        io::stdout().write_line("");
        io::stdout().write_line(#fmt("Search key: %?", root));

        if do_sequential {
            let start = time::precise_time_s();
            let bfs_tree = bfs(graph, root);
            let stop = time::precise_time_s();

            //total_seq += stop - start;

            io::stdout().write_line(
                #fmt("Sequential BFS completed in %? seconds.",
                     stop - start));

            if do_validate {
                let start = time::precise_time_s();
                assert(validate(edges, root, bfs_tree));
                let stop = time::precise_time_s();

                io::stdout().write_line(
                    #fmt("Validation completed in %? seconds.",
                         stop - start));
            }

            let start = time::precise_time_s();
            let bfs_tree = bfs2(graph, root);
            let stop = time::precise_time_s();

            total_seq += stop - start;

            io::stdout().write_line(
                #fmt("Alternate Sequential BFS completed in %? seconds.",
                     stop - start));

            if do_validate {
                let start = time::precise_time_s();
                assert(validate(edges, root, bfs_tree));
                let stop = time::precise_time_s();

                io::stdout().write_line(
                    #fmt("Validation completed in %? seconds.",
                         stop - start));
            }
        }

        let start = time::precise_time_s();
        let bfs_tree = pbfs(graph, root);
        let stop = time::precise_time_s();

        total_par += stop - start;

        io::stdout().write_line(#fmt("Parallel BFS completed in %? seconds.",
                                     stop - start));

        if do_validate {
            let start = time::precise_time_s();
            assert(validate(edges, root, bfs_tree));
            let stop = time::precise_time_s();

            io::stdout().write_line(#fmt("Validation completed in %? seconds.",
                                         stop - start));
        }
    };

    io::stdout().write_line("");
    io::stdout().write_line(
        #fmt("Total sequential: %? \t Total Parallel: %? \t Speedup: %?x",
             total_seq, total_par, total_seq / total_par));
}
<|endoftext|>


<commit_before>use metric::Metric;

pub struct StdCounter {
    pub value: i64
}

pub trait Counter : Metric {
    fn clear(&mut self);

    fn dec(&mut self, value: i64);

    fn inc(&mut self, value: i64);

    fn snapshot(&self) -> Self;

    fn new() -> Self;
}

impl Counter for StdCounter {
    fn clear(&mut self) {
        self.value = 0;
    }

    fn dec(&mut self, value: i64) {
        self.value -= value;
    }

    fn inc(&mut self, value: i64) {
        self.value += value;
    }

    fn snapshot(&self) ->  StdCounter {
        StdCounter { value: self.value }
    }

    fn new() -> StdCounter {
        StdCounter{ value: 0i64 }
    }
}

impl Metric for StdCounter {
}

#[cfg(test)]
mod test {
    use counter::StdCounter;
    use counter::Counter;

    #[test]
    fn increment_by_1() {
        let mut c = StdCounter{ value: 0 };
        c.inc(1);
        assert!(c.value == 1);
    }

    #[test]
    fn snapshot() {
        let c = StdCounter{value: 0};
        let mut c_snapshot = c.snapshot();

        c_snapshot.inc(1);

        assert!(c.value == 0);
        assert!(c_snapshot.value == 1);
    }
}<commit_msg>Move new()<commit_after>use metric::Metric;

pub struct StdCounter {
    pub value: i64
}

pub trait Counter : Metric {
    fn clear(&mut self);

    fn dec(&mut self, value: i64);

    fn inc(&mut self, value: i64);

    fn snapshot(&self) -> Self;
}

impl Counter for StdCounter {
    fn clear(&mut self) {
        self.value = 0;
    }

    fn dec(&mut self, value: i64) {
        self.value -= value;
    }

    fn inc(&mut self, value: i64) {
        self.value += value;
    }

    fn snapshot(&self) ->  StdCounter {
        StdCounter { value: self.value }
    }

}

impl Metric for StdCounter {
}

impl StdCounter {
    pub fn new() -> StdCounter {
        StdCounter{ value: 0i64 }
    }
}

#[cfg(test)]
mod test {
    use counter::StdCounter;
    use counter::Counter;

    #[test]
    fn increment_by_1() {
        let mut c = StdCounter{ value: 0 };
        c.inc(1);
        assert!(c.value == 1);
    }

    #[test]
    fn snapshot() {
        let c = StdCounter{value: 0};
        let mut c_snapshot = c.snapshot();

        c_snapshot.inc(1);

        assert!(c.value == 0);
        assert!(c_snapshot.value == 1);
    }
}<|endoftext|>


<commit_before><commit_msg>Findsig utility (#23)<commit_after>/*!
Find patterns utility.
*/

extern crate pelite;

use std::env;
use std::path::Path;
use std::io::{self, Write};

use pelite::{pe32, pe64};
use pelite::pattern as pat;

const HELP_TEXT: &'static str = "\
FINDSIG <FILE> [PAT]...

  FILE - Path to the input binary to scan.
  PAT  - Any number of patterns to find.

If no patterns are provided, they are interactively read line by line from stdin.

Find documentation about the pattern syntax here:
https://docs.rs/pelite/*/pelite/pattern/fn.parse.html
";

fn main() {
	// Get args and skip the invoker
	let mut args = env::args_os();
	args.next();

	// Read the input file
	if let Some(file_path) = args.next() {
		// Path and filename of the input file
		let file_path = Path::new(&file_path);
		let file_name = file_path.file_name().expect("path does not have a file name").to_str().unwrap();

		// Map the file into memory
		let file_map = pelite::FileMap::open(&file_path).expect("cannot open the input file");

		// Try reading as PE32
		if let Ok(pe) = pe32::PeFile::from_bytes(&file_map) {
			process_patterns(args, &mut |pattern, save| {
				let scanner = pe32::Pe::scanner(pe);
				let mut matches = scanner.matches_code(pattern);
				while matches.next_match(save) {
					print_match(file_name, save);
				}
			});
		}
		// Try reading as PE32+
		else if let Ok(pe) = pe64::PeFile::from_bytes(&file_map) {
			process_patterns(args, &mut |pattern, save| {
				let scanner = pe64::Pe::scanner(pe);
				let mut matches = scanner.matches_code(pattern);
				while matches.next_match(save) {
					print_match(file_name, save);
				}
			});
		}
		// Must be a valid PE binary
		else {
			panic!("file is not a valid PE binary");
		}
	}
	else {
		print!("{}", HELP_TEXT);
	}
}

fn process_patterns(args: env::ArgsOs, f: &mut FnMut(&[pat::Atom], &mut [u32])) {
	if args.len() > 0 {
		// Read from the command line args if available
		for pattern_string in args.filter_map(|pattern_string| pattern_string.into_string().ok()) {
			process_pattern(&pattern_string, f);
		}
	}
	else {
		// Read from standard input if no patterns were provided on command line
		print!("Interactive REPL, enter any pattern to find its matches.\nPress Ctrl-C to quit.\n");
		loop {
			// Print a nice REPL
			print!(">>> ");
			let _ = io::stdout().flush();
			// Read input from stdin, handle any kind of abort by detecting the lack of newline (?)
			let mut line = String::new();
			if io::stdin().read_line(&mut line).is_err() || line.len() == 0 {
				break;
			}
			// Only process non-empty lines, otherwise ask the user again
			let line = line.trim();
			if line.len() > 0 {
				process_pattern(&line, f);
			}
		}
	}
}
fn process_pattern(pattern_str: &str, f: &mut FnMut(&[pat::Atom], &mut [u32])) {
	// Parse the pattern
	let pattern = match pat::parse(pattern_str) {
		Ok(pattern) => pattern,
		Err(err) => {
			eprintln!("Pattern `{}` error: {}", pattern_str, err);
			return;
		},
	};
	// Print the header followed by its matches
	println!("Pattern `{}` matches:", pattern_str);
	let mut save = [0; 16];
	f(&pattern, &mut save);
}
fn print_match(file_name: &str, save: &[u32]) {
	print!("  {}!{:08x}", file_name, save[0]);
	if save[1] != 0 {
		print!("  [1/{:08x}", save[1]);
		for i in (2..save.len()).take_while(|&i| save[i] != 0) {
			print!(" {}/{:08x}", i, save[i]);
		}
		print!("]");
	}
	println!();
}
<|endoftext|>


<commit_before><commit_msg>Problem 16<commit_after>fn drop<T: Clone>(list: &[T], n: uint) -> ~[T] {
    list.iter().enumerate().filter_map(
        |(i,&ref e)|
            if i%n < n-1 {
                Some(e.clone())
            } else {
                None
            }
        ).collect()
}

fn main() {
    let list = ~['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
    println!("{:?}", drop(list, 3));
}

<|endoftext|>


<commit_before><commit_msg>cleanup<commit_after><|endoftext|>


<commit_before><commit_msg>Skip OBJ windows<commit_after><|endoftext|>


<commit_before><commit_msg>Fix stack overflow<commit_after><|endoftext|>


<commit_before>import std::bitv;

export t;
export create_tritv;
export tritv_clone;
export tritv_set;
export to_vec;
export trit;
export dont_care;
export ttrue;
export tfalse;
export tritv_get;
export tritv_set_all;
export tritv_difference;
export tritv_union;
export tritv_intersect;
export tritv_copy;
export tritv_clear;
export tritv_doesntcare;
export to_str;

/* for a fixed index:
   10 = "this constraint may or may not be true after execution"
   01 = "this constraint is definitely true"
   00 = "this constraint is definitely false"
   11 should never appear
 FIXME: typestate precondition (uncertain and val must
 have the same length; 11 should never appear in a given position)
*/

type t = rec(bitv::t uncertain, bitv::t val, uint nbits);
tag trit {
    ttrue;
    tfalse;
    dont_care;
}

fn create_tritv(uint len) -> t {
  ret rec(uncertain=bitv::create(len, true),
          val=bitv::create(len, false),
          nbits=len);
}

fn trit_minus(trit a, trit b) -> trit {
    /*   2 - anything = 2
         1 - 1 = 2
         1 - 0 is an error
         1 - 2 = 1
         0 - 1 is an error
         0 - anything else - 0
     */
  alt (a) {
    case (dont_care) { dont_care }
    case (ttrue) {
      alt (b) {
        case (ttrue)     { dont_care }
        case (tfalse)    { ttrue } /* internally contradictory, but
                                      I guess it'll get flagged? */
        case (dont_care) { ttrue }
      }
    }
    case (tfalse) {
      alt (b) {
        case (ttrue) { tfalse } /* see above comment */
        case (_)     { tfalse }
      }
    }
  }
}

fn trit_or(trit a, trit b) -> trit {
  alt (a) {
    case (dont_care) { b }
    case (ttrue)     { ttrue }
    case (tfalse)    {
      alt (b) {
        case (ttrue)  { dont_care } /* FIXME: ?????? */
        case (_)      { tfalse }
      }
    }
  }
}

// FIXME: This still seems kind of dodgy to me (that is,
// that 1 + ? = 1. But it might work out given that
// all variables start out in a 0 state. Probably I need
// to make it so that all constraints start out in a 0 state
// (we consider a constraint false until proven true), too.
fn trit_and(trit a, trit b) -> trit {
  alt (a) {
      case (dont_care) { b }  // also seems wrong for case b = ttrue
      case (ttrue)     {
          alt (b) {
              case (dont_care) { ttrue } // ??? Seems wrong
              case (ttrue)     { ttrue }
              // false wins, since if something is uninit
              // on one path, we care
              // (Rationale: it's always safe to assume that
         // a var is uninitialized or that a constraint
         // needs to be re-established)
              case (tfalse)    { tfalse }
          }
      }
      // Rationale: if it's uninit on one path,
      // we can consider it as uninit on all paths
    case (tfalse) { tfalse }
  }
  // if the result is dont_care, that means
  // a and b were both dont_care
}

fn change(bool changed, trit old, trit new) -> bool { changed || new != old }

fn tritv_difference(&t p1, &t p2) -> bool {
    let uint i = 0u;
    assert (p1.nbits == p2.nbits);
    let uint sz = p1.nbits;
    auto changed = false;
    while (i < sz) {
      auto old = tritv_get(p1, i);
      auto new = trit_minus(old, tritv_get(p2, i));
      changed = change(changed, old, new);
      tritv_set(i, p1, new);
      i += 1u;
    }
    ret changed;
}

fn tritv_union(&t p1, &t p2) -> bool {
    let uint i = 0u;
    assert (p1.nbits == p2.nbits);
    let uint sz = p1.nbits;
    auto changed = false;
    while (i < sz) {
      auto old = tritv_get(p1, i);
      auto new = trit_or(old, tritv_get(p2, i));
      changed = change(changed, old, new);
      tritv_set(i, p1, new);
      i += 1u;
    }
    ret changed;
}

fn tritv_intersect(&t p1, &t p2) -> bool {
    let uint i = 0u;
    assert (p1.nbits == p2.nbits);
    let uint sz = p1.nbits;
    auto changed = false;
    while (i < sz) {
      auto old = tritv_get(p1, i);
      auto new = trit_and(old, tritv_get(p2, i));
      changed = change(changed, old, new);
      tritv_set(i, p1, new);
      i += 1u;
    }
    ret changed;
}

fn tritv_get(&t v, uint i) -> trit {
  auto b1 = bitv::get(v.uncertain, i);
  auto b2 = bitv::get(v.val, i);
  assert (! (b1 && b2));
  if (b1)      { dont_care }
  else if (b2) { ttrue }
  else         { tfalse}
}

fn tritv_set(uint i, &t v, trit t) -> bool {
  auto old = tritv_get(v, i);
  alt (t) {
    case (dont_care) {
      bitv::set(v.uncertain, i, true);
      bitv::set(v.val, i, false);
    }
    case (ttrue) {
      bitv::set(v.uncertain, i, false);
      bitv::set(v.val, i, true);
    }
    case (tfalse) {
      bitv::set(v.uncertain, i, false);
      bitv::set(v.val, i, false);
    }
  }
  ret change(false, old, t);
}

fn tritv_copy(&t target, &t source) -> bool {
  let uint i = 0u;
  assert (target.nbits == source.nbits);
  auto changed = false;
  auto oldunc;
  auto newunc;
  auto oldval;
  auto newval;
  while (i < target.nbits) {
    oldunc = bitv::get(target.uncertain, i);
    newunc = bitv::get(source.uncertain, i);
    oldval = bitv::get(target.val, i);
    newval = bitv::get(source.val, i);
    bitv::set(target.uncertain, i, newunc);
    changed = changed || (oldunc && !newunc);
    bitv::set(target.val, i, newval);
    changed = changed || (oldval && !newval);
    i += 1u;
  }
  ret changed;
}

fn tritv_set_all(&t v) {
  let uint i = 0u;
  while (i < v.nbits) {
    tritv_set(i, v, ttrue);
    i += 1u;
  }
}

fn tritv_clear(&t v) {
  let uint i = 0u;
  while (i < v.nbits) {
    tritv_set(i, v, dont_care);
    i += 1u;
  }
}

fn tritv_clone(&t v) -> t {
  ret rec(uncertain=bitv::clone(v.uncertain),
          val=bitv::clone(v.val),
          nbits=v.nbits);
}

fn tritv_doesntcare(&t v) -> bool {
  let uint i = 0u;
  while (i < v.nbits) {
    if (tritv_get(v, i) != dont_care) {
      ret false;
    }
    i += 1u;
  }
  ret true;
}

fn to_vec(&t v) -> uint[] {
  let uint i = 0u;
  let uint[] rslt = ~[];
  while (i < v.nbits) {
    rslt += ~[alt (tritv_get(v, i)) {
        case (dont_care) { 2u }
        case (ttrue)     { 1u }
        case (tfalse)    { 0u } }];
    i += 1u;
  }
  ret rslt;
}

fn to_str(&t v) -> str {
  let uint i = 0u;
  let str rs = "";
  while (i < v.nbits) {
    rs += alt (tritv_get(v, i)) {
        case (dont_care) { "?" }
        case (ttrue)     { "1" }
        case (tfalse)    { "0" } };
    i += 1u;
  }
  ret rs;
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<commit_msg>rustc: Simplify tritv::copy; shaves a couple of seconds off typestate.<commit_after>import std::bitv;

export t;
export create_tritv;
export tritv_clone;
export tritv_set;
export to_vec;
export trit;
export dont_care;
export ttrue;
export tfalse;
export tritv_get;
export tritv_set_all;
export tritv_difference;
export tritv_union;
export tritv_intersect;
export tritv_copy;
export tritv_clear;
export tritv_doesntcare;
export to_str;

/* for a fixed index:
   10 = "this constraint may or may not be true after execution"
   01 = "this constraint is definitely true"
   00 = "this constraint is definitely false"
   11 should never appear
 FIXME: typestate precondition (uncertain and val must
 have the same length; 11 should never appear in a given position)
*/

type t = rec(bitv::t uncertain, bitv::t val, uint nbits);
tag trit {
    ttrue;
    tfalse;
    dont_care;
}

fn create_tritv(uint len) -> t {
  ret rec(uncertain=bitv::create(len, true),
          val=bitv::create(len, false),
          nbits=len);
}

fn trit_minus(trit a, trit b) -> trit {
    /*   2 - anything = 2
         1 - 1 = 2
         1 - 0 is an error
         1 - 2 = 1
         0 - 1 is an error
         0 - anything else - 0
     */
  alt (a) {
    case (dont_care) { dont_care }
    case (ttrue) {
      alt (b) {
        case (ttrue)     { dont_care }
        case (tfalse)    { ttrue } /* internally contradictory, but
                                      I guess it'll get flagged? */
        case (dont_care) { ttrue }
      }
    }
    case (tfalse) {
      alt (b) {
        case (ttrue) { tfalse } /* see above comment */
        case (_)     { tfalse }
      }
    }
  }
}

fn trit_or(trit a, trit b) -> trit {
  alt (a) {
    case (dont_care) { b }
    case (ttrue)     { ttrue }
    case (tfalse)    {
      alt (b) {
        case (ttrue)  { dont_care } /* FIXME: ?????? */
        case (_)      { tfalse }
      }
    }
  }
}

// FIXME: This still seems kind of dodgy to me (that is,
// that 1 + ? = 1. But it might work out given that
// all variables start out in a 0 state. Probably I need
// to make it so that all constraints start out in a 0 state
// (we consider a constraint false until proven true), too.
fn trit_and(trit a, trit b) -> trit {
  alt (a) {
      case (dont_care) { b }  // also seems wrong for case b = ttrue
      case (ttrue)     {
          alt (b) {
              case (dont_care) { ttrue } // ??? Seems wrong
              case (ttrue)     { ttrue }
              // false wins, since if something is uninit
              // on one path, we care
              // (Rationale: it's always safe to assume that
         // a var is uninitialized or that a constraint
         // needs to be re-established)
              case (tfalse)    { tfalse }
          }
      }
      // Rationale: if it's uninit on one path,
      // we can consider it as uninit on all paths
    case (tfalse) { tfalse }
  }
  // if the result is dont_care, that means
  // a and b were both dont_care
}

fn change(bool changed, trit old, trit new) -> bool { changed || new != old }

fn tritv_difference(&t p1, &t p2) -> bool {
    let uint i = 0u;
    assert (p1.nbits == p2.nbits);
    let uint sz = p1.nbits;
    auto changed = false;
    while (i < sz) {
      auto old = tritv_get(p1, i);
      auto new = trit_minus(old, tritv_get(p2, i));
      changed = change(changed, old, new);
      tritv_set(i, p1, new);
      i += 1u;
    }
    ret changed;
}

fn tritv_union(&t p1, &t p2) -> bool {
    let uint i = 0u;
    assert (p1.nbits == p2.nbits);
    let uint sz = p1.nbits;
    auto changed = false;
    while (i < sz) {
      auto old = tritv_get(p1, i);
      auto new = trit_or(old, tritv_get(p2, i));
      changed = change(changed, old, new);
      tritv_set(i, p1, new);
      i += 1u;
    }
    ret changed;
}

fn tritv_intersect(&t p1, &t p2) -> bool {
    let uint i = 0u;
    assert (p1.nbits == p2.nbits);
    let uint sz = p1.nbits;
    auto changed = false;
    while (i < sz) {
      auto old = tritv_get(p1, i);
      auto new = trit_and(old, tritv_get(p2, i));
      changed = change(changed, old, new);
      tritv_set(i, p1, new);
      i += 1u;
    }
    ret changed;
}

fn tritv_get(&t v, uint i) -> trit {
  auto b1 = bitv::get(v.uncertain, i);
  auto b2 = bitv::get(v.val, i);
  assert (! (b1 && b2));
  if (b1)      { dont_care }
  else if (b2) { ttrue }
  else         { tfalse}
}

fn tritv_set(uint i, &t v, trit t) -> bool {
  auto old = tritv_get(v, i);
  alt (t) {
    case (dont_care) {
      bitv::set(v.uncertain, i, true);
      bitv::set(v.val, i, false);
    }
    case (ttrue) {
      bitv::set(v.uncertain, i, false);
      bitv::set(v.val, i, true);
    }
    case (tfalse) {
      bitv::set(v.uncertain, i, false);
      bitv::set(v.val, i, false);
    }
  }
  ret change(false, old, t);
}

fn tritv_copy(&t target, &t source) -> bool {
  assert (target.nbits == source.nbits);
  auto changed = !bitv::equal(target.uncertain, source.uncertain) ||
    !bitv::equal(target.val, source.val);
  bitv::copy(target.uncertain, source.uncertain);
  bitv::copy(target.val, source.val);
  ret changed;
}

fn tritv_set_all(&t v) {
  let uint i = 0u;
  while (i < v.nbits) {
    tritv_set(i, v, ttrue);
    i += 1u;
  }
}

fn tritv_clear(&t v) {
  let uint i = 0u;
  while (i < v.nbits) {
    tritv_set(i, v, dont_care);
    i += 1u;
  }
}

fn tritv_clone(&t v) -> t {
  ret rec(uncertain=bitv::clone(v.uncertain),
          val=bitv::clone(v.val),
          nbits=v.nbits);
}

fn tritv_doesntcare(&t v) -> bool {
  let uint i = 0u;
  while (i < v.nbits) {
    if (tritv_get(v, i) != dont_care) {
      ret false;
    }
    i += 1u;
  }
  ret true;
}

fn to_vec(&t v) -> uint[] {
  let uint i = 0u;
  let uint[] rslt = ~[];
  while (i < v.nbits) {
    rslt += ~[alt (tritv_get(v, i)) {
        case (dont_care) { 2u }
        case (ttrue)     { 1u }
        case (tfalse)    { 0u } }];
    i += 1u;
  }
  ret rslt;
}

fn to_str(&t v) -> str {
  let uint i = 0u;
  let str rs = "";
  while (i < v.nbits) {
    rs += alt (tritv_get(v, i)) {
        case (dont_care) { "?" }
        case (ttrue)     { "1" }
        case (tfalse)    { "0" } };
    i += 1u;
  }
  ret rs;
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
//
<|endoftext|>


<commit_before><commit_msg>Benchmark<commit_after>#![feature(test)]

extern crate dssim;
extern crate imgref;
extern crate test;
extern crate lodepng;
use dssim::*;
use imgref::*;
use test::Bencher;

fn load(path: &str) -> Result<ImgVec<RGBAPLU>, lodepng::Error> {
    let image = lodepng::decode32_file(path)?;
    Ok(Img::new(image.buffer.to_rgbaplu(), image.width, image.height))
}

#[bench]
fn compare(bench: &mut Bencher) {
    let mut attr = dssim::Dssim::new();
    let other = &load("tests/test1-sm.png").unwrap();
    let orig = attr.create_image(&load("tests/test2-sm.png").unwrap()).unwrap();

    bench.iter(|| {
        let modif = attr.create_image(other).unwrap();
        attr.compare(&orig, modif)
    });
}
<|endoftext|>


<commit_before><commit_msg>The mail model uses derived JSON deserialization<commit_after><|endoftext|>


<commit_before><commit_msg>Update Journal When Starting/Stopping<commit_after><|endoftext|>


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

/// Module-level assembly support.
///
/// The macro defined here allows you to specify "top-level",
/// "file-scoped", or "module-level" assembly. These synonyms
/// all correspond to LLVM's module-level inline assembly instruction.
///
/// For example, `global_asm!("some assembly here")` translates to
/// LLVM's `module asm "some assembly here"`. All of LLVM's caveats
/// therefore apply.

use syntax::ast;
use syntax::ext::base;
use syntax::ext::base::*;
use syntax::codemap;
use syntax::feature_gate;
use syntax::ptr::P;
use syntax::symbol::Symbol;
use syntax_pos::Span;
use syntax::tokenstream;

use syntax::util::small_vector::SmallVector;

pub const MACRO: &'static str = "global_asm";

pub fn expand_global_asm<'cx>(cx: &'cx mut ExtCtxt,
                              sp: Span,
                              tts: &[tokenstream::TokenTree]) -> Box<base::MacResult + 'cx> {
    if !cx.ecfg.enable_global_asm() {
        feature_gate::emit_feature_err(&cx.parse_sess,
                                       MACRO,
                                       sp,
                                       feature_gate::GateIssue::Language,
                                       feature_gate::EXPLAIN_GLOBAL_ASM);
        return DummyResult::any(sp);
    }

    let mut p = cx.new_parser_from_tts(tts);
    let (asm, _) = match expr_to_string(cx,
                                        panictry!(p.parse_expr()),
                                        "inline assembly must be a string literal") {
        Some((s, st)) => (s, st),
        None => return DummyResult::any(sp),
    };

    MacEager::items(SmallVector::one(P(ast::Item {
        ident: ast::Ident::with_empty_ctxt(Symbol::intern("")),
        attrs: Vec::new(),
        id: ast::DUMMY_NODE_ID,
        node: ast::ItemKind::GlobalAsm(P(ast::GlobalAsm {
            asm: asm,
            ctxt: cx.backtrace(),
        })),
        vis: ast::Visibility::Inherited,
        span: sp,
    })))
}
<commit_msg>Replace ExpnId with SyntaxContext<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.

/// Module-level assembly support.
///
/// The macro defined here allows you to specify "top-level",
/// "file-scoped", or "module-level" assembly. These synonyms
/// all correspond to LLVM's module-level inline assembly instruction.
///
/// For example, `global_asm!("some assembly here")` translates to
/// LLVM's `module asm "some assembly here"`. All of LLVM's caveats
/// therefore apply.

use syntax::ast;
use syntax::ext::base;
use syntax::ext::base::*;
use syntax::feature_gate;
use syntax::ptr::P;
use syntax::symbol::Symbol;
use syntax_pos::Span;
use syntax::tokenstream;

use syntax::util::small_vector::SmallVector;

pub const MACRO: &'static str = "global_asm";

pub fn expand_global_asm<'cx>(cx: &'cx mut ExtCtxt,
                              sp: Span,
                              tts: &[tokenstream::TokenTree]) -> Box<base::MacResult + 'cx> {
    if !cx.ecfg.enable_global_asm() {
        feature_gate::emit_feature_err(&cx.parse_sess,
                                       MACRO,
                                       sp,
                                       feature_gate::GateIssue::Language,
                                       feature_gate::EXPLAIN_GLOBAL_ASM);
        return DummyResult::any(sp);
    }

    let mut p = cx.new_parser_from_tts(tts);
    let (asm, _) = match expr_to_string(cx,
                                        panictry!(p.parse_expr()),
                                        "inline assembly must be a string literal") {
        Some((s, st)) => (s, st),
        None => return DummyResult::any(sp),
    };

    MacEager::items(SmallVector::one(P(ast::Item {
        ident: ast::Ident::with_empty_ctxt(Symbol::intern("")),
        attrs: Vec::new(),
        id: ast::DUMMY_NODE_ID,
        node: ast::ItemKind::GlobalAsm(P(ast::GlobalAsm {
            asm: asm,
            ctxt: cx.backtrace(),
        })),
        vis: ast::Visibility::Inherited,
        span: sp,
    })))
}
<|endoftext|>


<commit_before><commit_msg>Tidy order of some fields in Vulkan structures, and tidy a few comments<commit_after><|endoftext|>