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

#![crate_name = "glfw_platform"]
#![comment = "A lightweight graphics device manager for Rust"]
#![license = "ASL2"]
#![crate_type = "lib"]

#![feature(macro_rules, phase)]

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

extern crate device;

use glfw::Context;

struct Wrap<'a>(&'a glfw::Glfw);

impl<'a> device::GlProvider for Wrap<'a> {
    fn get_proc_address(&self, name: &str) -> *const libc::c_void {
        let Wrap(provider) = *self;
        provider.get_proc_address(name)
    }
    fn is_extension_supported(&self, name: &str) -> bool {
        let Wrap(provider) = *self;
        provider.extension_supported(name)
    }
}

pub struct Platform<C> {
    pub context: C,
}

impl<C: Context> Platform<C> {
    #[allow(visible_private_types)]
    pub fn new<'a>(context: C, provider: &'a glfw::Glfw) -> (Platform<C>, Wrap<'a>)  {
        context.make_current();
        (Platform { context: context }, Wrap(provider))
    }
}

impl<C: Context> device::GraphicsContext<device::GlBackEnd> for Platform<C> {
    fn make_current(&self) {
        self.context.make_current();
    }

    fn swap_buffers(&self) {
        self.context.swap_buffers();
    }
}

pub fn create_window<'glfw, 'title, 'monitor, 'hints>(
    glfw: &'glfw glfw::Glfw,
    width: u32,
    height: u32,
    title: &'title str,
    mode: glfw::WindowMode<'monitor>,
    preferred_setup: &'hints [glfw::WindowHint],
) -> CreateWindow<'glfw, 'title, 'monitor, 'hints> {
    CreateWindow {
        glfw: glfw,
        args: (width, height, title, mode),
        hints: vec![preferred_setup],
    }
}

pub fn create_default_window(
    glfw: &glfw::Glfw,
    width: u32,
    height: u32,
    title: &str,
    mode: glfw::WindowMode
) -> Option<(glfw::Window, Receiver<(f64, glfw::WindowEvent)>)> {
    create_window(glfw, width, height, title, mode, [
        glfw::ContextVersion(3, 2),
        glfw::OpenglForwardCompat(true),
        glfw::OpenglProfile(glfw::OpenGlCoreProfile),
    ])
    .fallback([
        glfw::ContextVersion(2, 1),
    ])
    .apply().map(|(window, events)| {
        info!("[glfw_platform] Initialized with context version {}", window.get_context_version());
        (window, events)
    })
}

pub struct CreateWindow<'glfw, 'title, 'monitor, 'hints> {
    glfw: &'glfw glfw::Glfw,
    args: (u32, u32, &'title str, glfw::WindowMode<'monitor>),
    hints: Vec<&'hints [glfw::WindowHint]>,
}

impl<'glfw, 'title, 'monitor, 'hints> CreateWindow<'glfw, 'title, 'monitor, 'hints> {
    pub fn fallback(mut self, f: &'hints [glfw::WindowHint])
    -> CreateWindow<'glfw, 'title, 'monitor, 'hints> {
        self.hints.push(f);
        self
    }
    pub fn apply(self) -> Option<(glfw::Window, Receiver<(f64, glfw::WindowEvent)>)> {
        let CreateWindow {
            glfw,
            mut hints,
            args: (width, height, title, mode),
        } = self;

        glfw.set_error_callback::<()>(None);
        for setup in hints.mut_iter() {
            glfw.default_window_hints();
            for hint in setup.iter() {
                glfw.window_hint(*hint);
            }
            let r = glfw.create_window(width, height, title, mode);
            if r.is_some() {
                return r;
            }
        }
        None
    }
}
<commit_msg>init() is a more fitting name now<commit_after>// Copyright 2014 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.

#![crate_name = "glfw_platform"]
#![comment = "A lightweight graphics device manager for Rust"]
#![license = "ASL2"]
#![crate_type = "lib"]

#![feature(macro_rules, phase)]

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

extern crate device;

use glfw::Context;

struct Wrap<'a>(&'a glfw::Glfw);

impl<'a> device::GlProvider for Wrap<'a> {
    fn get_proc_address(&self, name: &str) -> *const libc::c_void {
        let Wrap(provider) = *self;
        provider.get_proc_address(name)
    }
    fn is_extension_supported(&self, name: &str) -> bool {
        let Wrap(provider) = *self;
        provider.extension_supported(name)
    }
}

pub struct Platform<C> {
    pub context: C,
}

impl<C: Context> Platform<C> {
    #[allow(visible_private_types)]
    pub fn new<'a>(context: C, provider: &'a glfw::Glfw) -> (Platform<C>, Wrap<'a>)  {
        context.make_current();
        (Platform { context: context }, Wrap(provider))
    }
}

impl<C: Context> device::GraphicsContext<device::GlBackEnd> for Platform<C> {
    fn make_current(&self) {
        self.context.make_current();
    }

    fn swap_buffers(&self) {
        self.context.swap_buffers();
    }
}

pub fn create_window<'glfw, 'title, 'monitor, 'hints>(
    glfw: &'glfw glfw::Glfw,
    width: u32,
    height: u32,
    title: &'title str,
    mode: glfw::WindowMode<'monitor>,
    preferred_setup: &'hints [glfw::WindowHint],
) -> CreateWindow<'glfw, 'title, 'monitor, 'hints> {
    CreateWindow {
        glfw: glfw,
        args: (width, height, title, mode),
        hints: vec![preferred_setup],
    }
}

pub fn create_default_window(
    glfw: &glfw::Glfw,
    width: u32,
    height: u32,
    title: &str,
    mode: glfw::WindowMode
) -> Option<(glfw::Window, Receiver<(f64, glfw::WindowEvent)>)> {
    create_window(glfw, width, height, title, mode, [
        glfw::ContextVersion(3, 2),
        glfw::OpenglForwardCompat(true),
        glfw::OpenglProfile(glfw::OpenGlCoreProfile),
    ])
    .fallback([
        glfw::ContextVersion(2, 1),
    ])
    .init().map(|(window, events)| {
        info!("[glfw_platform] Initialized with context version {}", window.get_context_version());
        (window, events)
    })
}

pub struct CreateWindow<'glfw, 'title, 'monitor, 'hints> {
    glfw: &'glfw glfw::Glfw,
    args: (u32, u32, &'title str, glfw::WindowMode<'monitor>),
    hints: Vec<&'hints [glfw::WindowHint]>,
}

