<commit_before>extern crate rand;

use rand::thread_rng;
use rand::distributions::Range;
use individual::Individual;

mod individual;

fn main() {
    let mut rng = thread_rng();
    let range = Range::new(-512.03_f64, 511.97); // range for Schwefel problem

    // initialize population
    let mut population: Vec<_> = (0..128).map(|_| {
        Individual::new(&range, &mut rng)
    }).collect();

    for i in 0..10000 {
        // generate mutated offspring
        population = population.iter().map(|x| {
            x.mutate(&range, &mut rng)
        }).collect();

        println!("{}th fitness: {}", i, best.fitness);
        let best = population.iter().min().unwrap();

        if best.fitness < 1000_f64 {
            println!("Solution: {:?}", best.solution);
            return;
        }
    }
    println!("Failed to converge.");
}
<commit_msg>Print only every 100th iteration<commit_after>extern crate rand;

use rand::thread_rng;
use rand::distributions::Range;
use individual::Individual;

mod individual;

fn main() {
    let mut rng = thread_rng();
    let range = Range::new(-512.03_f64, 511.97); // range for Schwefel problem

    // initialize population
    let mut population: Vec<_> = (0..128).map(|_| {
        Individual::new(&range, &mut rng)
    }).collect();

    for i in 0..10000 {
        // generate mutated offspring
        population = population.iter().map(|x| {
            x.mutate(&range, &mut rng)
        }).collect();

        let best = population.iter().min().unwrap();
        if i % 100 == 0 {
            println!("{}th fitness: {}", i, best.fitness);
        }

        if best.fitness < 1000_f64 {
            println!("Solution: {:?}", best.solution);
            return;
        }
    }
    println!("Failed to converge.");
}
<|endoftext|>


<commit_before>extern crate rust_guessing_game;

use std::io;
use std::rand;

use rust_guessing_game::my_funcs;

#[cfg(not(test))]
fn main() {
    println!("Guess the magic number!");
    let magic_number = ( rand::random::<uint>() % 100u ) + 1u;
    loop {
        let input = io::stdin().read_line().ok().expect("That was bad input");
        let input_optoin_uint: Option<uint> = from_str(input.as_slice().trim());
        let input_uint = match input_optoin_uint {
            Some(num) => num,
            None      => {
                println!("Please input a number");
                continue;
            }
        };
        println!("Guess = {}", input_uint);
        match my_funcs::compaire(input_uint, magic_number) {
            Less    => println!("Guess higher."),
            Greater => println!("Guess lower."),
            Equal   => {
                println!("You win!");
                return
            },
        }
    }
}
<commit_msg>Remove unneeded print<commit_after>extern crate rust_guessing_game;

use std::io;
use std::rand;

use rust_guessing_game::my_funcs;

#[cfg(not(test))]
fn main() {
    println!("Guess the magic number!");
    let magic_number = ( rand::random::<uint>() % 100u ) + 1u;
    loop {
        let input = io::stdin().read_line().ok().expect("That was bad input");
        let input_optoin_uint: Option<uint> = from_str(input.as_slice().trim());
        let input_uint = match input_optoin_uint {
            Some(num) => num,
            None      => {
                println!("Please input a number");
                continue;
            }
        };
        match my_funcs::compaire(input_uint, magic_number) {
            Less    => println!("Guess higher."),
            Greater => println!("Guess lower."),
            Equal   => {
                println!("You win!");
                return
            },
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement test for set_left_child<commit_after><|endoftext|>


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

//! A wrapper around another RNG that reseeds it after it
//! generates a certain number of random bytes.

use rand::{Rng, SeedableRng};
use default::Default;

/// How many bytes of entropy the underling RNG is allowed to generate
/// before it is reseeded.
static DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024;

/// A wrapper around any RNG which reseeds the underlying RNG after it
/// has generated a certain number of random bytes.
pub struct ReseedingRng<R, Rsdr> {
    priv rng: R,
    priv generation_threshold: uint,
    priv bytes_generated: uint,
    /// Controls the behaviour when reseeding the RNG.
    reseeder: Rsdr
}

impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
    /// Create a new `ReseedingRng` with the given parameters.
    ///
    /// # Arguments
    ///
    /// * `rng`: the random number generator to use.
    /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG.
    /// * `reseeder`: the reseeding object to use.
    pub fn new(rng: R, generation_threshold: uint, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> {
        ReseedingRng {
            rng: rng,
            generation_threshold: generation_threshold,
            bytes_generated: 0,
            reseeder: reseeder
        }
    }

    /// Reseed the internal RNG if the number of bytes that have been
    /// generated exceed the threshold.
    pub fn reseed_if_necessary(&mut self) {
        if self.bytes_generated >= self.generation_threshold {
            self.reseeder.reseed(&mut self.rng);
            self.bytes_generated = 0;
        }
    }
}

impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
    fn next_u32(&mut self) -> u32 {
        self.reseed_if_necessary();
        self.bytes_generated += 4;
        self.rng.next_u32()
    }

    fn next_u64(&mut self) -> u64 {
        self.reseed_if_necessary();
        self.bytes_generated += 8;
        self.rng.next_u64()
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        self.reseed_if_necessary();
        self.bytes_generated += dest.len();
        self.fill_bytes(dest)
    }
}

impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R>>
     SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
    fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
        self.rng.reseed(seed);
        self.reseeder = rsdr;
        self.bytes_generated = 0;
    }
    /// Create a new `ReseedingRng` from the given reseeder and
    /// seed. This uses a default value for `generation_threshold`.
    fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
        ReseedingRng {
            rng: SeedableRng::from_seed(seed),
            generation_threshold: DEFAULT_GENERATION_THRESHOLD,
            bytes_generated: 0,
            reseeder: rsdr
        }
    }
}

/// Something that can be used to reseed an RNG via `ReseedingRng`.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::{Rng, SeedableRng};
/// use std::rand::reseeding::{Reseeder, ReseedingRng};
///
/// struct TickTockReseeder { tick: bool }
/// impl Reseeder<rand::StdRng> for TickTockReseeder {
///     fn reseed(&mut self, rng: &mut rand::StdRng) {
///         let val = if self.tick {0} else {1};
///         rng.reseed(&[val]);
///         self.tick = !self.tick;
///     }
/// }
/// fn main() {
///     let rsdr = TickTockReseeder { tick: true };
///     let mut rng = ReseedingRng::new(rand::StdRng::new(), 10, rsdr);
///
///     // this will repeat, because it gets reseeded very regularly.
///     println(rng.gen_ascii_str(100));
/// }
///
/// ```
pub trait Reseeder<R> {
    /// Reseed the given RNG.
    fn reseed(&mut self, rng: &mut R);
}

/// Reseed an RNG using a `Default` instance. This reseeds by
/// replacing the RNG with the result of a `Default::default` call.
pub struct ReseedWithDefault;

impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
    fn reseed(&mut self, rng: &mut R) {
        *rng = Default::default();
    }
}
impl Default for ReseedWithDefault {
    fn default() -> ReseedWithDefault { ReseedWithDefault }
}

#[cfg(test)]
mod test {
    use super::*;
    use rand::{SeedableRng, Rng};
    use default::Default;
    use iter::range;
    use option::{None, Some};

    struct Counter {
        i: u32
    }

    impl Rng for Counter {
        fn next_u32(&mut self) -> u32 {
            self.i += 1;
            // very random
            self.i - 1
        }
    }
    impl Default for Counter {
        fn default() -> Counter {
            Counter { i: 0 }
        }
    }
    impl SeedableRng<u32> for Counter {
        fn reseed(&mut self, seed: u32) {
            self.i = seed;
        }
        fn from_seed(seed: u32) -> Counter {
            Counter { i: seed }
        }
    }
    type MyRng = ReseedingRng<Counter, ReseedWithDefault>;

    #[test]
    fn test_reseeding() {
        let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);

        let mut i = 0;
        for _ in range(0, 1000) {
            assert_eq!(rs.next_u32(), i % 100);
            i += 1;
        }
    }

    #[test]
    fn test_rng_seeded() {
        let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
        let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
        assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
    }

    #[test]
    fn test_rng_reseed() {
        let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
        let string1 = r.gen_ascii_str(100);

        r.reseed((ReseedWithDefault, 3));

        let string2 = r.gen_ascii_str(100);
        assert_eq!(string1, string2);
    }
}
<commit_msg>auto merge of #10213 : telotortium/rust/rand-fill_bytes-stack-overflow, r=huonw<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.

//! A wrapper around another RNG that reseeds it after it
//! generates a certain number of random bytes.

use rand::{Rng, SeedableRng};
use default::Default;

/// How many bytes of entropy the underling RNG is allowed to generate
/// before it is reseeded.
static DEFAULT_GENERATION_THRESHOLD: uint = 32 * 1024;

/// A wrapper around any RNG which reseeds the underlying RNG after it
/// has generated a certain number of random bytes.
pub struct ReseedingRng<R, Rsdr> {
    priv rng: R,
    priv generation_threshold: uint,
    priv bytes_generated: uint,
    /// Controls the behaviour when reseeding the RNG.
    reseeder: Rsdr
}

impl<R: Rng, Rsdr: Reseeder<R>> ReseedingRng<R, Rsdr> {
    /// Create a new `ReseedingRng` with the given parameters.
    ///
    /// # Arguments
    ///
    /// * `rng`: the random number generator to use.
    /// * `generation_threshold`: the number of bytes of entropy at which to reseed the RNG.
    /// * `reseeder`: the reseeding object to use.
    pub fn new(rng: R, generation_threshold: uint, reseeder: Rsdr) -> ReseedingRng<R,Rsdr> {
        ReseedingRng {
            rng: rng,
            generation_threshold: generation_threshold,
            bytes_generated: 0,
            reseeder: reseeder
        }
    }

    /// Reseed the internal RNG if the number of bytes that have been
    /// generated exceed the threshold.
    pub fn reseed_if_necessary(&mut self) {
        if self.bytes_generated >= self.generation_threshold {
            self.reseeder.reseed(&mut self.rng);
            self.bytes_generated = 0;
        }
    }
}

impl<R: Rng, Rsdr: Reseeder<R>> Rng for ReseedingRng<R, Rsdr> {
    fn next_u32(&mut self) -> u32 {
        self.reseed_if_necessary();
        self.bytes_generated += 4;
        self.rng.next_u32()
    }

    fn next_u64(&mut self) -> u64 {
        self.reseed_if_necessary();
        self.bytes_generated += 8;
        self.rng.next_u64()
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        self.reseed_if_necessary();
        self.bytes_generated += dest.len();
        self.rng.fill_bytes(dest)
    }
}

