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

//! Gecko's restyle damage computation (aka change hints, aka `nsChangeHint`).

use gecko_bindings::bindings;
use gecko_bindings::structs;
use gecko_bindings::structs::{nsChangeHint, nsStyleContext, nsStyleStructID};
use matching::{StyleChange, StyleDifference};
use properties::ComputedValues;
use servo_arc::Arc;
use std::ops::{BitAnd, BitOr, BitOrAssign, Not};

/// The representation of Gecko's restyle damage is just a wrapper over
/// `nsChangeHint`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GeckoRestyleDamage(nsChangeHint);

impl GeckoRestyleDamage {
    /// Trivially construct a new `GeckoRestyleDamage`.
    pub fn new(raw: nsChangeHint) -> Self {
        GeckoRestyleDamage(raw)
    }

    /// Get the inner change hint for this damage.
    pub fn as_change_hint(&self) -> nsChangeHint {
        self.0
    }

    /// Get an empty change hint, that is (`nsChangeHint(0)`).
    pub fn empty() -> Self {
        GeckoRestyleDamage(nsChangeHint(0))
    }

    /// Returns whether this restyle damage represents the empty damage.
    pub fn is_empty(&self) -> bool {
        self.0 == nsChangeHint(0)
    }

    /// Computes the `StyleDifference` (including the appropriate change hint)
    /// given an old style (in the form of a `nsStyleContext`, and a new style
    /// (in the form of `ComputedValues`).
    ///
    /// Note that we could in theory just get two `ComputedValues` here and diff
    /// them, but Gecko has an interesting optimization when they mark accessed
    /// structs, so they effectively only diff structs that have ever been
    /// accessed from layout.
    pub fn compute_style_difference(
        source: &nsStyleContext,
        old_style: &ComputedValues,
        new_style: &Arc<ComputedValues>,
    ) -> StyleDifference {
        let mut any_style_changed: bool = false;
        let hint = unsafe {
            bindings::Gecko_CalcStyleDifference(old_style,
                                                new_style,
                                                source.mBits,
                                                &mut any_style_changed)
        };
        let change = if any_style_changed { StyleChange::Changed } else { StyleChange::Unchanged };
        StyleDifference::new(GeckoRestyleDamage(hint), change)
    }

    /// Computes the `StyleDifference` between the two `ComputedValues` objects
    /// for the case where the old and new style are both `display: none`.
    ///
    /// In general we don't need to generate damage for such elements, but we
    /// do need to generate a frame reconstruction for `-moz-binding` changes,
    /// so that we can start loading the new binding.
    pub fn compute_undisplayed_style_difference(
        old_style: &ComputedValues,
        new_style: &ComputedValues,
    ) -> StyleDifference {
        let mut any_style_changed: bool = false;

        // Just compute the Display struct's difference.
        let display_struct_bit = 1 << (nsStyleStructID::eStyleStruct_Display as u32);
        let hint = unsafe {
            bindings::Gecko_CalcStyleDifference(old_style,
                                                new_style,
                                                display_struct_bit,
                                                &mut any_style_changed)
        };

        // Only pay attention to a reconstruct change hint.
        let damage = GeckoRestyleDamage(hint) & Self::reconstruct();

        let change = if damage.is_empty() { StyleChange::Changed } else { StyleChange::Unchanged };
        StyleDifference::new(damage, change)
    }

    /// Returns true if this restyle damage contains all the damage of |other|.
    pub fn contains(self, other: Self) -> bool {
        self & other == other
    }

    /// Gets restyle damage to reconstruct the entire frame, subsuming all
    /// other damage.
    pub fn reconstruct() -> Self {
        GeckoRestyleDamage(structs::nsChangeHint_nsChangeHint_ReconstructFrame)
    }
}

impl Default for GeckoRestyleDamage {
    fn default() -> Self {
        Self::empty()
    }
}

impl BitOr for GeckoRestyleDamage {
    type Output = Self;
    fn bitor(self, other: Self) -> Self {
        GeckoRestyleDamage(self.0 | other.0)
    }
}

impl BitOrAssign for GeckoRestyleDamage {
    fn bitor_assign(&mut self, other: Self) {
        *self = *self | other;
    }
}

impl BitAnd for GeckoRestyleDamage {
    type Output = Self;
    fn bitand(self, other: Self) -> Self {
        GeckoRestyleDamage(nsChangeHint((self.0).0 & (other.0).0))
    }
}

impl Not for GeckoRestyleDamage {
    type Output = Self;
    fn not(self) -> Self {
        GeckoRestyleDamage(nsChangeHint(!(self.0).0))
    }
}
<commit_msg>Fix up Gecko_CalcStyleDifference for Linux 32-bit ABI<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! Gecko's restyle damage computation (aka change hints, aka `nsChangeHint`).

use gecko_bindings::bindings;
use gecko_bindings::structs;
use gecko_bindings::structs::{nsChangeHint, nsStyleContext, nsStyleStructID};
use matching::{StyleChange, StyleDifference};
use properties::ComputedValues;
use servo_arc::Arc;
use std::ops::{BitAnd, BitOr, BitOrAssign, Not};

/// The representation of Gecko's restyle damage is just a wrapper over
/// `nsChangeHint`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GeckoRestyleDamage(nsChangeHint);

impl GeckoRestyleDamage {
    /// Trivially construct a new `GeckoRestyleDamage`.
    pub fn new(raw: nsChangeHint) -> Self {
        GeckoRestyleDamage(raw)
    }

    /// Get the inner change hint for this damage.
    pub fn as_change_hint(&self) -> nsChangeHint {
        self.0
    }

    /// Get an empty change hint, that is (`nsChangeHint(0)`).
    pub fn empty() -> Self {
        GeckoRestyleDamage(nsChangeHint(0))
    }

    /// Returns whether this restyle damage represents the empty damage.
    pub fn is_empty(&self) -> bool {
        self.0 == nsChangeHint(0)
    }

    /// Computes the `StyleDifference` (including the appropriate change hint)
    /// given an old style (in the form of a `nsStyleContext`, and a new style
    /// (in the form of `ComputedValues`).
    ///
    /// Note that we could in theory just get two `ComputedValues` here and diff
    /// them, but Gecko has an interesting optimization when they mark accessed
    /// structs, so they effectively only diff structs that have ever been
    /// accessed from layout.
    pub fn compute_style_difference(
        source: &nsStyleContext,
        old_style: &ComputedValues,
        new_style: &Arc<ComputedValues>,
    ) -> StyleDifference {
        let mut any_style_changed: bool = false;
        let hint = unsafe {
            bindings::Gecko_CalcStyleDifference(old_style,
                                                new_style,
                                                source.mBits,
                                                &mut any_style_changed)
        };
        let change = if any_style_changed { StyleChange::Changed } else { StyleChange::Unchanged };
        StyleDifference::new(GeckoRestyleDamage(nsChangeHint(hint)), change)
    }

    /// Computes the `StyleDifference` between the two `ComputedValues` objects
    /// for the case where the old and new style are both `display: none`.
    ///
    /// In general we don't need to generate damage for such elements, but we
    /// do need to generate a frame reconstruction for `-moz-binding` changes,
    /// so that we can start loading the new binding.
    pub fn compute_undisplayed_style_difference(
        old_style: &ComputedValues,
        new_style: &ComputedValues,
    ) -> StyleDifference {
        let mut any_style_changed: bool = false;

        // Just compute the Display struct's difference.
        let display_struct_bit = 1 << (nsStyleStructID::eStyleStruct_Display as u32);
        let hint = unsafe {
            bindings::Gecko_CalcStyleDifference(old_style,
                                                new_style,
                                                display_struct_bit,
                                                &mut any_style_changed)
        };

        // Only pay attention to a reconstruct change hint.
        let damage = GeckoRestyleDamage(nsChangeHint(hint)) & Self::reconstruct();

        let change = if damage.is_empty() { StyleChange::Changed } else { StyleChange::Unchanged };
        StyleDifference::new(damage, change)
    }

    /// Returns true if this restyle damage contains all the damage of |other|.
    pub fn contains(self, other: Self) -> bool {
        self & other == other
    }

    /// Gets restyle damage to reconstruct the entire frame, subsuming all
    /// other damage.
    pub fn reconstruct() -> Self {
        GeckoRestyleDamage(structs::nsChangeHint_nsChangeHint_ReconstructFrame)
    }
}

impl Default for GeckoRestyleDamage {
    fn default() -> Self {
        Self::empty()
    }
}

impl BitOr for GeckoRestyleDamage {
    type Output = Self;
    fn bitor(self, other: Self) -> Self {
        GeckoRestyleDamage(self.0 | other.0)
    }
}

impl BitOrAssign for GeckoRestyleDamage {
    fn bitor_assign(&mut self, other: Self) {
        *self = *self | other;
    }
}

impl BitAnd for GeckoRestyleDamage {
    type Output = Self;
    fn bitand(self, other: Self) -> Self {
        GeckoRestyleDamage(nsChangeHint((self.0).0 & (other.0).0))
    }
}

impl Not for GeckoRestyleDamage {
    type Output = Self;
    fn not(self) -> Self {
        GeckoRestyleDamage(nsChangeHint(!(self.0).0))
    }
}
<|endoftext|>


<commit_before><commit_msg>style: Remove layout.css.xul-box-display-values.survive-blockification.enabled.<commit_after><|endoftext|>