impl<'glfw, 'title, 'monitor, 'hints> CreateWindow<'glfw, 'title, 'monitor, 'hints> {
    pub fn fallback(mut self, f: &'hints [glfw::WindowHint])
    -> CreateWindow<'glfw, 'title, 'monitor, 'hints> {
        self.hints.push(f);
        self
    }
    pub fn init(self) -> Option<(glfw::Window, Receiver<(f64, glfw::WindowEvent)>)> {
        let CreateWindow {
            glfw,
            mut hints,
            args: (width, height, title, mode),
        } = self;

        glfw.set_error_callback::<()>(None);
        for setup in hints.mut_iter() {
            glfw.default_window_hints();
            for hint in setup.iter() {
                glfw.window_hint(*hint);
            }
            let r = glfw.create_window(width, height, title, mode);
            if r.is_some() {
                return r;
            }
        }
        None
    }
}
<|endoftext|>


<commit_before>use syscall::common::*;

#[path="../../kernel/syscall/common.rs"]
pub mod common;

#[cold]
#[inline(never)]
#[cfg(target_arch = "x86")]
pub unsafe fn syscall(mut a: usize, b: usize, c: usize, d: usize) -> usize {
    asm!("int 0x80"
        : "={eax}"(a)
        : "{eax}"(a), "{ebx}"(b), "{ecx}"(c), "{edx}"(d)
        : "memory"
        : "intel", "volatile");

    a
}

#[cold]
#[inline(never)]
#[cfg(target_arch = "x86_64")]
pub unsafe fn syscall(mut a: usize, b: usize, c: usize, d: usize) -> usize {
    asm!("int 0x80"
        : "={rax}"(a)
        : "{rax}"(a), "{rbx}"(b), "{rcx}"(c), "{rdx}"(d)
        : "memory"
        : "intel", "volatile");

    a
}

pub unsafe fn sys_debug(byte: u8) {
    syscall(SYS_DEBUG, byte as usize, 0, 0);
}

pub unsafe fn sys_brk(addr: usize) -> usize {
    syscall(SYS_BRK, addr, 0, 0)
}

pub unsafe fn sys_chdir(path: *const u8) -> usize {
    syscall(SYS_CHDIR, path as usize, 0, 0)
}

pub unsafe fn sys_clone(flags: usize) -> usize {
    syscall(SYS_CLONE, flags, 0, 0)
}

pub unsafe fn sys_close(fd: usize) -> usize {
    syscall(SYS_CLOSE, fd, 0, 0)
}

pub unsafe fn sys_clock_gettime(clock: usize, tp: *mut TimeSpec) -> usize{
    syscall(SYS_CLOCK_GETTIME, clock, tp as usize, 0)
}

pub unsafe fn sys_dup(fd: usize) -> usize {
    syscall(SYS_DUP, fd, 0, 0)
}

pub unsafe fn sys_execve(path: *const u8, args: *const *const u8) -> usize {
    syscall(SYS_EXECVE, path as usize, args as usize, 0)
}

pub unsafe fn sys_exit(status: isize) {
    syscall(SYS_EXIT, status as usize, 0, 0);
}

pub unsafe fn sys_fpath(fd: usize, buf: *mut u8, len: usize) -> usize {
    syscall(SYS_FPATH, fd, buf as usize, len)
}

//TODO: FSTAT

pub unsafe fn sys_fsync(fd: usize) -> usize {
    syscall(SYS_FSYNC, fd, 0, 0)
}

pub unsafe fn sys_ftruncate(fd: usize, len: usize) -> usize {
    syscall(SYS_FTRUNCATE, fd, len, 0)
}

pub unsafe fn sys_link(old: *const u8, new: *const u8) -> usize {
    syscall(SYS_LINK, old as usize, new as usize, 0)
}

pub unsafe fn sys_lseek(fd: usize, offset: isize, whence: usize) -> usize {
    syscall(SYS_LSEEK, fd, offset as usize, whence)
}

pub unsafe fn sys_nanosleep(req: *const TimeSpec, rem: *mut TimeSpec) -> usize{
    syscall(SYS_NANOSLEEP, req as usize, rem as usize, 0)
}

pub unsafe fn sys_open(path: *const u8, flags: usize, mode: usize) -> usize {
    syscall(SYS_OPEN, path as usize, flags, mode)
}

pub unsafe fn sys_read(fd: usize, buf: *mut u8, count: usize) -> usize {
    syscall(SYS_READ, fd, buf as usize, count)
}

pub unsafe fn sys_unlink(path: *const u8) -> usize {
    syscall(SYS_UNLINK, path as usize, 0, 0)
}

pub unsafe fn sys_write(fd: usize, buf: *const u8, count: usize) -> usize {
    syscall(SYS_WRITE, fd, buf as usize, count)
}

pub unsafe fn sys_yield() {
    syscall(SYS_YIELD, 0, 0, 0);
}

pub unsafe fn sys_alloc(size: usize) -> usize {
    syscall(SYS_ALLOC, size, 0, 0)
}

pub unsafe fn sys_realloc(ptr: usize, size: usize) -> usize {
    syscall(SYS_REALLOC, ptr, size, 0)
}

pub unsafe fn sys_realloc_inplace(ptr: usize, size: usize) -> usize {
    syscall(SYS_REALLOC_INPLACE, ptr, size, 0)
}

pub unsafe fn sys_unalloc(ptr: usize) {
    syscall(SYS_UNALLOC, ptr, 0, 0);
}
<commit_msg>Added function sys_mkdir to make a system call to create a directory<commit_after>use syscall::common::*;

#[path="../../kernel/syscall/common.rs"]
pub mod common;

#[cold]
#[inline(never)]
#[cfg(target_arch = "x86")]
pub unsafe fn syscall(mut a: usize, b: usize, c: usize, d: usize) -> usize {
    asm!("int 0x80"
        : "={eax}"(a)
        : "{eax}"(a), "{ebx}"(b), "{ecx}"(c), "{edx}"(d)
        : "memory"
        : "intel", "volatile");

    a
}

#[cold]
#[inline(never)]
#[cfg(target_arch = "x86_64")]
pub unsafe fn syscall(mut a: usize, b: usize, c: usize, d: usize) -> usize {
    asm!("int 0x80"
        : "={rax}"(a)
        : "{rax}"(a), "{rbx}"(b), "{rcx}"(c), "{rdx}"(d)
        : "memory"
        : "intel", "volatile");

    a
}

pub unsafe fn sys_debug(byte: u8) {
    syscall(SYS_DEBUG, byte as usize, 0, 0);
}

pub unsafe fn sys_brk(addr: usize) -> usize {
    syscall(SYS_BRK, addr, 0, 0)
}

pub unsafe fn sys_chdir(path: *const u8) -> usize {
    syscall(SYS_CHDIR, path as usize, 0, 0)
}

pub unsafe fn sys_clone(flags: usize) -> usize {
    syscall(SYS_CLONE, flags, 0, 0)
}

pub unsafe fn sys_close(fd: usize) -> usize {
    syscall(SYS_CLOSE, fd, 0, 0)
}

pub unsafe fn sys_clock_gettime(clock: usize, tp: *mut TimeSpec) -> usize{
    syscall(SYS_CLOCK_GETTIME, clock, tp as usize, 0)
}

pub unsafe fn sys_dup(fd: usize) -> usize {
    syscall(SYS_DUP, fd, 0, 0)
}

pub unsafe fn sys_execve(path: *const u8, args: *const *const u8) -> usize {
    syscall(SYS_EXECVE, path as usize, args as usize, 0)
}

pub unsafe fn sys_exit(status: isize) {
    syscall(SYS_EXIT, status as usize, 0, 0);
}

pub unsafe fn sys_fpath(fd: usize, buf: *mut u8, len: usize) -> usize {
    syscall(SYS_FPATH, fd, buf as usize, len)
}

//TODO: FSTAT

pub unsafe fn sys_fsync(fd: usize) -> usize {
    syscall(SYS_FSYNC, fd, 0, 0)
}

pub unsafe fn sys_ftruncate(fd: usize, len: usize) -> usize {
    syscall(SYS_FTRUNCATE, fd, len, 0)
}

pub unsafe fn sys_link(old: *const u8, new: *const u8) -> usize {
    syscall(SYS_LINK, old as usize, new as usize, 0)
}

pub unsafe fn sys_lseek(fd: usize, offset: isize, whence: usize) -> usize {
    syscall(SYS_LSEEK, fd, offset as usize, whence)
}

pub unsafe fn sys_mkdir(path: *const u8, mode: usize) -> usize{
    syscall(SYS_MKDIR, path, mode)
}

pub unsafe fn sys_nanosleep(req: *const TimeSpec, rem: *mut TimeSpec) -> usize{
    syscall(SYS_NANOSLEEP, req as usize, rem as usize, 0)
}

pub unsafe fn sys_open(path: *const u8, flags: usize, mode: usize) -> usize {
    syscall(SYS_OPEN, path as usize, flags, mode)
}

pub unsafe fn sys_read(fd: usize, buf: *mut u8, count: usize) -> usize {
    syscall(SYS_READ, fd, buf as usize, count)
}

pub unsafe fn sys_unlink(path: *const u8) -> usize {
    syscall(SYS_UNLINK, path as usize, 0, 0)
}

pub unsafe fn sys_write(fd: usize, buf: *const u8, count: usize) -> usize {
    syscall(SYS_WRITE, fd, buf as usize, count)
}

pub unsafe fn sys_yield() {
    syscall(SYS_YIELD, 0, 0, 0);
}

pub unsafe fn sys_alloc(size: usize) -> usize {
    syscall(SYS_ALLOC, size, 0, 0)
}

pub unsafe fn sys_realloc(ptr: usize, size: usize) -> usize {
    syscall(SYS_REALLOC, ptr, size, 0)
}

pub unsafe fn sys_realloc_inplace(ptr: usize, size: usize) -> usize {
    syscall(SYS_REALLOC_INPLACE, ptr, size, 0)
}

pub unsafe fn sys_unalloc(ptr: usize) {
    syscall(SYS_UNALLOC, ptr, 0, 0);
}
<|endoftext|>


<commit_before><commit_msg>Add a simple example of library use.<commit_after>extern crate string_cache;

use string_cache::{DefaultAtom, Atom};

fn main() {

    let mut interned_stuff = Vec::new();
    let text = "here is a sentence of text that will be tokenised and interned and some repeated \
                tokens is of text and";
    for word in text.split_whitespace() {
        let seen_before = interned_stuff.iter()
            // We can use impl PartialEq<T> where T is anything string-like to compare to
            // interned strings to either other interned strings, or actual strings  Comparing two
            // interned strings is very fast (normally a single cpu operation).
            .filter(|interned_word| interned_word == &word)
            .count();
        if seen_before > 0 {
            println!(r#"Seen the word "{}" {} times"#, word, seen_before);
        } else {
            println!(r#"Not seen the word "{}" before"#, word);
        }
        // We use the impl From<(Cow<'a, str>, or &'a str, or String) for Atom<Static> to intern a
        // new string
        interned_stuff.push(DefaultAtom::from(word));
    }
}
<|endoftext|>


<commit_before><commit_msg>angular bracket syntax for universal functions<commit_after><|endoftext|>


<commit_before><commit_msg>LeetCode: 234. Palindrome Linked List<commit_after>#[derive(Debug)]
struct Solution {}

// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
    pub val: i32,
    pub next: Option<Box<ListNode>>,
}

impl ListNode {
    #[inline]
    fn new(val: i32) -> Self {
        ListNode {
            next: None,
            val,
        }
    }
}

fn length(head: &Option<Box<ListNode>>) -> isize {
    let mut length = 0;
    let mut head = head;
    while let Some(val) = head {
        length += 1;
        head = &val.next;
    }
    length
}

fn split(mut head: Option<Box<ListNode>>, length: isize) -> (Option<Box<ListNode>>, Option<Box<ListNode>>) {
    let mut reversed = None as Option<Box<ListNode>>;
    for _ in 0..length {
        let mut node = head.unwrap();
        head = node.next.take();
        node.next = reversed;
        reversed = Some(node);
    }
    (head, reversed)
}

fn compare(head: &Option<Box<ListNode>>, tail: &Option<Box<ListNode>>) -> bool {
    let mut h = head;
    let mut t = tail;
    while h.is_some() && t.is_some() {
        println!("compare {:?} {:?}", h, t);
        if h.as_ref().unwrap() != t.as_ref().unwrap() {
            return false;
        }
        h = &h.as_ref().unwrap().next;
        t = &t.as_ref().unwrap().next;
    }
    true
}

impl Solution {
    pub fn is_palindrome(head: Option<Box<ListNode>>) -> bool {
        let mut len = length(&head);
        let (front, reversed) = split(head, len/2);
        if len % 2 == 1 {
            compare(&front.unwrap().next, &reversed)
        } else {
            compare(&front, &reversed)
        }
    }
}

fn main() {
    let sample =
        Some(Box::new(ListNode {
            val: 1,
            next: Some(Box::new(ListNode {
                val: 2,
                next: None as Option<Box<ListNode>>,
            })),
        }));
    // Some(Box::new(ListNode {
    //     val: 1,
    //     next: Some(Box::new(ListNode {
    //         val: 2,
    //         next: Some(Box::new(ListNode {
    //             val: 2,
    //             next: Some(Box::new(ListNode {
    //                 val: 1,
    //                 next: None as Option<Box<ListNode>>
    //             })),
    //         })),
    //     })),
    // }));
    println!("{:?}", Solution::is_palindrome(sample));
}
<|endoftext|>


<commit_before><commit_msg>Debug trait fun<commit_after><|endoftext|>


<commit_before><commit_msg>Alexa, where's the goddamn title?<commit_after><|endoftext|>


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

// Test spans of errors

const TUP: (usize,) = 5 << 64;
//~^ ERROR: attempted left shift with overflow [E0250]
const ARR: [i32; TUP.0] = [];

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>Fix failing tests on 32-bit machines<commit_after><|endoftext|>


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

// This file must never have a trailing newline

fn main() {
    let x = Some(3);
    let y = x.as_ref().unwrap_or(&5); //~ ERROR: borrowed value does not live long enough
}<|endoftext|>


<commit_before><commit_msg>Import std::error::Error directly in config module.<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for reading truncated files<commit_after>//! Ensure truncated images are read without panics.

use std::fs;
use std::path::PathBuf;
use std::io::Read;

extern crate image;
extern crate glob;

const BASE_PATH: [&'static str; 2] = [".", "tests"];
const IMAGE_DIR: &'static str = "images";

fn process_images<F>(dir: &str, input_decoder: Option<&str>, func: F)
where F: Fn(PathBuf) {
	let base: PathBuf = BASE_PATH.iter().collect();
	let decoders = &["tga", "tiff", "png", "gif", "bmp", "ico", "jpg"];
	for decoder in decoders {
		let mut path = base.clone();
		path.push(dir);
		path.push(decoder);
		path.push("*");
		path.push("*.".to_string() + match input_decoder {
			Some(val) => val,
			None => decoder
		});
		let pattern = &*format!("{}", path.display());
		for path in glob::glob(pattern).unwrap().filter_map(Result::ok) {
			func(path)
		}
	}
}

fn truncate_images(decoder: &str) {
    process_images(IMAGE_DIR, Some(decoder), |path| {
        println!("{:?}", path);
        let fin = fs::File::open(&path).unwrap();
        let max_length = 1000;
        let mut buf = Vec::with_capacity(max_length);
        fin.take(max_length as u64).read_to_end(&mut buf).unwrap();
        for i in 0..buf.len() {
            image::load_from_memory(&buf[..i+1]).ok();
        }
    })
}

#[test] #[ignore]
fn truncate_tga() {
    truncate_images("tga")
}

#[test] #[ignore]
fn truncate_tiff() {
    truncate_images("tiff")
}

#[test] #[ignore]
fn truncate_png() {
    truncate_images("png")
}

#[test] #[ignore]
fn truncate_gif() {
    truncate_images("gif")
}

#[test] #[ignore]
fn truncate_bmp() {
    truncate_images("bmp")
}

#[test] #[ignore]
fn truncate_ico() {
    truncate_images("ico")
}

#[test] #[ignore]
fn truncate_jpg() {
    truncate_images("jpg")
}
<|endoftext|>


<commit_before>use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::ops::Deref;
use std::sync::RwLock;
use std::sync::mpsc::{channel, Receiver, Sender};
use {Future, Poll, Async};
use task::{self, Task};
use lock::Lock;

/// A wrapped item of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedItem<T> {
    item: Arc<T>,
}

impl<T> Clone for SharedItem<T> {
    fn clone(&self) -> Self {
        SharedItem { item: self.item.clone() }
    }
}

impl<T> Deref for SharedItem<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.item.as_ref()
    }
}

