<commit_before><commit_msg>Add test to check library traits have #[must_use] attribute<commit_after>#![deny(unused_must_use)]
#![feature(futures_api, pin, arbitrary_self_types)]

use std::iter::Iterator;
use std::future::Future;

use std::task::{Poll, LocalWaker};
use std::pin::Pin;
use std::unimplemented;

struct MyFuture;

impl Future for MyFuture {
   type Output = u32;

   fn poll(self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<u32> {
      Poll::Pending
   }
}

fn iterator() -> impl Iterator {
   std::iter::empty::<u32>()
}

fn future() -> impl Future {
   MyFuture
}

fn square_fn_once() -> impl FnOnce(u32) -> u32 {
   |x| x * x
}

fn square_fn_mut() -> impl FnMut(u32) -> u32 {
   |x| x * x
}

fn square_fn() -> impl Fn(u32) -> u32 {
   |x| x * x
}

fn main() {
   iterator(); //~ ERROR unused implementer of `std::iter::Iterator` that must be used
   future(); //~ ERROR unused implementer of `std::future::Future` that must be used
   square_fn_once(); //~ ERROR unused implementer of `std::ops::FnOnce` that must be used
   square_fn_mut(); //~ ERROR unused implementer of `std::ops::FnMut` that must be used
   square_fn(); //~ ERROR unused implementer of `std::ops::Fn` that must be used
}<|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.

use target::Target;

pub fn target() -> Target {
    let mut base = super::android_base::opts();
    base.features = "+v7".to_string();

    Target {
        llvm_target: "arm-linux-androideabi".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
        arch: "arm".to_string(),
        target_os: "android".to_string(),
        target_env: "gnu".to_string(),
        target_vendor: "unknown".to_string(),
        options: base,
    }
}
<commit_msg>Auto merge of #33115 - mbrubeck:vfp3-d16, r=nrc<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.

use target::Target;

pub fn target() -> Target {
    let mut base = super::android_base::opts();
    base.features = "+v7,+vfp3,+d16".to_string();

    Target {
        llvm_target: "arm-linux-androideabi".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        data_layout: "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64".to_string(),
        arch: "arm".to_string(),
        target_os: "android".to_string(),
        target_env: "gnu".to_string(),
        target_vendor: "unknown".to_string(),
        options: base,
    }
}
<|endoftext|>


<commit_before><commit_msg>Add indexing for vars<commit_after><|endoftext|>


<commit_before><commit_msg>Fix #108 - ioctl bindings for ppc64BE<commit_after>/* automatically generated by rust-bindgen */

pub type __u32 = ::std::os::raw::c_uint;
pub const _HIDIOCGRDESCSIZE: __u32 = 1074022401;
pub const _HIDIOCGRDESC: __u32 = 1342457858;
<|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.

//! A simple test for testing many permutations of allowedness of
//! impl Trait
#![feature(conservative_impl_trait, universal_impl_trait, dyn_trait)]
use std::fmt::Debug;

// Allowed
fn in_parameters(_: impl Debug) { panic!() }

// Allowed
fn in_return() -> impl Debug { panic!() }

// Allowed
fn in_adt_in_parameters(_: Vec<impl Debug>) { panic!() }

// Allowed
fn in_adt_in_return() -> Vec<impl Debug> { panic!() }

// Disallowed
fn in_fn_parameter_in_parameters(_: fn(impl Debug)) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_fn_return_in_parameters(_: fn() -> impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_fn_parameter_in_return() -> fn(impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_fn_return_in_return() -> fn() -> impl Debug { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_dyn_Fn_parameter_in_parameters(_: &dyn Fn(impl Debug)) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_dyn_Fn_return_in_parameters(_: &dyn Fn() -> impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
// FIXME -- no error currently

// Disallowed
fn in_dyn_Fn_parameter_in_return() -> &'static dyn Fn(impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_dyn_Fn_return_in_return() -> &'static dyn Fn() -> impl Debug { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
// FIXME -- no error currently

// Disallowed
fn in_impl_Fn_parameter_in_parameters(_: &impl Fn(impl Debug)) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_impl_Fn_return_in_parameters(_: &impl Fn() -> impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
// FIXME -- no error currently

// Disallowed
fn in_impl_Fn_parameter_in_return() -> &'static impl Fn(impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_impl_Fn_return_in_return() -> &'static impl Fn() -> impl Debug { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
// FIXME -- no error currently

// Allowed
fn in_impl_Trait_in_parameters(_: impl Iterator<Item = impl Iterator>) { panic!() }

// Allowed
fn in_impl_Trait_in_return() -> impl IntoIterator<Item = impl IntoIterator> {
    vec![vec![0; 10], vec![12; 7], vec![8; 3]]
}

// Disallowed
struct InBraceStructField { x: impl Debug }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
struct InAdtInBraceStructField { x: Vec<impl Debug> }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
struct InTupleStructField(impl Debug);
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
enum InEnum {
    InBraceVariant { x: impl Debug },
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
    InTupleVariant(impl Debug),
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Allowed
trait InTraitDefnParameters {
    fn in_parameters(_: impl Debug);
}

// Disallowed
trait InTraitDefnReturn {
    fn in_return() -> impl Debug;
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Allowed and disallowed in trait impls
trait DummyTrait {
    type Out;
    fn in_trait_impl_parameter(impl Debug);
    fn in_trait_impl_return() -> Self::Out;
}
impl DummyTrait for () {
    type Out = impl Debug;
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

    fn in_trait_impl_parameter(_: impl Debug) { }
    // Allowed

    fn in_trait_impl_return() -> impl Debug { () }
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Allowed
struct DummyType;
impl DummyType {
    fn in_inherent_impl_parameters(_: impl Debug) { }
    fn in_inherent_impl_return() -> impl Debug { () }
}

// Disallowed
extern "C" {
    fn in_foreign_parameters(_: impl Debug);
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

    fn in_foreign_return() -> impl Debug;
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Allowed
extern "C" fn in_extern_fn_parameters(_: impl Debug) {
}

// Allowed
extern "C" fn in_extern_fn_return() -> impl Debug {
    22
}

type InTypeAlias<R> = impl Debug;
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

type InReturnInTypeAlias<R> = fn() -> impl Debug;
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed in impl headers
impl PartialEq<impl Debug> for () {
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Disallowed in impl headers
impl PartialEq<()> for impl Debug {
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Disallowed in inherent impls
impl impl Debug {
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Disallowed in inherent impls
struct InInherentImplAdt<T> { t: T }
impl InInherentImplAdt<impl Debug> {
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Disallowed in where clauses
fn in_fn_where_clause()
    where impl Debug: Debug
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

// Disallowed in where clauses
fn in_adt_in_fn_where_clause()
    where Vec<impl Debug>: Debug
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

// Disallowed
fn in_trait_parameter_in_fn_where_clause<T>()
    where T: PartialEq<impl Debug>
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

// Disallowed
fn in_Fn_parameter_in_fn_where_clause<T>()
    where T: Fn(impl Debug)
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

// Disallowed
fn in_Fn_return_in_fn_where_clause<T>()
    where T: Fn() -> impl Debug
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

fn main() {
    let _in_local_variable: impl Fn() = || {};
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
    let _in_return_in_local_variable = || -> impl Fn() { || {} };
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

<commit_msg>Add cases to where-allowed.rs<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.

//! A simple test for testing many permutations of allowedness of
//! impl Trait
#![feature(conservative_impl_trait, universal_impl_trait, dyn_trait)]
use std::fmt::Debug;

// Allowed
fn in_parameters(_: impl Debug) { panic!() }

// Allowed
fn in_return() -> impl Debug { panic!() }

// Allowed
fn in_adt_in_parameters(_: Vec<impl Debug>) { panic!() }

// Allowed
fn in_adt_in_return() -> Vec<impl Debug> { panic!() }

// Disallowed
fn in_fn_parameter_in_parameters(_: fn(impl Debug)) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_fn_return_in_parameters(_: fn() -> impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_fn_parameter_in_return() -> fn(impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_fn_return_in_return() -> fn() -> impl Debug { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_dyn_Fn_parameter_in_parameters(_: &dyn Fn(impl Debug)) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_dyn_Fn_return_in_parameters(_: &dyn Fn() -> impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_dyn_Fn_parameter_in_return() -> &'static dyn Fn(impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_dyn_Fn_return_in_return() -> &'static dyn Fn() -> impl Debug { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_impl_Fn_parameter_in_parameters(_: &impl Fn(impl Debug)) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_impl_Fn_return_in_parameters(_: &impl Fn() -> impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_impl_Fn_parameter_in_return() -> &'static impl Fn(impl Debug) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_impl_Fn_return_in_return() -> &'static impl Fn() -> impl Debug { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_Fn_parameter_in_generics<F: Fn(impl Debug)> (_: F) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
fn in_Fn_return_in_generics<F: Fn() -> impl Debug> (_: F) { panic!() }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Allowed
fn in_impl_Trait_in_parameters(_: impl Iterator<Item = impl Iterator>) { panic!() }

// Allowed
fn in_impl_Trait_in_return() -> impl IntoIterator<Item = impl IntoIterator> {
    vec![vec![0; 10], vec![12; 7], vec![8; 3]]
}

// Disallowed
struct InBraceStructField { x: impl Debug }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
struct InAdtInBraceStructField { x: Vec<impl Debug> }
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
struct InTupleStructField(impl Debug);
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed
enum InEnum {
    InBraceVariant { x: impl Debug },
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
    InTupleVariant(impl Debug),
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Allowed
trait InTraitDefnParameters {
    fn in_parameters(_: impl Debug);
}

// Disallowed
trait InTraitDefnReturn {
    fn in_return() -> impl Debug;
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Allowed and disallowed in trait impls
trait DummyTrait {
    type Out;
    fn in_trait_impl_parameter(impl Debug);
    fn in_trait_impl_return() -> Self::Out;
}
impl DummyTrait for () {
    type Out = impl Debug;
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

    fn in_trait_impl_parameter(_: impl Debug) { }
    // Allowed

    fn in_trait_impl_return() -> impl Debug { () }
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Allowed
struct DummyType;
impl DummyType {
    fn in_inherent_impl_parameters(_: impl Debug) { }
    fn in_inherent_impl_return() -> impl Debug { () }
}

// Disallowed
extern "C" {
    fn in_foreign_parameters(_: impl Debug);
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

    fn in_foreign_return() -> impl Debug;
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Allowed
extern "C" fn in_extern_fn_parameters(_: impl Debug) {
}

// Allowed
extern "C" fn in_extern_fn_return() -> impl Debug {
    22
}

type InTypeAlias<R> = impl Debug;
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

type InReturnInTypeAlias<R> = fn() -> impl Debug;
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types

// Disallowed in impl headers
impl PartialEq<impl Debug> for () {
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Disallowed in impl headers
impl PartialEq<()> for impl Debug {
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Disallowed in inherent impls
impl impl Debug {
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Disallowed in inherent impls
struct InInherentImplAdt<T> { t: T }
impl InInherentImplAdt<impl Debug> {
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

// Disallowed in where clauses
fn in_fn_where_clause()
    where impl Debug: Debug
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

// Disallowed in where clauses
fn in_adt_in_fn_where_clause()
    where Vec<impl Debug>: Debug
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

// Disallowed
fn in_trait_parameter_in_fn_where_clause<T>()
    where T: PartialEq<impl Debug>
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

// Disallowed
fn in_Fn_parameter_in_fn_where_clause<T>()
    where T: Fn(impl Debug)
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

// Disallowed
fn in_Fn_return_in_fn_where_clause<T>()
    where T: Fn() -> impl Debug
//~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
{
}

fn main() {
    let _in_local_variable: impl Fn() = || {};
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
    let _in_return_in_local_variable = || -> impl Fn() { || {} };
    //~^ ERROR `impl Trait` not allowed outside of function and inherent method return types
}

<|endoftext|>


<commit_before><commit_msg>Test StorageDead statements explicitly<commit_after>// ignore-wasm32-bare compiled with panic=abort by default

// Test that we generate StorageDead on unwind paths for generators.
//
// Basic block and local names can safely change, but the StorageDead statements
// should not go away.

#![feature(generators, generator_trait)]

struct Foo(i32);

impl Drop for Foo {
    fn drop(&mut self) {}
}

struct Bar(i32);

fn take<T>(_x: T) {}

fn main() {
    let _gen = || {
        let a = Foo(5);
        let b = Bar(6);
        yield;
        take(a);
        take(b);
    };
}

// END RUST SOURCE

// START rustc.main-{{closure}}.StateTransform.before.mir
// ...
// let _2: Foo;
// ...
// let mut _7: Foo;
// ...
// let mut _9: Bar;
// scope 1 {
//     let _3: Bar;
//     scope 2 {
//     }
// }
// bb0: {
//     StorageLive(_2);
//     _2 = Foo(const 5i32,);
//     StorageLive(_3);
//     _3 = Bar(const 6i32,);
//     ...
//     _1 = suspend(move _5) -> [resume: bb2, drop: bb4];
// }
// bb1 (cleanup): {
//     resume;
// }
// bb2: {
//     ...
//     StorageLive(_7);
//     _7 = move _2;
//     _6 = const take::<Foo>(move _7) -> [return: bb9, unwind: bb8];
// }
// bb3 (cleanup): {
//     StorageDead(_2);
//     drop(_1) -> bb1;
// }
// bb4: {
//     ...
//     StorageDead(_3);
//     drop(_2) -> [return: bb5, unwind: bb3];
// }
// bb5: {
//     StorageDead(_2);
//     drop(_1) -> [return: bb6, unwind: bb1];
// }
// bb6: {
//     generator_drop;
// }
// bb7 (cleanup): {
//     StorageDead(_3);
//     StorageDead(_2);
//     drop(_1) -> bb1;
// }
// bb8 (cleanup): {
//     StorageDead(_7);
//     goto -> bb7;
// }
// bb9: {
//     StorageDead(_7);
//     StorageLive(_9);
//     _9 = move _3;
//     _8 = const take::<Bar>(move _9) -> [return: bb10, unwind: bb11];
// }
// bb10: {
//     StorageDead(_9);
//     ...
//     StorageDead(_3);
//     StorageDead(_2);
//     drop(_1) -> [return: bb12, unwind: bb1];
// }
// bb11 (cleanup): {
//     StorageDead(_9);
//     goto -> bb7;
// }
// bb12: {
//     return;
// }
// END rustc.main-{{closure}}.StateTransform.before.mir
<|endoftext|>


<commit_before><commit_msg>Add subscription config type.<commit_after><|endoftext|>


<commit_before><commit_msg>Added N queens problem<commit_after>static side: i8 = 8;
static queens: i8 = 8;

fn place(mut board: [i8,..side*side], ix:i8) -> Option<[i8,..side*side]> {
    if board[ix] == 0 {
        return None
    };
    board[ix] = -1;
    let i1 = ix/side;
    let j1 = ix % side;
    for k in range(1,side) {
        let mut loc :i8 = i1 * side + k;
        board[loc] = 0;
        loc = k * side + j1;
        board[loc] = 0;
        loc = (i1-k) * side + (j1-k);
        if loc / side == i1 -k && loc % side == j1 - k && loc != ix && loc >= 0 { board[loc] = 0 };
        loc = loc + 2 * k;
        if loc / side == i1 - k && loc % side == j1 + k && loc != ix && loc >= 0 { board[loc] = 0};
        loc = loc + 2 * side * k;
        if loc / side == i1 + k && loc % side == j1 + k && loc != ix && loc < side*side { board[loc] = 0};
        loc = loc - 2 * k;
        if loc / side == i1 + k && loc % side == j1 - k && loc != ix && loc < side*side { board[loc] = 0};
    }
    Some(board)
}

fn tryplace(b : [i8,..side*side],ix:i8, nq: i8, mut score: u32) -> u32 {
    if nq == queens { return score + 1 }
    for ind in range(ix, side*side) {
        score = match place(b, ind) {
            Some(b2) => tryplace(b2, ind+1, nq+1, score),
            None() => score
        };
    }
    return score
}

fn main() {
    let b : [i8, ..side*side] = [1,..side*side];
    let score = tryplace(b, 0, 0, 0);
    println!("{}", score)
}
<|endoftext|>


<commit_before><commit_msg>Test alloca with #[repr(align(x))] on enum<commit_after>// compile-flags: -C no-prepopulate-passes
// ignore-tidy-linelength
// min-llvm-version 7.0

#![crate_type = "lib"]
#![feature(repr_align_enum)]

#[repr(align(64))]
pub enum Align64 {
    A(u32),
    B(u32),
}
// CHECK: %Align64 = type { [0 x i32], i32, [15 x i32] }

pub struct Nested64 {
    a: u8,
    b: Align64,
    c: u16,
}

// CHECK-LABEL: @align64
#[no_mangle]
pub fn align64(a: u32) -> Align64 {
// CHECK: %a64 = alloca %Align64, align 64
// CHECK: call void @llvm.memcpy.{{.*}}(i8* align 64 %{{.*}}, i8* align 64 %{{.*}}, i{{[0-9]+}} 64, i1 false)
    let a64 = Align64::A(a);
    a64
}

// CHECK-LABEL: @nested64
#[no_mangle]
pub fn nested64(a: u8, b: u32, c: u16) -> Nested64 {
// CHECK: %n64 = alloca %Nested64, align 64
    let n64 = Nested64 { a, b: Align64::B(b), c };
    n64
}
<|endoftext|>


<commit_before><commit_msg>Fix negation error<commit_after><|endoftext|>


<commit_before>extern crate sonos_discovery;

use sonos_discovery::Discover;

fn main() {
    let discovery = Discover::new().unwrap();
    let devices = discovery.start(None, None);
    for device in devices {
        println!("{}", device)
    }
}
<commit_msg>Unwrap devices<commit_after>extern crate sonos_discovery;

use sonos_discovery::Discover;

fn main() {
    let discovery = Discover::new().unwrap();
    let devices = discovery.start(None, None).unwrap();
    for device in devices {
        println!("{:?}", device)
    }
}
<|endoftext|>


<commit_before><commit_msg>attempt to implement lychrel detection, currently overflows<commit_after><|endoftext|>


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


<commit_before><commit_msg>Make next_input_id an InputId<commit_after><|endoftext|>


<commit_before><commit_msg>docs: updates examples for 2x release<commit_after><|endoftext|>


<commit_before><commit_msg>result<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #77663 - HeroicKatora:regression-tests-27675-object-safe, r=Aaron1011<commit_after>/// The compiler previously did not properly check the bound of `From` when it was used from type
/// of the dyn trait object (use in `copy_any` below). Since the associated type is under user
/// control in this usage, the compiler could be tricked to believe any type implemented any trait.
/// This would ICE, except for pure marker traits like `Copy`. It did not require providing an
/// instance of the dyn trait type, only name said type.
trait Setup {
    type From: Copy;
}

fn copy<U: Setup + ?Sized>(from: &U::From) -> U::From {
    *from
}

pub fn copy_any<T>(t: &T) -> T {
    copy::<dyn Setup<From=T>>(t)
    //~^ ERROR the trait bound `T: Copy` is not satisfied
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Invalid source code formating Fixed<commit_after><|endoftext|>


<commit_before><commit_msg>Somehow I never actually added the roundtrip estimator to vc.<commit_after>use super::*;
use super::super::async;
use std::time;
use std::collections;
use std::cmp;
use std::net;
use std::ops;
use uuid;
use super::super::packets::{Packet};

#[derive(Debug)]pub struct RoundtripEstimator {
    expected_echoes: collections::HashMap<uuid::Uuid, time::Instant>,
    estimation: Vec<u32>,
    required_echoes: usize,
    last_estimate: Option<u32>,
}

impl RoundtripEstimator {

    pub fn new(required_echoes: usize)->RoundtripEstimator {
        RoundtripEstimator {
            expected_echoes: collections::HashMap::default(),
            estimation: Vec::default(),
            required_echoes: required_echoes,
            last_estimate: None,
        }
    }

    pub fn get_last_estimate(&self)->Option<u32> {
        self.last_estimate
    }

    //Called once a second by established connections.
    pub fn tick<H: async::Handler>(&mut self, address: net::SocketAddr, endpoint_id: uuid::Uuid, service: &mut MioServiceProvider<H>) {
        let now = time::Instant::now();
        //Kill all echoes older than 5 seconds.
        let mut removing = Vec::with_capacity(self.expected_echoes.len());
        for i in self.expected_echoes.iter() {
            let dur = now.duration_since(*i.1);
            if dur.as_secs() >= 5 {
                removing.push(*i.0);
            }
        }
        for i in removing.iter() {
            self.expected_echoes.remove(i);
        }
        //Replace any if needed.
        if self.expected_echoes.len() < self.required_echoes {
            let needed_echoes = cmp::min(5, self.required_echoes-self.expected_echoes.len());
            for i in 0..needed_echoes {
                let uuid = uuid::Uuid::new_v4();
                self.expected_echoes.insert(uuid, now);
                service.send(Packet::Echo{endpoint: endpoint_id, uuid: uuid}, address);
            }
        }
    }

    pub fn handle_echo<H: async::Handler>(&mut self, connection_id: u64, echo_id: uuid::Uuid, service: &mut MioServiceProvider<H>) {
        if let Some(&instant) = self.expected_echoes.get(&echo_id) {
            let dur = time::Instant::now().duration_since(instant);
            let dur_ms: u64 = dur.as_secs()*1000+dur.subsec_nanos() as u64/1000000u64;
            self.estimation.push(dur_ms as u32);
            self.expected_echoes.remove(&echo_id);
        }
        if self.estimation.len() >= self.required_echoes {
            let average: u32 = self.estimation.iter().fold(0, ops::Add::add)/self.estimation.len() as u32;
            self.estimation.clear();
            service.handler.roundtrip_estimate(connection_id, average);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>test file I had lying around and had forgotten to commit<commit_after>
// check that we do not report a type like this as uninstantiable,
// even though it would be if the nxt field had type @foo:
enum foo = {x: uint, nxt: *foo};

fn main() {
    let x = foo({x: 0u, nxt: ptr::null()});
}

<|endoftext|>


<commit_before><commit_msg>Synchronize with free.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Fix order of evaluation<commit_after><|endoftext|>


<commit_before><commit_msg>Fix broken pipe panics<commit_after><|endoftext|>


<commit_before>use std::{cmp, fmt, ptr};
use std::cell::RefCell;
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;

use libc::{self, time_t};

use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;

/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associated with
/// a `Selector` attempts to register itself with a different `Selector`, the
/// operation will return with an error. This matches windows behavior.
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;

pub struct Selector {
    id: usize,
    kq: RawFd,
    changes: RefCell<KeventList>,
}

impl Selector {
    pub fn new() -> io::Result<Selector> {
        // offset by 1 to avoid choosing 0 as the id of a selector
        let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1;
        let kq = unsafe { try!(cvt(libc::kqueue())) };
        drop(set_cloexec(kq));

        Ok(Selector {
            id: id,
            kq: kq,
            changes: RefCell::new(KeventList(Vec::new())),
        })
    }

    pub fn id(&self) -> usize {
        self.id
    }

    pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> {
        let timeout = timeout.map(|to| {
            libc::timespec {
                tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t,
                tv_nsec: to.subsec_nanos() as libc::c_long,
            }
        });
        let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(0 as *const _);

        unsafe {
            let cnt = try!(cvt(libc::kevent(self.kq,
                                            0 as *const _,
                                            0,
                                            evts.sys_events.0.as_mut_ptr(),
                                            evts.sys_events.0.capacity() as i32,
                                            timeout)));

            self.changes.borrow_mut().0.clear();
            evts.sys_events.0.set_len(cnt as usize);

            Ok(evts.coalesce(awakener))
        }
    }

    pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
        trace!("registering; token={:?}; interests={:?}", token, interests);

        if interests.contains(Ready::readable()) {
            self.ev_register(fd,
                             token.into(),
                             libc::EVFILT_READ,
                             opts);
        }
        if interests.contains(Ready::writable()) {
            self.ev_register(fd,
                             token.into(),
                             libc::EVFILT_WRITE,
                             opts);
        }

        self.flush_changes()
    }

    pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
        // Just need to call register here since EV_ADD is a mod if already
        // registered
        self.register(fd, token, interests, opts)
    }

    pub fn deregister(&self, fd: RawFd) -> io::Result<()> {
        self.ev_push(fd, 0, libc::EVFILT_READ, libc::EV_DELETE);
        self.ev_push(fd, 0, libc::EVFILT_WRITE, libc::EV_DELETE);

        self.flush_changes()
    }

    fn ev_register(&self,
                   fd: RawFd,
                   token: usize,
                   filter: i16,
                   opts: PollOpt) {
        let mut flags = libc::EV_ADD;

        if opts.contains(PollOpt::edge()) {
            flags = flags | libc::EV_CLEAR;
        }

        if opts.contains(PollOpt::oneshot()) {
            flags = flags | libc::EV_ONESHOT;
        }

        self.ev_push(fd, token, filter, flags);
    }

    fn ev_push(&self,
               fd: RawFd,
               token: usize,
               filter: i16,
               flags: u16) {
        self.changes.borrow_mut().0.push(libc::kevent {
            ident: fd as ::libc::uintptr_t,
            filter: filter,
            flags: flags,
            fflags: 0,
            data: 0,
            udata: token as *mut _,
        });
    }

    fn flush_changes(&self) -> io::Result<()> {
        unsafe {
            let mut changes = self.changes.borrow_mut();
            try!(cvt(libc::kevent(self.kq,
                                  changes.0.as_mut_ptr() as *const _,
                                  changes.0.len() as i32,
                                  0 as *mut _,
                                  0,
                                  0 as *const _)));
            changes.0.clear();
            Ok(())
        }
    }
}

impl fmt::Debug for Selector {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Selector")
            .field("id", &self.id)
            .field("kq", &self.kq)
            .field("changes", &self.changes.borrow().0.len())
            .finish()
    }
}

impl Drop for Selector {
    fn drop(&mut self) {
        unsafe {
            let _ = libc::close(self.kq);
        }
    }
}

pub struct Events {
    sys_events: KeventList,
    events: Vec<Event>,
    event_map: HashMap<Token, usize>,
}

struct KeventList(Vec<libc::kevent>);

unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}

impl Events {
    pub fn with_capacity(cap: usize) -> Events {
        Events {
            sys_events: KeventList(Vec::with_capacity(cap)),
            events: Vec::with_capacity(cap),
            event_map: HashMap::with_capacity(cap)
        }
    }

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

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

    pub fn get(&self, idx: usize) -> Option<Event> {
        self.events.get(idx).map(|e| *e)
    }

    fn coalesce(&mut self, awakener: Token) -> bool {
        let mut ret = false;
        self.events.clear();
        self.event_map.clear();

        for e in self.sys_events.0.iter() {
            let token = Token(e.udata as usize);
            let len = self.events.len();

            if token == awakener {
                // TODO: Should this return an error if event is an error. It
                // is not critical as spurious wakeups are permitted.
                ret = true;
                continue;
            }

            let idx = *self.event_map.entry(token)
                .or_insert(len);

            if idx == len {
                // New entry, insert the default
                self.events.push(Event::new(Ready::none(), token));

            }

            if e.flags & libc::EV_ERROR != 0 {
                event::kind_mut(&mut self.events[idx]).insert(Ready::error());
            }

            if e.filter == libc::EVFILT_READ {
                event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
            } else if e.filter == libc::EVFILT_WRITE {
                event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
            }

            if e.flags & libc::EV_EOF != 0 {
                event::kind_mut(&mut self.events[idx]).insert(Ready::hup());

                // When the read end of the socket is closed, EV_EOF is set on
                // flags, and fflags contains the error if there is one.
                if e.fflags != 0 {
                    event::kind_mut(&mut self.events[idx]).insert(Ready::error());
                }
            }
        }

        ret
    }

    pub fn push_event(&mut self, event: Event) {
        self.events.push(event);
    }
}

impl fmt::Debug for Events {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Events {{ len: {} }}", self.sys_events.0.len())
    }
}
<commit_msg>Do not allocate for kevents + precise errors<commit_after>use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;

use libc::{self, time_t};

use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;

/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associated with
/// a `Selector` attempts to register itself with a different `Selector`, the
/// operation will return with an error. This matches windows behavior.
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;

macro_rules! kevent {
    ($id: expr, $filter: expr, $flags: expr, $data: expr) => {
        libc::kevent {
            ident: $id as ::libc::uintptr_t,
            filter: $filter,
            flags: $flags,
            fflags: 0,
            data: 0,
            udata: $data as *mut _,
        }
    }
}

pub struct Selector {
    id: usize,
    kq: RawFd,
}

impl Selector {
    pub fn new() -> io::Result<Selector> {
        // offset by 1 to avoid choosing 0 as the id of a selector
        let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1;
        let kq = unsafe { try!(cvt(libc::kqueue())) };
        drop(set_cloexec(kq));

        Ok(Selector {
            id: id,
            kq: kq,
        })
    }

    pub fn id(&self) -> usize {
        self.id
    }

    pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> {
        let timeout = timeout.map(|to| {
            libc::timespec {
                tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t,
                tv_nsec: to.subsec_nanos() as libc::c_long,
            }
        });
        let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut());

        unsafe {
            let cnt = try!(cvt(libc::kevent(self.kq,
                                            ptr::null(),
                                            0,
                                            evts.sys_events.0.as_mut_ptr(),
            // FIXME: needs a saturating cast here.
                                            evts.sys_events.0.capacity() as c_int,
                                            timeout)));
            evts.sys_events.0.set_len(cnt as usize);
            Ok(evts.coalesce(awakener))
        }
    }

    pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
        trace!("registering; token={:?}; interests={:?}", token, interests);

        let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } |
                    if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } |
                    libc::EV_RECEIPT;

        unsafe {
            let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE };
            let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE };
            let mut changes = [
                kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)),
                kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)),
            ];
            try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
                                           changes.as_mut_ptr(), changes.len() as c_int,
                                           ::std::ptr::null())));
            for change in changes.iter() {
                debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
                if change.data != 0 {
                    // there’s some error, but we want to ignore ENOENT error for EV_DELETE
                    let orig_flags = if change.filter == libc::EVFILT_READ { r } else { w };
                    if !(change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE != 0) {
                        return Err(::std::io::Error::from_raw_os_error(change.data as i32));
                    }
                }
            }
            Ok(())
        }
    }

    pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
        // Just need to call register here since EV_ADD is a mod if already
        // registered
        self.register(fd, token, interests, opts)
    }

    pub fn deregister(&self, fd: RawFd) -> io::Result<()> {
        unsafe {
            // EV_RECEIPT is a nice way to apply changes and get back per-event results while not
            // draining the actual changes.
            let filter = libc::EV_DELETE | libc::EV_RECEIPT;
            let mut changes = [
                kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
                kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
            ];
            try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
                                           changes.as_mut_ptr(), changes.len() as c_int,
                                           ::std::ptr::null())).map(|_| ()));
            if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT {
                return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
            }
            for change in changes.iter() {
                debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR);
                if change.data != 0 && change.data as i32 != libc::ENOENT {
                    return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
                }
            }
            Ok(())
        }
    }
}

impl fmt::Debug for Selector {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Selector")
            .field("id", &self.id)
            .field("kq", &self.kq)
            .finish()
    }
}

impl Drop for Selector {
    fn drop(&mut self) {
        unsafe {
            let _ = libc::close(self.kq);
        }
    }
}

pub struct Events {
    sys_events: KeventList,
    events: Vec<Event>,
    event_map: HashMap<Token, usize>,
}

struct KeventList(Vec<libc::kevent>);

unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}

impl Events {
    pub fn with_capacity(cap: usize) -> Events {
        Events {
            sys_events: KeventList(Vec::with_capacity(cap)),
            events: Vec::with_capacity(cap),
            event_map: HashMap::with_capacity(cap)
        }
    }

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

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

    pub fn get(&self, idx: usize) -> Option<Event> {
        self.events.get(idx).map(|e| *e)
    }

    fn coalesce(&mut self, awakener: Token) -> bool {
        let mut ret = false;
        self.events.clear();
        self.event_map.clear();

        for e in self.sys_events.0.iter() {
            let token = Token(e.udata as usize);
            let len = self.events.len();

            if token == awakener {
                // TODO: Should this return an error if event is an error. It
                // is not critical as spurious wakeups are permitted.
                ret = true;
                continue;
            }

            let idx = *self.event_map.entry(token)
                .or_insert(len);

            if idx == len {
                // New entry, insert the default
                self.events.push(Event::new(Ready::none(), token));

            }

            if e.flags & libc::EV_ERROR != 0 {
                event::kind_mut(&mut self.events[idx]).insert(Ready::error());
            }

            if e.filter == libc::EVFILT_READ {
                event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
            } else if e.filter == libc::EVFILT_WRITE {
                event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
            }

            if e.flags & libc::EV_EOF != 0 {
                event::kind_mut(&mut self.events[idx]).insert(Ready::hup());

                // When the read end of the socket is closed, EV_EOF is set on
                // flags, and fflags contains the error if there is one.
                if e.fflags != 0 {
                    event::kind_mut(&mut self.events[idx]).insert(Ready::error());
                }
            }
        }

        ret
    }

    pub fn push_event(&mut self, event: Event) {
        self.events.push(event);
    }
}

impl fmt::Debug for Events {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "Events {{ len: {} }}", self.sys_events.0.len())
    }
}

#[test]
fn does_not_register_rw() {
    use ::deprecated::{EventLoopBuilder, Handler};
    use ::unix::EventedFd;
    struct Nop;
    impl Handler for Nop {
        type Timeout = ();
        type Message = ();
    }

    // registering kqueue fd will fail if write is requested
    let kq = unsafe { libc::kqueue() };
    let kqf = EventedFd(&kq);
    let mut evtloop = EventLoopBuilder::new().build::<Nop>().expect("evt loop builds");
    evtloop.register(&kqf, Token(1234), Ready::readable() | Ready::writable(),
                     PollOpt::edge() | PollOpt::oneshot()).unwrap_err();
    evtloop.deregister(&kqf).unwrap();
    evtloop.register(&kqf, Token(1234), Ready::readable(),
                     PollOpt::edge() | PollOpt::oneshot()).unwrap();
}
<|endoftext|>


<commit_before><commit_msg>unit tests<commit_after>extern crate bloom;

#[cfg(test)]
mod tests {
    use super::bloom::BloomFilter;

    #[test]
    fn test_insert_and_exists() {
        let mut bf = BloomFilter::new(1000, 0.01);
        bf.insert(&"hello");
        assert!(bf.has(&"hello"));
    }

    #[test]
    fn test_insert_and_not_exists() {
        let mut bf = BloomFilter::new(1000, 0.001);
        bf.insert(&"hello");
        bf.insert(&"abcd");
        assert!(!bf.has(&"what"));
    }
}
<|endoftext|>


<commit_before><commit_msg>Simplify implementation of ContactStore::all_contacts()<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: Remove call to deprecated function<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unnecessary pub qualifier in forms example.<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing file<commit_after>use nom::types::CompleteByteSlice;
use std::fmt;

use column::Column;
use common::{column_identifier_no_alias, literal, opt_multispace, Literal};
use condition::{condition_expr, ConditionExpression};

#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub enum ColumnOrLiteral {
    Column(Column),
    Literal(Literal),
}

impl fmt::Display for ColumnOrLiteral {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ColumnOrLiteral::Column(ref c) => write!(f, "{}", c)?,
            ColumnOrLiteral::Literal(ref l) => write!(f, "{}", l.to_string())?,
        }
        Ok(())
    }
}

#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct CaseWhenExpression {
    pub condition: ConditionExpression,
    pub then_expr: ColumnOrLiteral,
    pub else_expr: Option<ColumnOrLiteral>,
}

impl fmt::Display for CaseWhenExpression {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "CASE WHEN {} THEN {}", self.condition, self.then_expr)?;
        if let Some(ref expr) = self.else_expr {
            write!(f, " ELSE {}", expr)?;
        }
        Ok(())
    }
}

named!(pub case_when_column<CompleteByteSlice, CaseWhenExpression>,
       do_parse!(
           tag_no_case!("case when") >>
           opt_multispace >>
           cond: condition_expr >>
           opt_multispace >>
           tag_no_case!("then") >>
           opt_multispace >>
           column: column_identifier_no_alias >>
           opt_multispace >>
           else_value: opt!(do_parse!(
               tag_no_case!("else") >>
               opt_multispace >>
               else_val: literal >>
               opt_multispace >>
               (else_val)
           )) >>
           tag_no_case!("end") >>
           (CaseWhenExpression {
               condition: cond,
               then_expr: ColumnOrLiteral::Column(column),
               else_expr: else_value.map(|v| ColumnOrLiteral::Literal(v)),
           })
       )
);
<|endoftext|>


<commit_before><commit_msg>Fix(sync): remove syncfiles for any ignored native files<commit_after><|endoftext|>


<commit_before><commit_msg>Added newline to page contents<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #128<commit_after>#[crate_id = "prob0128"];
#[crate_type = "rlib"];

//! # 定義
//!
//! 最内のリングを 0 周目のリングとする。
//! `r` 周目のリングの要素数を `a(r)` 、
//! `r` 週目のリングの、真北から数えて `m` 番目のセルの数値を `b(r, m)` とそれぞれおくと、
//!
//! ```math
//! a(0) = 1
//! a(r) = 6r if r > 0
//!
//! b(0, 0) = 1
//! b(r, m) = \sum_{k=0}^{r-1} a(k) + 1 + m
//!         = 1 + 6 + 12 + ... + 6(r-1) + 1 + m
//!         = 2 + 3r(r-1) + m
//! ```
//!
//! となる。利便性のため、任意の `m` について、`b(r, m)` は以下を満たすとする。
//!
//! ```math
//! b(r, m) = b(r, m + a(r)) if m < 0 or m >= 6r
//! ```
//!
//! また、上記式より以下を得る。
//!
//! ```
//! b(r+1, m_a) - b(r, m_b) = 6r + m_a - m_b
//! b(r, m_a) - b(r, m_b)   = m_a - m_b
//! b(r, m_a) - b(r-1, m_b) = 6(r-1) + m_a - m_b
//! ```
//!
//! _r_ 周目のリング中のセルは、リングのどの部分に属しているかで以下のように分類する。
//!
//! * 角 - `m = rk` を満たすセル。 `r+1` 周目のセル3つと、`r-1` 周目のセル 1 つと隣接する。
//!        `r > 0` の周に存在。
//! * 辺 - 角ではないセル。`r+1` 周目のセルと、 `r-1` 周目のセルそれぞれに 2 つに隣接する。
//!        `r > 1` の周に存在。
//!
//! # 解析
//!
//! ## `r=0` の場合
//!
//! 周囲のセルの数値との差は `1`. `2`, `3`, `4`, `5`, `6` であり、
//! `2`, `3`, `5` が素数なので、 `PD(1) = 3` となる。
//!
//! ## 辺の場合
//!
//! `r` 周目の辺に属するセルの場合、`r+1` 周目の連続したセル2つおよび
//! `r-1` 週目の連続したセル2つと隣接する。
//!
//! ### `m \neq 6r-1` の場合
//
//! `m \neq 6r-1` の場合、連続した 2 つセルとの差 2 つは、いずれかは必ず偶数となる。
//! よって、これら 4 つのセルの数値との差のうち素数となるのは最大 2 つである。
//! すなわち、辺のセルについては `PD(n)` が 3 となることはない。
//!
//! ### `m = 6r-1` の場合
//!
//! `m = 6r-1` の場合、隣接するセルの数値との差は以下である。
//!
//! * `b(r+1, 6r+4) - b(r, 6r-1)   = 6r+5`
//! * `b(r+1, 6r+5) - b(r, 6r-1)   = 6(r+1)`
//! * `b(r, 6r-1)   - b(r, 6r-2)   = 1`
//! * `b(r, 6r-1)   - b(r, 0)      = 6r-1`
//! * `b(r, 6r-1)   - b(r-1, 0)    = 12r-7`
//! * `b(r, 6r-1)   - b(r-1, 6r-7) = 6r`
//!
//! `6(r+1)`, `1`, `6r` は素数ではないため、`PD(n) = 3` となるセルは、
//! `6r+5`, `6r-1`, `12r-7` が素数でなければならない。
//!
//! なお、 `b(r, 6r-1) = 3r^2 + 3r + 1` である。
//!
//! ## 角の場合
//!
//! 角のセルに隣接するセルの数値は、以下の6種類である。ここで、 `k = m/r` である。
//!
//! * `b(r+1, rk-1+k)`
//! * `b(r+1, rk+k)`
//! * `b(r+1, rk+1+k)`
//! * `b(r, rk-1)`
//! * `b(r, rk+1)`
//! * `b(r-1, rk-k)`
//!
//! ### `k > 0` の場合
//!
//! `k > 0` の場合、セルと隣接するセルの数値との差は以下である。
//!
//! * `b(r+1, rk-1+k) - b(r, rk)     = 6r + k - 1`
//! * `b(r+1, rk+k)   - b(r, rk)     = 6r + k`
//! * `b(r+1, rk+1+k) - b(r, rk)     = 6r + k + 1`
//! * `b(r, rk)       - b(r, rk-1)   = 1`
//! * `b(r, rk+1)     - b(r, rk)     = 1`
//! * `b(r, rk)       - b(r-1, rk-k) = 6(r-1) + k`
//!
//! `k` が偶数の場合、`6r+k`, `6(r-1)+k` は偶数となる。
//! `k` が奇数の場合、`6r+k-1`, `6r+k+1` は偶数となる。
//! よって、`k > 1` の場合、`PD(3)` となることはない。
//!
//! ### `k = 0` の場合
//!
//! `k = 0` の場合、セルと隣接するセルの数値との差は以下である。
//!
//! * `b(r+1, -1) - b(r, 0)   = b(r+1, 6r+5) - b(r, 0) = 12r + 5`
//! * `b(r+1, 0)  - b(r, 0)   = 6r`
//! * `b(r+1, 1)  - b(r, 0)   = 6r + 1`
//! * `b(r, -1)   - b(r, 0)   = b(r, 6r-1) - b(r, 0) = 6r - 1`
//! * `b(r, 1)    - b(r, 0)   = 1`
//! * `b(r, 0)    - b(r-1, 0) = 6r(r-1)`
//!
//! `6r`, `6r(r-1)`, `1` は素数ではないため、`PD(n) = 3` となるためには、
//! `12r+5`, `6r+1`, `6r-1` が素数でなければならない。
//!
//! なお、 `b(r, 0) = 3r^2 - 3r + 2` である。
//!
//! # 解法
//!
//! `r > 0` について、以下すべてが素数の場合、 `PD(n) = 3` となる。
//!
//! ```math
//! 12r+5, 6r+1, 6r-1
//! ```
//!
//! `r > 1` について、以下すべてが素数の場合、 `PD(n) = 3` となる。
//!
//! ```math
//! 6r-1, 6r-5, 12r-7
//! ```
//!
//! `r=0` から順番にこれらを満たす数をカウントする。

extern mod math;

use std::util;
use math::prime::Prime;

pub static EXPECTED_ANSWER: &'static str = "14516824220";

#[deriving(Eq)]
struct PdTriple {
    n: uint,
    r: uint,
    triple: (uint, uint, uint)
}

struct PdTriples {
    r: uint,
    next: Option<PdTriple>
}

impl PdTriples {
    #[inline]
    fn new() -> PdTriples { PdTriples { r: 0, next: None } }
}

impl Iterator<PdTriple> for PdTriples {
    #[inline]
    fn next(&mut self) -> Option<PdTriple> {
        if self.next.is_some() {
            return util::replace(&mut self.next, None)
        }

        let r = self.r;
        self.r += 1;

        if r == 0 { return Some(PdTriple { n: 1, r: 0, triple: (2, 3, 5) }) }
        if r > 1 {
            let n = 3*r*r + 3*r + 1;
            self.next = Some(PdTriple { n: n, r: r, triple: (6*r-1, 6*r+5, 12*r-7) });
        }
        let n = 3*r*r - 3*r + 2;
        Some(PdTriple { n: n, r: r, triple: (12*r+5, 6*r+1, 6*r-1) })
    }
}

struct Pd3Nums {
    iter: PdTriples,
    ps: Prime
}

impl Pd3Nums {
    #[inline]
    fn new() -> Pd3Nums { Pd3Nums { iter: PdTriples::new(), ps: Prime::new() } }
}

impl Iterator<uint> for Pd3Nums {
    #[inline]
    fn next(&mut self) -> Option<uint> {
        loop {
            let PdTriple { n, triple: (a, b, c), ..} = self.iter.next().unwrap();
            if self.ps.contains(a) && self.ps.contains(b) && self.ps.contains(c) {
                return Some(n)
            }
        }
    }
}

pub fn solve() -> ~str {
    Pd3Nums::new().nth(2000 - 1).unwrap().to_str()
}

#[cfg(test)]
mod test {
    use super::{PdTriple, PdTriples, Pd3Nums};
    use std::iter::AdditiveIterator;

    fn a(r: uint) -> uint { if r == 0 { 1 } else { 6 * r } }
    fn b(r: uint, m: uint) -> uint {
        if r == 0 {
            assert_eq!(0, m);
            return 1
        }
        assert!(m < 6 * r);
        range(0, r).map(a).sum() + 1 + m
    }

    #[test]
    fn test_a() {
        assert_eq!(1, a(0));
        assert_eq!(6, a(1));
        assert_eq!(12, a(2));
    }

    #[test]
    fn test_b() {
        assert_eq!(1, b(0, 0));
        let mut n = 2;
        for r in range(1u, 10) {
            for m in range(0u, a(r)) {
                assert_eq!(n, b(r, m));
                n += 1;
            }
        }
    }

    #[test]
    fn pd_triples() {
        let mut it = PdTriples::new();
        assert_eq!(Some(PdTriple { n: b(0, 0), r: 0, triple: (2u, 3u, 5u)}), it.next());
        let n = b(1, 0);
        assert_eq!(Some(PdTriple { n: n, r: 1, triple: (b(2, 11) - n,
                                                        b(2, 1)  - n,
                                                        b(1, 5)  - n)}),
                   it.next());

        for r in range(2u, 100) {
            let n = b(r, 0);
            assert_eq!(Some(PdTriple { n: n, r: r, triple: (b(r+1, 6*r+5) - n,
                                                            b(r+1, 1)     - n,
                                                            b(r,   6*r-1) - n) }),
                       it.next());

            let n = b(r, 6*r-1);
            assert_eq!(Some(PdTriple { n: n, r: r, triple: (n - b(r,0),
                                                            b(r+1, 6*r+4) - n,
                                                            n - b(r-1, 0))}),
                       it.next());
        }
    }

    #[test]
    fn pd3_nums() {
        let mut it = Pd3Nums::new();
        assert_eq!(Some(1), it.next());

        let mut it = Pd3Nums::new();
        assert_eq!(Some(271), it.nth(9));
    }
}
<|endoftext|>


<commit_before><commit_msg>Add missing profiler.rs<commit_after>use fine_grained::Stopwatch;
use std::collections::HashMap;

use errors::*;

/// A profiler that gathers average run times code sections.
pub struct Profiler {
    main_watch: Stopwatch,
    watches: HashMap<&'static str, Stopwatch>,
    current_section: Option<&'static str>,
}

/// Profiling data collected by the `Profiler`.
pub struct ProfilingData {
    average_total_time: f64,
    average_section_times: HashMap<&'static str, f64>,
}

impl Profiler {
    /// Returns a new profiler.
    pub fn new() -> Self {
        Self {
            main_watch: Stopwatch::new(),
            watches: HashMap::with_capacity(10),
            current_section: None,
        }
    }

    /// Starts the timer corresponding to the given section.
    ///
    /// The currently running timer, if any, is stopped.
    pub fn start_section(&mut self, name: &'static str) {
        if self.current_section.is_some() {
            self.stop_current_section().unwrap();
        } else {
            self.main_watch.start();
        }

        self.watches
            .entry(name)
            .or_insert_with(Stopwatch::new)
            .start();

        self.current_section = Some(name);
    }

    /// Stops the currently running timer.
    fn stop_current_section(&mut self) -> Result<()> {
        ensure!(self.current_section.is_some(),
                "no stopwatches are currently running");

        let mut stopwatch =
            self.watches
                .get_mut(self.current_section.unwrap())
                .expect("current_section was set to an invalid value");
        stopwatch.lap();
        stopwatch.stop();

        Ok(())
    }

    /// Checks if lap counters for all watches match.
    fn check_lap_counters(&self) -> bool {
        let lap_count = self.main_watch.number_of_laps();

        for watch in self.watches.values() {
            if watch.number_of_laps() != lap_count {
                return false;
            }
        }

        true
    }

    /// Stops timing the current run and increases the lap counter.
    pub fn stop(&mut self) -> Result<()> {
        self.stop_current_section()?;

        self.main_watch.lap();
        self.main_watch.stop();

        Ok(())
    }

    /// Returns the collected data.
    ///
    /// The collected data includes the total average time, as well as average times for
    /// individual sections.
    pub fn get_data(&self) -> Result<ProfilingData> {
        debug_assert!(self.check_lap_counters(), "lap counters do not match");

        let lap_count = self.main_watch.number_of_laps() as f64;
        ensure!(lap_count > 0f64, "no data has been collected");

        Ok(ProfilingData {
               average_total_time: self.main_watch.total_time() as f64 / lap_count,
               average_section_times: self.watches
                                          .iter()
                                          .map(|(&section, watch)| {
                                                   (section, watch.total_time() as f64 / lap_count)
                                               })
                                          .collect(),
           })
    }
}
<|endoftext|>


<commit_before><commit_msg>Add an alias for 'me' command<commit_after><|endoftext|>


<commit_before><commit_msg>Update main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Disassemble movhi instruction<commit_after><|endoftext|>


<commit_before><commit_msg>Unwrapping result<commit_after><|endoftext|>


<commit_before><commit_msg>Subexpression test, small fixes<commit_after><|endoftext|>


<commit_before><commit_msg>Use AVLNode instead of full path<commit_after><|endoftext|>


<commit_before><commit_msg>Factor out getting an existing user in user subcommand.<commit_after><|endoftext|>


<commit_before><commit_msg>Adding xmpp (jabber) support? Either way we can use the process outlined for XMPP<commit_after>
use std::net::SocketAddr;
use std::io::{Write, Read};
use std::str::{from_utf8};

use futures::Future;
use futures::stream::Stream;

use tokio_core::io::{copy, Io};
use tokio_core::net::{TcpListener, TcpStream};
use tokio_core::reactor::Core;

struct XmlStream {
    stream: TcpStream,
    id: str,
    host: str,
}

<|endoftext|>


<commit_before><commit_msg>Add trace!() call to show config when runtime initializes<commit_after><|endoftext|>


<commit_before><commit_msg>make text box gui longer and round<commit_after><|endoftext|>


<commit_before><commit_msg>UTF-8 parsing functions return results now.<commit_after><|endoftext|>


<commit_before><commit_msg>initialize remote to atari state<commit_after><|endoftext|>


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


<commit_before><commit_msg>Upgraded to latest piston-event<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Touch up style and add some comments"<commit_after><|endoftext|>


<commit_before><commit_msg>Move directive code to its own function<commit_after><|endoftext|>


<commit_before><commit_msg>Tweaks<commit_after><|endoftext|>


<commit_before><commit_msg>#1 Added 8_expressions.rs<commit_after>// blocks are expressions
fn main() {
    let pi = std::f64::consts::PI;
    let r = 5.3;
    let area = {
        pi * r * r
    };

    println!("area: {:?}", area);
}<|endoftext|>


<commit_before><commit_msg>Add index find method benchmark<commit_after>#![feature(test)]

extern crate test;
extern crate bloodhound;

use test::Bencher;
use std::path::PathBuf;
use bloodhound::Index;

#[bench]
fn bench_find(b: &mut Bencher) {
    let mut index = Index::new(PathBuf::from("."));
    index.populate(None);
    b.iter(|| index.find("match", 5, true));
}
<|endoftext|>


<commit_before><commit_msg>Add problem #25<commit_after>extern mod euler;

use euler::calc::{ each_fib };
use euler::biguint::{ BigUint, from_str_radix };

fn main() {
    let mut i = 0;
    let limit = from_str_radix::<BigUint>(str::from_bytes(vec::from_elem(999, '9' as u8)), 10).get();
    for each_fib |f: &BigUint| {
        i += 1;
        if *f > limit { break; }
    }

    io::println(fmt!("%d", i));
}<|endoftext|>


<commit_before><commit_msg>Add example to load and print bundle<commit_after>use kbdgen::{Load, ProjectBundle};
use snafu::ErrorCompat;

fn main() {
    let path = std::env::args()
        .nth(1)
        .expect("Pass path to `.kbdgen` bundle as argument");

    match ProjectBundle::load(&path) {
        Ok(bundle) => eprintln!("{:#?}", bundle),
        Err(e) => {
            eprintln!("An error occurred: {}", e);
            if let Some(backtrace) = ErrorCompat::backtrace(&e) {
                println!("{}", backtrace);
            }
        }
    }
}
<|endoftext|>


<commit_before>//! soundstream.rs
//!
//! A real-time soundstream demo that smoothly copies input
//! from a microphone straight to the output. If <Space> is
//! pressed, the SoundStream thread will begin to calculate
//! and print the samplerate to demonstrate the inter-task
//! event handling.
//!
//! Note: Beware of feedback!

#![feature(globs)]

extern crate piston;

use piston::{
    keyboard,
    AssetStore,
    Game,
    GameEvent,
    GameWindow,
    GameWindowSDL2,
    GameWindowSettings,
    KeyPress,
    KeyPressArgs,
    SoundStream,
    SoundStreamSettings
};

// Structs
//------------------------------

/// Main application struct.
pub struct App {
    /// Channel for sending information to the audio stream.
    stream_chan: Option<Sender<GameEvent<'static>>> // Channel for sending Events.
}

/// The audio is non-blocking and needs it's own struct.
pub struct AppSoundStream {
    /// Channel for receiving game events from main game stream.
    chan: Option<Receiver<GameEvent<'static>>>, // Channel for receiving Events.
    is_exit: bool, // Trigger for closing the stream.
    is_print: bool, // Toggle for printing the sample_rate.
    buffer: Vec<f32> // Buffer for passing input to output.
}

// Game Method Implementations
//------------------------------

impl Game for App {

    /// Setup / load the app stuff ready for the main loop.
    /// If using a SoundStream, it must be created within this method.
    fn load(&mut self, asset_store: &mut AssetStore) {

        // Create a channel for communicating events with the soundstream.
        // Note: this channel is used for sending InteractiveEvents, but
        // the same technique could be used here to create custom channels
        // that can safely send any kind of unique data.
        let (send, recv) = channel();
        self.stream_chan = Some(send);

        // Create the soundstream on it's own thread for non-blocking, real-time audio.
        // "soundstreamer" will setup and iterate soundstream using portaudio.
        spawn(proc() {
            let mut soundstream =
                AppSoundStream::new(Some(recv)).run(SoundStreamSettings::cd_quality());
        });

    }

    /// Keypress callback.
    fn key_press(&mut self, args: &KeyPressArgs) {
        println!("Game thread key: {}", args.key);
    }

    /*
    /// Specify the event sending channel. This must be done if we wish
    /// to send interactive events to the SoundStream.
    fn get_event_sender(&self) -> Option<Sender<GameEvent<'static>>> {
        self.stream_chan.clone()
    }
    */
}

impl Drop for App {
    /// Tell the soundstream to exit when App is destroyed.
    fn drop(&mut self) {
        let chan = self.stream_chan.clone();
        match chan {
            Some(sender) => sender.send(KeyPress(KeyPressArgs { key: keyboard::Escape })),
            None => ()
        }
    }
}

impl App {
    /// Creates a new application.
    pub fn new() -> App {
        App {
            stream_chan: None
        }
    }
}

// SoundStream Method Implementations
//------------------------------

impl SoundStream for AppSoundStream {

    /// Load (called prior to main soundstream loop).
    fn load(&mut self) {
        println!("Press <Spacebar> to start/stop printing the real-time sample rate.");
    }

    /// Update (gets called prior to audio_in/audio_out).
    fn update(&mut self, settings: &SoundStreamSettings, dt: u64) {
        if self.is_print {
            let dtsec: f64 = dt as f64 / 1000000000f64;
            println!("Real-time sample rate: {}", (1f64 / dtsec) * settings.frames as f64);
        }
    }

    /// AudioInput
    fn audio_in(&mut self, input: &Vec<f32>, settings: &SoundStreamSettings) {
        self.buffer = input.clone();
    }

    /// AudioOutput
    fn audio_out(&mut self, output: &mut Vec<f32>, settings: &SoundStreamSettings) {
        *output = self.buffer.clone()
    }

    /// KeyPress
    fn key_press(&mut self, args: &KeyPressArgs) {
        println!("Soundstream thread key: {}", args.key);
        if args.key == keyboard::Space {
            let b_print = if self.is_print { false } else { true };
            self.is_print = b_print;
        }
        if args.key == keyboard::Escape {
            self.is_exit = true;
        }
    }

    /*
    /// Retrieve Events for callback (i.e. mouse, keyboard).
    fn check_for_event(&self) -> Option<GameEvent<'static>> {
        match self.chan {
            Some(ref receiver) => match receiver.try_recv() {
                Ok(event) => Some(event),
                Err(_) => None
            },
            None => None
        }
    }
    */

    /// Setup the exit condition (is checked once per buffer).
    fn exit(&self) -> bool { self.is_exit }

}

impl AppSoundStream {
    /// AppSoundStream constructor.
    pub fn new(recv: Option<Receiver<GameEvent<'static>>>) -> AppSoundStream {
        AppSoundStream {
            chan: recv,
            is_exit: false,
            is_print: false,
            buffer: vec![]
        }
    }
}

// Main
//------------------------------

#[start]
fn start(argc: int, argv: **u8) -> int {
    // Run gui on the main thread.
    native::start(argc, argv, main)
}

fn main() {
    let mut window: GameWindowSDL2 = GameWindow::new(
        GameWindowSettings {
            title: "soundstream".to_string(),
            size: [300, 300],
            fullscreen: false,
            exit_on_esc: true,
            background_color: [0.1, 0.1, 0.1, 0.1],
        }
    );

    let mut asset_store = AssetStore::from_folder("assets");
    let mut app = App::new();
    app.run(&mut window, &mut asset_store);
}

//------------------------------
<commit_msg>Closes #357<commit_after>//! soundstream.rs
//!
//! A real-time soundstream demo that smoothly copies input
//! from a microphone straight to the output. If <Space> is
//! pressed, the SoundStream thread will begin to calculate
//! and print the samplerate to demonstrate the inter-task
//! event handling.
//!
//! Note: Beware of feedback!

#![feature(globs)]

extern crate piston;

use piston::{
    keyboard,
    AssetStore,
    Game,
    GameEvent,
    GameWindow,
    GameWindowSDL2,
    GameWindowSettings,
    KeyPress,
    KeyPressArgs,
    SoundStream,
    SoundStreamSettings
};

// Structs
//------------------------------

/// Main application struct.
pub struct App {
    /// Channel for sending information to the audio stream.
    stream_chan: Option<Sender<GameEvent<'static>>> // Channel for sending Events.
}

/// The audio is non-blocking and needs it's own struct.
pub struct AppSoundStream {
    /// Channel for receiving game events from main game stream.
    chan: Option<Receiver<GameEvent<'static>>>, // Channel for receiving Events.
    should_exit: bool, // Trigger for closing the stream.
    should_print: bool, // Toggle for printing the sample_rate.
    buffer: Vec<f32> // Buffer for passing input to output.
}

// Game Method Implementations
//------------------------------

impl Game for App {

    /// Setup / load the app stuff ready for the main loop.
    /// If using a SoundStream, it must be created within this method.
    fn load(&mut self, asset_store: &mut AssetStore) {

        // Create a channel for communicating events with the soundstream.
        // Note: this channel is used for sending InteractiveEvents, but
        // the same technique could be used here to create custom channels
        // that can safely send any kind of unique data.
        let (send, recv) = channel();
        self.stream_chan = Some(send);

        // Create the soundstream on it's own thread for non-blocking, real-time audio.
        // "soundstreamer" will setup and iterate soundstream using portaudio.
        spawn(proc() {
            let mut soundstream =
                AppSoundStream::new(Some(recv)).run(SoundStreamSettings::cd_quality());
        });

    }

    /// Keypress callback.
    fn key_press(&mut self, args: &KeyPressArgs) {
        println!("Game thread key: {}", args.key);
    }

    /*
    /// Specify the event sending channel. This must be done if we wish
    /// to send interactive events to the SoundStream.
    fn get_event_sender(&self) -> Option<Sender<GameEvent<'static>>> {
        self.stream_chan.clone()
    }
    */
}

impl Drop for App {
    /// Tell the soundstream to exit when App is destroyed.
    fn drop(&mut self) {
        let chan = self.stream_chan.clone();
        match chan {
            Some(sender) => sender.send(KeyPress(KeyPressArgs { key: keyboard::Escape })),
            None => ()
        }
    }
}

impl App {
    /// Creates a new application.
    pub fn new() -> App {
        App {
            stream_chan: None
        }
    }
}

// SoundStream Method Implementations
//------------------------------

impl SoundStream for AppSoundStream {

    /// Load (called prior to main soundstream loop).
    fn load(&mut self) {
        println!("Press <Spacebar> to start/stop printing the real-time sample rate.");
    }

    /// Update (gets called prior to audio_in/audio_out).
    fn update(&mut self, settings: &SoundStreamSettings, dt: u64) {
        if self.should_print {
            let dtsec: f64 = dt as f64 / 1000000000f64;
            println!("Real-time sample rate: {}", (1f64 / dtsec) * settings.frames as f64);
        }
    }

    /// AudioInput
    fn audio_in(&mut self, input: &Vec<f32>, settings: &SoundStreamSettings) {
        self.buffer = input.clone();
    }

    /// AudioOutput
    fn audio_out(&mut self, output: &mut Vec<f32>, settings: &SoundStreamSettings) {
        *output = self.buffer.clone()
    }

    /// KeyPress
    fn key_press(&mut self, args: &KeyPressArgs) {
        println!("Soundstream thread key: {}", args.key);
        if args.key == keyboard::Space {
            let print = if self.should_print { false } else { true };
            self.should_print = print;
        }
        if args.key == keyboard::Escape {
            self.should_exit = true;
        }
    }

    /*
    /// Retrieve Events for callback (i.e. mouse, keyboard).
    fn check_for_event(&self) -> Option<GameEvent<'static>> {
        match self.chan {
            Some(ref receiver) => match receiver.try_recv() {
                Ok(event) => Some(event),
                Err(_) => None
            },
            None => None
        }
    }
    */

    /// Setup the exit condition (is checked once per buffer).
    fn exit(&self) -> bool { self.should_exit }

}

impl AppSoundStream {
    /// AppSoundStream constructor.
    pub fn new(recv: Option<Receiver<GameEvent<'static>>>) -> AppSoundStream {
        AppSoundStream {
            chan: recv,
            should_exit: false,
            should_print: false,
            buffer: vec![]
        }
    }
}

// Main
//------------------------------

#[start]
fn start(argc: int, argv: **u8) -> int {
    // Run gui on the main thread.
    native::start(argc, argv, main)
}

fn main() {
    let mut window: GameWindowSDL2 = GameWindow::new(
        GameWindowSettings {
            title: "soundstream".to_string(),
            size: [300, 300],
            fullscreen: false,
            exit_on_esc: true,
            background_color: [0.1, 0.1, 0.1, 0.1],
        }
    );

    let mut asset_store = AssetStore::from_folder("assets");
    let mut app = App::new();
    app.run(&mut window, &mut asset_store);
}

//------------------------------
<|endoftext|>


<commit_before><commit_msg>added todotxt.rs<commit_after>

struct Todo {
        id: int,
        todo: str,
        priority: int,
        raw_todo: str
}
<|endoftext|>


<commit_before><commit_msg>`UTC` was renamed in new `chrono` version (v0.4.0)<commit_after><|endoftext|>


<commit_before><commit_msg>Add functions to get by id and remove with FileLockEntry<commit_after><|endoftext|>


<commit_before><commit_msg>Change the struct of `parse::ast::Path`.<commit_after><|endoftext|>


<commit_before>use gl;
use version::Version;
use version::Api;

use CapabilitiesSource;
use backend::Facade;
use context::Context;
use ContextExt;

use std::{ffi, mem, ptr};
use std::rc::Rc;

use GlObject;
use Handle;

use program::ProgramCreationError;

/// A single, compiled but unlinked, shader.
pub struct Shader {
    context: Rc<Context>,
    id: Handle,
}

impl GlObject for Shader {
    type Id = Handle;

    #[inline]
    fn get_id(&self) -> Handle {
        self.id
    }
}

impl Drop for Shader {
    fn drop(&mut self) {
        let ctxt = self.context.make_current();

        unsafe {
            match self.id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.DeleteShader(id);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.DeleteObjectARB(id);
                }
            }
        }
    }
}