<commit_before><commit_msg>Add rust code for all-your-base<commit_after>///
/// Convert a number between two bases.
///
/// A number is any slice of digits.
/// A digit is any unsigned integer (e.g. u8, u16, u32, u64, or usize).
/// Bases are specified as unsigned integers.
///
/// Return an `Err(.)` if the conversion is impossible.
/// The tests do not test for specific values inside the `Err(.)`.
///
///
/// You are allowed to change the function signature as long as all test still pass.
///
///
/// Example:
/// Input
///   number: &[4, 2]
///   from_base: 10
///   to_base: 2
/// Result
///   Ok(vec![1, 0, 1, 0, 1, 0])
///
/// The example corresponds to converting the number 42 from decimal
/// which is equivalent to 101010 in binary.
///
///
/// Notes:
///  * The empty slice ( "[]" ) is equal to the number 0.
///  * Never output leading 0 digits. However, your function must be able to
///     process input with leading 0 digits.
///
#[allow(unused_variables)]
pub fn convert(number: &[u32], from_base: u32, to_base: u32) -> Result<Vec<u32>, ()> {
    if number.into_iter().any(|&x| x >= from_base) {
        return Err(());
    }

    if from_base < 2 || to_base < 2 {
        return Err(());
    }

    let mut r = number.into_iter().fold(0, |acc, &x| acc * from_base + x);

    let mut result = (0..)
        .take_while(move |&x| r >= to_base.pow(x as u32))
        .map(|x| {
            let d = r % to_base;
            r /= to_base;
            d
        })
        .collect::<Vec<_>>();

    result.reverse();

    Ok(result)
}
<|endoftext|>


<commit_before><commit_msg>Switch to absolute offsets for extend comment word<commit_after><|endoftext|>


<commit_before>use crate::schema::*;
use diesel::*;

#[test]
fn insert_from_table() {
    use crate::schema::posts::dsl::*;
    let conn = connection_with_sean_and_tess_in_users_table();
    insert_into(posts)
        .values(users::table)
        .into_columns((user_id, title, body))
        .execute(&conn)
        .unwrap();

    let data = posts.select((user_id, title, body)).load(&conn);
    let expected = vec![
        (1, String::from("Sean"), None::<String>),
        (2, String::from("Tess"), None),
    ];
    assert_eq!(Ok(expected), data);
}

#[test]
fn insert_from_table_reference() {
    use crate::schema::posts::dsl::*;
    let conn = connection_with_sean_and_tess_in_users_table();
    insert_into(posts)
        .values(&users::table)
        .into_columns((user_id, title, body))
        .execute(&conn)
        .unwrap();

    let data = posts.select((user_id, title, body)).load(&conn);
    let expected = vec![
        (1, String::from("Sean"), None::<String>),
        (2, String::from("Tess"), None),
    ];
    assert_eq!(Ok(expected), data);
}