impl<S, R: SeedableRng<S>, Rsdr: Reseeder<R>>
     SeedableRng<(Rsdr, S)> for ReseedingRng<R, Rsdr> {
    fn reseed(&mut self, (rsdr, seed): (Rsdr, S)) {
        self.rng.reseed(seed);
        self.reseeder = rsdr;
        self.bytes_generated = 0;
    }
    /// Create a new `ReseedingRng` from the given reseeder and
    /// seed. This uses a default value for `generation_threshold`.
    fn from_seed((rsdr, seed): (Rsdr, S)) -> ReseedingRng<R, Rsdr> {
        ReseedingRng {
            rng: SeedableRng::from_seed(seed),
            generation_threshold: DEFAULT_GENERATION_THRESHOLD,
            bytes_generated: 0,
            reseeder: rsdr
        }
    }
}

/// Something that can be used to reseed an RNG via `ReseedingRng`.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::{Rng, SeedableRng};
/// use std::rand::reseeding::{Reseeder, ReseedingRng};
///
/// struct TickTockReseeder { tick: bool }
/// impl Reseeder<rand::StdRng> for TickTockReseeder {
///     fn reseed(&mut self, rng: &mut rand::StdRng) {
///         let val = if self.tick {0} else {1};
///         rng.reseed(&[val]);
///         self.tick = !self.tick;
///     }
/// }
/// fn main() {
///     let rsdr = TickTockReseeder { tick: true };
///     let mut rng = ReseedingRng::new(rand::StdRng::new(), 10, rsdr);
///
///     // this will repeat, because it gets reseeded very regularly.
///     println(rng.gen_ascii_str(100));
/// }
///
/// ```
pub trait Reseeder<R> {
    /// Reseed the given RNG.
    fn reseed(&mut self, rng: &mut R);
}

/// Reseed an RNG using a `Default` instance. This reseeds by
/// replacing the RNG with the result of a `Default::default` call.
pub struct ReseedWithDefault;

impl<R: Rng + Default> Reseeder<R> for ReseedWithDefault {
    fn reseed(&mut self, rng: &mut R) {
        *rng = Default::default();
    }
}
impl Default for ReseedWithDefault {
    fn default() -> ReseedWithDefault { ReseedWithDefault }
}

#[cfg(test)]
mod test {
    use super::*;
    use rand::{SeedableRng, Rng};
    use default::Default;
    use iter::range;
    use option::{None, Some};

    struct Counter {
        i: u32
    }

    impl Rng for Counter {
        fn next_u32(&mut self) -> u32 {
            self.i += 1;
            // very random
            self.i - 1
        }
    }
    impl Default for Counter {
        fn default() -> Counter {
            Counter { i: 0 }
        }
    }
    impl SeedableRng<u32> for Counter {
        fn reseed(&mut self, seed: u32) {
            self.i = seed;
        }
        fn from_seed(seed: u32) -> Counter {
            Counter { i: seed }
        }
    }
    type MyRng = ReseedingRng<Counter, ReseedWithDefault>;

    #[test]
    fn test_reseeding() {
        let mut rs = ReseedingRng::new(Counter {i:0}, 400, ReseedWithDefault);

        let mut i = 0;
        for _ in range(0, 1000) {
            assert_eq!(rs.next_u32(), i % 100);
            i += 1;
        }
    }

    #[test]
    fn test_rng_seeded() {
        let mut ra: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
        let mut rb: MyRng = SeedableRng::from_seed((ReseedWithDefault, 2));
        assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
    }

    #[test]
    fn test_rng_reseed() {
        let mut r: MyRng = SeedableRng::from_seed((ReseedWithDefault, 3));
        let string1 = r.gen_ascii_str(100);

        r.reseed((ReseedWithDefault, 3));

        let string2 = r.gen_ascii_str(100);
        assert_eq!(string1, string2);
    }

    static fill_bytes_v_len: uint = 13579;
    #[test]
    fn test_rng_fill_bytes() {
        use rand::task_rng;
        let mut v = ~[0u8, .. fill_bytes_v_len];
        task_rng().fill_bytes(v);

        // Sanity test: if we've gotten here, `fill_bytes` has not infinitely
        // recursed.
        assert_eq!(v.len(), fill_bytes_v_len);

        // To test that `fill_bytes` actually did something, check that the
        // average of `v` is not 0.
        let mut sum = 0.0;
        for &x in v.iter() {
            sum += x as f64;
        }
        assert!(sum / v.len() as f64 != 0.0);
    }
}
<|endoftext|>


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

// This test case tests the incremental compilation hash (ICH) implementation
// for function interfaces.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(conservative_impl_trait)]
#![feature(intrinsics)]
#![feature(linkage)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

// Add Parameter ---------------------------------------------------------------

#[cfg(cfail1)]
fn add_parameter() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn add_parameter(p: i32) {}

// Add Return Type -------------------------------------------------------------

#[cfg(cfail1)]
fn add_return_type() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn add_return_type() -> () {}

// Change Parameter Type -------------------------------------------------------