/// A wrapped error of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedError<E> {
    error: Arc<E>,
}

impl<T> Clone for SharedError<T> {
    fn clone(&self) -> Self {
        SharedError { error: self.error.clone() }
    }
}

impl<E> Deref for SharedError<E> {
    type Target = E;

    fn deref(&self) -> &E {
        &self.error.as_ref()
    }
}

impl<T> SharedItem<T> {
    fn new(item: T) -> Self {
        SharedItem { item: Arc::new(item) }
    }
}

impl<E> SharedError<E> {
    fn new(error: E) -> Self {
        SharedError { error: Arc::new(error) }
    }
}

/// The data that has to be synced to implement `Shared`, in order to satisfy the `Future` trait's constraints.
struct SyncedInner<F>
    where F: Future
{
    original_future: F, // The original future
    result: Option<Result<Async<SharedItem<F::Item>>, SharedError<F::Error>>>, // The original future result wrapped with `SharedItem`/`SharedError`
}

struct Inner<F>
    where F: Future
{
    synced_inner: RwLock<SyncedInner<F>>,
    tasks_unpark_started: AtomicBool,
    tasks_receiver: Lock<Receiver<Task>>, // When original future is polled and ready, unparks all the tasks in that channel
}

/// TODO: doc
#[must_use = "futures do nothing unless polled"]
pub struct Shared<F>
    where F: Future
{
    inner: Arc<Inner<F>>,
    tasks_sender: Sender<Task>,
}

pub fn new<F>(future: F) -> Shared<F>
    where F: Future
{
    let (tasks_sender, tasks_receiver) = channel();
    Shared {
        inner: Arc::new(Inner {
            synced_inner: RwLock::new(SyncedInner {
                original_future: future,
                result: None,
            }),
            tasks_unpark_started: AtomicBool::new(false),
            tasks_receiver: Lock::new(tasks_receiver),
        }),
        tasks_sender: tasks_sender,
    }
}

impl<F> Future for Shared<F>
    where F: Future
{
    type Item = SharedItem<F::Item>;
    type Error = SharedError<F::Error>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let mut polled_result: Option<Result<Async<SharedItem<F::Item>>, SharedError<F::Error>>> =
            None;

        // If the result is ready, just return it
        match self.inner.synced_inner.try_read() {
            Ok(inner_guard) => {
                let ref inner = *inner_guard;
                if let Some(ref result) = inner.result {
                    return result.clone();
                }
            }
            _ => {} // Mutex is locked for write
        }

        // The result was not ready.
        match self.inner.synced_inner.try_write() {
            Ok(mut inner_guard) => {
                let ref mut inner = *inner_guard;

                // By the time that synced_inner was unlocked, other thread could poll the result,
                // so we check if result has a value
                if inner.result.is_some() {
                    polled_result = inner.result.clone();
                } else {
                    match inner.original_future.poll() {
                        Ok(Async::Ready(item)) => {
                            inner.result = Some(Ok(Async::Ready(SharedItem::new(item))));
                            polled_result = inner.result.clone();
                        }
                        Err(error) => {
                            inner.result = Some(Err(SharedError::new(error)));
                            polled_result = inner.result.clone();
                        }
                        Ok(Async::NotReady) => {} // Will be handled later
                    }
                }
            }
            Err(_) => {} // Will be handled later
        }

        if let Some(result) = polled_result {
            match self.inner.synced_inner.try_read() {
                Ok(inner_guard) => {
                    let ref inner = *inner_guard;
                    self.inner.tasks_unpark_started.store(true, Ordering::Relaxed);
                    match self.inner.tasks_receiver.try_lock() {
                        Some(tasks_receiver_guard) => {
                            let ref tasks_receiver = *tasks_receiver_guard;
                            loop {
                                match tasks_receiver.try_recv() {
                                    Ok(task) => task.unpark(),
                                    _ => break,
                                }
                            }
                        }
                        None => {} // Other thread is unparking the tasks
                    }

                    return result.clone();
                }
                _ => {
                    // The mutex is locked for write, after the poll was ready.
                    // The context that locked for write will unpark the tasks.
                }
            }
        }

        let t = task::park();
        let _ = self.tasks_sender.send(t);
        if self.inner.tasks_unpark_started.load(Ordering::Relaxed) {
            // If the tasks unpark has started, synced_inner can be locked for read,
            // and its result has value (not None).
            // The result must be read here because it is possible that the task,
            // t (see variable above), had not been unparked.
            match self.inner.synced_inner.try_read() {
                Ok(inner_guard) => {
                    let ref inner = *inner_guard;
                    return inner.result.as_ref().unwrap().clone();
                }
                _ => {
                    // The mutex is locked for write, so the sent task will be unparked later
                }
            }
        }

        Ok(Async::NotReady)
    }
}

impl<F> Clone for Shared<F>
    where F: Future
{
    fn clone(&self) -> Self {
        Shared {
            inner: self.inner.clone(),
            tasks_sender: self.tasks_sender.clone(),
        }
    }
}
<commit_msg>Use UnsafeCell instead of RwLock<commit_after>use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::ops::Deref;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::cell::UnsafeCell;
use std::marker::Sync;
use {Future, Poll, Async};
use task::{self, Task};
use lock::Lock;

/// A wrapped item of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedItem<T> {
    item: Arc<T>,
}

impl<T> Clone for SharedItem<T> {
    fn clone(&self) -> Self {
        SharedItem { item: self.item.clone() }
    }
}

impl<T> Deref for SharedItem<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.item.as_ref()
    }
}

/// A wrapped error of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedError<E> {
    error: Arc<E>,
}

impl<T> Clone for SharedError<T> {
    fn clone(&self) -> Self {
        SharedError { error: self.error.clone() }
    }
}

impl<E> Deref for SharedError<E> {
    type Target = E;

    fn deref(&self) -> &E {
        &self.error.as_ref()
    }
}

impl<T> SharedItem<T> {
    fn new(item: T) -> Self {
        SharedItem { item: Arc::new(item) }
    }
}

impl<E> SharedError<E> {
    fn new(error: E) -> Self {
        SharedError { error: Arc::new(error) }
    }
}

/// The data that has to be synced to implement `Shared`, in order to satisfy the `Future` trait's constraints.
struct SyncedInner<F>
    where F: Future
{
    original_future: F, // The original future
}

struct Inner<F>
    where F: Future
{
    synced_inner: Lock<SyncedInner<F>>,
    tasks_unpark_started: AtomicBool,
    tasks_receiver: Lock<Receiver<Task>>, // When original future is polled and ready, unparks all the tasks in that channel
    result: UnsafeCell<Option<Result<Async<SharedItem<F::Item>>, SharedError<F::Error>>>>, // The original future result wrapped with `SharedItem`/`SharedError`
}

unsafe impl<F> Sync for Inner<F> where F: Future {}

/// TODO: doc
#[must_use = "futures do nothing unless polled"]
pub struct Shared<F>
    where F: Future
{
    inner: Arc<Inner<F>>,
    tasks_sender: Sender<Task>,
}

pub fn new<F>(future: F) -> Shared<F>
    where F: Future
{
    let (tasks_sender, tasks_receiver) = channel();
    Shared {
        inner: Arc::new(Inner {
            synced_inner: Lock::new(SyncedInner {
                original_future: future,
            }),
            tasks_unpark_started: AtomicBool::new(false),
            tasks_receiver: Lock::new(tasks_receiver),
            result: UnsafeCell::new(None),
        }),
        tasks_sender: tasks_sender,
    }
}

impl<F> Future for Shared<F>
    where F: Future
{
    type Item = SharedItem<F::Item>;
    type Error = SharedError<F::Error>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let mut polled_result: Option<Result<Async<SharedItem<F::Item>>, SharedError<F::Error>>> = None;

        // If the result is ready, just return it
        if self.inner.tasks_unpark_started.load(Ordering::Relaxed) {
            unsafe {
                if let Some(ref result) = *self.inner.result.get() {
                    return result.clone();
                }
            }
        }

        // The result was not ready.
        match self.inner.synced_inner.try_lock() {
            Some(mut inner_guard) => {
                let ref mut inner = *inner_guard;

                // By the time that synced_inner was unlocked, other thread could poll the result,
                // so we check if result has a value
                unsafe {
                    if (*self.inner.result.get()).is_some() {
                        polled_result = (*self.inner.result.get()).clone();
                    } else {
                        match inner.original_future.poll() {
                            Ok(Async::Ready(item)) => {
                                *self.inner.result.get() = Some(Ok(Async::Ready(SharedItem::new(item))));
                                polled_result = (*self.inner.result.get()).clone();
                            }
                            Err(error) => {
                                *self.inner.result.get() = Some(Err(SharedError::new(error)));
                                polled_result = (*self.inner.result.get()).clone();
                            }
                            Ok(Async::NotReady) => {} // Will be handled later
                        }
                    }
                }
            }
            None => {} // Will be handled later
        }

        if let Some(result) = polled_result {
            self.inner.tasks_unpark_started.store(true, Ordering::Relaxed);
            match self.inner.tasks_receiver.try_lock() {
                Some(tasks_receiver_guard) => {
                    let ref tasks_receiver = *tasks_receiver_guard;
                    loop {
                        match tasks_receiver.try_recv() {
                            Ok(task) => task.unpark(),
                            _ => break,
                        }
                    }
                }
                None => {} // Other thread is unparking the tasks
            }

            return result.clone();
        }

        let t = task::park();
        let _ = self.tasks_sender.send(t);
        if self.inner.tasks_unpark_started.load(Ordering::Relaxed) {
            // If the tasks unpark has started, self.inner.result has a value (not None).
            // The result must be read here because it is possible that the task,
            // t (see variable above), had not been unparked.
            unsafe {
                if let Some(ref result) = *self.inner.result.get() {
                    return result.clone();
                }
            }
        }

        Ok(Async::NotReady)
    }
}