#[test]
fn insert_from_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    users
        .select((id, name.concat(" says hi")))
        .insert_into(posts)
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
fn insert_from_select_reference() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    let select = users.select((id, name.concat(" says hi")));
    insert_into(posts)
        .values(&select)
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
fn insert_from_boxed() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    users
        .select((id, name.concat(" says hi")))
        .into_boxed()
        .insert_into(posts)
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
fn insert_from_boxed_reference() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    let select = users.select((id, name.concat(" says hi"))).into_boxed();
    insert_into(posts)
        .values(&select)
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "sqlite")]
fn insert_or_ignore_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    sql_query("CREATE UNIQUE INDEX foo ON posts (user_id)")
        .execute(&conn)
        .unwrap();

    insert_or_ignore_into(posts)
        .values(users.select((id, name.concat(" says hi"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();
    insert_or_ignore_into(posts)
        .values(users.select((id, name.concat(" says bye"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "sqlite")]
fn insert_or_replace_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    sql_query("CREATE UNIQUE INDEX foo ON posts (user_id)")
        .execute(&conn)
        .unwrap();

    replace_into(posts)
        .values(users.select((id, name.concat(" says hi"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();
    replace_into(posts)
        .values(users.select((id, name.concat(" says bye"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says bye", "Tess says bye"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "mysql")]
// We can't share the test with SQLite because it modifies
// schema, but we can at least make sure the query is *syntactically* valid.
fn insert_or_ignore_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    insert_or_ignore_into(posts)
        .values(users.select((id, name.concat(" says hi"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "mysql")]
// We can't share the test with SQLite because it modifies
// schema, but we can at least make sure the query is *syntactically* valid.
fn insert_or_replace_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    replace_into(posts)
        .values(users.select((id, name.concat(" says hi"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(all(feature = "postgres", feature = "sqlite"))]
fn on_conflict_do_nothing_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    sql_query("CREATE UNIQUE INDEX ON posts (title)")
        .execute(&conn)
        .unwrap();
    let query = users
        .select((id, name.concat(" says hi")))
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict_do_nothing();

    let inserted_rows = query.execute(&conn).unwrap();
    assert_eq!(2, inserted_rows);
    let inserted_rows = query.execute(&conn).unwrap();
    assert_eq!(0, inserted_rows);

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "sqlite")]
fn on_conflict_do_nothing_with_select_for_sqlite() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    sql_query("CREATE UNIQUE INDEX index_on_title  ON posts (title)")
        .execute(&conn)
        .unwrap();

    let inserted_rows = users
        .select((id, name.concat(" says hi")))
        .filter(diesel::dsl::sql(" 1=1 "))
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict_do_nothing()
        .execute(&conn)
        .unwrap();
    assert_eq!(2, inserted_rows);
    let inserted_rows = users
        .select((id, name.concat(" says hi")))
        .filter(diesel::dsl::sql(" 1=1 "))
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict_do_nothing()
        .execute(&conn)
        .unwrap();
    assert_eq!(0, inserted_rows);

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "postgres")]
fn on_conflict_do_update_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    sql_query("CREATE UNIQUE INDEX ON posts (title)")
        .execute(&conn)
        .unwrap();
    let query = users
        .select((id, name.concat(" says hi")))
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict(title)
        .do_update()
        .set(body.eq("updated"));

    query.execute(&conn).unwrap();

    insert_into(users)
        .values(name.eq("Ruby"))
        .execute(&conn)
        .unwrap();

    query.execute(&conn).unwrap();

    let data = posts.select((title, body)).load(&conn).unwrap();
    let expected = vec![
        (String::from("Sean says hi"), Some(String::from("updated"))),
        (String::from("Tess says hi"), Some(String::from("updated"))),
        (String::from("Ruby says hi"), None),
    ];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "sqlite")]
fn on_conflict_do_update_with_select_for_sqlite() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    sql_query("CREATE UNIQUE INDEX index_on_title  ON posts (title)")
        .execute(&conn)
        .unwrap();

    users
        .select((id, name.concat(" says hi")))
        .filter(diesel::dsl::sql("1=1"))
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict(title)
        .do_update()
        .set(body.eq("updated"))
        .execute(&conn)
        .unwrap();

    insert_into(users)
        .values(name.eq("Ruby"))
        .execute(&conn)
        .unwrap();

    users
        .select((id, name.concat(" says hi")))
        .filter(diesel::dsl::sql("1=1"))
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict(title)
        .do_update()
        .set(body.eq("updated"))
        .execute(&conn)
        .unwrap();

    let data = posts.select((title, body)).load(&conn).unwrap();
    let expected = vec![
        (String::from("Sean says hi"), Some(String::from("updated"))),
        (String::from("Tess says hi"), Some(String::from("updated"))),
        (String::from("Ruby says hi"), None),
    ];
    assert_eq!(expected, data);
}

#[test]
#[cfg(all(feature = "postgres", feature = "sqlite"))]
fn on_conflict_do_update_with_boxed_select() {
    use schema::posts::dsl::*;
    use schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    sql_query("CREATE UNIQUE INDEX index_on_title  ON posts (title)")
        .execute(&conn)
        .unwrap();

    users
        .select((id, name.concat(" says hi")))
        .into_boxed()
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict(title)
        .do_update()
        .set(body.eq("updated"))
        .execute(&conn)
        .unwrap();

    insert_into(users)
        .values(name.eq("Ruby"))
        .execute(&conn)
        .unwrap();

    users
        .select((id, name.concat(" says hi")))
        .into_boxed()
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict(title)
        .do_update()
        .set(body.eq("updated"))
        .execute(&conn)
        .unwrap();

    let data = posts.select((title, body)).load(&conn).unwrap();
    let expected = vec![
        (String::from("Sean says hi"), Some(String::from("updated"))),
        (String::from("Tess says hi"), Some(String::from("updated"))),
        (String::from("Ruby says hi"), None),
    ];
    assert_eq!(expected, data);
}
<commit_msg>Unify test cases<commit_after>use crate::schema::*;
use diesel::*;

#[test]
fn insert_from_table() {
    use crate::schema::posts::dsl::*;
    let conn = connection_with_sean_and_tess_in_users_table();
    insert_into(posts)
        .values(users::table)
        .into_columns((user_id, title, body))
        .execute(&conn)
        .unwrap();

    let data = posts.select((user_id, title, body)).load(&conn);
    let expected = vec![
        (1, String::from("Sean"), None::<String>),
        (2, String::from("Tess"), None),
    ];
    assert_eq!(Ok(expected), data);
}

#[test]
fn insert_from_table_reference() {
    use crate::schema::posts::dsl::*;
    let conn = connection_with_sean_and_tess_in_users_table();
    insert_into(posts)
        .values(&users::table)
        .into_columns((user_id, title, body))
        .execute(&conn)
        .unwrap();

    let data = posts.select((user_id, title, body)).load(&conn);
    let expected = vec![
        (1, String::from("Sean"), None::<String>),
        (2, String::from("Tess"), None),
    ];
    assert_eq!(Ok(expected), data);
}

#[test]
fn insert_from_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    users
        .select((id, name.concat(" says hi")))
        .insert_into(posts)
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
fn insert_from_select_reference() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    let select = users.select((id, name.concat(" says hi")));
    insert_into(posts)
        .values(&select)
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
fn insert_from_boxed() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    users
        .select((id, name.concat(" says hi")))
        .into_boxed()
        .insert_into(posts)
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
fn insert_from_boxed_reference() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    let select = users.select((id, name.concat(" says hi"))).into_boxed();
    insert_into(posts)
        .values(&select)
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "sqlite")]
fn insert_or_ignore_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    sql_query("CREATE UNIQUE INDEX foo ON posts (user_id)")
        .execute(&conn)
        .unwrap();

    insert_or_ignore_into(posts)
        .values(users.select((id, name.concat(" says hi"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();
    insert_or_ignore_into(posts)
        .values(users.select((id, name.concat(" says bye"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "sqlite")]
fn insert_or_replace_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();
    sql_query("CREATE UNIQUE INDEX foo ON posts (user_id)")
        .execute(&conn)
        .unwrap();

    replace_into(posts)
        .values(users.select((id, name.concat(" says hi"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();
    replace_into(posts)
        .values(users.select((id, name.concat(" says bye"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says bye", "Tess says bye"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "mysql")]
// We can't share the test with SQLite because it modifies
// schema, but we can at least make sure the query is *syntactically* valid.
fn insert_or_ignore_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    insert_or_ignore_into(posts)
        .values(users.select((id, name.concat(" says hi"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(feature = "mysql")]
// We can't share the test with SQLite because it modifies
// schema, but we can at least make sure the query is *syntactically* valid.
fn insert_or_replace_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    replace_into(posts)
        .values(users.select((id, name.concat(" says hi"))))
        .into_columns((user_id, title))
        .execute(&conn)
        .unwrap();

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(any(feature = "postgres", feature = "sqlite"))]
fn on_conflict_do_nothing_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    sql_query("CREATE UNIQUE INDEX index_on_title ON posts (title)")
        .execute(&conn)
        .unwrap();
    let query = users
        .select((id, name.concat(" says hi")))
        .filter(id.ge(0)) // Sqlite needs a where claues
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict_do_nothing();

    let inserted_rows = query.execute(&conn).unwrap();
    assert_eq!(2, inserted_rows);
    let inserted_rows = query.execute(&conn).unwrap();
    assert_eq!(0, inserted_rows);

    let data = posts.select(title).load::<String>(&conn).unwrap();
    let expected = vec!["Sean says hi", "Tess says hi"];
    assert_eq!(expected, data);
}

#[test]
#[cfg(any(feature = "postgres", feature = "sqlite"))]
fn on_conflict_do_update_with_select() {
    use crate::schema::posts::dsl::*;
    use crate::schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    sql_query("CREATE UNIQUE INDEX index_on_title ON posts (title)")
        .execute(&conn)
        .unwrap();
    let query = users
        .select((id, name.concat(" says hi")))
        .filter(id.ge(0)) // exists because sqlite needs a where clause
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict(title)
        .do_update()
        .set(body.eq("updated"));

    query.execute(&conn).unwrap();

    insert_into(users)
        .values(name.eq("Ruby"))
        .execute(&conn)
        .unwrap();

    query.execute(&conn).unwrap();

    let data = posts.select((title, body)).load(&conn).unwrap();
    let expected = vec![
        (String::from("Sean says hi"), Some(String::from("updated"))),
        (String::from("Tess says hi"), Some(String::from("updated"))),
        (String::from("Ruby says hi"), None),
    ];
    assert_eq!(expected, data);
}

#[test]
#[cfg(all(feature = "postgres", feature = "sqlite"))]
fn on_conflict_do_update_with_boxed_select() {
    use schema::posts::dsl::*;
    use schema::users::dsl::{id, name, users};

    let conn = connection_with_sean_and_tess_in_users_table();

    sql_query("CREATE UNIQUE INDEX index_on_title  ON posts (title)")
        .execute(&conn)
        .unwrap();

    users
        .select((id, name.concat(" says hi")))
        .into_boxed()
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict(title)
        .do_update()
        .set(body.eq("updated"))
        .execute(&conn)
        .unwrap();

    insert_into(users)
        .values(name.eq("Ruby"))
        .execute(&conn)
        .unwrap();

    users
        .select((id, name.concat(" says hi")))
        .into_boxed()
        .insert_into(posts)
        .into_columns((user_id, title))
        .on_conflict(title)
        .do_update()
        .set(body.eq("updated"))
        .execute(&conn)
        .unwrap();

    let data = posts.select((title, body)).load(&conn).unwrap();
    let expected = vec![
        (String::from("Sean says hi"), Some(String::from("updated"))),
        (String::from("Tess says hi"), Some(String::from("updated"))),
        (String::from("Ruby says hi"), None),
    ];
    assert_eq!(expected, data);
}
<|endoftext|>


<commit_before><commit_msg>add test<commit_after>#[macro_use]
extern crate generator;

use generator::Generator;

unsafe fn f0() {
    let mut i = 0;
    println!("{}", i);

    _yield_!();

    i = 100;
    println!("{}", i);

    _yield_!();

    i = 1000;
    println!("{}", i);
}

unsafe fn f1() -> u32 {
    let mut j = 0;
    let mut i:i32;
    while j < 10 {
        i = _yield!(j);
        println!("get send: {:?}", i);
        j+=1;
    }

    return 10000;
}

unsafe fn f2() -> (u64, u64, u64)
{
    let mut i = 0u64;
    while i < 10 {
        _yield_!((i, i+1, i+2));
        i+=1;
    }

    // the last return is not deal with carefully
    (0, 0, 0)
}

#[test]
fn test_main() {
    let mut g = generator!(f0());

    g.next();
    g.next();
    g.next();

    let mut g = generator!(f1(), <i32>);
    let mut i = 0;
    while !g.is_done() {
        println!("get yield: {:?}", g.send(i));
        i += 1;
    }

    let g = generator!(f2());
    for x in g {
        println!("get{:?}", x);
    }
}
<|endoftext|>


<commit_before><commit_msg>Rust: Problem 6<commit_after>/// # Sum square difference
/// # Problem 6
/// The sum of the squares of the first ten natural numbers is
/// > 12 + 22 + ... + 102 = 385
/// The square of the sum of the first ten natural numbers is,
/// > (1 + 2 + ... + 10)2 = 552 = 3025
/// Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
/// Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

use std::num::pow;
use std::iter::AdditiveIterator;

fn main() {
  let sum_squares = range(1, 101).map(|n| pow(n, 2)).sum();
  let squares_sum = pow(range(1, 101).sum(), 2);

  println!("{}", squares_sum - sum_squares );
}
<|endoftext|>


<commit_before><commit_msg>Fix: Add ID reporting<commit_after><|endoftext|>


<commit_before><commit_msg>newline spacing<commit_after><|endoftext|>


<commit_before><commit_msg>Prioritize 'original' field in 'largest' methods<commit_after><|endoftext|>


<commit_before><commit_msg>Update episode_count and episode_length definitions (#2)<commit_after><|endoftext|>


<commit_before><commit_msg>Add timer test for incrementing 1s<commit_after><|endoftext|>


<commit_before><commit_msg>More progress<commit_after><|endoftext|>


<commit_before><commit_msg>hello world for rust<commit_after><|endoftext|>


<commit_before><commit_msg>Added Stack module<commit_after>/*!
    Heterogeneous Stack

    No need for any code - Rust can already do that.

# Example
```rust
    let s = ();
    let s = (1u, s);     //append
    let s = ('c', s);
    let (ch, s) = s;    //consume
    let (num, s) = s;
    println!("Stack: {} {} {}", ch, num, s);
```
*/
<|endoftext|>


<commit_before><commit_msg>added soul count mechanic<commit_after><|endoftext|>


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

use std::collections::HashSet;

use build::{Build, Compiler};

#[derive(Hash, Eq, PartialEq, Clone, Debug)]
pub struct Step<'a> {
    pub src: Source<'a>,
    pub target: &'a str,
}

macro_rules! targets {
    ($m:ident) => {
        $m! {
            // Step representing building the stageN compiler. This is just the
            // compiler executable itself, not any of the support libraries
            (rustc, Rustc { stage: u32 }),

            // Steps for the two main cargo builds, one for the standard library
            // and one for the compiler itself. These are parameterized over the
            // stage output they're going to be placed in along with the
            // compiler which is producing the copy of libstd or librustc
            (libstd, Libstd { stage: u32, compiler: Compiler<'a> }),
            (librustc, Librustc { stage: u32, compiler: Compiler<'a> }),

            // Links the standard library/librustc produced by the compiler
            // provided into the host's directory also provided.
            (libstd_link, LibstdLink {
                stage: u32,
                compiler: Compiler<'a>,
                host: &'a str
            }),
            (librustc_link, LibrustcLink {
                stage: u32,
                compiler: Compiler<'a>,
                host: &'a str
            }),

            // Steps for long-running native builds. Ideally these wouldn't
            // actually exist and would be part of build scripts, but for now
            // these are here.
            //
            // There aren't really any parameters to this, but empty structs
            // with braces are unstable so we just pick something that works.
            (llvm, Llvm { _dummy: () }),
            (compiler_rt, CompilerRt { _dummy: () }),

            // Steps for various pieces of documentation that we can generate,
            // the 'doc' step is just a pseudo target to depend on a bunch of
            // others.
            (doc, Doc { stage: u32 }),
            (doc_book, DocBook { stage: u32 }),
            (doc_nomicon, DocNomicon { stage: u32 }),
            (doc_style, DocStyle { stage: u32 }),
            (doc_standalone, DocStandalone { stage: u32 }),
            (doc_std, DocStd { stage: u32 }),
            (doc_rustc, DocRustc { stage: u32 }),

            // Steps for running tests. The 'check' target is just a pseudo
            // target to depend on a bunch of others.
            (check, Check { stage: u32, compiler: Compiler<'a> }),
        }
    }
}

macro_rules! item { ($a:item) => ($a) }

macro_rules! define_source {
    ($(($short:ident, $name:ident { $($args:tt)* }),)*) => {
        item! {
            #[derive(Hash, Eq, PartialEq, Clone, Debug)]
            pub enum Source<'a> {
                $($name { $($args)* }),*
            }
        }
    }
}

targets!(define_source);

pub fn all(build: &Build) -> Vec<Step> {
    let mut ret = Vec::new();
    let mut all = HashSet::new();
    for target in top_level(build) {
        fill(build, &target, &mut ret, &mut all);
    }
    return ret;

    fn fill<'a>(build: &'a Build,
                target: &Step<'a>,
                ret: &mut Vec<Step<'a>>,
                set: &mut HashSet<Step<'a>>) {
        if set.insert(target.clone()) {
            for dep in target.deps(build) {
                fill(build, &dep, ret, set);
            }
            ret.push(target.clone());
        }
    }
}

fn top_level(build: &Build) -> Vec<Step> {
    let mut targets = Vec::new();
    let stage = build.flags.stage.unwrap_or(2);

    let host = Step {
        src: Source::Llvm { _dummy: () },
        target: build.flags.host.iter().next()
                     .unwrap_or(&build.config.build),
    };
    let target = Step {
        src: Source::Llvm { _dummy: () },
        target: build.flags.target.iter().next().map(|x| &x[..])
                     .unwrap_or(host.target)
    };

    add_steps(build, stage, &host, &target, &mut targets);

    if targets.len() == 0 {
        let t = Step {
            src: Source::Llvm { _dummy: () },
            target: &build.config.build,
        };
        targets.push(t.doc(stage));
        for host in build.config.host.iter() {
            if !build.flags.host.contains(host) {
                continue
            }
            let host = t.target(host);
            if host.target == build.config.build {
                targets.push(host.librustc(stage, host.compiler(stage)));
            } else {
                targets.push(host.librustc_link(stage, t.compiler(stage),
                                                host.target));
            }
            for target in build.config.target.iter() {
                if !build.flags.target.contains(target) {
                    continue
                }

                if host.target == build.config.build {
                    targets.push(host.target(target)
                                     .libstd(stage, host.compiler(stage)));
                } else {
                    targets.push(host.target(target)
                                     .libstd_link(stage, t.compiler(stage),
                                                  host.target));
                }
            }
        }
    }

    return targets

}

fn add_steps<'a>(build: &'a Build,
                 stage: u32,
                 host: &Step<'a>,
                 target: &Step<'a>,
                 targets: &mut Vec<Step<'a>>) {
    for step in build.flags.step.iter() {
        let compiler = host.target(&build.config.build).compiler(stage);
        match &step[..] {
            "libstd" => targets.push(target.libstd(stage, compiler)),
            "librustc" => targets.push(target.librustc(stage, compiler)),
            "libstd-link" => targets.push(target.libstd_link(stage, compiler,
                                                             host.target)),
            "librustc-link" => targets.push(target.librustc_link(stage, compiler,
                                                                 host.target)),
            "rustc" => targets.push(host.rustc(stage)),
            "llvm" => targets.push(target.llvm(())),
            "compiler-rt" => targets.push(target.compiler_rt(())),
            "doc-style" => targets.push(host.doc_style(stage)),
            "doc-standalone" => targets.push(host.doc_standalone(stage)),
            "doc-nomicon" => targets.push(host.doc_nomicon(stage)),
            "doc-book" => targets.push(host.doc_book(stage)),
            "doc-std" => targets.push(host.doc_std(stage)),
            "doc-rustc" => targets.push(host.doc_rustc(stage)),
            "doc" => targets.push(host.doc(stage)),
            "check" => targets.push(host.check(stage, compiler)),
            _ => panic!("unknown build target: `{}`", step),
        }
    }
}

macro_rules! constructors {
    ($(($short:ident, $name:ident { $($arg:ident: $t:ty),* }),)*) => {$(
        fn $short(&self, $($arg: $t),*) -> Step<'a> {
            Step {
                src: Source::$name { $($arg: $arg),* },
                target: self.target,
            }
        }
    )*}
}

impl<'a> Step<'a> {
    fn compiler(&self, stage: u32) -> Compiler<'a> {
        Compiler::new(stage, self.target)
    }

    fn target(&self, target: &'a str) -> Step<'a> {
        Step { target: target, src: self.src.clone() }
    }

    targets!(constructors);

    pub fn deps(&self, build: &'a Build) -> Vec<Step<'a>> {
        match self.src {
            Source::Rustc { stage: 0 } => {
                Vec::new()
            }
            Source::Rustc { stage } => {
                let compiler = Compiler::new(stage - 1, &build.config.build);
                vec![self.librustc(stage - 1, compiler)]
            }
            Source::Librustc { stage, compiler } => {
                vec![self.libstd(stage, compiler), self.llvm(())]
            }
            Source::Libstd { stage: _, compiler } => {
                vec![self.compiler_rt(()),
                     self.rustc(compiler.stage).target(compiler.host)]
            }
            Source::LibrustcLink { stage, compiler, host } => {
                vec![self.librustc(stage, compiler),
                     self.libstd_link(stage, compiler, host)]
            }
            Source::LibstdLink { stage, compiler, host } => {
                vec![self.libstd(stage, compiler),
                     self.target(host).rustc(stage)]
            }
            Source::CompilerRt { _dummy } => {
                vec![self.llvm(()).target(&build.config.build)]
            }
            Source::Llvm { _dummy } => Vec::new(),
            Source::DocStd { stage } => {
                vec![self.libstd(stage, self.compiler(stage))]
            }
            Source::DocBook { stage } |
            Source::DocNomicon { stage } |
            Source::DocStyle { stage } |
            Source::DocStandalone { stage } => {
                vec![self.rustc(stage)]
            }
            Source::DocRustc { stage } => {
                vec![self.doc_std(stage)]
            }
            Source::Doc { stage } => {
                vec![self.doc_book(stage), self.doc_nomicon(stage),
                     self.doc_style(stage), self.doc_standalone(stage),
                     self.doc_std(stage)]
            }
            Source::Check { stage, compiler: _ } => {
                vec![]
            }
        }
    }
}
<commit_msg>rustbuild: Refactor adding steps manually<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.

use std::collections::HashSet;

use build::{Build, Compiler};

#[derive(Hash, Eq, PartialEq, Clone, Debug)]
pub struct Step<'a> {
    pub src: Source<'a>,
    pub target: &'a str,
}

macro_rules! targets {
    ($m:ident) => {
        $m! {
            // Step representing building the stageN compiler. This is just the
            // compiler executable itself, not any of the support libraries
            (rustc, Rustc { stage: u32 }),

            // Steps for the two main cargo builds, one for the standard library
            // and one for the compiler itself. These are parameterized over the
            // stage output they're going to be placed in along with the
            // compiler which is producing the copy of libstd or librustc
            (libstd, Libstd { stage: u32, compiler: Compiler<'a> }),
            (librustc, Librustc { stage: u32, compiler: Compiler<'a> }),

            // Links the standard library/librustc produced by the compiler
            // provided into the host's directory also provided.
            (libstd_link, LibstdLink {
                stage: u32,
                compiler: Compiler<'a>,
                host: &'a str
            }),
            (librustc_link, LibrustcLink {
                stage: u32,
                compiler: Compiler<'a>,
                host: &'a str
            }),

            // Steps for long-running native builds. Ideally these wouldn't
            // actually exist and would be part of build scripts, but for now
            // these are here.
            //
            // There aren't really any parameters to this, but empty structs
            // with braces are unstable so we just pick something that works.
            (llvm, Llvm { _dummy: () }),
            (compiler_rt, CompilerRt { _dummy: () }),

            // Steps for various pieces of documentation that we can generate,
            // the 'doc' step is just a pseudo target to depend on a bunch of
            // others.
            (doc, Doc { stage: u32 }),
            (doc_book, DocBook { stage: u32 }),
            (doc_nomicon, DocNomicon { stage: u32 }),
            (doc_style, DocStyle { stage: u32 }),
            (doc_standalone, DocStandalone { stage: u32 }),
            (doc_std, DocStd { stage: u32 }),
            (doc_rustc, DocRustc { stage: u32 }),

            // Steps for running tests. The 'check' target is just a pseudo
            // target to depend on a bunch of others.
            (check, Check { stage: u32, compiler: Compiler<'a> }),
        }
    }
}

macro_rules! item { ($a:item) => ($a) }

macro_rules! define_source {
    ($(($short:ident, $name:ident { $($args:tt)* }),)*) => {
        item! {
            #[derive(Hash, Eq, PartialEq, Clone, Debug)]
            pub enum Source<'a> {
                $($name { $($args)* }),*
            }
        }
    }
}

targets!(define_source);

pub fn all(build: &Build) -> Vec<Step> {
    let mut ret = Vec::new();
    let mut all = HashSet::new();
    for target in top_level(build) {
        fill(build, &target, &mut ret, &mut all);
    }
    return ret;

    fn fill<'a>(build: &'a Build,
                target: &Step<'a>,
                ret: &mut Vec<Step<'a>>,
                set: &mut HashSet<Step<'a>>) {
        if set.insert(target.clone()) {
            for dep in target.deps(build) {
                fill(build, &dep, ret, set);
            }
            ret.push(target.clone());
        }
    }
}

fn top_level(build: &Build) -> Vec<Step> {
    let mut targets = Vec::new();
    let stage = build.flags.stage.unwrap_or(2);

    let host = Step {
        src: Source::Llvm { _dummy: () },
        target: build.flags.host.iter().next()
                     .unwrap_or(&build.config.build),
    };
    let target = Step {
        src: Source::Llvm { _dummy: () },
        target: build.flags.target.iter().next().map(|x| &x[..])
                     .unwrap_or(host.target)
    };

    add_steps(build, stage, &host, &target, &mut targets);

    if targets.len() == 0 {
        let t = Step {
            src: Source::Llvm { _dummy: () },
            target: &build.config.build,
        };
        targets.push(t.doc(stage));
        for host in build.config.host.iter() {
            if !build.flags.host.contains(host) {
                continue
            }
            let host = t.target(host);
            if host.target == build.config.build {
                targets.push(host.librustc(stage, host.compiler(stage)));
            } else {
                targets.push(host.librustc_link(stage, t.compiler(stage),
                                                host.target));
            }
            for target in build.config.target.iter() {
                if !build.flags.target.contains(target) {
                    continue
                }

                if host.target == build.config.build {
                    targets.push(host.target(target)
                                     .libstd(stage, host.compiler(stage)));
                } else {
                    targets.push(host.target(target)
                                     .libstd_link(stage, t.compiler(stage),
                                                  host.target));
                }
            }
        }
    }

    return targets

}

fn add_steps<'a>(build: &'a Build,
                 stage: u32,
                 host: &Step<'a>,
                 target: &Step<'a>,
                 targets: &mut Vec<Step<'a>>) {
    struct Context<'a> {
        stage: u32,
        compiler: Compiler<'a>,
        _dummy: (),
        host: &'a str,
    }
    for step in build.flags.step.iter() {

        // The macro below insists on hygienic access to all local variables, so
        // we shove them all in a struct and subvert hygiene by accessing struct
        // fields instead,
        let cx = Context {
            stage: stage,
            compiler: host.target(&build.config.build).compiler(stage),
            _dummy: (),
            host: host.target,
        };
        macro_rules! add_step {
            ($(($short:ident, $name:ident { $($arg:ident: $t:ty),* }),)*) => ({$(
                let name = stringify!($short).replace("_", "-");
                if &step[..] == &name[..] {
                    targets.push(target.$short($(cx.$arg),*));
                    continue
                }
                drop(name);
            )*})
        }

        targets!(add_step);
    }
}

macro_rules! constructors {
    ($(($short:ident, $name:ident { $($arg:ident: $t:ty),* }),)*) => {$(
        fn $short(&self, $($arg: $t),*) -> Step<'a> {
            Step {
                src: Source::$name { $($arg: $arg),* },
                target: self.target,
            }
        }
    )*}
}

impl<'a> Step<'a> {
    fn compiler(&self, stage: u32) -> Compiler<'a> {
        Compiler::new(stage, self.target)
    }

    fn target(&self, target: &'a str) -> Step<'a> {
        Step { target: target, src: self.src.clone() }
    }

    targets!(constructors);

    pub fn deps(&self, build: &'a Build) -> Vec<Step<'a>> {
        match self.src {
            Source::Rustc { stage: 0 } => {
                Vec::new()
            }
            Source::Rustc { stage } => {
                let compiler = Compiler::new(stage - 1, &build.config.build);
                vec![self.librustc(stage - 1, compiler)]
            }
            Source::Librustc { stage, compiler } => {
                vec![self.libstd(stage, compiler), self.llvm(())]
            }
            Source::Libstd { stage: _, compiler } => {
                vec![self.compiler_rt(()),
                     self.rustc(compiler.stage).target(compiler.host)]
            }
            Source::LibrustcLink { stage, compiler, host } => {
                vec![self.librustc(stage, compiler),
                     self.libstd_link(stage, compiler, host)]
            }
            Source::LibstdLink { stage, compiler, host } => {
                vec![self.libstd(stage, compiler),
                     self.target(host).rustc(stage)]
            }
            Source::CompilerRt { _dummy } => {
                vec![self.llvm(()).target(&build.config.build)]
            }
            Source::Llvm { _dummy } => Vec::new(),
            Source::DocStd { stage } => {
                vec![self.libstd(stage, self.compiler(stage))]
            }
            Source::DocBook { stage } |
            Source::DocNomicon { stage } |
            Source::DocStyle { stage } |
            Source::DocStandalone { stage } => {
                vec![self.rustc(stage)]
            }
            Source::DocRustc { stage } => {
                vec![self.doc_std(stage)]
            }
            Source::Doc { stage } => {
                vec![self.doc_book(stage), self.doc_nomicon(stage),
                     self.doc_style(stage), self.doc_standalone(stage),
                     self.doc_std(stage)]
            }
            Source::Check { stage, compiler: _ } => {
                vec![]
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Day3 not implemented<commit_after><|endoftext|>


<commit_before><commit_msg>Updated all tests to use the new test! macro<commit_after><|endoftext|>


<commit_before><commit_msg>Add decode tests for block transfer operations<commit_after><|endoftext|>


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


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

pub use self::imp::OsRng;

use mem;

fn next_u32(mut fill_buf: &mut FnMut(&mut [u8])) -> u32 {
    let mut buf: [u8; 4] = [0; 4];
    fill_buf(&mut buf);
    unsafe { mem::transmute::<[u8; 4], u32>(buf) }
}

fn next_u64(mut fill_buf: &mut FnMut(&mut [u8])) -> u64 {
    let mut buf: [u8; 8] = [0; 8];
    fill_buf(&mut buf);
    unsafe { mem::transmute::<[u8; 8], u64>(buf) }
}

#[cfg(all(unix,
          not(target_os = "ios"),
          not(target_os = "openbsd"),
          not(target_os = "freebsd"),
          not(target_os = "fuchsia")))]
mod imp {
    use self::OsRngInner::*;
    use super::{next_u32, next_u64};

    use fs::File;
    use io;
    use libc;
    use rand::Rng;
    use rand::reader::ReaderRng;
    use sys::os::errno;

    #[cfg(all(target_os = "linux",
              any(target_arch = "x86_64",
                  target_arch = "x86",
                  target_arch = "arm",
                  target_arch = "aarch64",
                  target_arch = "powerpc",
                  target_arch = "powerpc64",
                  target_arch = "s390x")))]
    fn getrandom(buf: &mut [u8]) -> libc::c_long {
        #[cfg(target_arch = "x86_64")]
        const NR_GETRANDOM: libc::c_long = 318;
        #[cfg(target_arch = "x86")]
        const NR_GETRANDOM: libc::c_long = 355;
        #[cfg(target_arch = "arm")]
        const NR_GETRANDOM: libc::c_long = 384;
        #[cfg(target_arch = "s390x")]
        const NR_GETRANDOM: libc::c_long = 349;
        #[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))]
        const NR_GETRANDOM: libc::c_long = 359;
        #[cfg(target_arch = "aarch64")]
        const NR_GETRANDOM: libc::c_long = 278;

        const GRND_NONBLOCK: libc::c_uint = 0x0001;

        unsafe {
            libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)
        }
    }

    #[cfg(not(all(target_os = "linux",
                  any(target_arch = "x86_64",
                      target_arch = "x86",
                      target_arch = "arm",
                      target_arch = "aarch64",
                      target_arch = "powerpc",
                      target_arch = "powerpc64",
                      target_arch = "s390x"))))]
    fn getrandom(_buf: &mut [u8]) -> libc::c_long { -1 }

    fn getrandom_fill_bytes(v: &mut [u8]) {
        let mut read = 0;
        while read < v.len() {
            let result = getrandom(&mut v[read..]);
            if result == -1 {
                let err = errno() as libc::c_int;
                if err == libc::EINTR {
                    continue;
                } else if err == libc::EAGAIN {
                    // if getrandom() returns EAGAIN it would have blocked
                    // because the non-blocking pool (urandom) has not
                    // initialized in the kernel yet due to a lack of entropy
                    // the fallback we do here is to avoid blocking applications
                    // which could depend on this call without ever knowing
                    // they do and don't have a work around. The PRNG of
                    // /dev/urandom will still be used but not over a completely
                    // full entropy pool
                    let reader = File::open("/dev/urandom").expect("Unable to open /dev/urandom");
                    let mut reader_rng = ReaderRng::new(reader);
                    reader_rng.fill_bytes(&mut v[read..]);
                    read += v.len();
                } else {
                    panic!("unexpected getrandom error: {}", err);
                }
            } else {
                read += result as usize;
            }
        }
    }

    #[cfg(all(target_os = "linux",
              any(target_arch = "x86_64",
                  target_arch = "x86",
                  target_arch = "arm",
                  target_arch = "aarch64",
                  target_arch = "powerpc",
                  target_arch = "powerpc64",
                  target_arch = "s390x")))]
    fn is_getrandom_available() -> bool {
        use sync::atomic::{AtomicBool, Ordering};
        use sync::Once;

        static CHECKER: Once = Once::new();
        static AVAILABLE: AtomicBool = AtomicBool::new(false);

        CHECKER.call_once(|| {
            let mut buf: [u8; 0] = [];
            let result = getrandom(&mut buf);
            let available = if result == -1 {
                let err = io::Error::last_os_error().raw_os_error();
                err != Some(libc::ENOSYS)
            } else {
                true
            };
            AVAILABLE.store(available, Ordering::Relaxed);
        });

        AVAILABLE.load(Ordering::Relaxed)
    }

    #[cfg(not(all(target_os = "linux",
                  any(target_arch = "x86_64",
                      target_arch = "x86",
                      target_arch = "arm",
                      target_arch = "aarch64",
                      target_arch = "powerpc",
                      target_arch = "powerpc64",
                      target_arch = "s390x"))))]
    fn is_getrandom_available() -> bool { false }

    pub struct OsRng {
        inner: OsRngInner,
    }

    enum OsRngInner {
        OsGetrandomRng,
        OsReaderRng(ReaderRng<File>),
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            if is_getrandom_available() {
                return Ok(OsRng { inner: OsGetrandomRng });
            }

            let reader = File::open("/dev/urandom")?;
            let reader_rng = ReaderRng::new(reader);

            Ok(OsRng { inner: OsReaderRng(reader_rng) })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            match self.inner {
                OsGetrandomRng => next_u32(&mut getrandom_fill_bytes),
                OsReaderRng(ref mut rng) => rng.next_u32(),
            }
        }
        fn next_u64(&mut self) -> u64 {
            match self.inner {
                OsGetrandomRng => next_u64(&mut getrandom_fill_bytes),
                OsReaderRng(ref mut rng) => rng.next_u64(),
            }
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            match self.inner {
                OsGetrandomRng => getrandom_fill_bytes(v),
                OsReaderRng(ref mut rng) => rng.fill_bytes(v)
            }
        }
    }
}

#[cfg(target_os = "openbsd")]
mod imp {
    use super::{next_u32, next_u64};

    use io;
    use libc;
    use sys::os::errno;
    use rand::Rng;

    pub struct OsRng {
        // dummy field to ensure that this struct cannot be constructed outside
        // of this module
        _dummy: (),
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            Ok(OsRng { _dummy: () })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            next_u32(&mut |v| self.fill_bytes(v))
        }
        fn next_u64(&mut self) -> u64 {
            next_u64(&mut |v| self.fill_bytes(v))
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            // getentropy(2) permits a maximum buffer size of 256 bytes
            for s in v.chunks_mut(256) {
                let ret = unsafe {
                    libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len())
                };
                if ret == -1 {
                    panic!("unexpected getentropy error: {}", errno());
                }
            }
        }
    }
}

#[cfg(target_os = "ios")]
mod imp {
    use super::{next_u32, next_u64};

    use io;
    use ptr;
    use rand::Rng;
    use libc::{c_int, size_t};

    pub struct OsRng {
        // dummy field to ensure that this struct cannot be constructed outside
        // of this module
        _dummy: (),
    }

    enum SecRandom {}

    #[allow(non_upper_case_globals)]
    const kSecRandomDefault: *const SecRandom = ptr::null();

    #[link(name = "Security", kind = "framework")]
    #[cfg(not(cargobuild))]
    extern {}

    extern {
        fn SecRandomCopyBytes(rnd: *const SecRandom,
                              count: size_t, bytes: *mut u8) -> c_int;
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            Ok(OsRng { _dummy: () })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            next_u32(&mut |v| self.fill_bytes(v))
        }
        fn next_u64(&mut self) -> u64 {
            next_u64(&mut |v| self.fill_bytes(v))
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            let ret = unsafe {
                SecRandomCopyBytes(kSecRandomDefault, v.len(),
                                   v.as_mut_ptr())
            };
            if ret == -1 {
                panic!("couldn't generate random bytes: {}",
                       io::Error::last_os_error());
            }
        }
    }
}

#[cfg(target_os = "freebsd")]
mod imp {
    use super::{next_u32, next_u64};

    use io;
    use libc;
    use rand::Rng;
    use ptr;

    pub struct OsRng {
        // dummy field to ensure that this struct cannot be constructed outside
        // of this module
        _dummy: (),
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            Ok(OsRng { _dummy: () })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            next_u32(&mut |v| self.fill_bytes(v))
        }
        fn next_u64(&mut self) -> u64 {
            next_u64(&mut |v| self.fill_bytes(v))
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            let mib = [libc::CTL_KERN, libc::KERN_ARND];
            // kern.arandom permits a maximum buffer size of 256 bytes
            for s in v.chunks_mut(256) {
                let mut s_len = s.len();
                let ret = unsafe {
                    libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint,
                                 s.as_mut_ptr() as *mut _, &mut s_len,
                                 ptr::null(), 0)
                };
                if ret == -1 || s_len != s.len() {
                    panic!("kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
                           ret, s.len(), s_len);
                }
            }
        }
    }
}

#[cfg(target_os = "fuchsia")]
mod imp {
    use super::{next_u32, next_u64};

    use io;
    use rand::Rng;

    #[link(name = "magenta")]
    extern {
        fn mx_cprng_draw(buffer: *mut u8, len: usize) -> isize;
    }

    fn getrandom(buf: &mut [u8]) -> isize {
        unsafe { mx_cprng_draw(buf.as_mut_ptr(), buf.len()) }
    }

    pub struct OsRng {
        // dummy field to ensure that this struct cannot be constructed outside
        // of this module
        _dummy: (),
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            Ok(OsRng { _dummy: () })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            next_u32(&mut |v| self.fill_bytes(v))
        }
        fn next_u64(&mut self) -> u64 {
            next_u64(&mut |v| self.fill_bytes(v))
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            let mut buf = v;
            while !buf.is_empty() {
                let ret = getrandom(buf);
                if ret < 0 {
                    panic!("kernel mx_cprng_draw call failed! (returned {}, buf.len() {})",
                        ret, buf.len());
                }
                let move_buf = buf;
                buf = &mut move_buf[(ret as usize)..];
            }
        }
    }
}
<commit_msg>std: Track change to cprng syscall signature (Fuchsia)<commit_after>// Copyright 2013-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.

pub use self::imp::OsRng;

use mem;

fn next_u32(mut fill_buf: &mut FnMut(&mut [u8])) -> u32 {
    let mut buf: [u8; 4] = [0; 4];
    fill_buf(&mut buf);
    unsafe { mem::transmute::<[u8; 4], u32>(buf) }
}

fn next_u64(mut fill_buf: &mut FnMut(&mut [u8])) -> u64 {
    let mut buf: [u8; 8] = [0; 8];
    fill_buf(&mut buf);
    unsafe { mem::transmute::<[u8; 8], u64>(buf) }
}

#[cfg(all(unix,
          not(target_os = "ios"),
          not(target_os = "openbsd"),
          not(target_os = "freebsd"),
          not(target_os = "fuchsia")))]
mod imp {
    use self::OsRngInner::*;
    use super::{next_u32, next_u64};

    use fs::File;
    use io;
    use libc;
    use rand::Rng;
    use rand::reader::ReaderRng;
    use sys::os::errno;

    #[cfg(all(target_os = "linux",
              any(target_arch = "x86_64",
                  target_arch = "x86",
                  target_arch = "arm",
                  target_arch = "aarch64",
                  target_arch = "powerpc",
                  target_arch = "powerpc64",
                  target_arch = "s390x")))]
    fn getrandom(buf: &mut [u8]) -> libc::c_long {
        #[cfg(target_arch = "x86_64")]
        const NR_GETRANDOM: libc::c_long = 318;
        #[cfg(target_arch = "x86")]
        const NR_GETRANDOM: libc::c_long = 355;
        #[cfg(target_arch = "arm")]
        const NR_GETRANDOM: libc::c_long = 384;
        #[cfg(target_arch = "s390x")]
        const NR_GETRANDOM: libc::c_long = 349;
        #[cfg(any(target_arch = "powerpc", target_arch = "powerpc64"))]
        const NR_GETRANDOM: libc::c_long = 359;
        #[cfg(target_arch = "aarch64")]
        const NR_GETRANDOM: libc::c_long = 278;

        const GRND_NONBLOCK: libc::c_uint = 0x0001;

        unsafe {
            libc::syscall(NR_GETRANDOM, buf.as_mut_ptr(), buf.len(), GRND_NONBLOCK)
        }
    }

    #[cfg(not(all(target_os = "linux",
                  any(target_arch = "x86_64",
                      target_arch = "x86",
                      target_arch = "arm",
                      target_arch = "aarch64",
                      target_arch = "powerpc",
                      target_arch = "powerpc64",
                      target_arch = "s390x"))))]
    fn getrandom(_buf: &mut [u8]) -> libc::c_long { -1 }

    fn getrandom_fill_bytes(v: &mut [u8]) {
        let mut read = 0;
        while read < v.len() {
            let result = getrandom(&mut v[read..]);
            if result == -1 {
                let err = errno() as libc::c_int;
                if err == libc::EINTR {
                    continue;
                } else if err == libc::EAGAIN {
                    // if getrandom() returns EAGAIN it would have blocked
                    // because the non-blocking pool (urandom) has not
                    // initialized in the kernel yet due to a lack of entropy
                    // the fallback we do here is to avoid blocking applications
                    // which could depend on this call without ever knowing
                    // they do and don't have a work around. The PRNG of
                    // /dev/urandom will still be used but not over a completely
                    // full entropy pool
                    let reader = File::open("/dev/urandom").expect("Unable to open /dev/urandom");
                    let mut reader_rng = ReaderRng::new(reader);
                    reader_rng.fill_bytes(&mut v[read..]);
                    read += v.len();
                } else {
                    panic!("unexpected getrandom error: {}", err);
                }
            } else {
                read += result as usize;
            }
        }
    }

    #[cfg(all(target_os = "linux",
              any(target_arch = "x86_64",
                  target_arch = "x86",
                  target_arch = "arm",
                  target_arch = "aarch64",
                  target_arch = "powerpc",
                  target_arch = "powerpc64",
                  target_arch = "s390x")))]
    fn is_getrandom_available() -> bool {
        use sync::atomic::{AtomicBool, Ordering};
        use sync::Once;

        static CHECKER: Once = Once::new();
        static AVAILABLE: AtomicBool = AtomicBool::new(false);

        CHECKER.call_once(|| {
            let mut buf: [u8; 0] = [];
            let result = getrandom(&mut buf);
            let available = if result == -1 {
                let err = io::Error::last_os_error().raw_os_error();
                err != Some(libc::ENOSYS)
            } else {
                true
            };
            AVAILABLE.store(available, Ordering::Relaxed);
        });

        AVAILABLE.load(Ordering::Relaxed)
    }

    #[cfg(not(all(target_os = "linux",
                  any(target_arch = "x86_64",
                      target_arch = "x86",
                      target_arch = "arm",
                      target_arch = "aarch64",
                      target_arch = "powerpc",
                      target_arch = "powerpc64",
                      target_arch = "s390x"))))]
    fn is_getrandom_available() -> bool { false }

    pub struct OsRng {
        inner: OsRngInner,
    }

    enum OsRngInner {
        OsGetrandomRng,
        OsReaderRng(ReaderRng<File>),
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            if is_getrandom_available() {
                return Ok(OsRng { inner: OsGetrandomRng });
            }

            let reader = File::open("/dev/urandom")?;
            let reader_rng = ReaderRng::new(reader);

            Ok(OsRng { inner: OsReaderRng(reader_rng) })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            match self.inner {
                OsGetrandomRng => next_u32(&mut getrandom_fill_bytes),
                OsReaderRng(ref mut rng) => rng.next_u32(),
            }
        }
        fn next_u64(&mut self) -> u64 {
            match self.inner {
                OsGetrandomRng => next_u64(&mut getrandom_fill_bytes),
                OsReaderRng(ref mut rng) => rng.next_u64(),
            }
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            match self.inner {
                OsGetrandomRng => getrandom_fill_bytes(v),
                OsReaderRng(ref mut rng) => rng.fill_bytes(v)
            }
        }
    }
}