#[cfg(cfail1)]
fn type_of_parameter(p: i32) {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn type_of_parameter(p: i64) {}

// Change Parameter Type Reference ---------------------------------------------

#[cfg(cfail1)]
fn type_of_parameter_ref(p: &i32) {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn type_of_parameter_ref(p: &mut i32) {}

// Change Parameter Order ------------------------------------------------------

#[cfg(cfail1)]
fn order_of_parameters(p1: i32, p2: i32) {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn order_of_parameters(p2: i32, p1: i32) {}

// Unsafe ----------------------------------------------------------------------

#[cfg(cfail1)]
fn make_unsafe() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
unsafe fn make_unsafe() {}

// Extern ----------------------------------------------------------------------

#[cfg(cfail1)]
fn make_extern() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
extern fn make_extern() {}

// Extern C Extern Rust-Intrinsic ----------------------------------------------

#[cfg(cfail1)]
extern "C" fn make_intrinsic() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
extern "rust-intrinsic" fn make_intrinsic() {}

// Type Parameter --------------------------------------------------------------

#[cfg(cfail1)]
fn type_parameter() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn type_parameter<T>() {}

// Lifetime Parameter ----------------------------------------------------------

#[cfg(cfail1)]
fn lifetime_parameter() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn lifetime_parameter<'a>() {}

// Trait Bound -----------------------------------------------------------------

#[cfg(cfail1)]
fn trait_bound<T>() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn trait_bound<T: Eq>() {}

// Builtin Bound ---------------------------------------------------------------

#[cfg(cfail1)]
fn builtin_bound<T>() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn builtin_bound<T: Send>() {}

// Lifetime Bound --------------------------------------------------------------

#[cfg(cfail1)]
fn lifetime_bound<T>() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn lifetime_bound<'a, T: 'a>() {}

// Second Trait Bound ----------------------------------------------------------

#[cfg(cfail1)]
fn second_trait_bound<T: Eq>() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn second_trait_bound<T: Eq + Clone>() {}

// Second Builtin Bound --------------------------------------------------------

#[cfg(cfail1)]
fn second_builtin_bound<T: Send>() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn second_builtin_bound<T: Send + Sized>() {}

// Second Lifetime Bound -------------------------------------------------------

#[cfg(cfail1)]
fn second_lifetime_bound<'a, T: 'a>() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn second_lifetime_bound<'a, 'b, T: 'a + 'b>() {}

// Inline ----------------------------------------------------------------------

#[cfg(cfail1)]
fn inline() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[inline]
fn inline() {}

// Inline Never ----------------------------------------------------------------

#[cfg(cfail1)]
fn inline_never() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[inline(never)]
fn inline_never() {}

// No Mangle -------------------------------------------------------------------

#[cfg(cfail1)]
fn no_mangle() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[no_mangle]
fn no_mangle() {}

// Linkage ---------------------------------------------------------------------

#[cfg(cfail1)]
fn linkage() {}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
#[linkage]
fn linkage() {}

// Return Impl Trait -----------------------------------------------------------

#[cfg(cfail1)]
fn return_impl_trait() -> i32 {
    0
}

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn return_impl_trait() -> impl Clone {
    0
}

// Change Return Type Indirectly -----------------------------------------------

struct ReferencedType1;
struct ReferencedType2;

mod change_return_type_indirectly {
    #[cfg(cfail1)]
    use super::ReferencedType1 as ReturnType;
    #[cfg(not(cfail1))]
    use super::ReferencedType2 as ReturnType;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    fn indirect_return_type() -> ReturnType {
        ReturnType {}
    }
}

// Change Parameter Type Indirectly --------------------------------------------

mod change_parameter_type_indirectly {
    #[cfg(cfail1)]
    use super::ReferencedType1 as ParameterType;
    #[cfg(not(cfail1))]
    use super::ReferencedType2 as ParameterType;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    fn indirect_parameter_type(p: ParameterType) {}
}

// Change Trait Bound Indirectly -----------------------------------------------

trait ReferencedTrait1 {}
trait ReferencedTrait2 {}

mod change_trait_bound_indirectly {
    #[cfg(cfail1)]
    use super::ReferencedTrait1 as Trait;
    #[cfg(not(cfail1))]
    use super::ReferencedTrait2 as Trait;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    fn indirect_trait_bound<T: Trait>(p: T) {}
}

// Change Trait Bound Indirectly In Where Clause -------------------------------

mod change_trait_bound_indirectly_in_where_clause {
    #[cfg(cfail1)]
    use super::ReferencedTrait1 as Trait;
    #[cfg(not(cfail1))]
    use super::ReferencedTrait2 as Trait;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    fn indirect_trait_bound_where<T>(p: T) where T: Trait {}
}
<|endoftext|>


<commit_before><commit_msg>add const generics<commit_after>// run-pass
#![feature(const_generics)]
#![allow(incomplete_features)]

fn foo<const N: usize>(v: &[u8; N]) -> &[u8] {
    v
}

fn main() {
    assert_eq!(foo(&[1, 2]), &[1, 2]);
}
<|endoftext|>


<commit_before><commit_msg>add example: facility<commit_after>// Copyright (c) 2016 Yusuke Sasaki
//
// This software is released under the MIT License.
// See http://opensource.org/licenses/mit-license.php or <LICENSE>.

extern crate gurobi;
extern crate itertools;
use gurobi::*;
use itertools::*;

fn main() {
  // warehouse demand in thousands of units.
  let demand = vec![15f64, 18.0, 14.0, 20.0];

  // plant capacity in thousands of units.
  let capacity = vec![20f64, 22.0, 17.0, 19.0, 18.0];

  // fixed costs for each plant.
  let fixed_costs = vec![12000f64, 15000.0, 17000.0, 13000.0, 16000.0];

  // transportation costs per thousands units.
  let trans_costs = vec![vec![4000f64, 2000.0, 3000.0, 2500.0, 4500.0],
                         vec![2500f64, 2600.0, 3400.0, 3000.0, 4000.0],
                         vec![1200f64, 1800.0, 2600.0, 4100.0, 3000.0],
                         vec![2200f64, 2600.0, 3100.0, 3700.0, 3200.0]];

  let env = Env::new("facility.log").unwrap();
  let mut model = env.new_model("facility").unwrap();

  let mut coeff = Vec::with_capacity(fixed_costs.len() + fixed_costs.len() * demand.len());

  // plant open decision variables.
  // open[p] == 1 means that plant p is open.
  let mut open = Vec::with_capacity(fixed_costs.len());
  for (p, &cost) in fixed_costs.iter().enumerate() {
    open.push(model.add_var(&format!("Open{}", p), Binary).unwrap());
    coeff.push(cost);
  }
  let open = open;

  // transportation decision variables.
  // how much transport from a plant p to a warehouse w
  let mut transport = Vec::with_capacity(trans_costs.len());
  for (w, costs) in trans_costs.iter().enumerate() {
    transport.push(Vec::with_capacity(costs.len()));
    for (p, &cost) in costs.iter().enumerate() {
      transport.last_mut()
        .unwrap()
        .push(model.add_var(&format!("Trans{}.{}", p, w), Continuous(0.0, INFINITY)).unwrap());
      coeff.push(cost);
    }
  }
  let transport = transport;

  let expr = Zip::new((open.iter().chain(transport.iter().flatten()), coeff))
    .fold(LinExpr::new(), |expr, (x, c)| expr + c * x);
  model.set_objective(expr, Minimize).unwrap();
  model.update().unwrap();

  for (p, (&capacity, open)) in Zip::new((&capacity, &open)).enumerate() {
    let lhs = transport.iter().map(|t| &t[p]).fold(LinExpr::new(), |expr, t| expr + t);
    model.add_constr(&format!("Capacity{}", p), lhs - capacity * open, Less, 0.0).unwrap();
  }

  for (w, (&demand, transport)) in Zip::new((&demand, &transport)).enumerate() {
    let lhs = transport.iter().fold(LinExpr::new(), |expr, t| expr + t);
    model.add_constr(&format!("Demand{}", w), lhs, Equal, demand).unwrap();
  }

  for o in open.iter() {
    o.set(&mut model, attr::Start, 1.0).unwrap();
  }

  println!("Initial guesss:");
  let max_fixed = fixed_costs.iter().cloned().fold(-1. / 0., f64::max);
  for (p, (open, &cost)) in Zip::new((&open, &fixed_costs)).enumerate() {
    if cost == max_fixed {
      open.set(&mut model, attr::Start, 0.0).unwrap();
      println!("Closing plant {}", p);
      break;
    }
  }
  println!("");

  // use barrier to solve root relaxation.
  model.get_env_mut().set(param::Method, 2).unwrap();

  // solve.
  model.optimize().unwrap();

  // print solution.
  println!("\nTOTAL COSTS: {}", model.get(attr::ObjVal).unwrap());
  println!("SOLUTION:");
  for (p, open) in open.iter().enumerate() {
    let x = open.get(&model, attr::X).unwrap();
    if x == 1.0 {
      println!("Plant {} is open", p);
      for (w, trans) in transport.iter().enumerate() {
        let t = trans[p].get(&model, attr::X).unwrap();
        if t > 0.0 {
          println!("  Transport {} units to warehouse {}", t, w);
        }
      }
    } else {
      println!("Plant {} is closed!", p);
    }
  }

  model.write("facility.lp").unwrap();
  model.write("facility.sol").unwrap();
}
<|endoftext|>


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

#![unstable(reason = "not public", issue = "0", feature = "fd")]

use cmp;
use io::{self, Read};
use libc::{self, c_int, c_void, ssize_t};
use mem;
use sync::atomic::{AtomicBool, Ordering};
use sys::cvt;
use sys_common::AsInner;

#[derive(Debug)]
pub struct FileDesc {
    fd: c_int,
}

fn max_len() -> usize {
    // The maximum read limit on most posix-like systems is `SSIZE_MAX`,
    // with the man page quoting that if the count of bytes to read is
    // greater than `SSIZE_MAX` the result is "unspecified".
    //
    // On macOS, however, apparently the 64-bit libc is either buggy or
    // intentionally showing odd behavior by rejecting any read with a size
    // larger than or equal to INT_MAX. To handle both of these the read
    // size is capped on both platforms.
    if cfg!(target_os = "macos") {
        <c_int>::max_value() as usize - 1
    } else {
        <ssize_t>::max_value() as usize
    }
}

impl FileDesc {
    pub fn new(fd: c_int) -> FileDesc {
        FileDesc { fd: fd }
    }

    pub fn raw(&self) -> c_int { self.fd }

    /// Extracts the actual filedescriptor without closing it.
    pub fn into_raw(self) -> c_int {
        let fd = self.fd;
        mem::forget(self);
        fd
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        let ret = cvt(unsafe {
            libc::read(self.fd,
                       buf.as_mut_ptr() as *mut c_void,
                       cmp::min(buf.len(), max_len()))
        })?;
        Ok(ret as usize)
    }

    pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
        let mut me = self;
        (&mut me).read_to_end(buf)
    }

    pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        #[cfg(target_os = "android")]
        use super::android::cvt_pread64;

        #[cfg(target_os = "emscripten")]
        unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
            -> io::Result<isize>
        {
            use libc::pread64;
            cvt(pread64(fd, buf, count, offset as i32))
        }

        #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
        unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
            -> io::Result<isize>
        {
            #[cfg(target_os = "linux")]
            use libc::pread64;
            #[cfg(not(target_os = "linux"))]
            use libc::pread as pread64;
            cvt(pread64(fd, buf, count, offset))
        }

        unsafe {
            cvt_pread64(self.fd,
                        buf.as_mut_ptr() as *mut c_void,
                        cmp::min(buf.len(), max_len()),
                        offset as i64)
                .map(|n| n as usize)
        }
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        let ret = cvt(unsafe {
            libc::write(self.fd,
                        buf.as_ptr() as *const c_void,
                        cmp::min(buf.len(), max_len()))
        })?;
        Ok(ret as usize)
    }

    pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
        #[cfg(target_os = "android")]
        use super::android::cvt_pwrite64;

        #[cfg(target_os = "emscripten")]
        unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
            -> io::Result<isize>
        {
            use libc::pwrite64;
            cvt(pwrite64(fd, buf, count, offset as i32))
        }

        #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
        unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
            -> io::Result<isize>
        {
            #[cfg(target_os = "linux")]
            use libc::pwrite64;
            #[cfg(not(target_os = "linux"))]
            use libc::pwrite as pwrite64;
            cvt(pwrite64(fd, buf, count, offset))
        }

        unsafe {
            cvt_pwrite64(self.fd,
                         buf.as_ptr() as *const c_void,
                         cmp::min(buf.len(), max_len()),
                         offset as i64)
                .map(|n| n as usize)
        }
    }

    #[cfg(not(any(target_env = "newlib",
                  target_os = "solaris",
                  target_os = "emscripten",
                  target_os = "fuchsia",
                  target_os = "l4re",
                  target_os = "haiku")))]
    pub fn set_cloexec(&self) -> io::Result<()> {
        unsafe {
            cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
            Ok(())
        }
    }
    #[cfg(any(target_env = "newlib",
              target_os = "solaris",
              target_os = "emscripten",
              target_os = "fuchsia",
              target_os = "l4re",
              target_os = "haiku"))]
    pub fn set_cloexec(&self) -> io::Result<()> {
        unsafe {
            let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
            let new = previous | libc::FD_CLOEXEC;
            if new != previous {
                cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
            }
            Ok(())
        }
    }

    #[cfg(target_os = "linux")]
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        unsafe {
            let v = nonblocking as c_int;
            cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
            Ok(())
        }
    }

    #[cfg(not(target_os = "linux"))]
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        unsafe {
            let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
            let new = if nonblocking {
                previous | libc::O_NONBLOCK
            } else {
                previous & !libc::O_NONBLOCK
            };
            if new != previous {
                cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
            }
            Ok(())
        }
    }

    pub fn duplicate(&self) -> io::Result<FileDesc> {
        // We want to atomically duplicate this file descriptor and set the
        // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
        // flag, however, isn't supported on older Linux kernels (earlier than
        // 2.6.24).
        //
        // To detect this and ensure that CLOEXEC is still set, we
        // follow a strategy similar to musl [1] where if passing
        // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
        // supported (the third parameter, 0, is always valid), so we stop
        // trying that.
        //
        // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
        // resolve so we at least compile this.
        //
        // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
        #[cfg(any(target_os = "android", target_os = "haiku"))]
        use libc::F_DUPFD as F_DUPFD_CLOEXEC;
        #[cfg(not(any(target_os = "android", target_os="haiku")))]
        use libc::F_DUPFD_CLOEXEC;

        let make_filedesc = |fd| {
            let fd = FileDesc::new(fd);
            fd.set_cloexec()?;
            Ok(fd)
        };
        static TRY_CLOEXEC: AtomicBool =
            AtomicBool::new(!cfg!(target_os = "android"));
        let fd = self.raw();
        if TRY_CLOEXEC.load(Ordering::Relaxed) {
            match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
                // We *still* call the `set_cloexec` method as apparently some
                // linux kernel at some point stopped setting CLOEXEC even
                // though it reported doing so on F_DUPFD_CLOEXEC.
                Ok(fd) => {
                    return Ok(if cfg!(target_os = "linux") {
                        make_filedesc(fd)?
                    } else {
                        FileDesc::new(fd)
                    })
                }
                Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
                    TRY_CLOEXEC.store(false, Ordering::Relaxed);
                }
                Err(e) => return Err(e),
            }
        }
        cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
    }
}

impl<'a> Read for &'a FileDesc {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        (**self).read(buf)
    }
}

impl AsInner<c_int> for FileDesc {
    fn as_inner(&self) -> &c_int { &self.fd }
}

impl Drop for FileDesc {
    fn drop(&mut self) {
        // Note that errors are ignored when closing a file descriptor. The
        // reason for this is that if an error occurs we don't actually know if
        // the file descriptor was closed or not, and if we retried (for
        // something like EINTR), we might close another valid file descriptor
        // (opened after we closed ours.
        let _ = unsafe { libc::close(self.fd) };
    }
}
<commit_msg>Do not silently truncate offsets for `read_at`/`write_at` on emscripten<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.

#![unstable(reason = "not public", issue = "0", feature = "fd")]

use cmp;
use io::{self, Read};
use libc::{self, c_int, c_void, ssize_t};
use mem;
use sync::atomic::{AtomicBool, Ordering};
use sys::cvt;
use sys_common::AsInner;