impl<F> Clone for Shared<F>
    where F: Future
{
    fn clone(&self) -> Self {
        Shared {
            inner: self.inner.clone(),
            tasks_sender: self.tasks_sender.clone(),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add example from README<commit_after>extern crate slog;

use slog::*;
use std::thread;

fn main() {
    let root = Logger::root().add("example", "basic").end();
    let log = root.new().add("thread-name", "main").end();
    let tlog = root.new().add("thread-name", "sleep1000").end();

    log.set_drain(
        drain::duplicate(
            drain::filter_level(Level::Info, drain::stream(std::io::stderr())),
            drain::stream(std::io::stdout()),
            )
        );

    let join = thread::spawn(move || {
        tlog.info("subthread started");
        thread::sleep_ms(1000);
        tlog.info("subthread finished");
    });

    let time_ms = 10000;
    log.info("sleep").add("time", time_ms);
    thread::sleep_ms(time_ms);

    log.info("join");

    join.join().unwrap();
    log.warning("exit");
}

<|endoftext|>


<commit_before><commit_msg>Added an example of drawing a heart<commit_after>extern crate turtle;

use turtle::Turtle;

fn main() {
    let mut turtle = Turtle::new();

    turtle.set_speed(7);
    turtle.set_pen_size(3.0);
    turtle.set_pen_color("red");

    turtle.pen_up();
    turtle.forward(-50.0);
    turtle.pen_down();

    turtle.left(50.0);
    turtle.forward(111.65);
    turtle.set_speed(10);
    curve(&mut turtle);
    turtle.left(120.0);
    curve(&mut turtle);
    turtle.set_speed(7);
    turtle.forward(111.65);

    turtle.forward(20.0);
    for _ in 0..10 {
        turtle.right(2.0);
        turtle.forward(2.0);
    }

    turtle.set_background_color("pink");
}

fn curve(turtle: &mut Turtle) {
    for _ in 0..100 {
        turtle.right(2.0);
        turtle.forward(2.0);
    }
}
<|endoftext|>


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

// aux-build:pub-use-extern-macros.rs

#![feature(use_extern_macros)]

extern crate macros;

// @has pub_use_extern_macros/macro.bar.html
// @!has pub_use_extern_macros/index.html 'pub use macros::bar;'
pub use macros::bar;

// @has pub_use_extern_macros/macro.baz.html
// @!has pub_use_extern_macros/index.html 'pub use macros::baz;'
#[doc(inline)]
pub use macros::baz;

// @has pub_use_extern_macros/macro.quux.html
// @!has pub_use_extern_macros/index.html 'pub use macros::quux;'
#[doc(hidden)]
pub use macros::quux;
<commit_msg>fix @!has conditions in pub-use-extern-macros test<commit_after>// Copyright 2017 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.

// aux-build:pub-use-extern-macros.rs

#![feature(use_extern_macros)]

extern crate macros;

// @has pub_use_extern_macros/macro.bar.html
// @!has pub_use_extern_macros/index.html '//code' 'pub use macros::bar;'
pub use macros::bar;

// @has pub_use_extern_macros/macro.baz.html
// @!has pub_use_extern_macros/index.html '//code' 'pub use macros::baz;'
#[doc(inline)]
pub use macros::baz;

// @has pub_use_extern_macros/macro.quux.html
// @!has pub_use_extern_macros/index.html '//code' 'pub use macros::quux;'
#[doc(hidden)]
pub use macros::quux;
<|endoftext|>


<commit_before><commit_msg>Add viewport x and y offsets<commit_after><|endoftext|>


<commit_before><commit_msg>tests/addressbook_test: cargofmt<commit_after><|endoftext|>


<commit_before>#![feature(globs)] // Allow global imports

extern crate gl;
extern crate graphics;
extern crate native;
extern crate piston;
extern crate sdl2_game_window;

use sdl2_game_window::GameWindowSDL2;

use piston::*;
use gl::types::*;
use std::mem;
use std::ptr;
use std::str;

pub struct App {
  vao: u32,
  vbo: u32
}

impl Game for App {
  fn load(&mut self) {
    gl::ClearColor(0.0, 0.0, 0.0, 1.0);
  }

  fn render(&mut self, _:&RenderArgs) {
    gl::Clear(gl::COLOR_BUFFER_BIT);

    // Draw a triangle from the 3 vertices
    gl::DrawArrays(gl::TRIANGLES, 0, 3);
  }
}

impl App {
  pub fn new() -> App {
    App {
      vao: 0,
      vbo: 0
    }
  }

  pub fn destroy(&mut self) {
    unsafe {
        gl::DeleteBuffers(1, &self.vbo);
        gl::DeleteVertexArrays(1, &self.vao);
    }
  }
}

// Vertex data
static VERTEX_DATA: [GLfloat, ..6] = [
     0.0,  0.5,
     0.5, -0.5,
    -0.5, -0.5
];

// Shader sources
static VS_SRC: &'static str =
   "#version 150\n\
in vec2 position;\n\
void main() {\n\
gl_Position = vec4(position, 0.0, 1.0);\n\
}";

static FS_SRC: &'static str =
   "#version 150\n\
out vec4 out_color;\n\
void main() {\n\
out_color = vec4(1.0, 1.0, 1.0, 1.0);\n\
}";

fn compile_shader(src: &str, ty: GLenum) -> GLuint {
    let shader = gl::CreateShader(ty);
    unsafe {
        // Attempt to compile the shader
        src.with_c_str(|ptr| gl::ShaderSource(shader, 1, &ptr, ptr::null()));
        gl::CompileShader(shader);

        // Get the compile status
        let mut status = gl::FALSE as GLint;
        gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);

        // Fail on error
        if status != (gl::TRUE as GLint) {
            let mut len = 0;
            gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);
            let mut buf = Vec::from_elem(len as uint - 1, 0u8); // subtract 1 to skip the trailing null character
            gl::GetShaderInfoLog(shader, len, ptr::mut_null(), buf.as_mut_ptr() as *mut GLchar);
            fail!("{}", str::from_utf8(buf.as_slice()).expect("ShaderInfoLog not valid utf8"));
        }
    }
    shader
}

fn link_program(vs: GLuint, fs: GLuint) -> GLuint {
    let program = gl::CreateProgram();
    gl::AttachShader(program, vs);
    gl::AttachShader(program, fs);
    gl::LinkProgram(program);
    unsafe {
        // Get the link status
        let mut status = gl::FALSE as GLint;
        gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);

        // Fail on error
        if status != (gl::TRUE as GLint) {
            let mut len: GLint = 0;
            gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut len);
            let mut buf = Vec::from_elem(len as uint - 1, 0u8); // subtract 1 to skip the trailing null character
            gl::GetProgramInfoLog(program, len, ptr::mut_null(), buf.as_mut_ptr() as *mut GLchar);
            fail!("{}", str::from_utf8(buf.as_slice()).expect("ProgramInfoLog not valid utf8"));
        }
    }
    program
}

fn main() {
  let game_iter_settings = GameIteratorSettings {
    updates_per_second: 30,
    max_frames_per_second: 30
  };

  let mut window = GameWindowSDL2::new(
    GameWindowSettings {
      title: "playform".to_string(),
      size: [800, 600],
      fullscreen: false,
      exit_on_esc: true
    }
  );

  // It is essential to make the context current before calling `gl::load_with`.
  // window.make_current();

  // Load the OpenGL function pointers
  //gl::load_with(|s| glfw.get_proc_address(s));

  let mut app = App::new();

  let vs = compile_shader(VS_SRC, gl::VERTEX_SHADER);
  let fs = compile_shader(FS_SRC, gl::FRAGMENT_SHADER);
  let program = link_program(vs, fs);

  unsafe {
    // Create Vertex Array Object
    gl::GenVertexArrays(1, &mut app.vao);
    gl::BindVertexArray(app.vao);

    // Create a Vertex Buffer Object and copy the vertex data to it
    gl::GenBuffers(1, &mut app.vbo);
    gl::BindBuffer(gl::ARRAY_BUFFER, app.vbo);
    gl::BufferData(gl::ARRAY_BUFFER,
                    (VERTEX_DATA.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,
                    mem::transmute(&VERTEX_DATA[0]),
                    gl::STATIC_DRAW);

    gl::UseProgram(program);
    "out_color".with_c_str(|ptr| gl::BindFragDataLocation(program, 0, ptr));

    // Specify the layout of the vertex data
    let pos_attr = "position".with_c_str(|ptr| gl::GetAttribLocation(program, ptr));
    gl::EnableVertexAttribArray(pos_attr as GLuint);
    gl::VertexAttribPointer(pos_attr as GLuint, 2, gl::FLOAT,
                            gl::FALSE as GLboolean, 0, ptr::null());
  }

  app.run(&mut window, &game_iter_settings);
}
<commit_msg>3D positions passed to shader<commit_after>#![feature(globs)] // Allow global imports

extern crate gl;
extern crate graphics;
extern crate native;
extern crate piston;
extern crate sdl2_game_window;

use sdl2_game_window::GameWindowSDL2;

use piston::*;
use gl::types::*;
use std::mem;
use std::ptr;
use std::str;

pub struct App {
  vao: u32,
  vbo: u32
}

impl Game for App {
  fn load(&mut self) {
    gl::ClearColor(0.0, 0.0, 0.0, 1.0);
  }

  fn render(&mut self, _:&RenderArgs) {
    gl::Clear(gl::COLOR_BUFFER_BIT);

    // Draw a triangle from the 3 vertices
    gl::DrawArrays(gl::TRIANGLES, 0, 3);
  }
}

impl App {
  pub fn new() -> App {
    App {
      vao: 0,
      vbo: 0
    }
  }

  pub fn destroy(&mut self) {
    unsafe {
        gl::DeleteBuffers(1, &self.vbo);
        gl::DeleteVertexArrays(1, &self.vao);
    }
  }
}

// Vertex data
static VERTEX_DATA: [GLfloat, ..9] = [
     0.0,  0.5, 0.0,
     0.5, -0.5, 0.0,
    -0.5, -0.5, 0.0,
];

// Shader sources
static VS_SRC: &'static str =
   "#version 150\n\
in vec3 position;\n\
void main() {\n\
gl_Position = vec4(position, 1.0);\n\
}";

static FS_SRC: &'static str =
   "#version 150\n\
out vec4 out_color;\n\
void main() {\n\
out_color = vec4(1.0, 1.0, 1.0, 1.0);\n\
}";

fn compile_shader(src: &str, ty: GLenum) -> GLuint {
    let shader = gl::CreateShader(ty);
    unsafe {
        // Attempt to compile the shader
        src.with_c_str(|ptr| gl::ShaderSource(shader, 1, &ptr, ptr::null()));
        gl::CompileShader(shader);

        // Get the compile status
        let mut status = gl::FALSE as GLint;
        gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);

        // Fail on error
        if status != (gl::TRUE as GLint) {
            let mut len = 0;
            gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);
            let mut buf = Vec::from_elem(len as uint - 1, 0u8); // subtract 1 to skip the trailing null character
            gl::GetShaderInfoLog(shader, len, ptr::mut_null(), buf.as_mut_ptr() as *mut GLchar);
            fail!("{}", str::from_utf8(buf.as_slice()).expect("ShaderInfoLog not valid utf8"));
        }
    }
    shader
}

fn link_program(vs: GLuint, fs: GLuint) -> GLuint {
    let program = gl::CreateProgram();
    gl::AttachShader(program, vs);
    gl::AttachShader(program, fs);
    gl::LinkProgram(program);

    unsafe {
        // Get the link status
        let mut status = gl::FALSE as GLint;
        gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);

        // Fail on error
        if status != (gl::TRUE as GLint) {
            let mut len: GLint = 0;
            gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut len);
            let mut buf = Vec::from_elem(len as uint - 1, 0u8); // subtract 1 to skip the trailing null character
            gl::GetProgramInfoLog(program, len, ptr::mut_null(), buf.as_mut_ptr() as *mut GLchar);
            fail!("{}", str::from_utf8(buf.as_slice()).expect("ProgramInfoLog not valid utf8"));
        }
    }
    program
}