/// Builds an individual shader.
pub fn build_shader<F>(facade: &F, shader_type: gl::types::GLenum, source_code: &str)
                       -> Result<Shader, ProgramCreationError> where F: Facade
{
    unsafe {
        let mut ctxt = facade.get_context().make_current();

        if ctxt.capabilities.supported_glsl_versions.is_empty() {
            return Err(ProgramCreationError::CompilationNotSupported);
        }

        if !check_shader_type_compatibility(&mut ctxt, shader_type) {
            return Err(ProgramCreationError::ShaderTypeNotSupported);
        }

        let source_code = ffi::CString::new(source_code.as_bytes()).unwrap();

        let id = if ctxt.version >= &Version(Api::Gl, 2, 0) ||
                    ctxt.version >= &Version(Api::GlEs, 2, 0)
        {
            Handle::Id(ctxt.gl.CreateShader(shader_type))
        } else if ctxt.extensions.gl_arb_shader_objects {
            Handle::Handle(ctxt.gl.CreateShaderObjectARB(shader_type))
        } else {
            unreachable!()
        };

        if id == Handle::Id(0) || id == Handle::Handle(0 as gl::types::GLhandleARB) {
            return Err(ProgramCreationError::ShaderTypeNotSupported);
        }

        match id {
            Handle::Id(id) => {
                assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                        ctxt.version >= &Version(Api::GlEs, 2, 0));
                ctxt.gl.ShaderSource(id, 1, [ source_code.as_ptr() ].as_ptr(), ptr::null());
            },
            Handle::Handle(id) => {
                assert!(ctxt.extensions.gl_arb_shader_objects);
                ctxt.gl.ShaderSourceARB(id, 1, [ source_code.as_ptr() ].as_ptr(), ptr::null());
            }
        }

        // compiling
        {
            ctxt.report_debug_output_errors.set(false);

            match id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0)||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.CompileShader(id);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.CompileShaderARB(id);
                }
            }

            ctxt.report_debug_output_errors.set(true);
        }

        // checking compilation success by reading a flag on the shader
        let compilation_success = {
            let mut compilation_success: gl::types::GLint = mem::uninitialized();
            match id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.GetShaderiv(id, gl::COMPILE_STATUS, &mut compilation_success);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.GetObjectParameterivARB(id, gl::OBJECT_COMPILE_STATUS_ARB,
                                                    &mut compilation_success);
                }
            }
            compilation_success
        };

        if compilation_success == 1 {
            Ok(Shader {
                context: facade.get_context().clone(),
                id: id
            })

        } else {
            // compilation error
            let mut error_log_size: gl::types::GLint = mem::uninitialized();

            match id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.GetShaderiv(id, gl::INFO_LOG_LENGTH, &mut error_log_size);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.GetObjectParameterivARB(id, gl::OBJECT_INFO_LOG_LENGTH_ARB,
                                                    &mut error_log_size);
                }
            }

            let mut error_log: Vec<u8> = Vec::with_capacity(error_log_size as usize);

            match id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.GetShaderInfoLog(id, error_log_size, &mut error_log_size,
                                             error_log.as_mut_ptr() as *mut gl::types::GLchar);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.GetInfoLogARB(id, error_log_size, &mut error_log_size,
                                          error_log.as_mut_ptr() as *mut gl::types::GLchar);
                }
            }

            error_log.set_len(error_log_size as usize);

            match String::from_utf8(error_log) {
                Ok(msg) => Err(ProgramCreationError::CompilationError(msg)),
                Err(_) => Err(
                    ProgramCreationError::CompilationError("Could not convert the log \
                                                            message to UTF-8".to_owned())
                ),
            }
        }
    }
}