#[cfg(target_os = "openbsd")]
mod imp {
    use super::{next_u32, next_u64};

    use io;
    use libc;
    use sys::os::errno;
    use rand::Rng;

    pub struct OsRng {
        // dummy field to ensure that this struct cannot be constructed outside
        // of this module
        _dummy: (),
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            Ok(OsRng { _dummy: () })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            next_u32(&mut |v| self.fill_bytes(v))
        }
        fn next_u64(&mut self) -> u64 {
            next_u64(&mut |v| self.fill_bytes(v))
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            // getentropy(2) permits a maximum buffer size of 256 bytes
            for s in v.chunks_mut(256) {
                let ret = unsafe {
                    libc::getentropy(s.as_mut_ptr() as *mut libc::c_void, s.len())
                };
                if ret == -1 {
                    panic!("unexpected getentropy error: {}", errno());
                }
            }
        }
    }
}

#[cfg(target_os = "ios")]
mod imp {
    use super::{next_u32, next_u64};

    use io;
    use ptr;
    use rand::Rng;
    use libc::{c_int, size_t};

    pub struct OsRng {
        // dummy field to ensure that this struct cannot be constructed outside
        // of this module
        _dummy: (),
    }

    enum SecRandom {}

    #[allow(non_upper_case_globals)]
    const kSecRandomDefault: *const SecRandom = ptr::null();