fn main() {
  let game_iter_settings = GameIteratorSettings {
    updates_per_second: 30,
    max_frames_per_second: 30
  };

  let mut window = GameWindowSDL2::new(
    GameWindowSettings {
      title: "playform".to_string(),
      size: [800, 600],
      fullscreen: false,
      exit_on_esc: true
    }
  );

  let mut app = App::new();

  let vs = compile_shader(VS_SRC, gl::VERTEX_SHADER);
  let fs = compile_shader(FS_SRC, gl::FRAGMENT_SHADER);
  let program = link_program(vs, fs);

  unsafe {
    // Create Vertex Array Object
    gl::GenVertexArrays(1, &mut app.vao);
    gl::BindVertexArray(app.vao);

    // Create a Vertex Buffer Object and copy the vertex data to it
    gl::GenBuffers(1, &mut app.vbo);
    gl::BindBuffer(gl::ARRAY_BUFFER, app.vbo);
    gl::BufferData(gl::ARRAY_BUFFER,
                    (VERTEX_DATA.len() * mem::size_of::<GLfloat>()) as GLsizeiptr,
                    mem::transmute(&VERTEX_DATA[0]),
                    gl::STATIC_DRAW);

    gl::UseProgram(program);
    "out_color".with_c_str(|ptr| gl::BindFragDataLocation(program, 0, ptr));

    // Specify the layout of the vertex data
    let pos_attr = "position".with_c_str(|ptr| gl::GetAttribLocation(program, ptr) as u32);
    gl::EnableVertexAttribArray(pos_attr);
    gl::VertexAttribPointer(pos_attr, 3, gl::FLOAT,
                            gl::FALSE as GLboolean, 0, ptr::null());
  }

  app.run(&mut window, &game_iter_settings);
}
<|endoftext|>


<commit_before><commit_msg>main: match BuildFile<commit_after><|endoftext|>


<commit_before><commit_msg>Test for #876<commit_after>// -*- rust -*-
// xfail-test
// error-pattern:mismatch
use std;
import std::vec::*;

fn main() {
    let y;
    let x : char = last(y);
}
<|endoftext|>


<commit_before><commit_msg>WIP: support for enumeration types<commit_after>// This file is part of Grust, GObject introspection bindings for Rust
//
// Copyright (C) 2015  Mikhail Zabaluev <mikhail.zabaluev@gmail.com>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

use gtype::GType;
use types::gint;

pub trait EnumType {
    fn get_type() -> GType;
    fn from_int(v: gint) -> Option<Self>;
    fn to_int(&self) -> gint;
}
<|endoftext|>


<commit_before>

/* Simple getopt alternative. Construct a vector of options, either by using
 * reqopt, optopt, and optflag or by building them from components yourself,
 * and pass them to getopts, along with a vector of actual arguments (not
 * including argv[0]). You'll either get a failure code back, or a match.
 * You'll have to verify whether the amount of 'free' arguments in the match
 * is what you expect. Use opt_* accessors (bottom of the file) to get
 * argument values out of the match object.
 */
import option::some;
import option::none;
export opt;
export reqopt;
export optopt;
export optflag;
export optflagopt;
export optmulti;
export getopts;
export result;
export success;
export failure;
export match;
export fail_;
export fail_str;
export opt_present;
export opt_str;
export opt_strs;
export opt_maybe_str;
export opt_default;

tag name { long(str); short(char); }

tag hasarg { yes; no; maybe; }

tag occur { req; optional; multi; }

type opt = rec(name name, hasarg hasarg, occur occur);

fn mkname(str nm) -> name {
    ret if (str::char_len(nm) == 1u) {
            short(str::char_at(nm, 0u))
        } else { long(nm) };
}

fn reqopt(str name) -> opt {
    ret rec(name=mkname(name), hasarg=yes, occur=req);
}

fn optopt(str name) -> opt {
    ret rec(name=mkname(name), hasarg=yes, occur=optional);
}

fn optflag(str name) -> opt {
    ret rec(name=mkname(name), hasarg=no, occur=optional);
}

fn optflagopt(str name) -> opt {
    ret rec(name=mkname(name), hasarg=maybe, occur=optional);
}

fn optmulti(str name) -> opt {
    ret rec(name=mkname(name), hasarg=yes, occur=multi);
}

tag optval { val(str); given; }

type match = rec(vec[opt] opts, vec[mutable vec[optval]] vals, vec[str] free);

fn is_arg(str arg) -> bool {
    ret str::byte_len(arg) > 1u && arg.(0) == '-' as u8;
}

fn name_str(name nm) -> str {
    ret alt (nm) {
            case (short(?ch)) { str::from_char(ch) }
            case (long(?s)) { s }
        };
}

fn find_opt(vec[opt] opts, name nm) -> option::t[uint] {
    auto i = 0u;
    auto l = vec::len[opt](opts);
    while (i < l) {
        if (opts.(i).name == nm) { ret some[uint](i); }
        i += 1u;
    }
    ret none[uint];
}

tag fail_ {
    argument_missing(str);
    unrecognized_option(str);
    option_missing(str);
    option_duplicated(str);
    unexpected_argument(str);
}

fn fail_str(fail_ f) -> str {
    ret alt (f) {
            case (argument_missing(?nm)) {
                "Argument to option '" + nm + "' missing."
            }
            case (unrecognized_option(?nm)) {
                "Unrecognized option: '" + nm + "'."
            }
            case (option_missing(?nm)) {
                "Required option '" + nm + "' missing."
            }
            case (option_duplicated(?nm)) {
                "Option '" + nm + "' given more than once."
            }
            case (unexpected_argument(?nm)) {
                "Option " + nm + " does not take an argument."
            }
        };
}

tag result { success(match); failure(fail_); }

fn getopts(vec[str] args, vec[opt] opts) -> result {
    auto n_opts = vec::len[opt](opts);
    fn f(uint x) -> vec[optval] { ret vec::empty(); }
    auto vals = vec::init_fn_mut[vec[optval]](f, n_opts);
    let vec[str] free = [];
    auto l = vec::len[str](args);
    auto i = 0u;
    while (i < l) {
        auto cur = args.(i);
        auto curlen = str::byte_len(cur);
        if (!is_arg(cur)) {
            vec::push[str](free, cur);
        } else if (str::eq(cur, "--")) {
            free += vec::slice[str](args, i + 1u, l);
            break;
        } else {
            auto names;
            auto i_arg = option::none[str];
            if (cur.(1) == '-' as u8) {
                auto tail = str::slice(cur, 2u, curlen);
                auto eq = str::index(tail, '=' as u8);
                if (eq == -1) {
                    names = [long(tail)];
                } else {
                    names = [long(str::slice(tail, 0u, eq as uint))];
                    i_arg =
                        option::some[str](str::slice(tail, (eq as uint) + 1u,
                                                     curlen - 2u));
                }
            } else {
                auto j = 1u;
                names = [];
                while (j < curlen) {
                    auto range = str::char_range_at(cur, j);
                    vec::push[name](names, short(range._0));
                    j = range._1;
                }
            }
            auto name_pos = 0u;
            for (name nm in names) {
                name_pos += 1u;
                auto optid;
                alt (find_opt(opts, nm)) {
                    case (some(?id)) { optid = id; }
                    case (none) {
                        ret failure(unrecognized_option(name_str(nm)));
                    }
                }
                alt (opts.(optid).hasarg) {
                    case (no) {
                        if (!option::is_none[str](i_arg)) {
                            ret failure(unexpected_argument(name_str(nm)));
                        }
                        vec::push[optval](vals.(optid), given);
                    }
                    case (maybe) {
                        if (!option::is_none[str](i_arg)) {
                            vec::push[optval](vals.(optid),
                                              val(option::get[str](i_arg)));
                        } else if (name_pos < vec::len[name](names) ||
                                       i + 1u == l || is_arg(args.(i + 1u))) {
                            vec::push[optval](vals.(optid), given);
                        } else {
                            i += 1u;
                            vec::push[optval](vals.(optid), val(args.(i)));
                        }
                    }
                    case (yes) {
                        if (!option::is_none[str](i_arg)) {
                            vec::push[optval](vals.(optid),
                                              val(option::get[str](i_arg)));
                        } else if (i + 1u == l) {
                            ret failure(argument_missing(name_str(nm)));
                        } else {
                            i += 1u;
                            vec::push[optval](vals.(optid), val(args.(i)));
                        }
                    }
                }
            }
        }
        i += 1u;
    }
    i = 0u;
    while (i < n_opts) {
        auto n = vec::len[optval](vals.(i));
        auto occ = opts.(i).occur;
        if (occ == req) {
            if (n == 0u) {
                ret failure(option_missing(name_str(opts.(i).name)));
            }
        }
        if (occ != multi) {
            if (n > 1u) {
                ret failure(option_duplicated(name_str(opts.(i).name)));
            }
        }
        i += 1u;
    }
    ret success(rec(opts=opts, vals=vals, free=free));
}

fn opt_vals(match m, str nm) -> vec[optval] {
    ret alt (find_opt(m.opts, mkname(nm))) {
            case (some(?id)) { m.vals.(id) }
            case (none) { log_err "No option '" + nm + "' defined."; fail }
        };
}

fn opt_val(match m, str nm) -> optval { ret opt_vals(m, nm).(0); }

fn opt_present(match m, str nm) -> bool {
    ret vec::len[optval](opt_vals(m, nm)) > 0u;
}

fn opt_str(match m, str nm) -> str {
    ret alt (opt_val(m, nm)) { case (val(?s)) { s } case (_) { fail } };
}

fn opt_strs(match m, str nm) -> vec[str] {
    let vec[str] acc = [];
    for (optval v in opt_vals(m, nm)) {
        alt (v) { case (val(?s)) { vec::push[str](acc, s); } case (_) { } }
    }
    ret acc;
}

fn opt_maybe_str(match m, str nm) -> option::t[str] {
    auto vals = opt_vals(m, nm);
    if (vec::len[optval](vals) == 0u) { ret none[str]; }
    ret alt (vals.(0)) {
            case (val(?s)) { some[str](s) }
            case (_) { none[str] }
        };
}

/// Returns none if the option was not present, `def` if the option was
/// present but no argument was provided, and the argument if the option was
/// present and an argument was provided.
fn opt_default(match m, str nm, str def) -> option::t[str] {
    auto vals = opt_vals(m, nm);
    if (vec::len[optval](vals) == 0u) { ret none[str]; }
    ret alt (vals.(0)) {
            case (val(?s)) { some[str](s) }
            case (_) { some[str](def) }
        }
}
// 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>stdlib: Port most of getopts over to interior vectors<commit_after>

/* Simple getopt alternative. Construct a vector of options, either by using
 * reqopt, optopt, and optflag or by building them from components yourself,
 * and pass them to getopts, along with a vector of actual arguments (not
 * including argv[0]). You'll either get a failure code back, or a match.
 * You'll have to verify whether the amount of 'free' arguments in the match
 * is what you expect. Use opt_* accessors (bottom of the file) to get
 * argument values out of the match object.
 */
import option::some;
import option::none;
export opt;
export reqopt;
export optopt;
export optflag;
export optflagopt;
export optmulti;
export getopts;
export result;
export success;
export failure;
export match;
export fail_;
export fail_str;
export opt_present;
export opt_str;
export opt_strs;
export opt_maybe_str;
export opt_default;

tag name { long(str); short(char); }

tag hasarg { yes; no; maybe; }

tag occur { req; optional; multi; }

type opt = rec(name name, hasarg hasarg, occur occur);

fn mkname(str nm) -> name {
    ret if (str::char_len(nm) == 1u) {
            short(str::char_at(nm, 0u))
        } else { long(nm) };
}

fn reqopt(str name) -> opt {
    ret rec(name=mkname(name), hasarg=yes, occur=req);
}