#[derive(Debug)]
pub struct FileDesc {
    fd: c_int,
}

fn max_len() -> usize {
    // The maximum read limit on most posix-like systems is `SSIZE_MAX`,
    // with the man page quoting that if the count of bytes to read is
    // greater than `SSIZE_MAX` the result is "unspecified".
    //
    // On macOS, however, apparently the 64-bit libc is either buggy or
    // intentionally showing odd behavior by rejecting any read with a size
    // larger than or equal to INT_MAX. To handle both of these the read
    // size is capped on both platforms.
    if cfg!(target_os = "macos") {
        <c_int>::max_value() as usize - 1
    } else {
        <ssize_t>::max_value() as usize
    }
}

impl FileDesc {
    pub fn new(fd: c_int) -> FileDesc {
        FileDesc { fd: fd }
    }

    pub fn raw(&self) -> c_int { self.fd }

    /// Extracts the actual filedescriptor without closing it.
    pub fn into_raw(self) -> c_int {
        let fd = self.fd;
        mem::forget(self);
        fd
    }

    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
        let ret = cvt(unsafe {
            libc::read(self.fd,
                       buf.as_mut_ptr() as *mut c_void,
                       cmp::min(buf.len(), max_len()))
        })?;
        Ok(ret as usize)
    }

    pub fn read_to_end(&self, buf: &mut Vec<u8>) -> io::Result<usize> {
        let mut me = self;
        (&mut me).read_to_end(buf)
    }

    pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        #[cfg(target_os = "android")]
        use super::android::cvt_pread64;

        #[cfg(target_os = "emscripten")]
        unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
            -> io::Result<isize>
        {
            use convert::TryInto;
            use libc::pread64;
            // pread64 on emscripten actually takes a 32 bit offset
            if let Ok(o) = offset.try_into() {
                cvt(pread64(fd, buf, count, o))
            } else {
                Err(io::Error::new(io::ErrorKind::InvalidInput,
                                   "cannot pread >2GB"))
            }
        }

        #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
        unsafe fn cvt_pread64(fd: c_int, buf: *mut c_void, count: usize, offset: i64)
            -> io::Result<isize>
        {
            #[cfg(target_os = "linux")]
            use libc::pread64;
            #[cfg(not(target_os = "linux"))]
            use libc::pread as pread64;
            cvt(pread64(fd, buf, count, offset))
        }

        unsafe {
            cvt_pread64(self.fd,
                        buf.as_mut_ptr() as *mut c_void,
                        cmp::min(buf.len(), max_len()),
                        offset as i64)
                .map(|n| n as usize)
        }
    }

    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
        let ret = cvt(unsafe {
            libc::write(self.fd,
                        buf.as_ptr() as *const c_void,
                        cmp::min(buf.len(), max_len()))
        })?;
        Ok(ret as usize)
    }

    pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
        #[cfg(target_os = "android")]
        use super::android::cvt_pwrite64;

        #[cfg(target_os = "emscripten")]
        unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
            -> io::Result<isize>
        {
            use convert::TryInto;
            use libc::pwrite64;
            // pwrite64 on emscripten actually takes a 32 bit offset
            if let Ok(o) = offset.try_into() {
                cvt(pwrite64(fd, buf, count, o))
            } else {
                Err(io::Error::new(io::ErrorKind::InvalidInput,
                                   "cannot pwrite >2GB"))
            }
        }

        #[cfg(not(any(target_os = "android", target_os = "emscripten")))]
        unsafe fn cvt_pwrite64(fd: c_int, buf: *const c_void, count: usize, offset: i64)
            -> io::Result<isize>
        {
            #[cfg(target_os = "linux")]
            use libc::pwrite64;
            #[cfg(not(target_os = "linux"))]
            use libc::pwrite as pwrite64;
            cvt(pwrite64(fd, buf, count, offset))
        }

        unsafe {
            cvt_pwrite64(self.fd,
                         buf.as_ptr() as *const c_void,
                         cmp::min(buf.len(), max_len()),
                         offset as i64)
                .map(|n| n as usize)
        }
    }

    #[cfg(not(any(target_env = "newlib",
                  target_os = "solaris",
                  target_os = "emscripten",
                  target_os = "fuchsia",
                  target_os = "l4re",
                  target_os = "haiku")))]
    pub fn set_cloexec(&self) -> io::Result<()> {
        unsafe {
            cvt(libc::ioctl(self.fd, libc::FIOCLEX))?;
            Ok(())
        }
    }
    #[cfg(any(target_env = "newlib",
              target_os = "solaris",
              target_os = "emscripten",
              target_os = "fuchsia",
              target_os = "l4re",
              target_os = "haiku"))]
    pub fn set_cloexec(&self) -> io::Result<()> {
        unsafe {
            let previous = cvt(libc::fcntl(self.fd, libc::F_GETFD))?;
            let new = previous | libc::FD_CLOEXEC;
            if new != previous {
                cvt(libc::fcntl(self.fd, libc::F_SETFD, new))?;
            }
            Ok(())
        }
    }

    #[cfg(target_os = "linux")]
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        unsafe {
            let v = nonblocking as c_int;
            cvt(libc::ioctl(self.fd, libc::FIONBIO, &v))?;
            Ok(())
        }
    }

    #[cfg(not(target_os = "linux"))]
    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
        unsafe {
            let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?;
            let new = if nonblocking {
                previous | libc::O_NONBLOCK
            } else {
                previous & !libc::O_NONBLOCK
            };
            if new != previous {
                cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?;
            }
            Ok(())
        }
    }

    pub fn duplicate(&self) -> io::Result<FileDesc> {
        // We want to atomically duplicate this file descriptor and set the
        // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
        // flag, however, isn't supported on older Linux kernels (earlier than
        // 2.6.24).
        //
        // To detect this and ensure that CLOEXEC is still set, we
        // follow a strategy similar to musl [1] where if passing
        // F_DUPFD_CLOEXEC causes `fcntl` to return EINVAL it means it's not
        // supported (the third parameter, 0, is always valid), so we stop
        // trying that.
        //
        // Also note that Android doesn't have F_DUPFD_CLOEXEC, but get it to
        // resolve so we at least compile this.
        //
        // [1]: http://comments.gmane.org/gmane.linux.lib.musl.general/2963
        #[cfg(any(target_os = "android", target_os = "haiku"))]
        use libc::F_DUPFD as F_DUPFD_CLOEXEC;
        #[cfg(not(any(target_os = "android", target_os="haiku")))]
        use libc::F_DUPFD_CLOEXEC;

        let make_filedesc = |fd| {
            let fd = FileDesc::new(fd);
            fd.set_cloexec()?;
            Ok(fd)
        };
        static TRY_CLOEXEC: AtomicBool =
            AtomicBool::new(!cfg!(target_os = "android"));
        let fd = self.raw();
        if TRY_CLOEXEC.load(Ordering::Relaxed) {
            match cvt(unsafe { libc::fcntl(fd, F_DUPFD_CLOEXEC, 0) }) {
                // We *still* call the `set_cloexec` method as apparently some
                // linux kernel at some point stopped setting CLOEXEC even
                // though it reported doing so on F_DUPFD_CLOEXEC.
                Ok(fd) => {
                    return Ok(if cfg!(target_os = "linux") {
                        make_filedesc(fd)?
                    } else {
                        FileDesc::new(fd)
                    })
                }
                Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {
                    TRY_CLOEXEC.store(false, Ordering::Relaxed);
                }
                Err(e) => return Err(e),
            }
        }
        cvt(unsafe { libc::fcntl(fd, libc::F_DUPFD, 0) }).and_then(make_filedesc)
    }
}

impl<'a> Read for &'a FileDesc {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        (**self).read(buf)
    }
}

impl AsInner<c_int> for FileDesc {
    fn as_inner(&self) -> &c_int { &self.fd }
}

impl Drop for FileDesc {
    fn drop(&mut self) {
        // Note that errors are ignored when closing a file descriptor. The
        // reason for this is that if an error occurs we don't actually know if
        // the file descriptor was closed or not, and if we retried (for
        // something like EINTR), we might close another valid file descriptor
        // (opened after we closed ours.
        let _ = unsafe { libc::close(self.fd) };
    }
}
<|endoftext|>


<commit_before>// NB: this file is #include_str'ed into the compiler, re-parsed
// and injected into each crate the compiler builds. Keep it small.

mod intrinsic {
    #[legacy_exports];

    pub use rusti::visit_tydesc;

    // FIXME (#2712): remove this when the interface has settled and the
    // version in sys is no longer present.
    pub fn get_tydesc<T>() -> *TyDesc {
        rusti::get_tydesc::<T>() as *TyDesc
    }

    pub enum TyDesc = {
        size: uint,
        align: uint
        // Remaining fields not listed
    };

    trait TyVisitor {
        fn visit_bot() -> bool;
        fn visit_nil() -> bool;
        fn visit_bool() -> bool;

        fn visit_int() -> bool;
        fn visit_i8() -> bool;
        fn visit_i16() -> bool;
        fn visit_i32() -> bool;
        fn visit_i64() -> bool;

        fn visit_uint() -> bool;
        fn visit_u8() -> bool;
        fn visit_u16() -> bool;
        fn visit_u32() -> bool;
        fn visit_u64() -> bool;

        fn visit_float() -> bool;
        fn visit_f32() -> bool;
        fn visit_f64() -> bool;

        fn visit_char() -> bool;
        fn visit_str() -> bool;

        fn visit_estr_box() -> bool;
        fn visit_estr_uniq() -> bool;
        fn visit_estr_slice() -> bool;
        fn visit_estr_fixed(n: uint, sz: uint, align: uint) -> bool;