pub fn check_shader_type_compatibility<C>(ctxt: &C, shader_type: gl::types::GLenum)
                                          -> bool where C: CapabilitiesSource
{
    match shader_type {
        gl::VERTEX_SHADER | gl::FRAGMENT_SHADER => (),
        gl::GEOMETRY_SHADER => {
            if !(ctxt.get_version() >= &Version(Api::Gl, 3, 0))
                && !(ctxt.get_version() >= &Version(Api::GlEs, 3, 2))
                && !ctxt.get_extensions().gl_arb_geometry_shader4
                && !ctxt.get_extensions().gl_ext_geometry_shader4
                && !ctxt.get_extensions().gl_ext_geometry_shader
                && !ctxt.get_extensions().gl_oes_geometry_shader
            {
                return false;
            }
        },
        gl::TESS_CONTROL_SHADER | gl::TESS_EVALUATION_SHADER => {
            if !(ctxt.get_version() >= &Version(Api::Gl, 4, 0))
                && !(ctxt.get_version() >= &Version(Api::GlEs, 3, 2))
                && !ctxt.get_extensions().gl_arb_tessellation_shader
                && !ctxt.get_extensions().gl_oes_tessellation_shader
            {
                return false;
            }
        },
        gl::COMPUTE_SHADER => {
            if !(ctxt.get_version() >= &Version(Api::Gl, 4, 3))
                && !(ctxt.get_version() >= &Version(Api::GlEs, 3, 1))
                && !ctxt.get_extensions().gl_arb_compute_shader
            {
                return false;
            }
        },
        _ => unreachable!()
    };

    true
}
<commit_msg>Fix wrong minimum core version of geometry shaders<commit_after>use gl;
use version::Version;
use version::Api;