fn optopt(str name) -> opt {
    ret rec(name=mkname(name), hasarg=yes, occur=optional);
}

fn optflag(str name) -> opt {
    ret rec(name=mkname(name), hasarg=no, occur=optional);
}

fn optflagopt(str name) -> opt {
    ret rec(name=mkname(name), hasarg=maybe, occur=optional);
}

fn optmulti(str name) -> opt {
    ret rec(name=mkname(name), hasarg=yes, occur=multi);
}

tag optval { val(str); given; }

type match = rec(opt[] opts, (optval[])[mutable] vals, vec[str] free);

fn is_arg(str arg) -> bool {
    ret str::byte_len(arg) > 1u && arg.(0) == '-' as u8;
}

fn name_str(name nm) -> str {
    ret alt (nm) {
            case (short(?ch)) { str::from_char(ch) }
            case (long(?s)) { s }
        };
}

fn find_opt(&opt[] opts, name nm) -> option::t[uint] {
    auto i = 0u;
    auto l = ivec::len[opt](opts);
    while (i < l) {
        if (opts.(i).name == nm) { ret some[uint](i); }
        i += 1u;
    }
    ret none[uint];
}

tag fail_ {
    argument_missing(str);
    unrecognized_option(str);
    option_missing(str);
    option_duplicated(str);
    unexpected_argument(str);
}

fn fail_str(fail_ f) -> str {
    ret alt (f) {
            case (argument_missing(?nm)) {
                "Argument to option '" + nm + "' missing."
            }
            case (unrecognized_option(?nm)) {
                "Unrecognized option: '" + nm + "'."
            }
            case (option_missing(?nm)) {
                "Required option '" + nm + "' missing."
            }
            case (option_duplicated(?nm)) {
                "Option '" + nm + "' given more than once."
            }
            case (unexpected_argument(?nm)) {
                "Option " + nm + " does not take an argument."
            }
        };
}

tag result { success(match); failure(fail_); }

fn getopts(vec[str] args, vec[opt] opts) -> result {
    // FIXME: Remove this vec->ivec conversion.
    auto args_ivec = ~[]; auto opts_ivec = ~[];
    for (str arg in args) { args_ivec += ~[arg]; }
    for (opt o in opts) { opts_ivec += ~[o]; }
    ret getopts_ivec(args_ivec, opts_ivec);
}

fn getopts_ivec(&str[] args, &opt[] opts) -> result {
    auto n_opts = ivec::len[opt](opts);
    fn f(uint x) -> optval[] { ret ~[]; }
    auto vals = ivec::init_fn_mut[optval[]](f, n_opts);
    let vec[str] free = [];
    auto l = ivec::len[str](args);
    auto i = 0u;
    while (i < l) {
        auto cur = args.(i);
        auto curlen = str::byte_len(cur);
        if (!is_arg(cur)) {
            free += [cur];
        } else if (str::eq(cur, "--")) {
            auto j = i + 1u;
            while (j < l) {
                free += [args.(j)];
                j += 1u;
            }
            break;
        } else {
            auto names;
            auto i_arg = option::none[str];
            if (cur.(1) == '-' as u8) {
                auto tail = str::slice(cur, 2u, curlen);
                auto eq = str::index(tail, '=' as u8);
                if (eq == -1) {
                    names = ~[long(tail)];
                } else {
                    names = ~[long(str::slice(tail, 0u, eq as uint))];
                    i_arg =
                        option::some[str](str::slice(tail, (eq as uint) + 1u,
                                                     curlen - 2u));
                }
            } else {
                auto j = 1u;
                names = ~[];
                while (j < curlen) {
                    auto range = str::char_range_at(cur, j);
                    names += ~[short(range._0)];
                    j = range._1;
                }
            }
            auto name_pos = 0u;
            for (name nm in names) {
                name_pos += 1u;
                auto optid;
                alt (find_opt(opts, nm)) {
                    case (some(?id)) { optid = id; }
                    case (none) {
                        ret failure(unrecognized_option(name_str(nm)));
                    }
                }
                alt (opts.(optid).hasarg) {
                    case (no) {
                        if (!option::is_none[str](i_arg)) {
                            ret failure(unexpected_argument(name_str(nm)));
                        }
                        vals.(optid) += ~[given];
                    }
                    case (maybe) {
                        if (!option::is_none[str](i_arg)) {
                            vals.(optid) += ~[val(option::get(i_arg))];
                        } else if (name_pos < ivec::len[name](names) ||
                                       i + 1u == l || is_arg(args.(i + 1u))) {
                            vals.(optid) += ~[given];
                        } else {
                            i += 1u;
                            vals.(optid) += ~[val(args.(i))];
                        }
                    }
                    case (yes) {
                        if (!option::is_none[str](i_arg)) {
                            vals.(optid) += ~[val(option::get[str](i_arg))];
                        } else if (i + 1u == l) {
                            ret failure(argument_missing(name_str(nm)));
                        } else {
                            i += 1u;
                            vals.(optid) += ~[val(args.(i))];
                        }
                    }
                }
            }
        }
        i += 1u;
    }
    i = 0u;
    while (i < n_opts) {
        auto n = ivec::len[optval](vals.(i));
        auto occ = opts.(i).occur;
        if (occ == req) {
            if (n == 0u) {
                ret failure(option_missing(name_str(opts.(i).name)));
            }
        }
        if (occ != multi) {
            if (n > 1u) {
                ret failure(option_duplicated(name_str(opts.(i).name)));
            }
        }
        i += 1u;
    }
    ret success(rec(opts=opts, vals=vals, free=free));
}

fn opt_vals(match m, str nm) -> optval[] {
    ret alt (find_opt(m.opts, mkname(nm))) {
            case (some(?id)) { m.vals.(id) }
            case (none) { log_err "No option '" + nm + "' defined."; fail }
        };
}

fn opt_val(match m, str nm) -> optval { ret opt_vals(m, nm).(0); }

fn opt_present(match m, str nm) -> bool {
    ret ivec::len[optval](opt_vals(m, nm)) > 0u;
}

fn opt_str(match m, str nm) -> str {
    ret alt (opt_val(m, nm)) { case (val(?s)) { s } case (_) { fail } };
}

fn opt_strs(match m, str nm) -> vec[str] {
    let vec[str] acc = [];
    for (optval v in opt_vals(m, nm)) {
        alt (v) { case (val(?s)) { acc += [s]; } case (_) { } }
    }
    ret acc;
}

fn opt_strs_ivec(match m, str nm) -> str[] {
    let str[] acc = ~[];
    for (optval v in opt_vals(m, nm)) {
        alt (v) { case (val(?s)) { acc += ~[s]; } case (_) { } }
    }
    ret acc;
}

fn opt_maybe_str(match m, str nm) -> option::t[str] {
    auto vals = opt_vals(m, nm);
    if (ivec::len[optval](vals) == 0u) { ret none[str]; }
    ret alt (vals.(0)) {
            case (val(?s)) { some[str](s) }
            case (_) { none[str] }
        };
}

/// Returns none if the option was not present, `def` if the option was
/// present but no argument was provided, and the argument if the option was
/// present and an argument was provided.
fn opt_default(match m, str nm, str def) -> option::t[str] {
    auto vals = opt_vals(m, nm);
    if (ivec::len[optval](vals) == 0u) { ret none[str]; }
    ret alt (vals.(0)) {
            case (val(?s)) { some[str](s) }
            case (_) { some[str](def) }
        }
}
// 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>add test case for enum disambiguation<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//error-pattern:unresolved enum variant

fn main() {
    // a bug in the parser is allowing this:
    let a() = 13;
}
<|endoftext|>


<commit_before><commit_msg>Fix: Properly mark doctests as notrust<commit_after><|endoftext|>


<commit_before><commit_msg>vec: start using the Allocator trait<commit_after><|endoftext|>


<commit_before><commit_msg>Upgrade to latest rust-sdl2<commit_after><|endoftext|>


<commit_before>use git2::Error as Git2Error;

use libimagstore::hook::error::HookError as HE;
use libimagstore::hook::error::HookErrorKind as HEK;
use libimagstore::hook::result::HookResult;

generate_error_module!(
    generate_error_types!(GitHookError, GitHookErrorKind,
        ConfigError => "Configuration Error",
        NoConfigError => "No Configuration",
        ConfigTypeError => "Configuration value type wrong",

        RepositoryError                   => "Error while interacting with git repository",
        RepositoryInitError               => "Error while loading the git repository",
        RepositoryBackendError            => "Error in the git library",
        RepositoryBranchError             => "Error while interacting with git branch(es)",
        RepositoryBranchNameFetchingError => "Error while fetching branch name",
        RepositoryIndexFetchingError      => "Error while fetching Repository Index",
        RepositoryIndexWritingError       => "Error while writing Repository Index",
        RepositoryPathAddingError         => "Error while adding Path to Index",
        RepositoryCommittingError         => "Error while committing",
        RepositoryParentFetchingError     => "Error while fetching parent of commit",

        HeadFetchError                    => "Error while getting HEAD",
        NotOnBranch                       => "No Branch is checked out",
        MkRepo                            => "Repository creation error",
        MkSignature                       => "Error while building Signature object",

        RepositoryFileStatusError         => "Error while getting file status",

        GitConfigFetchError               => "Error fetching git config",
        GitConfigEditorFetchError         => "Error fetching 'editor' from git config",
        EditorError                       => "Error while calling editor"
    );
);

impl GitHookError {

    pub fn inside_of<T>(self, h: HEK) -> HookResult<T> {
        Err(HE::new(h, Some(Box::new(self))))
    }

}

impl From<GitHookError> for HE {

    fn from(he: GitHookError) -> HE {
        HE::new(HEK::HookExecutionError, Some(Box::new(he)))
    }

}

impl From<Git2Error> for GitHookError {

    fn from(ge: Git2Error) -> GitHookError {
        GitHookError::new(GitHookErrorKind::RepositoryBackendError, Some(Box::new(ge)))
    }

}

pub trait MapIntoHookError<T> {
    fn map_into_hook_error(self) -> Result<T, HE>;
}

impl<T> MapIntoHookError<T> for Result<T, GitHookError> {

    fn map_into_hook_error(self) -> Result<T, HE> {
        self.map_err(|e| HE::new(HEK::HookExecutionError, Some(Box::new(e))))
    }

}

pub use self::error::GitHookError;
pub use self::error::GitHookErrorKind;
pub use self::error::MapErrInto;

<commit_msg>Add error kind for wrong branch checked out<commit_after>use git2::Error as Git2Error;

use libimagstore::hook::error::HookError as HE;
use libimagstore::hook::error::HookErrorKind as HEK;
use libimagstore::hook::result::HookResult;

generate_error_module!(
    generate_error_types!(GitHookError, GitHookErrorKind,
        ConfigError => "Configuration Error",
        NoConfigError => "No Configuration",
        ConfigTypeError => "Configuration value type wrong",

        RepositoryError                   => "Error while interacting with git repository",
        RepositoryInitError               => "Error while loading the git repository",
        RepositoryBackendError            => "Error in the git library",
        RepositoryBranchError             => "Error while interacting with git branch(es)",
        RepositoryBranchNameFetchingError => "Error while fetching branch name",
        RepositoryWrongBranchError        => "Error because repository is on wrong branch",
        RepositoryIndexFetchingError      => "Error while fetching Repository Index",
        RepositoryIndexWritingError       => "Error while writing Repository Index",
        RepositoryPathAddingError         => "Error while adding Path to Index",
        RepositoryCommittingError         => "Error while committing",
        RepositoryParentFetchingError     => "Error while fetching parent of commit",

        HeadFetchError                    => "Error while getting HEAD",
        NotOnBranch                       => "No Branch is checked out",
        MkRepo                            => "Repository creation error",
        MkSignature                       => "Error while building Signature object",

        RepositoryFileStatusError         => "Error while getting file status",

        GitConfigFetchError               => "Error fetching git config",
        GitConfigEditorFetchError         => "Error fetching 'editor' from git config",
        EditorError                       => "Error while calling editor"
    );
);