    #[link(name = "Security", kind = "framework")]
    #[cfg(not(cargobuild))]
    extern {}

    extern {
        fn SecRandomCopyBytes(rnd: *const SecRandom,
                              count: size_t, bytes: *mut u8) -> c_int;
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            Ok(OsRng { _dummy: () })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            next_u32(&mut |v| self.fill_bytes(v))
        }
        fn next_u64(&mut self) -> u64 {
            next_u64(&mut |v| self.fill_bytes(v))
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            let ret = unsafe {
                SecRandomCopyBytes(kSecRandomDefault, v.len(),
                                   v.as_mut_ptr())
            };
            if ret == -1 {
                panic!("couldn't generate random bytes: {}",
                       io::Error::last_os_error());
            }
        }
    }
}

#[cfg(target_os = "freebsd")]
mod imp {
    use super::{next_u32, next_u64};

    use io;
    use libc;
    use rand::Rng;
    use ptr;

    pub struct OsRng {
        // dummy field to ensure that this struct cannot be constructed outside
        // of this module
        _dummy: (),
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            Ok(OsRng { _dummy: () })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            next_u32(&mut |v| self.fill_bytes(v))
        }
        fn next_u64(&mut self) -> u64 {
            next_u64(&mut |v| self.fill_bytes(v))
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            let mib = [libc::CTL_KERN, libc::KERN_ARND];
            // kern.arandom permits a maximum buffer size of 256 bytes
            for s in v.chunks_mut(256) {
                let mut s_len = s.len();
                let ret = unsafe {
                    libc::sysctl(mib.as_ptr(), mib.len() as libc::c_uint,
                                 s.as_mut_ptr() as *mut _, &mut s_len,
                                 ptr::null(), 0)
                };
                if ret == -1 || s_len != s.len() {
                    panic!("kern.arandom sysctl failed! (returned {}, s.len() {}, oldlenp {})",
                           ret, s.len(), s_len);
                }
            }
        }
    }
}