use CapabilitiesSource;
use backend::Facade;
use context::Context;
use ContextExt;

use std::{ffi, mem, ptr};
use std::rc::Rc;

use GlObject;
use Handle;

use program::ProgramCreationError;

/// A single, compiled but unlinked, shader.
pub struct Shader {
    context: Rc<Context>,
    id: Handle,
}

impl GlObject for Shader {
    type Id = Handle;

    #[inline]
    fn get_id(&self) -> Handle {
        self.id
    }
}

impl Drop for Shader {
    fn drop(&mut self) {
        let ctxt = self.context.make_current();

        unsafe {
            match self.id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.DeleteShader(id);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.DeleteObjectARB(id);
                }
            }
        }
    }
}

/// Builds an individual shader.
pub fn build_shader<F>(facade: &F, shader_type: gl::types::GLenum, source_code: &str)
                       -> Result<Shader, ProgramCreationError> where F: Facade
{
    unsafe {
        let mut ctxt = facade.get_context().make_current();

        if ctxt.capabilities.supported_glsl_versions.is_empty() {
            return Err(ProgramCreationError::CompilationNotSupported);
        }

        if !check_shader_type_compatibility(&mut ctxt, shader_type) {
            return Err(ProgramCreationError::ShaderTypeNotSupported);
        }

        let source_code = ffi::CString::new(source_code.as_bytes()).unwrap();

        let id = if ctxt.version >= &Version(Api::Gl, 2, 0) ||
                    ctxt.version >= &Version(Api::GlEs, 2, 0)
        {
            Handle::Id(ctxt.gl.CreateShader(shader_type))
        } else if ctxt.extensions.gl_arb_shader_objects {
            Handle::Handle(ctxt.gl.CreateShaderObjectARB(shader_type))
        } else {
            unreachable!()
        };

        if id == Handle::Id(0) || id == Handle::Handle(0 as gl::types::GLhandleARB) {
            return Err(ProgramCreationError::ShaderTypeNotSupported);
        }

        match id {
            Handle::Id(id) => {
                assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                        ctxt.version >= &Version(Api::GlEs, 2, 0));
                ctxt.gl.ShaderSource(id, 1, [ source_code.as_ptr() ].as_ptr(), ptr::null());
            },
            Handle::Handle(id) => {
                assert!(ctxt.extensions.gl_arb_shader_objects);
                ctxt.gl.ShaderSourceARB(id, 1, [ source_code.as_ptr() ].as_ptr(), ptr::null());
            }
        }

        // compiling
        {
            ctxt.report_debug_output_errors.set(false);

            match id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0)||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.CompileShader(id);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.CompileShaderARB(id);
                }
            }

            ctxt.report_debug_output_errors.set(true);
        }

        // checking compilation success by reading a flag on the shader
        let compilation_success = {
            let mut compilation_success: gl::types::GLint = mem::uninitialized();
            match id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.GetShaderiv(id, gl::COMPILE_STATUS, &mut compilation_success);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.GetObjectParameterivARB(id, gl::OBJECT_COMPILE_STATUS_ARB,
                                                    &mut compilation_success);
                }
            }
            compilation_success
        };

        if compilation_success == 1 {
            Ok(Shader {
                context: facade.get_context().clone(),
                id: id
            })

        } else {
            // compilation error
            let mut error_log_size: gl::types::GLint = mem::uninitialized();

            match id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.GetShaderiv(id, gl::INFO_LOG_LENGTH, &mut error_log_size);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.GetObjectParameterivARB(id, gl::OBJECT_INFO_LOG_LENGTH_ARB,
                                                    &mut error_log_size);
                }
            }

            let mut error_log: Vec<u8> = Vec::with_capacity(error_log_size as usize);

            match id {
                Handle::Id(id) => {
                    assert!(ctxt.version >= &Version(Api::Gl, 2, 0) ||
                            ctxt.version >= &Version(Api::GlEs, 2, 0));
                    ctxt.gl.GetShaderInfoLog(id, error_log_size, &mut error_log_size,
                                             error_log.as_mut_ptr() as *mut gl::types::GLchar);
                },
                Handle::Handle(id) => {
                    assert!(ctxt.extensions.gl_arb_shader_objects);
                    ctxt.gl.GetInfoLogARB(id, error_log_size, &mut error_log_size,
                                          error_log.as_mut_ptr() as *mut gl::types::GLchar);
                }
            }

            error_log.set_len(error_log_size as usize);

            match String::from_utf8(error_log) {
                Ok(msg) => Err(ProgramCreationError::CompilationError(msg)),
                Err(_) => Err(
                    ProgramCreationError::CompilationError("Could not convert the log \
                                                            message to UTF-8".to_owned())
                ),
            }
        }
    }
}