impl GitHookError {

    pub fn inside_of<T>(self, h: HEK) -> HookResult<T> {
        Err(HE::new(h, Some(Box::new(self))))
    }

}

impl From<GitHookError> for HE {

    fn from(he: GitHookError) -> HE {
        HE::new(HEK::HookExecutionError, Some(Box::new(he)))
    }

}

impl From<Git2Error> for GitHookError {

    fn from(ge: Git2Error) -> GitHookError {
        GitHookError::new(GitHookErrorKind::RepositoryBackendError, Some(Box::new(ge)))
    }

}

pub trait MapIntoHookError<T> {
    fn map_into_hook_error(self) -> Result<T, HE>;
}

impl<T> MapIntoHookError<T> for Result<T, GitHookError> {

    fn map_into_hook_error(self) -> Result<T, HE> {
        self.map_err(|e| HE::new(HEK::HookExecutionError, Some(Box::new(e))))
    }

}

pub use self::error::GitHookError;
pub use self::error::GitHookErrorKind;
pub use self::error::MapErrInto;

<|endoftext|>


<commit_before><commit_msg>Use closure to limit scope of borrowed ref<commit_after><|endoftext|>


<commit_before><commit_msg>Move offset line.<commit_after><|endoftext|>


<commit_before><commit_msg>fix(scanner): tokenize strings<commit_after><|endoftext|>


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


<commit_before><commit_msg>auto merge of #10772 : alexcrichton/rust/issue-3053, r=alexcrichton<commit_after>// exec-env:RUST_POISON_ON_FREE=1

// Test that we root `x` even though it is found in immutable memory,
// because it is moved.

#[feature(managed_boxes)];

fn free<T>(x: @T) {}

struct Foo {
    f: @Bar
}

struct Bar {
    g: int
}

fn lend(x: @Foo) -> int {
    let y = &x.f.g;
    free(x); // specifically here, if x is not rooted, it will be freed
    *y
}

pub fn main() {
    assert_eq!(lend(@Foo {f: @Bar {g: 22}}), 22);
}
<|endoftext|>


<commit_before><commit_msg>fun with string slices<commit_after><|endoftext|>


<commit_before>use arch::context::Context;
use arch::memory;

use collections::string::ToString;

use common::event::MouseEvent;
use common::time::{self, Duration};

use core::{cmp, mem, ptr, slice};

use graphics::display::VBEMODEINFO;

use super::{Packet, Pipe, Setup};
use super::desc::*;

pub trait Hci {
    fn msg(&mut self, address: u8, endpoint: u8, pipe: Pipe, msgs: &[Packet]) -> usize;

    fn descriptor(&mut self,
                         address: u8,
                         descriptor_type: u8,
                         descriptor_index: u8,
                         descriptor_ptr: usize,
                         descriptor_len: usize) {
        self.msg(address, 0, Pipe::Control, &[
            Packet::Setup(&Setup::get_descriptor(descriptor_type, descriptor_index, 0, descriptor_len as u16)),
            Packet::In(&mut unsafe { slice::from_raw_parts_mut(descriptor_ptr as *mut u8, descriptor_len as usize) }),
            Packet::Out(&[])
        ]);
    }

    unsafe fn device(&mut self, address: u8) where Self: Sized + 'static {
        self.msg(0, 0, Pipe::Control, &[
            Packet::Setup(&Setup::set_address(address)),
            Packet::In(&mut [])
        ]);

        let mut desc_dev = box DeviceDescriptor::default();
        self.descriptor(address,
                        DESC_DEV,
                        0,
                        (&mut *desc_dev as *mut DeviceDescriptor) as usize,
                        mem::size_of_val(&*desc_dev));
        debugln!("{:#?}", *desc_dev);

        if desc_dev.manufacturer_string > 0 {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.manufacturer_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Manufacturer: {}", desc_str.str());
        }

        if desc_dev.product_string > 0 {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.product_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Product: {}", desc_str.str());
        }

        if desc_dev.serial_string > 0 {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.serial_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Serial: {}", desc_str.str());
        }

        for configuration in 0..(*desc_dev).configurations {
            let desc_cfg_len = 1023;
            let desc_cfg_buf = memory::alloc(desc_cfg_len) as *mut u8;
            for i in 0..desc_cfg_len as isize {
                ptr::write(desc_cfg_buf.offset(i), 0);
            }
            self.descriptor(address,
                            DESC_CFG,
                            configuration,
                            desc_cfg_buf as usize,
                            desc_cfg_len);

            let desc_cfg = ptr::read(desc_cfg_buf as *const ConfigDescriptor);
            debugln!("{:#?}", desc_cfg);

            if desc_cfg.string > 0 {
                let mut desc_str = box StringDescriptor::default();
                self.descriptor(address,
                                DESC_STR,
                                desc_cfg.string,
                                (&mut *desc_str as *mut StringDescriptor) as usize,
                                mem::size_of_val(&*desc_str));
                debugln!("Configuration: {}", desc_str.str());
            }

            let mut hid = false;

            let mut i = desc_cfg.length as isize;
            while i < desc_cfg.total_length as isize {
                let length = ptr::read(desc_cfg_buf.offset(i));
                let descriptor_type = ptr::read(desc_cfg_buf.offset(i + 1));
                match descriptor_type {
                    DESC_INT => {
                        let desc_int = ptr::read(desc_cfg_buf.offset(i) as *const InterfaceDescriptor);
                        debugln!("{:#?}", desc_int);

                        if desc_int.string > 0 {
                            let mut desc_str = box StringDescriptor::default();
                            self.descriptor(address,
                                            DESC_STR,
                                            desc_int.string,
                                            (&mut *desc_str as *mut StringDescriptor) as usize,
                                            mem::size_of_val(&*desc_str));
                            debugln!("Interface: {}", desc_str.str());
                        }
                    }
                    DESC_END => {
                        let desc_end = ptr::read(desc_cfg_buf.offset(i) as *const EndpointDescriptor);
                        debugln!("{:#?}", desc_end);

                        let endpoint = desc_end.address & 0xF;
                        let in_len = desc_end.max_packet_size as usize;

                        if hid {
                            let this = self as *mut Hci;
                            Context::spawn("kuhci_hid".to_string(), box move || {
                                debugln!("Starting HID driver");

                                let in_ptr = memory::alloc(in_len) as *mut u8;

                                loop {
                                    for i in 0..in_len as isize {
                                        ptr::write(in_ptr.offset(i), 0);
                                    }

                                    if (*this).msg(address, endpoint, Pipe::Isochronous, &[
                                        Packet::In(&mut slice::from_raw_parts_mut(in_ptr, in_len))
                                    ]) > 0 {
                                        let buttons = ptr::read(in_ptr.offset(0) as *const u8) as usize;
                                        let x = ptr::read(in_ptr.offset(1) as *const u16) as usize;
                                        let y = ptr::read(in_ptr.offset(3) as *const u16) as usize;

                                        let mode_info = &*VBEMODEINFO;
                                        let mouse_x = (x * mode_info.xresolution as usize) / 32768;
                                        let mouse_y = (y * mode_info.yresolution as usize) / 32768;

                                        let mouse_event = MouseEvent {
                                            x: cmp::max(0, cmp::min(mode_info.xresolution as i32 - 1, mouse_x as i32)),
                                            y: cmp::max(0, cmp::min(mode_info.yresolution as i32 - 1, mouse_y as i32)),
                                            left_button: buttons & 1 == 1,
                                            middle_button: buttons & 4 == 4,
                                            right_button: buttons & 2 == 2,
                                        };
                                        ::env().events.lock().push_back(mouse_event.to_event());
                                    }

                                    Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep();
                                }
                            });
                        }
                    }
                    DESC_HID => {
                        let desc_hid = &*(desc_cfg_buf.offset(i) as *const HIDDescriptor);
                        debugln!("{:#?}", desc_hid);
                        hid = true;
                    }
                    _ => {
                        debugln!("Unknown Descriptor Length {} Type {:X}", length as usize, descriptor_type);
                    }
                }
                i += length as isize;
            }

            memory::unalloc(desc_cfg_buf as usize);
        }
    }
}
<commit_msg>Comment out some USB debugging<commit_after>use arch::context::Context;
use arch::memory;

use collections::string::ToString;

use common::event::MouseEvent;
use common::time::{self, Duration};

use core::{cmp, mem, ptr, slice};

use graphics::display::VBEMODEINFO;

use super::{Packet, Pipe, Setup};
use super::desc::*;

pub trait Hci {
    fn msg(&mut self, address: u8, endpoint: u8, pipe: Pipe, msgs: &[Packet]) -> usize;

    fn descriptor(&mut self,
                         address: u8,
                         descriptor_type: u8,
                         descriptor_index: u8,
                         descriptor_ptr: usize,
                         descriptor_len: usize) {
        self.msg(address, 0, Pipe::Control, &[
            Packet::Setup(&Setup::get_descriptor(descriptor_type, descriptor_index, 0, descriptor_len as u16)),
            Packet::In(&mut unsafe { slice::from_raw_parts_mut(descriptor_ptr as *mut u8, descriptor_len as usize) }),
            Packet::Out(&[])
        ]);
    }

    unsafe fn device(&mut self, address: u8) where Self: Sized + 'static {
        self.msg(0, 0, Pipe::Control, &[
            Packet::Setup(&Setup::set_address(address)),
            Packet::In(&mut [])
        ]);

        let mut desc_dev = box DeviceDescriptor::default();
        self.descriptor(address,
                        DESC_DEV,
                        0,
                        (&mut *desc_dev as *mut DeviceDescriptor) as usize,
                        mem::size_of_val(&*desc_dev));
        //debugln!("{:#?}", *desc_dev);

        if desc_dev.manufacturer_string > 0 {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.manufacturer_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Manufacturer: {}", desc_str.str());
        }

        if desc_dev.product_string > 0 {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.product_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Product: {}", desc_str.str());
        }

        if desc_dev.serial_string > 0 {
            let mut desc_str = box StringDescriptor::default();
            self.descriptor(address,
                            DESC_STR,
                            desc_dev.serial_string,
                            (&mut *desc_str as *mut StringDescriptor) as usize,
                            mem::size_of_val(&*desc_str));
            debugln!("Serial: {}", desc_str.str());
        }