        fn visit_box(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_uniq(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_ptr(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_rptr(mtbl: uint, inner: *TyDesc) -> bool;

        fn visit_vec(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_unboxed_vec(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_evec_box(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_evec_uniq(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_evec_slice(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_evec_fixed(n: uint, sz: uint, align: uint,
                            mtbl: uint, inner: *TyDesc) -> bool;

        fn visit_enter_rec(n_fields: uint,
                           sz: uint, align: uint) -> bool;
        fn visit_rec_field(i: uint, name: &str,
                           mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_leave_rec(n_fields: uint,
                           sz: uint, align: uint) -> bool;

        fn visit_enter_class(n_fields: uint,
                             sz: uint, align: uint) -> bool;
        fn visit_class_field(i: uint, name: &str,
                             mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_leave_class(n_fields: uint,
                             sz: uint, align: uint) -> bool;

        fn visit_enter_tup(n_fields: uint,
                           sz: uint, align: uint) -> bool;
        fn visit_tup_field(i: uint, inner: *TyDesc) -> bool;
        fn visit_leave_tup(n_fields: uint,
                           sz: uint, align: uint) -> bool;

        fn visit_enter_enum(n_variants: uint,
                            sz: uint, align: uint) -> bool;
        fn visit_enter_enum_variant(variant: uint,
                                    disr_val: int,
                                    n_fields: uint,
                                    name: &str) -> bool;
        fn visit_enum_variant_field(i: uint, inner: *TyDesc) -> bool;
        fn visit_leave_enum_variant(variant: uint,
                                    disr_val: int,
                                    n_fields: uint,
                                    name: &str) -> bool;
        fn visit_leave_enum(n_variants: uint,
                            sz: uint, align: uint) -> bool;

        fn visit_enter_fn(purity: uint, proto: uint,
                          n_inputs: uint, retstyle: uint) -> bool;
        fn visit_fn_input(i: uint, mode: uint, inner: *TyDesc) -> bool;
        fn visit_fn_output(retstyle: uint, inner: *TyDesc) -> bool;
        fn visit_leave_fn(purity: uint, proto: uint,
                          n_inputs: uint, retstyle: uint) -> bool;

        fn visit_trait() -> bool;
        fn visit_var() -> bool;
        fn visit_var_integral() -> bool;
        fn visit_param(i: uint) -> bool;
        fn visit_self() -> bool;
        fn visit_type() -> bool;
        fn visit_opaque_box() -> bool;
        fn visit_constr(inner: *TyDesc) -> bool;
        fn visit_closure_ptr(ck: uint) -> bool;
    }

    #[abi = "rust-intrinsic"]
    extern mod rusti {
        #[legacy_exports];
        fn get_tydesc<T>() -> *();
        fn visit_tydesc(++td: *TyDesc, &&tv: TyVisitor);
    }
}
<commit_msg>Update FIXME number<commit_after>// NB: this file is #include_str'ed into the compiler, re-parsed
// and injected into each crate the compiler builds. Keep it small.

mod intrinsic {
    #[legacy_exports];

    pub use rusti::visit_tydesc;

    // FIXME (#3727): remove this when the interface has settled and the
    // version in sys is no longer present.
    pub fn get_tydesc<T>() -> *TyDesc {
        rusti::get_tydesc::<T>() as *TyDesc
    }

    pub enum TyDesc = {
        size: uint,
        align: uint
        // Remaining fields not listed
    };

    trait TyVisitor {
        fn visit_bot() -> bool;
        fn visit_nil() -> bool;
        fn visit_bool() -> bool;

        fn visit_int() -> bool;
        fn visit_i8() -> bool;
        fn visit_i16() -> bool;
        fn visit_i32() -> bool;
        fn visit_i64() -> bool;

        fn visit_uint() -> bool;
        fn visit_u8() -> bool;
        fn visit_u16() -> bool;
        fn visit_u32() -> bool;
        fn visit_u64() -> bool;

        fn visit_float() -> bool;
        fn visit_f32() -> bool;
        fn visit_f64() -> bool;

        fn visit_char() -> bool;
        fn visit_str() -> bool;

        fn visit_estr_box() -> bool;
        fn visit_estr_uniq() -> bool;
        fn visit_estr_slice() -> bool;
        fn visit_estr_fixed(n: uint, sz: uint, align: uint) -> bool;

        fn visit_box(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_uniq(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_ptr(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_rptr(mtbl: uint, inner: *TyDesc) -> bool;

        fn visit_vec(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_unboxed_vec(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_evec_box(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_evec_uniq(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_evec_slice(mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_evec_fixed(n: uint, sz: uint, align: uint,
                            mtbl: uint, inner: *TyDesc) -> bool;

        fn visit_enter_rec(n_fields: uint,
                           sz: uint, align: uint) -> bool;
        fn visit_rec_field(i: uint, name: &str,
                           mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_leave_rec(n_fields: uint,
                           sz: uint, align: uint) -> bool;

        fn visit_enter_class(n_fields: uint,
                             sz: uint, align: uint) -> bool;
        fn visit_class_field(i: uint, name: &str,
                             mtbl: uint, inner: *TyDesc) -> bool;
        fn visit_leave_class(n_fields: uint,
                             sz: uint, align: uint) -> bool;

        fn visit_enter_tup(n_fields: uint,
                           sz: uint, align: uint) -> bool;
        fn visit_tup_field(i: uint, inner: *TyDesc) -> bool;
        fn visit_leave_tup(n_fields: uint,
                           sz: uint, align: uint) -> bool;

        fn visit_enter_enum(n_variants: uint,
                            sz: uint, align: uint) -> bool;
        fn visit_enter_enum_variant(variant: uint,
                                    disr_val: int,
                                    n_fields: uint,
                                    name: &str) -> bool;
        fn visit_enum_variant_field(i: uint, inner: *TyDesc) -> bool;
        fn visit_leave_enum_variant(variant: uint,
                                    disr_val: int,
                                    n_fields: uint,
                                    name: &str) -> bool;
        fn visit_leave_enum(n_variants: uint,
                            sz: uint, align: uint) -> bool;

        fn visit_enter_fn(purity: uint, proto: uint,
                          n_inputs: uint, retstyle: uint) -> bool;
        fn visit_fn_input(i: uint, mode: uint, inner: *TyDesc) -> bool;
        fn visit_fn_output(retstyle: uint, inner: *TyDesc) -> bool;
        fn visit_leave_fn(purity: uint, proto: uint,
                          n_inputs: uint, retstyle: uint) -> bool;

        fn visit_trait() -> bool;
        fn visit_var() -> bool;
        fn visit_var_integral() -> bool;
        fn visit_param(i: uint) -> bool;
        fn visit_self() -> bool;
        fn visit_type() -> bool;
        fn visit_opaque_box() -> bool;
        fn visit_constr(inner: *TyDesc) -> bool;
        fn visit_closure_ptr(ck: uint) -> bool;
    }

    #[abi = "rust-intrinsic"]
    extern mod rusti {
        #[legacy_exports];
        fn get_tydesc<T>() -> *();
        fn visit_tydesc(++td: *TyDesc, &&tv: TyVisitor);
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove outdated comment<commit_after><|endoftext|>


<commit_before>#![feature(phase)]
#![crate_name = "terrain"]

extern crate cgmath;
extern crate gfx;
#[phase(plugin)]
extern crate gfx_macros;
extern crate glfw;
extern crate native;
extern crate time;
extern crate genmesh;
extern crate noise;

use cgmath::FixedArray;
use cgmath::{Matrix4, Point3, Vector3};
use cgmath::{Transform, AffineMatrix3};
use gfx::{Device, DeviceHelper};
use glfw::Context;
use genmesh::{Vertices, MapToVertices, Triangulate};
use genmesh::generators::Plane;
use time::precise_time_s;

use noise::source::Perlin;
use noise::source::Source;

#[vertex_format]
struct Vertex {
    #[name = "a_Pos"]
    pos: [f32, ..3],

    #[name = "a_Color"]
    color: [f32, ..3],
}

impl Clone for Vertex {
    fn clone(&self) -> Vertex {
        Vertex { pos: self.pos, color: self.color }
    }
}

// The shader_param attribute makes sure the following struct can be used to
// pass parameters to a shader. Its argument is the name of the type that will
// be generated to represent your the program. Search for link_program below, to
// see how it's used.
#[shader_param(MyProgram)]
struct Params {
    #[name = "u_Model"]
    model: [[f32, ..4], ..4],

    #[name = "u_View"]
    view: [[f32, ..4], ..4],

    #[name = "u_Proj"]
    proj: [[f32, ..4], ..4],
}

static VERTEX_SRC: gfx::ShaderSource = shaders! {
GLSL_120: b"
    #version 120

    attribute vec3 a_Pos;
    attribute vec3 a_Color;
    varying vec3 v_Color;

    uniform mat4 u_Model;
    uniform mat4 u_View;
    uniform mat4 u_Proj;

    void main() {
        v_Color = a_Color;
        gl_Position = u_Proj * u_View * u_Model * vec4(a_Pos, 1.0);
    }
"
GLSL_150: b"
    #version 150 core

    in vec3 a_Pos;
    in vec3 a_Color;
    out vec3 v_Color;

    uniform mat4 u_Model;
    uniform mat4 u_View;
    uniform mat4 u_Proj;

    void main() {
        v_Color = a_Color;
        gl_Position = u_Proj * u_View * u_Model * vec4(a_Pos, 1.0);
    }
"
};

static FRAGMENT_SRC: gfx::ShaderSource = shaders! {
GLSL_120: b"
    #version 120

    varying vec3 v_Color;
    out vec4 o_Color;

    void main() {
        o_Color = vec4(v_Color, 1.0);
    }
"
GLSL_150: b"
    #version 150 core

    in vec3 v_Color;
    out vec4 o_Color;

    void main() {
        o_Color = vec4(v_Color, 1.0);
    }
"
};

// We need to run on the main thread, so ensure we are using the `native` runtime. This is
// technically not needed, since this is the default, but it's not guaranteed.
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
     native::start(argc, argv, main)
}

fn calculate_color(height: f32) -> [f32, ..3] {
    if height > 8.0 {
        [0.9, 0.9, 0.9] // white
    } else if height > 0.0 {
        [0.7, 0.7, 0.7] // greay
    } else if height > -5.0 {
        [0.2, 0.7, 0.2] // green
    } else {
        [0.2, 0.2, 0.7] // blue
    }
}

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

    glfw.window_hint(glfw::ContextVersion(3, 2));
    glfw.window_hint(glfw::OpenglForwardCompat(true));
    glfw.window_hint(glfw::OpenglProfile(glfw::OpenGlCoreProfile));

    let (window, events) = glfw
        .create_window(800, 600, "Terrain example", glfw::Windowed)
        .expect("Failed to create GLFW window.");

    window.make_current();
    glfw.set_error_callback(glfw::FAIL_ON_ERRORS);
    window.set_key_polling(true);

    let (w, h) = window.get_framebuffer_size();
    let frame = gfx::Frame::new(w as u16, h as u16);

    let mut device = gfx::GlDevice::new(|s| glfw.get_proc_address(s));
    let mut renderer = device.create_renderer();

    let state = gfx::DrawState::new().depth(gfx::state::LessEqual, true);

    let noise = Perlin::new();

    let vertex_data: Vec<Vertex> = Plane::subdivide(256, 256)
        .vertex(|(x, y)| {
            let h = noise.get(x, y, 0.0) * 32.0;
            Vertex {
                pos: [-25.0 * x, 25.0 * y, h],
                color: calculate_color(h),
            }
        })
        .triangulate()
        .vertices()
        .collect();

    let mesh = device.create_mesh(vertex_data);
    let slice = mesh.get_slice(gfx::TriangleList);

    let prog: MyProgram = device
        .link_program(VERTEX_SRC.clone(), FRAGMENT_SRC.clone())
        .unwrap();

    let aspect = w as f32 / h as f32;
    let mut data = Params {
        model: Matrix4::identity().into_fixed(),
        view: Matrix4::identity().into_fixed(),
        proj: cgmath::perspective(cgmath::deg(60.0f32), aspect,
                                  0.1, 1000.0).into_fixed(),
    };

    let clear_data = gfx::ClearData {
        color: Some([0.3, 0.3, 0.3, 1.0]),
        depth: Some(1.0),
        stencil: None,
    };

    while !window.should_close() {
        glfw.poll_events();
        for (_, event) in glfw::flush_messages(&events) {
            match event {
                glfw::KeyEvent(glfw::KeyEscape, _, glfw::Press, _) =>
                    window.set_should_close(true),
                _ => {},
            }
        }

        let time = precise_time_s() as f32;
        let x = time.sin();
        let y = time.cos();
        let view: AffineMatrix3<f32> = Transform::look_at(
            &Point3::new(x * 32.0, y * 32.0, 16.0),
            &Point3::new(0.0, 0.0, 0.0),
            &Vector3::unit_z(),
        );
        data.view = view.mat.into_fixed();

        renderer.reset();
        renderer.clear(clear_data, &frame);
        renderer.draw(&mesh, slice, &frame, (&prog, &data), &state).unwrap();
        device.submit(renderer.as_buffer());

        window.swap_buffers();
    }
}
<commit_msg>flipped plane to match latest genmesh<commit_after>#![feature(phase)]
#![crate_name = "terrain"]

extern crate cgmath;
extern crate gfx;
#[phase(plugin)]
extern crate gfx_macros;
extern crate glfw;
extern crate native;
extern crate time;
extern crate genmesh;
extern crate noise;

use cgmath::FixedArray;
use cgmath::{Matrix4, Point3, Vector3};
use cgmath::{Transform, AffineMatrix3};
use gfx::{Device, DeviceHelper};
use glfw::Context;
use genmesh::{Vertices, MapToVertices, Triangulate};
use genmesh::generators::Plane;
use time::precise_time_s;

use noise::source::Perlin;
use noise::source::Source;

#[vertex_format]
struct Vertex {
    #[name = "a_Pos"]
    pos: [f32, ..3],

    #[name = "a_Color"]
    color: [f32, ..3],
}

impl Clone for Vertex {
    fn clone(&self) -> Vertex {
        Vertex { pos: self.pos, color: self.color }
    }
}

// The shader_param attribute makes sure the following struct can be used to
// pass parameters to a shader. Its argument is the name of the type that will
// be generated to represent your the program. Search for link_program below, to
// see how it's used.
#[shader_param(MyProgram)]
struct Params {
    #[name = "u_Model"]
    model: [[f32, ..4], ..4],

    #[name = "u_View"]
    view: [[f32, ..4], ..4],

    #[name = "u_Proj"]
    proj: [[f32, ..4], ..4],
}

static VERTEX_SRC: gfx::ShaderSource = shaders! {
GLSL_120: b"
    #version 120

    attribute vec3 a_Pos;
    attribute vec3 a_Color;
    varying vec3 v_Color;

    uniform mat4 u_Model;
    uniform mat4 u_View;
    uniform mat4 u_Proj;

    void main() {
        v_Color = a_Color;
        gl_Position = u_Proj * u_View * u_Model * vec4(a_Pos, 1.0);
    }
"
GLSL_150: b"
    #version 150 core

    in vec3 a_Pos;
    in vec3 a_Color;
    out vec3 v_Color;

    uniform mat4 u_Model;
    uniform mat4 u_View;
    uniform mat4 u_Proj;

    void main() {
        v_Color = a_Color;
        gl_Position = u_Proj * u_View * u_Model * vec4(a_Pos, 1.0);
    }
"
};

static FRAGMENT_SRC: gfx::ShaderSource = shaders! {
GLSL_120: b"
    #version 120

    varying vec3 v_Color;
    out vec4 o_Color;

    void main() {
        o_Color = vec4(v_Color, 1.0);
    }
"
GLSL_150: b"
    #version 150 core

    in vec3 v_Color;
    out vec4 o_Color;

    void main() {
        o_Color = vec4(v_Color, 1.0);
    }
"
};

// We need to run on the main thread, so ensure we are using the `native` runtime. This is
// technically not needed, since this is the default, but it's not guaranteed.
#[start]
fn start(argc: int, argv: *const *const u8) -> int {
     native::start(argc, argv, main)
}

fn calculate_color(height: f32) -> [f32, ..3] {
    if height > 8.0 {
        [0.9, 0.9, 0.9] // white
    } else if height > 0.0 {
        [0.7, 0.7, 0.7] // greay
    } else if height > -5.0 {
        [0.2, 0.7, 0.2] // green
    } else {
        [0.2, 0.2, 0.7] // blue
    }
}

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

    glfw.window_hint(glfw::ContextVersion(3, 2));
    glfw.window_hint(glfw::OpenglForwardCompat(true));
    glfw.window_hint(glfw::OpenglProfile(glfw::OpenGlCoreProfile));

    let (window, events) = glfw
        .create_window(800, 600, "Terrain example", glfw::Windowed)
        .expect("Failed to create GLFW window.");

    window.make_current();
    glfw.set_error_callback(glfw::FAIL_ON_ERRORS);
    window.set_key_polling(true);

    let (w, h) = window.get_framebuffer_size();
    let frame = gfx::Frame::new(w as u16, h as u16);

    let mut device = gfx::GlDevice::new(|s| glfw.get_proc_address(s));
    let mut renderer = device.create_renderer();

    let state = gfx::DrawState::new().depth(gfx::state::LessEqual, true);

    let noise = Perlin::new();
    let vertex_data: Vec<Vertex> = Plane::subdivide(256, 256)
        .vertex(|(x, y)| {
            let h = noise.get(x, y, 0.0) * 32.0;
            Vertex {
                pos: [25.0 * x, 25.0 * y, h],
                color: calculate_color(h),
            }
        })
        .triangulate()
        .vertices()
        .collect();

    let mesh = device.create_mesh(vertex_data);
    let slice = mesh.get_slice(gfx::TriangleList);

    let prog: MyProgram = device
        .link_program(VERTEX_SRC.clone(), FRAGMENT_SRC.clone())
        .unwrap();

    let aspect = w as f32 / h as f32;
    let mut data = Params {
        model: Matrix4::identity().into_fixed(),
        view: Matrix4::identity().into_fixed(),
        proj: cgmath::perspective(cgmath::deg(60.0f32), aspect,
                                  0.1, 1000.0).into_fixed(),
    };

    let clear_data = gfx::ClearData {
        color: Some([0.3, 0.3, 0.3, 1.0]),
        depth: Some(1.0),
        stencil: None,
    };

    while !window.should_close() {
        glfw.poll_events();
        for (_, event) in glfw::flush_messages(&events) {
            match event {
                glfw::KeyEvent(glfw::KeyEscape, _, glfw::Press, _) =>
                    window.set_should_close(true),
                _ => {},
            }
        }

        let time = precise_time_s() as f32;
        let x = time.sin();
        let y = time.cos();
        let view: AffineMatrix3<f32> = Transform::look_at(
            &Point3::new(x * 32.0, y * 32.0, 16.0),
            &Point3::new(0.0, 0.0, 0.0),
            &Vector3::unit_z(),
        );
        data.view = view.mat.into_fixed();

        renderer.reset();
        renderer.clear(clear_data, &frame);
        renderer.draw(&mesh, slice, &frame, (&prog, &data), &state).unwrap();
        device.submit(renderer.as_buffer());

        window.swap_buffers();
    }
}
<|endoftext|>


<commit_before><commit_msg>Support for vars file change<commit_after><|endoftext|>


<commit_before>

// lib/option::rs
tag t[T] { none; some(T); }

type operator[T, U] = fn(&T) -> U ;

fn get[T](&t[T] opt) -> T {
    ret alt (opt) { case (some(?x)) { x } case (none) { fail } };
}

fn map[T, U](&operator[T, U] f, &t[T] opt) -> t[U] {
    ret alt (opt) {
            case (some(?x)) { some[U](f(x)) }
            case (none) { none[U] }
        };
}

fn is_none[T](&t[T] opt) -> bool {
    ret alt (opt) { case (none) { true } case (some(_)) { false } };
}

fn from_maybe[T](&T def, &t[T] opt) -> T {
    auto f = bind util::id[T](_);
    ret maybe[T, T](def, f, opt);
}

fn maybe[T, U](&U def, fn(&T) -> U  f, &t[T] opt) -> U {
    ret alt (opt) { case (none) { def } case (some(?t)) { f(t) } };
}

// Can be defined in terms of the above when/if we have const bind.
fn may[T](fn(&T)  f, &t[T] opt) {
    alt (opt) { case (none) {/* nothing */ } case (some(?t)) { f(t); } }
}
// 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: Add option::is_some<commit_after>

// lib/option::rs
tag t[T] { none; some(T); }

type operator[T, U] = fn(&T) -> U ;

fn get[T](&t[T] opt) -> T {
    ret alt (opt) { case (some(?x)) { x } case (none) { fail } };
}

fn map[T, U](&operator[T, U] f, &t[T] opt) -> t[U] {
    ret alt (opt) {
            case (some(?x)) { some[U](f(x)) }
            case (none) { none[U] }
        };
}

fn is_none[T](&t[T] opt) -> bool {
    ret alt (opt) { case (none) { true } case (some(_)) { false } };
}

fn is_some[T](&t[T] opt) -> bool {
    ret !is_none(opt);
}

fn from_maybe[T](&T def, &t[T] opt) -> T {
    auto f = bind util::id[T](_);
    ret maybe[T, T](def, f, opt);
}

fn maybe[T, U](&U def, fn(&T) -> U  f, &t[T] opt) -> U {
    ret alt (opt) { case (none) { def } case (some(?t)) { f(t) } };
}

// Can be defined in terms of the above when/if we have const bind.
fn may[T](fn(&T)  f, &t[T] opt) {
    alt (opt) { case (none) {/* nothing */ } case (some(?t)) { f(t); } }
}
// 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>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! # The Rust standard library
//!
//! The Rust standard library is a group of interrelated modules defining
//! the core language traits, operations on built-in data types, collections,
//! platform abstractions, the task scheduler, runtime support for language
//! features and other common functionality.
//!
//! `std` includes modules corresponding to each of the integer types,
//! each of the floating point types, the `bool` type, tuples, characters,
//! strings (`str`), vectors (`vec`), managed boxes (`managed`), owned
//! boxes (`owned`), and unsafe pointers and references (`ptr`, `borrowed`).
//! Additionally, `std` provides pervasive types (`option` and `result`),
//! task creation and communication primitives (`task`, `comm`), platform
//! abstractions (`os` and `path`), basic I/O abstractions (`io`), common
//! traits (`kinds`, `ops`, `cmp`, `num`, `to_str`), and complete bindings
//! to the C standard library (`libc`).
//!
//! # Standard library injection and the Rust prelude
//!
//! `std` is imported at the topmost level of every crate by default, as
//! if the first line of each crate was
//!
//!     extern mod std;
//!
//! This means that the contents of std can be accessed from any context
//! with the `std::` path prefix, as in `use std::vec`, `use std::task::spawn`,
//! etc.
//!
//! Additionally, `std` contains a `prelude` module that reexports many of the
//! most common types, traits and functions. The contents of the prelude are
//! imported into every *module* by default.  Implicitly, all modules behave as if
//! they contained the following prologue:
//!
//!     use std::prelude::*;

#[crate_id = "std#0.10-pre"];
#[comment = "The Rust standard library"];
#[license = "MIT/ASL2"];
#[crate_type = "rlib"];
#[crate_type = "dylib"];
#[doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
      html_favicon_url = "http://www.rust-lang.org/favicon.ico",
      html_root_url = "http://static.rust-lang.org/doc/master")];

#[feature(macro_rules, globs, asm, managed_boxes, thread_local, link_args, simd)];

// Don't link to std. We are std.
#[no_std];

#[deny(non_camel_case_types)];
#[deny(missing_doc)];
#[allow(unknown_features)];

// When testing libstd, bring in libuv as the I/O backend so tests can print
// things and all of the std::io tests have an I/O interface to run on top
// of
#[cfg(test)] extern mod rustuv = "rustuv";
#[cfg(test)] extern mod native = "native";
#[cfg(test)] extern mod green = "green";

// Make extra accessible for benchmarking
#[cfg(test)] extern mod extra = "extra";

// Make std testable by not duplicating lang items. See #2912
#[cfg(test)] extern mod realstd = "std";
#[cfg(test)] pub use kinds = realstd::kinds;
#[cfg(test)] pub use ops = realstd::ops;
#[cfg(test)] pub use cmp = realstd::cmp;

mod macros;

mod rtdeps;

/* The Prelude. */

pub mod prelude;

/* Primitive types */

#[path = "num/float_macros.rs"] mod float_macros;
#[path = "num/int_macros.rs"]   mod int_macros;
#[path = "num/uint_macros.rs"]  mod uint_macros;

#[path = "num/int.rs"]  pub mod int;
#[path = "num/i8.rs"]   pub mod i8;
#[path = "num/i16.rs"]  pub mod i16;
#[path = "num/i32.rs"]  pub mod i32;
#[path = "num/i64.rs"]  pub mod i64;

#[path = "num/uint.rs"] pub mod uint;
#[path = "num/u8.rs"]   pub mod u8;
#[path = "num/u16.rs"]  pub mod u16;
#[path = "num/u32.rs"]  pub mod u32;
#[path = "num/u64.rs"]  pub mod u64;

#[path = "num/f32.rs"]   pub mod f32;
#[path = "num/f64.rs"]   pub mod f64;

pub mod unit;
pub mod bool;
pub mod char;
pub mod tuple;

pub mod vec;
pub mod vec_ng;
pub mod at_vec;
pub mod str;

pub mod ascii;
pub mod send_str;

pub mod ptr;
pub mod owned;
pub mod managed;
pub mod reference;
pub mod rc;
pub mod gc;

/* Core language traits */

#[cfg(not(test))] pub mod kinds;
#[cfg(not(test))] pub mod ops;
#[cfg(not(test))] pub mod cmp;

/* Common traits */

pub mod from_str;
pub mod num;
pub mod iter;
pub mod to_str;
pub mod to_bytes;
pub mod clone;
pub mod hash;
pub mod container;
pub mod default;
pub mod any;

/* Common data structures */

pub mod option;
pub mod result;
pub mod hashmap;
pub mod cell;
pub mod trie;

/* Tasks and communication */

pub mod task;
pub mod comm;
pub mod local_data;
pub mod sync;

/* Runtime and platform support */

#[unstable]
pub mod libc;
pub mod c_str;
pub mod os;
pub mod io;
pub mod path;
pub mod rand;
pub mod run;
pub mod cast;
pub mod fmt;
pub mod cleanup;
#[deprecated]
pub mod condition;
pub mod logging;
pub mod util;
pub mod mem;

/* Unsupported interfaces */

#[unstable]
pub mod repr;
#[unstable]
pub mod reflect;

// Private APIs
#[unstable]
pub mod unstable;

/* For internal use, not exported */

mod unicode;
#[path = "num/cmath.rs"]
mod cmath;

// FIXME #7809: This shouldn't be pub, and it should be reexported under 'unstable'
// but name resolution doesn't work without it being pub.
#[unstable]
pub mod rt;

// A curious inner-module that's not exported that contains the binding
// 'std' so that macro-expanded references to std::error and such
// can be resolved within libstd.
#[doc(hidden)]
mod std {
    pub use clone;
    pub use cmp;
    pub use comm;
    pub use condition;
    pub use fmt;
    pub use io;
    pub use kinds;
    pub use local_data;
    pub use logging;
    pub use logging;
    pub use option;
    pub use os;
    pub use rt;
    pub use str;
    pub use to_bytes;
    pub use to_str;
    pub use unstable;
}
<commit_msg>Remove double-use of logging.<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! # The Rust standard library
//!
//! The Rust standard library is a group of interrelated modules defining
//! the core language traits, operations on built-in data types, collections,
//! platform abstractions, the task scheduler, runtime support for language
//! features and other common functionality.
//!
//! `std` includes modules corresponding to each of the integer types,
//! each of the floating point types, the `bool` type, tuples, characters,
//! strings (`str`), vectors (`vec`), managed boxes (`managed`), owned
//! boxes (`owned`), and unsafe pointers and references (`ptr`, `borrowed`).
//! Additionally, `std` provides pervasive types (`option` and `result`),
//! task creation and communication primitives (`task`, `comm`), platform
//! abstractions (`os` and `path`), basic I/O abstractions (`io`), common
//! traits (`kinds`, `ops`, `cmp`, `num`, `to_str`), and complete bindings
//! to the C standard library (`libc`).
//!
//! # Standard library injection and the Rust prelude
//!
//! `std` is imported at the topmost level of every crate by default, as
//! if the first line of each crate was
//!
//!     extern mod std;
//!
//! This means that the contents of std can be accessed from any context
//! with the `std::` path prefix, as in `use std::vec`, `use std::task::spawn`,
//! etc.
//!
//! Additionally, `std` contains a `prelude` module that reexports many of the
//! most common types, traits and functions. The contents of the prelude are
//! imported into every *module* by default.  Implicitly, all modules behave as if
//! they contained the following prologue:
//!
//!     use std::prelude::*;

#[crate_id = "std#0.10-pre"];
#[comment = "The Rust standard library"];
#[license = "MIT/ASL2"];
#[crate_type = "rlib"];
#[crate_type = "dylib"];
#[doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
      html_favicon_url = "http://www.rust-lang.org/favicon.ico",
      html_root_url = "http://static.rust-lang.org/doc/master")];

#[feature(macro_rules, globs, asm, managed_boxes, thread_local, link_args, simd)];

// Don't link to std. We are std.
#[no_std];

#[deny(non_camel_case_types)];
#[deny(missing_doc)];
#[allow(unknown_features)];

// When testing libstd, bring in libuv as the I/O backend so tests can print
// things and all of the std::io tests have an I/O interface to run on top
// of
#[cfg(test)] extern mod rustuv = "rustuv";
#[cfg(test)] extern mod native = "native";
#[cfg(test)] extern mod green = "green";

// Make extra accessible for benchmarking
#[cfg(test)] extern mod extra = "extra";

// Make std testable by not duplicating lang items. See #2912
#[cfg(test)] extern mod realstd = "std";
#[cfg(test)] pub use kinds = realstd::kinds;
#[cfg(test)] pub use ops = realstd::ops;
#[cfg(test)] pub use cmp = realstd::cmp;

mod macros;

mod rtdeps;

/* The Prelude. */

pub mod prelude;

/* Primitive types */

#[path = "num/float_macros.rs"] mod float_macros;
#[path = "num/int_macros.rs"]   mod int_macros;
#[path = "num/uint_macros.rs"]  mod uint_macros;

#[path = "num/int.rs"]  pub mod int;
#[path = "num/i8.rs"]   pub mod i8;
#[path = "num/i16.rs"]  pub mod i16;
#[path = "num/i32.rs"]  pub mod i32;
#[path = "num/i64.rs"]  pub mod i64;

#[path = "num/uint.rs"] pub mod uint;
#[path = "num/u8.rs"]   pub mod u8;
#[path = "num/u16.rs"]  pub mod u16;
#[path = "num/u32.rs"]  pub mod u32;
#[path = "num/u64.rs"]  pub mod u64;

#[path = "num/f32.rs"]   pub mod f32;
#[path = "num/f64.rs"]   pub mod f64;

pub mod unit;
pub mod bool;
pub mod char;
pub mod tuple;

pub mod vec;
pub mod vec_ng;
pub mod at_vec;
pub mod str;

pub mod ascii;
pub mod send_str;

pub mod ptr;
pub mod owned;
pub mod managed;
pub mod reference;
pub mod rc;
pub mod gc;

/* Core language traits */

#[cfg(not(test))] pub mod kinds;
#[cfg(not(test))] pub mod ops;
#[cfg(not(test))] pub mod cmp;

/* Common traits */

pub mod from_str;
pub mod num;
pub mod iter;
pub mod to_str;
pub mod to_bytes;
pub mod clone;
pub mod hash;
pub mod container;
pub mod default;
pub mod any;

/* Common data structures */

pub mod option;
pub mod result;
pub mod hashmap;
pub mod cell;
pub mod trie;

/* Tasks and communication */

pub mod task;
pub mod comm;
pub mod local_data;
pub mod sync;

/* Runtime and platform support */

#[unstable]
pub mod libc;
pub mod c_str;
pub mod os;
pub mod io;
pub mod path;
pub mod rand;
pub mod run;
pub mod cast;
pub mod fmt;
pub mod cleanup;
#[deprecated]
pub mod condition;
pub mod logging;
pub mod util;
pub mod mem;

/* Unsupported interfaces */

#[unstable]
pub mod repr;
#[unstable]
pub mod reflect;

// Private APIs
#[unstable]
pub mod unstable;

/* For internal use, not exported */

mod unicode;
#[path = "num/cmath.rs"]
mod cmath;

// FIXME #7809: This shouldn't be pub, and it should be reexported under 'unstable'
// but name resolution doesn't work without it being pub.
#[unstable]
pub mod rt;

// A curious inner-module that's not exported that contains the binding
// 'std' so that macro-expanded references to std::error and such
// can be resolved within libstd.
#[doc(hidden)]
mod std {
    pub use clone;
    pub use cmp;
    pub use comm;
    pub use condition;
    pub use fmt;
    pub use io;
    pub use kinds;
    pub use local_data;
    pub use logging;
    pub use option;
    pub use os;
    pub use rt;
    pub use str;
    pub use to_bytes;
    pub use to_str;
    pub use unstable;
}
<|endoftext|>


<commit_before><commit_msg>Add regression test<commit_after>// Regression test for #5233

#![feature(const_generics)]
#![allow(incomplete_features)]
#![warn(clippy::indexing_slicing, clippy::iter_cloned_collect)]

pub struct KotomineArray<T, const N: usize> {
    arr: [T; N],
}

impl<T: std::clone::Clone, const N: usize> KotomineArray<T, N> {
    pub fn ice(self) {
        let _ = self.arr[..];
        let _ = self.arr.iter().cloned().collect::<Vec<_>>();
    }
}

fn main() {}
<|endoftext|>


<commit_before>extern crate regex;
use std::env::*;
use std::fs::File;
use std::path::Path;
use std::error::Error;
use std::io::prelude::*;

#[derive(Clone, Debug)]
pub struct AWSCredentials {
    key: String,
    secret: String
}

#[derive(Debug)]
enum CredentialErr {
    NoEnvironmentVariables,
    NoCredentialsFile,
}

struct ProfileCredentialsError;

impl AWSCredentials {
    pub fn new(key:&str, secret:&str) -> AWSCredentials {
        AWSCredentials {
            key: key.to_string(),
            secret: secret.to_string()
        }
    }

    pub fn get_aws_access_key_id(&self) -> &str {
    	&self.key
    }

    pub fn get_aws_secret_key(&self) -> &str {
    	&self.secret
    }
}

pub trait AWSCredentialsProvider {
	fn get_credentials(&self) -> &AWSCredentials;
	fn refresh(&mut self);
}

// class for environment
pub struct EnvironmentCredentialsProvider {
    credentials: AWSCredentials
}

impl AWSCredentialsProvider for EnvironmentCredentialsProvider {
	fn refresh(&mut self) {
        let env_key = match var("AWS_ACCESS_KEY_ID") {
            Ok(val) => val,
            Err(_) => {println!("couldn't find access key");
                "".to_string() }
        };
        let env_secret = match var("AWS_SECRET_KEY") {
            Ok(val) => val,
            Err(_) => {println!("couldn't find secret key");
                "".to_string() }
        };

        if env_key.len() <= 0 || env_secret.len() <= 0 {
            panic!("Couldn't find credentials in environment.");
            // return Err(CredentialErr::NoEnvironmentVariables);
        };

        self.credentials = AWSCredentials{key: env_key, secret: env_secret};
	}

	fn get_credentials(&self) -> &AWSCredentials {
		return &self.credentials;
	}
}

// class for file based
pub struct FileCredentialsProvider {
    credentials: AWSCredentials
}

impl AWSCredentialsProvider for FileCredentialsProvider {
	fn refresh(&mut self) {
        let path = Path::new("sample-credentials");
        let display = path.display();

        let mut file = match File::open(&path) {
            Err(why) => panic!("couldn't open {}: {}", display,
                                                       Error::description(&why)),
            Ok(file) => file,
        };

        let mut contents = String::new();
        match file.read_to_string(&mut contents) {
            Err(why) => panic!("couldn't read {}: {}", display,
                                                       Error::description(&why)),
            Ok(_) => {},
        }

        let profile_key = String::from("ACCESS_KEY");
        let secret_key = String::from("SECRET_KEY");

        self.credentials = AWSCredentials{ key: profile_key, secret: secret_key };
    }

    fn get_credentials(&self) -> &AWSCredentials {
		return &self.credentials;
	}
}

// class for IAM role
pub struct IAMRoleCredentialsProvider {
    credentials: AWSCredentials
}

pub struct DefaultAWSCredentialsProviderChain {
    credentials: AWSCredentials
}

impl DefaultAWSCredentialsProviderChain {
    pub fn new() -> DefaultAWSCredentialsProviderChain {
        return DefaultAWSCredentialsProviderChain {credentials: AWSCredentials{ key: "a".to_string(), secret: "b".to_string() } };
    }

    pub fn get_credentials(&self) -> &AWSCredentials {
        return &self.credentials;
    }

    pub fn refresh(&mut self) {
        // fetch creds in order: env, file, IAM
        // pretend we got credentials here
        self.credentials = AWSCredentials{ key: "a2".to_string(), secret: "b2".to_string() };
    }
}

// From http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs
// 1. environment variables
// 2. central credentials file (named profile is supplied, otherwise default)
// 3. IAM role (if running on an EC2 instance)
// impl DefaultAWSCredentialsProviderChain {
//
// }
<commit_msg>Closer to working chaining.<commit_after>extern crate regex;
use std::env::*;
use std::fs::File;
use std::path::Path;
use std::error::Error;
use std::io::prelude::*;

#[derive(Clone, Debug)]
pub struct AWSCredentials {
    key: String,
    secret: String
}

#[derive(Debug)]
enum CredentialErr {
    NoEnvironmentVariables,
    NoCredentialsFile,
}

struct ProfileCredentialsError;

impl AWSCredentials {
    pub fn new(key:&str, secret:&str) -> AWSCredentials {
        AWSCredentials {
            key: key.to_string(),
            secret: secret.to_string()
        }
    }

    pub fn get_aws_access_key_id(&self) -> &str {
    	&self.key
    }

    pub fn get_aws_secret_key(&self) -> &str {
    	&self.secret
    }
}

pub trait AWSCredentialsProvider {
    fn new() -> Self;
	fn get_credentials(&self) -> &AWSCredentials;
	fn refresh(&mut self);
}

// class for environment
pub struct EnvironmentCredentialsProvider {
    credentials: AWSCredentials
}

impl AWSCredentialsProvider for EnvironmentCredentialsProvider {
    fn new() -> EnvironmentCredentialsProvider {
        return EnvironmentCredentialsProvider {credentials: AWSCredentials{ key: "a".to_string(), secret: "b".to_string() } };
    }

	fn refresh(&mut self) {
        let env_key = match var("AWS_ACCESS_KEY_ID") {
            Ok(val) => val,
            Err(_) => {println!("couldn't find access key");
                "".to_string() }
        };
        let env_secret = match var("AWS_SECRET_KEY") {
            Ok(val) => val,
            Err(_) => {println!("couldn't find secret key");
                "".to_string() }
        };

        if env_key.len() <= 0 || env_secret.len() <= 0 {
            panic!("Couldn't find credentials in environment.");
            // return Err(CredentialErr::NoEnvironmentVariables);
        };

        self.credentials = AWSCredentials{key: env_key, secret: env_secret};
	}

	fn get_credentials(&self) -> &AWSCredentials {
		return &self.credentials;
	}
}

// class for file based
pub struct FileCredentialsProvider {
    credentials: AWSCredentials
}

impl AWSCredentialsProvider for FileCredentialsProvider {
    fn new() -> FileCredentialsProvider {
        return FileCredentialsProvider {credentials: AWSCredentials{ key: "a".to_string(), secret: "b".to_string() } };
    }

	fn refresh(&mut self) {
        let path = Path::new("sample-credentials");
        let display = path.display();

        let mut file = match File::open(&path) {
            Err(why) => panic!("couldn't open {}: {}", display,
                                                       Error::description(&why)),
            Ok(file) => file,
        };

        let mut contents = String::new();
        match file.read_to_string(&mut contents) {
            Err(why) => panic!("couldn't read {}: {}", display,
                                                       Error::description(&why)),
            Ok(_) => {},
        }

        let profile_key = String::from("ACCESS_KEY");
        let secret_key = String::from("SECRET_KEY");

        self.credentials = AWSCredentials{ key: profile_key, secret: secret_key };
    }

    fn get_credentials(&self) -> &AWSCredentials {
		return &self.credentials;
	}
}

// class for IAM role
pub struct IAMRoleCredentialsProvider {
    credentials: AWSCredentials
}

pub struct DefaultAWSCredentialsProviderChain {
    credentials: AWSCredentials
}

impl DefaultAWSCredentialsProviderChain {
    pub fn new() -> DefaultAWSCredentialsProviderChain {
        return DefaultAWSCredentialsProviderChain {credentials: AWSCredentials{ key: "a".to_string(), secret: "b".to_string() } };
    }

    pub fn get_credentials(&self) -> &AWSCredentials {
        return &self.credentials;
    }

    pub fn refresh(&mut self) {
        // fetch creds in order: env, file, IAM
        // pretend we got credentials here
        self.credentials = AWSCredentials{ key: "a2".to_string(), secret: "b2".to_string() };

        let mut env_provider = EnvironmentCredentialsProvider::new();
        env_provider.refresh();
        let credentials = env_provider.get_credentials();
        println!("creds from env: {}, {}", credentials.get_aws_access_key_id(), credentials.get_aws_secret_key());
        // if not blank, use it to populate self.credentials

        if credentials.get_aws_access_key_id().len() <= 0 || credentials.get_aws_secret_key().len() <= 0 {
            panic!("Couldn't find credentials in environment.");
            // return Err(CredentialErr::NoEnvironmentVariables);
        };
        self.credentials = AWSCredentials{ key: credentials.get_aws_access_key_id().to_string(), secret: credentials.get_aws_secret_key().to_string() }; //credentials.clone();
    }
}

// From http://blogs.aws.amazon.com/security/post/Tx3D6U6WSFGOK2H/A-New-and-Standardized-Way-to-Manage-Credentials-in-the-AWS-SDKs
// 1. environment variables
// 2. central credentials file (named profile is supplied, otherwise default)
// 3. IAM role (if running on an EC2 instance)
// impl DefaultAWSCredentialsProviderChain {
//
// }
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 1074<commit_after>// https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/
pub fn num_submatrix_sum_target(matrix: Vec<Vec<i32>>, target: i32) -> i32 {
    todo!()
}

fn main() {
    println!(
        "{}",
        num_submatrix_sum_target(vec![vec![0, 1, 0], vec![1, 1, 1], vec![0, 1, 0]], 0)
    ); // 4
    println!(
        "{}",
        num_submatrix_sum_target(vec![vec![1, -1], vec![-1, 1]], 0)
    ); // 5
    println!("{}", num_submatrix_sum_target(vec![vec![904]], 0)); // 0
}
<|endoftext|>