pub fn check_shader_type_compatibility<C>(ctxt: &C, shader_type: gl::types::GLenum)
                                          -> bool where C: CapabilitiesSource
{
    match shader_type {
        gl::VERTEX_SHADER | gl::FRAGMENT_SHADER => (),
        gl::GEOMETRY_SHADER => {
            if !(ctxt.get_version() >= &Version(Api::Gl, 3, 2))
                && !(ctxt.get_version() >= &Version(Api::GlEs, 3, 2))
                && !ctxt.get_extensions().gl_arb_geometry_shader4
                && !ctxt.get_extensions().gl_ext_geometry_shader4
                && !ctxt.get_extensions().gl_ext_geometry_shader
                && !ctxt.get_extensions().gl_oes_geometry_shader
            {
                return false;
            }
        },
        gl::TESS_CONTROL_SHADER | gl::TESS_EVALUATION_SHADER => {
            if !(ctxt.get_version() >= &Version(Api::Gl, 4, 0))
                && !(ctxt.get_version() >= &Version(Api::GlEs, 3, 2))
                && !ctxt.get_extensions().gl_arb_tessellation_shader
                && !ctxt.get_extensions().gl_oes_tessellation_shader
            {
                return false;
            }
        },
        gl::COMPUTE_SHADER => {
            if !(ctxt.get_version() >= &Version(Api::Gl, 4, 3))
                && !(ctxt.get_version() >= &Version(Api::GlEs, 3, 1))
                && !ctxt.get_extensions().gl_arb_compute_shader
            {
                return false;
            }
        },
        _ => unreachable!()
    };

    true
}
<|endoftext|>


<commit_before><commit_msg>this fixes the siginfo_t, adds missing pthread externs.<commit_after><|endoftext|>