        for configuration in 0..(*desc_dev).configurations {
            let desc_cfg_len = 1023;
            let desc_cfg_buf = memory::alloc(desc_cfg_len) as *mut u8;
            for i in 0..desc_cfg_len as isize {
                ptr::write(desc_cfg_buf.offset(i), 0);
            }
            self.descriptor(address,
                            DESC_CFG,
                            configuration,
                            desc_cfg_buf as usize,
                            desc_cfg_len);

            let desc_cfg = ptr::read(desc_cfg_buf as *const ConfigDescriptor);
            //debugln!("{:#?}", desc_cfg);

            if desc_cfg.string > 0 {
                let mut desc_str = box StringDescriptor::default();
                self.descriptor(address,
                                DESC_STR,
                                desc_cfg.string,
                                (&mut *desc_str as *mut StringDescriptor) as usize,
                                mem::size_of_val(&*desc_str));
                //debugln!("Configuration: {}", desc_str.str());
            }

            let mut hid = false;

            let mut i = desc_cfg.length as isize;
            while i < desc_cfg.total_length as isize {
                let length = ptr::read(desc_cfg_buf.offset(i));
                let descriptor_type = ptr::read(desc_cfg_buf.offset(i + 1));
                match descriptor_type {
                    DESC_INT => {
                        let desc_int = ptr::read(desc_cfg_buf.offset(i) as *const InterfaceDescriptor);
                        //debugln!("{:#?}", desc_int);

                        if desc_int.string > 0 {
                            let mut desc_str = box StringDescriptor::default();
                            self.descriptor(address,
                                            DESC_STR,
                                            desc_int.string,
                                            (&mut *desc_str as *mut StringDescriptor) as usize,
                                            mem::size_of_val(&*desc_str));
                            //debugln!("Interface: {}", desc_str.str());
                        }
                    }
                    DESC_END => {
                        let desc_end = ptr::read(desc_cfg_buf.offset(i) as *const EndpointDescriptor);
                        //debugln!("{:#?}", desc_end);

                        let endpoint = desc_end.address & 0xF;
                        let in_len = desc_end.max_packet_size as usize;

                        if hid {
                            let this = self as *mut Hci;
                            Context::spawn("kuhci_hid".to_string(), box move || {
                                debugln!("Starting HID driver");

                                let in_ptr = memory::alloc(in_len) as *mut u8;

                                loop {
                                    for i in 0..in_len as isize {
                                        ptr::write(in_ptr.offset(i), 0);
                                    }

                                    if (*this).msg(address, endpoint, Pipe::Isochronous, &[
                                        Packet::In(&mut slice::from_raw_parts_mut(in_ptr, in_len))
                                    ]) > 0 {
                                        let buttons = ptr::read(in_ptr.offset(0) as *const u8) as usize;
                                        let x = ptr::read(in_ptr.offset(1) as *const u16) as usize;
                                        let y = ptr::read(in_ptr.offset(3) as *const u16) as usize;

                                        let mode_info = &*VBEMODEINFO;
                                        let mouse_x = (x * mode_info.xresolution as usize) / 32768;
                                        let mouse_y = (y * mode_info.yresolution as usize) / 32768;

                                        let mouse_event = MouseEvent {
                                            x: cmp::max(0, cmp::min(mode_info.xresolution as i32 - 1, mouse_x as i32)),
                                            y: cmp::max(0, cmp::min(mode_info.yresolution as i32 - 1, mouse_y as i32)),
                                            left_button: buttons & 1 == 1,
                                            middle_button: buttons & 4 == 4,
                                            right_button: buttons & 2 == 2,
                                        };
                                        ::env().events.lock().push_back(mouse_event.to_event());
                                    }

                                    Duration::new(0, 10 * time::NANOS_PER_MILLI).sleep();
                                }
                            });
                        }
                    }
                    DESC_HID => {
                        //let desc_hid = &*(desc_cfg_buf.offset(i) as *const HIDDescriptor);
                        //debugln!("{:#?}", desc_hid);
                        hid = true;
                    }
                    _ => {
                        debugln!("Unknown Descriptor Length {} Type {:X}", length as usize, descriptor_type);
                    }
                }
                i += length as isize;
            }

            memory::unalloc(desc_cfg_buf as usize);
        }
    }
}
<|endoftext|>


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

// Test that we evaluate projection predicates to winnow out
// candidates during trait selection and method resolution (#20296).
// If we don't properly winnow out candidates based on the output type
// `Output=[A]`, then the impl marked with `(*)` is seen to conflict
// with all the others.

#![feature(associated_types, default_type_params)]

use std::ops::Deref;

pub trait MyEq<Sized? U=Self> for Sized? {
    fn eq(&self, u: &U) -> bool;
}

impl<A, B> MyEq<[B]> for [A]
    where A : MyEq<B>
{
    fn eq(&self, other: &[B]) -> bool {
        self.len() == other.len() &&
            self.iter().zip(other.iter())
                       .all(|(a, b)| MyEq::eq(a, b))
    }
}

// (*) This impl conflicts with everything unless the `Output=[A]`
// constraint is considered.
impl<'a, A, B, Lhs> MyEq<[B; 0]> for Lhs
    where A: MyEq<B>, Lhs: Deref<Output=[A]>
{
    fn eq(&self, other: &[B; 0]) -> bool {
        MyEq::eq(&**self, other.as_slice())
    }
}

struct DerefWithHelper<H, T> {
    pub helper: H
}

trait Helper<T> {
    fn helper_borrow(&self) -> &T;
}

impl<T> Helper<T> for Option<T> {
    fn helper_borrow(&self) -> &T {
        self.as_ref().unwrap()
    }
}

impl<T, H: Helper<T>> Deref for DerefWithHelper<H, T> {
    type Output = T;

    fn deref(&self) -> &T {
        self.helper.helper_borrow()
    }
}

pub fn check<T: MyEq>(x: T, y: T) -> bool {
    let d: DerefWithHelper<Option<T>, T> = DerefWithHelper { helper: Some(x) };
    d.eq(&y)
}

pub fn main() {
}
<commit_msg>fix rpass test with s/Output/Target/g<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Test that we evaluate projection predicates to winnow out
// candidates during trait selection and method resolution (#20296).
// If we don't properly winnow out candidates based on the output type
// `Target=[A]`, then the impl marked with `(*)` is seen to conflict
// with all the others.

#![feature(associated_types, default_type_params)]

use std::ops::Deref;

pub trait MyEq<Sized? U=Self> for Sized? {
    fn eq(&self, u: &U) -> bool;
}

impl<A, B> MyEq<[B]> for [A]
    where A : MyEq<B>
{
    fn eq(&self, other: &[B]) -> bool {
        self.len() == other.len() &&
            self.iter().zip(other.iter())
                       .all(|(a, b)| MyEq::eq(a, b))
    }
}

// (*) This impl conflicts with everything unless the `Target=[A]`
// constraint is considered.
impl<'a, A, B, Lhs> MyEq<[B; 0]> for Lhs
    where A: MyEq<B>, Lhs: Deref<Target=[A]>
{
    fn eq(&self, other: &[B; 0]) -> bool {
        MyEq::eq(&**self, other.as_slice())
    }
}

struct DerefWithHelper<H, T> {
    pub helper: H
}

trait Helper<T> {
    fn helper_borrow(&self) -> &T;
}

impl<T> Helper<T> for Option<T> {
    fn helper_borrow(&self) -> &T {
        self.as_ref().unwrap()
    }
}

impl<T, H: Helper<T>> Deref for DerefWithHelper<H, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.helper.helper_borrow()
    }
}

pub fn check<T: MyEq>(x: T, y: T) -> bool {
    let d: DerefWithHelper<Option<T>, T> = DerefWithHelper { helper: Some(x) };
    d.eq(&y)
}

pub fn main() {
}
<|endoftext|>


<commit_before><commit_msg>debuginfo: Added test case for local variables declared with destructuring.<commit_after>// Copyright 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.

// xfail-test

// GDB doesn't know about UTF-32 character encoding and will print a rust char as only its numerical
// value.

// compile-flags:-Z extra-debug-info
// debugger:break zzz
// debugger:run
// debugger:finish

// debugger:print a
// check:$1 = 9898

// debugger:print b
// check:$2 = false

fn main() {
    let (a, b) : (int, bool) = (9898, false);

    zzz();
}

fn zzz() {()}<|endoftext|>


<commit_before><commit_msg>Test for (previously uncaught) infinite loop identified by matthewjasper.<commit_after>// Copyright 2018 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.

// rust-lang/rust#45696: This test checks the compiler won't infinite
// loop when you declare a variable of type `struct A(Box<A>, ...);`
// (which is impossible to construct but *is* possible to declare; see
// also issues #4287, #44933, and #52852).
//
// We will explicitly test AST-borrowck, NLL, and migration modes;
// thus we will also skip the automated compare-mode=nll.

// revisions: ast nll migrate
// ignore-compare-mode-nll

#![cfg_attr(nll, feature(nll))]
//[migrate]compile-flags: -Z borrowck=migrate -Z two-phase-borrows

// run-pass

// This test has structs and functions that are by definiton unusable
// all over the place, so just go ahead and allow dead_code
#![allow(dead_code)]

// direct regular recursion with indirect ownership via box
struct C { field: Box<C> }

// direct non-regular recursion with indirect ownership via box
struct D { field: Box<(D, D)> }

// indirect regular recursion with indirect ownership via box.
struct E { field: F }
struct F { field: Box<E> }

// indirect non-regular recursion with indirect ownership via box.
struct G { field: (F, F) }
struct H { field: Box<E> }

// These enums are cases that are not currently hit by the
// `visit_terminator_drop` recursion down a type's structural
// definition.
//
// But it seems prudent to include them in this test as variants on
// the above, in that they are similarly non-constructable data types
// with destructors that would diverge.
enum I { One(Box<I>) }
enum J { One(Box<J>), Two(Box<J>) }

fn impossible_to_call_c(_c: C) { }
fn impossible_to_call_d(_d: D) { }
fn impossible_to_call_e(_e: E) { }
fn impossible_to_call_f(_f: F) { }
fn impossible_to_call_g(_g: G) { }
fn impossible_to_call_h(_h: H) { }
fn impossible_to_call_i(_i: I) { }
fn impossible_to_call_j(_j: J) { }

fn main() {

}
<|endoftext|>


<commit_before><commit_msg>add codegen test<commit_after>// Copyright 2017 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.

// compile-flags: -O
#![crate_type="lib"]
#![feature(maybe_uninit)]

use std::mem::MaybeUninit;

// Boxing a `MaybeUninit` value should not copy junk from the stack
#[no_mangle]
pub fn box_uninitialized() -> Box<MaybeUninit<usize>> {
    // CHECK-LABEL: @box_uninitialized
    // CHECK-NOT: store
    Box::new(MaybeUninit::uninitialized())
}
<|endoftext|>


<commit_before><commit_msg>linux: add missing copyright to linux.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Keep track of files modified by the sync<commit_after><|endoftext|>


<commit_before><commit_msg>Unstable crate test is used...<commit_after>extern crate test;

extern crate cards;
extern crate pokereval;

use test::Bencher;
use cards::deck::{Deck};
use pokereval::{original}; // two evaluation methods
//perfect

#[bench]
fn bench_original_evaluation(b: &mut Bencher) {
    let mut deck = Deck::new();

    b.iter(|| {
    // try on 10 hands
        for _ in 0..10 {
            let c1 = deck.draw();
            let c2 = deck.draw();
            let c3 = deck.draw();
            let c4 = deck.draw();
            let c5 = deck.draw();

            let _rank_original = original::eval_5cards([&c1, &c2, &c3, &c4, &c5]);
       }
       deck.reset();
    });
}
<|endoftext|>


<commit_before><commit_msg>better error messages<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed password<commit_after><|endoftext|>


<commit_before><commit_msg>In the middle of something<commit_after><|endoftext|>


<commit_before><commit_msg>	modified:   src/main.rs<commit_after><|endoftext|>