#[cfg(target_os = "fuchsia")]
mod imp {
    use super::{next_u32, next_u64};

    use io;
    use rand::Rng;

    #[link(name = "magenta")]
    extern {
        fn mx_cprng_draw(buffer: *mut u8, len: usize, actual: *mut usize) -> i32;
    }

    fn getrandom(buf: &mut [u8]) -> Result<usize, i32> {
        unsafe {
            let mut actual = 0;
            let status = mx_cprng_draw(buf.as_mut_ptr(), buf.len(), &mut actual);
            if status == 0 {
                Ok(actual)
            } else {
                Err(status)
            }
        }
    }

    pub struct OsRng {
        // dummy field to ensure that this struct cannot be constructed outside
        // of this module
        _dummy: (),
    }

    impl OsRng {
        /// Create a new `OsRng`.
        pub fn new() -> io::Result<OsRng> {
            Ok(OsRng { _dummy: () })
        }
    }

    impl Rng for OsRng {
        fn next_u32(&mut self) -> u32 {
            next_u32(&mut |v| self.fill_bytes(v))
        }
        fn next_u64(&mut self) -> u64 {
            next_u64(&mut |v| self.fill_bytes(v))
        }
        fn fill_bytes(&mut self, v: &mut [u8]) {
            let mut buf = v;
            while !buf.is_empty() {
                let ret = getrandom(buf);
                match ret {
                    Err(err) => {
                        panic!("kernel mx_cprng_draw call failed! (returned {}, buf.len() {})",
                            err, buf.len())
                    }
                    Ok(actual) => {
                        let move_buf = buf;
                        buf = &mut move_buf[(actual as usize)..];
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Adjust crate attributes<commit_after><|endoftext|>


<commit_before><commit_msg>Allow a key per listener.<commit_after><|endoftext|>


<commit_before><commit_msg>The persister only needs to care about the bodies.<commit_after><|endoftext|>


<commit_before><commit_msg>Update codegen for latest nightly.<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #33169 - swgillespie:issue32829, r=eddyb<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.
#![feature(const_fn)]

const bad : u32 = {
    {
        5; //~ ERROR: blocks in constants are limited to items and tail expressions
        0
    }
};

const bad_two : u32 = {
    {
        invalid();
        //~^ ERROR: blocks in constants are limited to items and tail expressions
        //~^^ ERROR: calls in constants are limited to constant functions, struct and enum
        0
    }
};

const bad_three : u32 = {
    {
        valid();
        //~^ ERROR: blocks in constants are limited to items and tail expressions
        0
    }
};

static bad_four : u32 = {
    {
        5; //~ ERROR: blocks in statics are limited to items and tail expressions
        0
    }
};

static bad_five : u32 = {
    {
        invalid();
        //~^ ERROR: blocks in statics are limited to items and tail expressions
        //~^^ ERROR: calls in statics are limited to constant functions, struct and enum
        0
    }
};

static bad_six : u32 = {
    {
        valid();
        //~^ ERROR: blocks in statics are limited to items and tail expressions
        0
    }
};

static mut bad_seven : u32 = {
    {
        5; //~ ERROR: blocks in statics are limited to items and tail expressions
        0
    }
};

static mut bad_eight : u32 = {
    {
        invalid();
        //~^ ERROR: blocks in statics are limited to items and tail expressions
        //~^^ ERROR: calls in statics are limited to constant functions, struct and enum
        0
    }
};

static mut bad_nine : u32 = {
    {
        valid();
        //~^ ERROR: blocks in statics are limited to items and tail expressions
        0
    }
};

fn invalid() {}
const fn valid() {}

fn main() {}
<|endoftext|>


<commit_before>extern crate find_folder;
extern crate gfx_device_gl;

use std::path::PathBuf;
use piston_window::{PistonWindow, Texture, Flip, TextureSettings};

pub struct Manager {
    assets_path: PathBuf,
}

impl Manager {
    pub fn new() -> Self {
        Manager { assets_path: find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap() }
    }

    pub fn get_asset(&self, name: &str) -> PathBuf {
        self.assets_path.join(name)
    }

    pub fn get_font(&self) -> PathBuf {
        self.get_asset("NotoSans-Regular.ttf")
    }

    pub fn load_texture(&self, window: &PistonWindow) -> Texture<gfx_device_gl::Resources> {
        Texture::from_path(&mut *window.factory.borrow_mut(), self.get_asset("skeleton.png"), Flip::None, &TextureSettings::new()).unwrap()
    }
}

#[test]
fn new() {
    let manager = Manager::new();
    assert!(!manager.assets_path.to_string_lossy().is_empty());
    assert!(manager.assets_path.is_absolute());
    assert!(manager.assets_path.exists());
    assert!(manager.assets_path.is_dir());
}

#[test]
fn get_asset() {
    let manager = Manager::new();
    let asset_path = manager.get_asset("test");
    assert!(asset_path.to_string_lossy().len() > manager.assets_path.to_string_lossy().len());
}

#[test]
fn get_font() {
    let manager = Manager::new();
    let font_path = manager.get_font();
    assert!(font_path.is_absolute());
    assert!(font_path.is_file());
    assert_eq!("ttf", font_path.extension().unwrap());
}
<commit_msg>Format<commit_after>extern crate find_folder;
extern crate gfx_device_gl;

use std::path::PathBuf;
use piston_window::{PistonWindow, Texture, Flip, TextureSettings};

pub struct Manager {
    assets_path: PathBuf,
}

impl Manager {
    pub fn new() -> Self {
        Manager { assets_path: find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap() }
    }

    pub fn get_asset(&self, name: &str) -> PathBuf {
        self.assets_path.join(name)
    }

    pub fn get_font(&self) -> PathBuf {
        self.get_asset("NotoSans-Regular.ttf")
    }

    pub fn load_texture(&self, window: &PistonWindow) -> Texture<gfx_device_gl::Resources> {
        Texture::from_path(&mut *window.factory.borrow_mut(),
                           self.get_asset("skeleton.png"),
                           Flip::None,
                           &TextureSettings::new())
            .unwrap()
    }
}

#[test]
fn new() {
    let manager = Manager::new();
    assert!(!manager.assets_path.to_string_lossy().is_empty());
    assert!(manager.assets_path.is_absolute());
    assert!(manager.assets_path.exists());
    assert!(manager.assets_path.is_dir());
}

#[test]
fn get_asset() {
    let manager = Manager::new();
    let asset_path = manager.get_asset("test");
    assert!(asset_path.to_string_lossy().len() > manager.assets_path.to_string_lossy().len());
}

#[test]
fn get_font() {
    let manager = Manager::new();
    let font_path = manager.get_font();
    assert!(font_path.is_absolute());
    assert!(font_path.is_file());
    assert_eq!("ttf", font_path.extension().unwrap());
}
<|endoftext|>


<commit_before><commit_msg>fixup! Factor out the "naive" implementation functionality.<commit_after>macro_rules! special_cases {
    ($($icount: expr, $in_: ident $iwidth: expr,
       $ocount: expr, $out: ident $owidth: expr,
       $instr: expr, $promote: ident);*;) => {{
        let mut map = ::std::collections::HashMap::new();
        $(
            map.insert((::ty::Type::new(stringify!($in_), $iwidth, $icount),
                        ::ty::Type::new(stringify!($out), $owidth, $ocount)),
                       ($instr, ::src::Promotion::$promote));
            )*
            map
    }}
}
<|endoftext|>


<commit_before><commit_msg>Add Rust implememtation<commit_after>// https://www.hackerrank.com/challenges/angry-professor/problem

/*
 * Implementation questions:
 *
 * 1. Why do I need to use `&t` in: `filter(|&t| t <= 0)`?
 */

use std::io;
use std::fmt;
use std::convert::TryFrom;

struct Case {
    min_students_on_time: i32,
    arrival_times: Vec<i32>,
}

enum Answer {
    YES,
    NO,
}

impl fmt::Display for Answer {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Answer::YES => write!(f, "YES"),
            Answer::NO => write!(f, "NO"),
        }
    }
}

fn main() {
    let cases = to_int(&read_line());
    for _ in 0..cases {
        let case = read_case();
        println!("{}", is_class_cancelled(case));
    }
}

fn read_line() -> String {
    let mut buffer = String::new();
    io::stdin()
        .read_line(&mut buffer)
        .expect("Failed to read line");
    return buffer.trim().to_owned();
}

fn to_int(str: &str) -> i32 {
    return str.parse::<i32>().unwrap();
}

fn read_case_first_line() -> (i32, i32) {
    let line = &read_line();
    let list: Vec<&str> = line.split(" ").collect();
    let students = to_int(list[0]);
    let min_students_on_time = to_int(list[1]);
    return (students, min_students_on_time);
}

fn read_case_second_line() -> Vec<i32> {
    let line = &read_line();
    let list: Vec<&str> = line.split(" ").collect();
    return list.into_iter().map(|x| to_int(x)).collect();
}

fn read_case() -> Case {
    let (students, min_students_on_time) = read_case_first_line();
    let arrival_times = read_case_second_line();
    let arrivals_size = i32::try_from(arrival_times.len()).unwrap();
    assert_eq!(students, arrivals_size, "arrival_times size is not correct");
    return Case {
        min_students_on_time: min_students_on_time,
        arrival_times: arrival_times,
    };
}

fn is_class_cancelled(case: Case) -> Answer {
    let students_on_time = case.arrival_times.into_iter().filter(|&t| t <= 0).count();
    if i32::try_from(students_on_time).unwrap() >= case.min_students_on_time {
        return Answer::NO;
    }
    return Answer::YES;
}
<|endoftext|>


<commit_before><commit_msg>Add test for icompr!()<commit_after>#![feature(phase)]

#[phase(link, plugin)]

extern crate itertools;

use std::iter::AdditiveIterator;

#[test]
fn icompr() {
    let log = "GET / 4096\nGET /home/ 16301\nPOST /home/ 49\nGET / 4096\n";
    let lines = log.lines();
    let rows = icompr!(line.words() for line in lines);
    let ngets = icompr!(1i for mut row in rows if row.next() == Some("GET")).sum();
    assert_eq!(ngets, 3i);
}
<|endoftext|>


<commit_before>generate_error_module!(
    generate_error_types!(GitHookError, GitHookErrorKind,
        ConfigError => "Configuration Error",
        ConfigTypeError => "Configuration value type wrong",
        RepositoryError                   => "Error while interacting with git repository",
        RepositoryBranchError             => "Error while interacting with git branch(es)",
        RepositoryBranchNameFetchingError => "Error while fetching branch name",
        RepositorySignatureFetchingError  => "Error while fetching Authors/Committers signature",
        RepositoryIndexFetchingError      => "Error while fetching Repository Index",
        RepositoryPathAddingError         => "Error while adding Path to Index",
        RepositoryTreeWritingError        => "Error while writing repository tree",
        RepositoryTreeFindingError        => "Error while finding repository tree",
        RepositoryCommitFindingError      => "Error while finding commit",
        RepositoryCommittingError         => "Error while committing",
        HeadFetchError                    => "Error while getting HEAD",
        NotOnBranch                       => "No Branch is checked out",
        MkRepo => "Repository creation error",
        MkSignature => "Error while building Signature object"
    );
);

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

<commit_msg>Add GitHookError::inside_if()<commit_after>use libimagstore::hook::error::HookError as HE;
use libimagstore::hook::error::HookErrorKind as HEK;
use libimagstore::hook::result::HookResult;

generate_error_module!(
    generate_error_types!(GitHookError, GitHookErrorKind,
        ConfigError => "Configuration Error",
        ConfigTypeError => "Configuration value type wrong",
        RepositoryError                   => "Error while interacting with git repository",
        RepositoryBranchError             => "Error while interacting with git branch(es)",
        RepositoryBranchNameFetchingError => "Error while fetching branch name",
        RepositorySignatureFetchingError  => "Error while fetching Authors/Committers signature",
        RepositoryIndexFetchingError      => "Error while fetching Repository Index",
        RepositoryPathAddingError         => "Error while adding Path to Index",
        RepositoryTreeWritingError        => "Error while writing repository tree",
        RepositoryTreeFindingError        => "Error while finding repository tree",
        RepositoryCommitFindingError      => "Error while finding commit",
        RepositoryCommittingError         => "Error while committing",
        HeadFetchError                    => "Error while getting HEAD",
        NotOnBranch                       => "No Branch is checked out",
        MkRepo => "Repository creation error",
        MkSignature => "Error while building Signature object"
    );
);

impl GitHookError {

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

}

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

<|endoftext|>


<commit_before><commit_msg>Apply clippy suggestion<commit_after><|endoftext|>