<commit_before>//! Implementations of the [`quickcheck::Arbitrary`](quickcheck_dep::Arbitrary) trait.
//!
//! This enables users to write tests such as this, and have test values provided automatically:
//!
//! ```
//! # #![allow(dead_code)]
//! # use quickcheck_dep::quickcheck;
//! # #[cfg(pretend_we_didnt_rename_the_dependency)]
//! use quickcheck::quickcheck;
//! use time::Date;
//!
//! struct DateRange {
//!     from: Date,
//!     to: Date,
//! }
//!
//! impl DateRange {
//!     fn new(from: Date, to: Date) -> Result<Self, ()> {
//!         Ok(DateRange { from, to })
//!     }
//! }
//!
//! quickcheck! {
//!     fn date_range_is_well_defined(from: Date, to: Date) -> bool {
//!         let r = DateRange::new(from, to);
//!         if from <= to {
//!             r.is_ok()
//!         } else {
//!             r.is_err()
//!         }
//!     }
//! }
//! ```
//!
//! An implementation for `Instant` is intentionally omitted since its values are only meaningful in
//! relation to a [`Duration`], and obtaining an `Instant` from a [`Duration`] is very simple
//! anyway.

use alloc::boxed::Box;

use quickcheck_dep::{empty_shrinker, single_shrinker, Arbitrary, Gen};

use crate::date::{MAX_YEAR, MIN_YEAR};
use crate::util::days_in_year;
use crate::{Date, Duration, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday};

/// Obtain an arbitrary value between the minimum and maximum inclusive.
macro_rules! arbitrary_between {
    ($type:ty; $gen:expr, $min:expr, $max:expr) => {{
        let min = $min;
        let max = $max;
        let range = max - min;
        <$type>::arbitrary($gen).rem_euclid(range + 1) + min
    }};
}

impl Arbitrary for Date {
    fn arbitrary(g: &mut Gen) -> Self {
        let year = arbitrary_between!(i32; g, MIN_YEAR, MAX_YEAR);
        let ordinal = arbitrary_between!(u16; g, 1, days_in_year(year));
        Self::__from_ordinal_date_unchecked(year, ordinal)
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            self.to_ordinal_date()
                .shrink()
                .flat_map(|(year, ordinal)| Self::from_ordinal_date(year, ordinal)),
        )
    }
}

impl Arbitrary for Duration {
    fn arbitrary(g: &mut Gen) -> Self {
        let seconds = i64::arbitrary(g);
        let mut nanoseconds = arbitrary_between!(i32; g, 0, 999_999_999);

        // Coerce the sign if necessary. Also allow for the creation of a negative Duration under
        // one second.
        if seconds < 0 || (seconds == 0 && bool::arbitrary(g)) {
            nanoseconds *= -1;
        }

        Self::new_unchecked(seconds, nanoseconds)
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            (self.subsec_nanoseconds(), self.whole_seconds())
                .shrink()
                .map(|(mut nanoseconds, seconds)| {
                    // Coerce the sign if necessary.
                    if (seconds > 0 && nanoseconds < 0) || (seconds < 0 && nanoseconds > 0) {
                        nanoseconds *= -1;
                    }

                    Self::new_unchecked(seconds, nanoseconds)
                }),
        )
    }
}

impl Arbitrary for Time {
    fn arbitrary(g: &mut Gen) -> Self {
        Self::__from_hms_nanos_unchecked(
            arbitrary_between!(u8; g, 0, 23),
            arbitrary_between!(u8; g, 0, 59),
            arbitrary_between!(u8; g, 0, 59),
            arbitrary_between!(u32; g, 0, 999_999_999),
        )
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            self.as_hms_nano()
                .shrink()
                .map(|(hour, minute, second, nanosecond)| {
                    Self::__from_hms_nanos_unchecked(hour, minute, second, nanosecond)
                }),
        )
    }
}

impl Arbitrary for PrimitiveDateTime {
    fn arbitrary(g: &mut Gen) -> Self {
        Self::new(Date::arbitrary(g), Time::arbitrary(g))
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            (self.date, self.time)
                .shrink()
                .map(|(date, time)| Self { date, time }),
        )
    }
}

impl Arbitrary for UtcOffset {
    fn arbitrary(g: &mut Gen) -> Self {
        let hours = arbitrary_between!(i8; g, -23, 23);
        let mut minutes = arbitrary_between!(i8; g, 0, 59);
        let mut seconds = arbitrary_between!(i8; g, 0, 59);

        // Coerce the signs if necessary. Also allow for the creation of a negative offset under one
        // hour.
        if hours < 0
            || (hours == 0 && bool::arbitrary(g))
            || (hours == 0 && minutes == 0 && bool::arbitrary(g))
        {
            minutes *= -1;
            seconds *= -1;
        }

        Self::__from_hms_unchecked(hours, minutes, seconds)
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            self.as_hms()
                .shrink()
                .map(|(hours, mut minutes, mut seconds)| {
                    // Coerce the signs if necessary.
                    if (hours > 0 && minutes < 0) || (hours < 0 && minutes > 0) {
                        minutes *= -1;
                    }
                    if (hours > 0 && seconds < 0)
                        || (hours < 0 && seconds > 0)
                        || (minutes > 0 && seconds < 0)
                        || (minutes < 0 && seconds > 0)
                    {
                        seconds *= -1;
                    }

                    Self::__from_hms_unchecked(hours, minutes, seconds)
                }),
        )
    }
}

impl Arbitrary for OffsetDateTime {
    fn arbitrary(g: &mut Gen) -> Self {
        let datetime = PrimitiveDateTime::arbitrary(g);
        let offset = UtcOffset::arbitrary(g);
        datetime.assume_offset(offset)
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            (self.utc_datetime.utc_to_offset(self.offset), self.offset)
                .shrink()
                .map(|(utc_datetime, offset)| utc_datetime.assume_offset(offset)),
        )
    }
}

impl Arbitrary for Weekday {
    fn arbitrary(g: &mut Gen) -> Self {
        use Weekday::*;
        match arbitrary_between!(u8; g, 0, 6) {
            0 => Monday,
            1 => Tuesday,
            2 => Wednesday,
            3 => Thursday,
            4 => Friday,
            5 => Saturday,
            _ => Sunday,
        }
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        match self {
            Self::Monday => empty_shrinker(),
            _ => single_shrinker(self.previous()),
        }
    }
}
<commit_msg>Remove unnecessary coercion in quickcheck shrinker<commit_after>//! Implementations of the [`quickcheck::Arbitrary`](quickcheck_dep::Arbitrary) trait.
//!
//! This enables users to write tests such as this, and have test values provided automatically:
//!
//! ```
//! # #![allow(dead_code)]
//! # use quickcheck_dep::quickcheck;
//! # #[cfg(pretend_we_didnt_rename_the_dependency)]
//! use quickcheck::quickcheck;
//! use time::Date;
//!
//! struct DateRange {
//!     from: Date,
//!     to: Date,
//! }
//!
//! impl DateRange {
//!     fn new(from: Date, to: Date) -> Result<Self, ()> {
//!         Ok(DateRange { from, to })
//!     }
//! }
//!
//! quickcheck! {
//!     fn date_range_is_well_defined(from: Date, to: Date) -> bool {
//!         let r = DateRange::new(from, to);
//!         if from <= to {
//!             r.is_ok()
//!         } else {
//!             r.is_err()
//!         }
//!     }
//! }
//! ```
//!
//! An implementation for `Instant` is intentionally omitted since its values are only meaningful in
//! relation to a [`Duration`], and obtaining an `Instant` from a [`Duration`] is very simple
//! anyway.

use alloc::boxed::Box;

use quickcheck_dep::{empty_shrinker, single_shrinker, Arbitrary, Gen};

use crate::date::{MAX_YEAR, MIN_YEAR};
use crate::util::days_in_year;
use crate::{Date, Duration, OffsetDateTime, PrimitiveDateTime, Time, UtcOffset, Weekday};

/// Obtain an arbitrary value between the minimum and maximum inclusive.
macro_rules! arbitrary_between {
    ($type:ty; $gen:expr, $min:expr, $max:expr) => {{
        let min = $min;
        let max = $max;
        let range = max - min;
        <$type>::arbitrary($gen).rem_euclid(range + 1) + min
    }};
}

impl Arbitrary for Date {
    fn arbitrary(g: &mut Gen) -> Self {
        let year = arbitrary_between!(i32; g, MIN_YEAR, MAX_YEAR);
        let ordinal = arbitrary_between!(u16; g, 1, days_in_year(year));
        Self::__from_ordinal_date_unchecked(year, ordinal)
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            self.to_ordinal_date()
                .shrink()
                .flat_map(|(year, ordinal)| Self::from_ordinal_date(year, ordinal)),
        )
    }
}

impl Arbitrary for Duration {
    fn arbitrary(g: &mut Gen) -> Self {
        let seconds = i64::arbitrary(g);
        let mut nanoseconds = arbitrary_between!(i32; g, 0, 999_999_999);

        // Coerce the sign if necessary. Also allow for the creation of a negative Duration under
        // one second.
        if seconds < 0 || (seconds == 0 && bool::arbitrary(g)) {
            nanoseconds *= -1;
        }

        Self::new_unchecked(seconds, nanoseconds)
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            (self.subsec_nanoseconds(), self.whole_seconds())
                .shrink()
                .map(|(mut nanoseconds, seconds)| {
                    // Coerce the sign if necessary.
                    if (seconds > 0 && nanoseconds < 0) || (seconds < 0 && nanoseconds > 0) {
                        nanoseconds *= -1;
                    }

                    Self::new_unchecked(seconds, nanoseconds)
                }),
        )
    }
}

impl Arbitrary for Time {
    fn arbitrary(g: &mut Gen) -> Self {
        Self::__from_hms_nanos_unchecked(
            arbitrary_between!(u8; g, 0, 23),
            arbitrary_between!(u8; g, 0, 59),
            arbitrary_between!(u8; g, 0, 59),
            arbitrary_between!(u32; g, 0, 999_999_999),
        )
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            self.as_hms_nano()
                .shrink()
                .map(|(hour, minute, second, nanosecond)| {
                    Self::__from_hms_nanos_unchecked(hour, minute, second, nanosecond)
                }),
        )
    }
}

impl Arbitrary for PrimitiveDateTime {
    fn arbitrary(g: &mut Gen) -> Self {
        Self::new(Date::arbitrary(g), Time::arbitrary(g))
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            (self.date, self.time)
                .shrink()
                .map(|(date, time)| Self { date, time }),
        )
    }
}

impl Arbitrary for UtcOffset {
    fn arbitrary(g: &mut Gen) -> Self {
        let hours = arbitrary_between!(i8; g, -23, 23);
        let mut minutes = arbitrary_between!(i8; g, 0, 59);
        let mut seconds = arbitrary_between!(i8; g, 0, 59);

        // Coerce the signs if necessary. Also allow for the creation of a negative offset under one
        // hour.
        if hours < 0
            || (hours == 0 && bool::arbitrary(g))
            || (hours == 0 && minutes == 0 && bool::arbitrary(g))
        {
            minutes *= -1;
            seconds *= -1;
        }

        Self::__from_hms_unchecked(hours, minutes, seconds)
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            self.as_hms().shrink().map(|(hours, minutes, seconds)| {
                Self::__from_hms_unchecked(hours, minutes, seconds)
            }),
        )
    }
}

impl Arbitrary for OffsetDateTime {
    fn arbitrary(g: &mut Gen) -> Self {
        let datetime = PrimitiveDateTime::arbitrary(g);
        let offset = UtcOffset::arbitrary(g);
        datetime.assume_offset(offset)
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        Box::new(
            (self.utc_datetime.utc_to_offset(self.offset), self.offset)
                .shrink()
                .map(|(utc_datetime, offset)| utc_datetime.assume_offset(offset)),
        )
    }
}

impl Arbitrary for Weekday {
    fn arbitrary(g: &mut Gen) -> Self {
        use Weekday::*;
        match arbitrary_between!(u8; g, 0, 6) {
            0 => Monday,
            1 => Tuesday,
            2 => Wednesday,
            3 => Thursday,
            4 => Friday,
            5 => Saturday,
            _ => Sunday,
        }
    }

    fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
        match self {
            Self::Monday => empty_shrinker(),
            _ => single_shrinker(self.previous()),
        }
    }
}
<|endoftext|>


<commit_before>#[derive(PartialEq, Debug, Copy, Clone)]
pub enum TwigValueRef<'a> {
    Num(TwigNumberRef<'a>),
    Str(&'a str),
}

impl<'a> TwigValueRef<'a> {
    pub fn new_big_num<'c>(num: &'c str) -> TwigValueRef<'c> {
        TwigValueRef::Num(TwigNumberRef::Big(num))
    }

    pub fn new_float<'c>(num: f64) -> TwigValueRef<'c> {
        TwigValueRef::Num(TwigNumberRef::Float(num))
    }

    pub fn new_int<'c>(num: i64) -> TwigValueRef<'c> {
        TwigValueRef::Num(TwigNumberRef::Int(num))
    }

    pub fn new_str<'c>(s: &'c str) -> TwigValueRef<'c> {
        TwigValueRef::Str(s)
    }
}

impl<'a> Into<TwigValue> for TwigValueRef<'a> {
    fn into(self) -> TwigValue {
        match self {
            TwigValueRef::Num(n) => TwigValue::Num(n.into()),
            TwigValueRef::Str(s) => TwigValue::Str(s.into()),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum TwigValue {
    Num(OwnedTwigNumber),
    Str(String),
}

/// Parsed twig number representation.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum TwigNumberRef<'a> {
    Big(&'a str),
    Float(f64),
    Int(i64),
}

/// Parsed twig number representation.
#[derive(PartialEq, Debug, Clone)]
pub enum OwnedTwigNumber {
    Big(String),
    Float(f64),
    Int(i64),
}

impl<'a> Into<OwnedTwigNumber> for TwigNumberRef<'a> {
    fn into(self) -> OwnedTwigNumber {
        match self {
            TwigNumberRef::Big(n) => OwnedTwigNumber::Big(n.to_string()),
            TwigNumberRef::Float(v) => OwnedTwigNumber::Float(v),
            TwigNumberRef::Int(v) => OwnedTwigNumber::Int(v),
        }
    }
}
<commit_msg>Rename OwnedTwigNumber to TwigNumber.<commit_after>#[derive(PartialEq, Debug, Copy, Clone)]
pub enum TwigValueRef<'a> {
    Num(TwigNumberRef<'a>),
    Str(&'a str),
}

impl<'a> TwigValueRef<'a> {
    pub fn new_big_num<'c>(num: &'c str) -> TwigValueRef<'c> {
        TwigValueRef::Num(TwigNumberRef::Big(num))
    }

    pub fn new_float<'c>(num: f64) -> TwigValueRef<'c> {
        TwigValueRef::Num(TwigNumberRef::Float(num))
    }

    pub fn new_int<'c>(num: i64) -> TwigValueRef<'c> {
        TwigValueRef::Num(TwigNumberRef::Int(num))
    }

    pub fn new_str<'c>(s: &'c str) -> TwigValueRef<'c> {
        TwigValueRef::Str(s)
    }
}

impl<'a> Into<TwigValue> for TwigValueRef<'a> {
    fn into(self) -> TwigValue {
        match self {
            TwigValueRef::Num(n) => TwigValue::Num(n.into()),
            TwigValueRef::Str(s) => TwigValue::Str(s.into()),
        }
    }
}

#[derive(PartialEq, Debug, Clone)]
pub enum TwigValue {
    Num(TwigNumber),
    Str(String),
}

/// Parsed twig number representation.
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum TwigNumberRef<'a> {
    Big(&'a str),
    Float(f64),
    Int(i64),
}

/// Parsed twig number representation.
#[derive(PartialEq, Debug, Clone)]
pub enum TwigNumber {
    Big(String),
    Float(f64),
    Int(i64),
}

impl<'a> Into<TwigNumber> for TwigNumberRef<'a> {
    fn into(self) -> TwigNumber {
        match self {
            TwigNumberRef::Big(n) => TwigNumber::Big(n.to_string()),
            TwigNumberRef::Float(v) => TwigNumber::Float(v),
            TwigNumberRef::Int(v) => TwigNumber::Int(v),
        }
    }
}
<|endoftext|>


<commit_before>use std::num::NonZeroU8;
use std::{fmt, ops};

/// Interests used in registering.
///
/// Interests are used in [registering] [`event::Source`]s with [`Poll`], they
/// indicate what readiness should be monitored for. For example if a socket is
/// registered with [readable] interests and the socket becomes writable, no
/// event will be returned from a call to [`poll`].
///
/// The size of `Option<Interests>` should be identical to itself.
///
/// ```
/// use std::mem::size_of;
/// use mio::Interests;
///
/// assert_eq!(size_of::<Option<Interests>>(), size_of::<Interests>());
/// ```
///
/// [registering]: crate::Registry::register
/// [`event::Source`]: crate::event::Source
/// [`Poll`]: crate::Poll
/// [readable]: Interests::READABLE
/// [`poll`]: crate::Poll::poll
#[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Interests(NonZeroU8);

// These must be unique.
const READABLE: u8 = 0b0_001;
const WRITABLE: u8 = 0b0_010;
// The following are not available on all platforms.
#[cfg_attr(
    not(any(
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "ios",
        target_os = "macos"
    )),
    allow(dead_code)
)]
const AIO: u8 = 0b0_100;
#[cfg_attr(not(target_os = "freebsd"), allow(dead_code))]
const LIO: u8 = 0b1_000;

impl Interests {
    /// Returns a `Interests` set representing readable interests.
    pub const READABLE: Interests = Interests(unsafe { NonZeroU8::new_unchecked(READABLE) });

    /// Returns a `Interests` set representing writable interests.
    pub const WRITABLE: Interests = Interests(unsafe { NonZeroU8::new_unchecked(WRITABLE) });

    /// Returns a `Interests` set representing AIO completion interests.
    #[cfg(any(
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "ios",
        target_os = "macos"
    ))]
    pub const AIO: Interests = Interests(unsafe { NonZeroU8::new_unchecked(AIO) });

    /// Returns a `Interests` set representing LIO completion interests.
    #[cfg(target_os = "freebsd")]
    pub const LIO: Interests = Interests(unsafe { NonZeroU8::new_unchecked(LIO) });

    /// Returns true if the value includes readable readiness.
    pub fn is_readable(self) -> bool {
        (self.0.get() & READABLE) != 0
    }

    /// Returns true if the value includes writable readiness.
    pub fn is_writable(self) -> bool {
        (self.0.get() & WRITABLE) != 0
    }

    /// Returns true if `Interests` contains AIO readiness
    pub fn is_aio(self) -> bool {
        (self.0.get() & AIO) != 0
    }

    /// Returns true if `Interests` contains LIO readiness
    pub fn is_lio(self) -> bool {
        (self.0.get() & LIO) != 0
    }
}

impl ops::BitOr for Interests {
    type Output = Self;

    #[inline]
    fn bitor(self, other: Self) -> Self {
        Interests(unsafe { NonZeroU8::new_unchecked(self.0.get() | other.0.get()) })
    }
}

impl ops::BitOrAssign for Interests {
    #[inline]
    fn bitor_assign(&mut self, other: Self) {
        self.0 = (*self | other).0;
    }
}

impl fmt::Debug for Interests {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut one = false;
        if self.is_readable() {
            if one {
                write!(fmt, " | ")?
            }
            write!(fmt, "READABLE")?;
            one = true
        }
        if self.is_writable() {
            if one {
                write!(fmt, " | ")?
            }
            write!(fmt, "WRITABLE")?;
            one = true
        }
        #[cfg(any(
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "ios",
            target_os = "macos"
        ))]
        {
            if self.is_aio() {
                if one {
                    write!(fmt, " | ")?
                }
                write!(fmt, "AIO")?;
                one = true
            }
        }
        #[cfg(any(target_os = "freebsd"))]
        {
            if self.is_lio() {
                if one {
                    write!(fmt, " | ")?
                }
                write!(fmt, "LIO")?;
                one = true
            }
        }
        debug_assert!(one, "printing empty interests");
        Ok(())
    }
}
<commit_msg>Add Interests::and<commit_after>use std::num::NonZeroU8;
use std::{fmt, ops};

/// Interests used in registering.
///
/// Interests are used in [registering] [`event::Source`]s with [`Poll`], they
/// indicate what readiness should be monitored for. For example if a socket is
/// registered with [readable] interests and the socket becomes writable, no
/// event will be returned from a call to [`poll`].
///
/// The size of `Option<Interests>` should be identical to itself.
///
/// ```
/// use std::mem::size_of;
/// use mio::Interests;
///
/// assert_eq!(size_of::<Option<Interests>>(), size_of::<Interests>());
/// ```
///
/// [registering]: crate::Registry::register
/// [`event::Source`]: crate::event::Source
/// [`Poll`]: crate::Poll
/// [readable]: Interests::READABLE
/// [`poll`]: crate::Poll::poll
#[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Interests(NonZeroU8);

// These must be unique.
const READABLE: u8 = 0b0_001;
const WRITABLE: u8 = 0b0_010;
// The following are not available on all platforms.
#[cfg_attr(
    not(any(
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "ios",
        target_os = "macos"
    )),
    allow(dead_code)
)]
const AIO: u8 = 0b0_100;
#[cfg_attr(not(target_os = "freebsd"), allow(dead_code))]
const LIO: u8 = 0b1_000;

impl Interests {
    /// Returns a `Interests` set representing readable interests.
    pub const READABLE: Interests = Interests(unsafe { NonZeroU8::new_unchecked(READABLE) });

    /// Returns a `Interests` set representing writable interests.
    pub const WRITABLE: Interests = Interests(unsafe { NonZeroU8::new_unchecked(WRITABLE) });

    /// Returns a `Interests` set representing AIO completion interests.
    #[cfg(any(
        target_os = "dragonfly",
        target_os = "freebsd",
        target_os = "ios",
        target_os = "macos"
    ))]
    pub const AIO: Interests = Interests(unsafe { NonZeroU8::new_unchecked(AIO) });

    /// Returns a `Interests` set representing LIO completion interests.
    #[cfg(target_os = "freebsd")]
    pub const LIO: Interests = Interests(unsafe { NonZeroU8::new_unchecked(LIO) });

    /// Add together two `Interests`.
    ///
    /// This does the same thing as the `BitOr` implementation, but is a
    /// constant function.
    ///
    /// ```
    /// use mio::Interests;
    ///
    /// const INTERESTS: Interests = Interests::READABLE.and(Interests::WRITABLE);
    /// # fn silent_dead_code_warning(_: Interests) { }
    /// # silent_dead_code_warning(INTERESTS)
    /// ```
    pub const fn and(self, other: Interests) -> Interests {
        Interests(unsafe { NonZeroU8::new_unchecked(self.0.get() | other.0.get()) })
    }

    /// Returns true if the value includes readable readiness.
    pub fn is_readable(self) -> bool {
        (self.0.get() & READABLE) != 0
    }

    /// Returns true if the value includes writable readiness.
    pub fn is_writable(self) -> bool {
        (self.0.get() & WRITABLE) != 0
    }

    /// Returns true if `Interests` contains AIO readiness
    pub fn is_aio(self) -> bool {
        (self.0.get() & AIO) != 0
    }

    /// Returns true if `Interests` contains LIO readiness
    pub fn is_lio(self) -> bool {
        (self.0.get() & LIO) != 0
    }
}

impl ops::BitOr for Interests {
    type Output = Self;

    #[inline]
    fn bitor(self, other: Self) -> Self {
        Interests(unsafe { NonZeroU8::new_unchecked(self.0.get() | other.0.get()) })
    }
}

impl ops::BitOrAssign for Interests {
    #[inline]
    fn bitor_assign(&mut self, other: Self) {
        self.0 = (*self | other).0;
    }
}

impl fmt::Debug for Interests {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut one = false;
        if self.is_readable() {
            if one {
                write!(fmt, " | ")?
            }
            write!(fmt, "READABLE")?;
            one = true
        }
        if self.is_writable() {
            if one {
                write!(fmt, " | ")?
            }
            write!(fmt, "WRITABLE")?;
            one = true
        }
        #[cfg(any(
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "ios",
            target_os = "macos"
        ))]
        {
            if self.is_aio() {
                if one {
                    write!(fmt, " | ")?
                }
                write!(fmt, "AIO")?;
                one = true
            }
        }
        #[cfg(any(target_os = "freebsd"))]
        {
            if self.is_lio() {
                if one {
                    write!(fmt, " | ")?
                }
                write!(fmt, "LIO")?;
                one = true
            }
        }
        debug_assert!(one, "printing empty interests");
        Ok(())
    }
}
<|endoftext|>


<commit_before>use std::fs::File;
use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
use std::path::Path;

use dynimage::DynamicImage;
use image::ImageFormat;
use {ImageError, ImageResult};

use super::free_functions;

/// A multi-format image reader.
///
/// Wraps an input reader to facilitate automatic detection of an image's format, appropriate
/// decoding method, and dispatches into the set of supported [`ImageDecoder`] implementations.
///
/// ## Usage
///
/// Opening a file, deducing the format based on the file path automatically, and trying to decode
/// the image contained can be performed by constructing the reader and immediately consuming it.
///
/// ```no_run
/// # use image::ImageError;
/// # use image::io::Reader;
/// # fn main() -> Result<(), ImageError> {
/// let image = Reader::open("path/to/image.png")?
///     .decode()?;
/// # Ok(()) }
/// ```
///
/// It is also possible to make a guess based on the content. This is especially handy if the
/// source is some blob in memory and you have constructed the reader in another way. Here is an
/// example with a `pnm` black-and-white subformat that encodes its pixel matrix with ascii values.
///
/// ```no_run
/// # use image::ImageError;
/// # use image::io::Reader;
/// # fn main() -> Result<(), ImageError> {
/// use std::io::Cursor;
/// use image::ImageFormat;
///
/// let raw_data = b"P1 2 2\
///     0 1\
///     1 0";
///
/// let mut reader = Reader::new(Cursor::new(raw_data));
/// reader.guess_format().expect("Cursor io never fails");
/// assert_eq!(reader.format(), Some(ImageFormat::PNM));
///
/// let image = reader.decode()?;
/// # Ok(()) }
/// ```
///
/// As a final fallback or if only a specific format must be used, the reader always allows manual
/// specification of the supposed image format with [`set_format`].
///
/// [`set_format`]: #method.set_format
/// [`ImageDecoder`]: ../trait.ImageDecoder.html
pub struct Reader<R: Read> {
    /// The reader.
    inner: R,
    /// The format, if one has been set or deduced.
    format: Option<ImageFormat>,
}

impl<R: Read> Reader<R> {
    /// Create a new image reader without a preset format.
    ///
    /// It is possible to guess the format based on the content of the read object with
    /// [`guess_format`], or to set the format directly with [`set_format`].
    ///
    /// [`guess_format`]: #method.guess_format
    /// [`set_format`]: method.set_format
    pub fn new(reader: R) -> Self {
        Reader {
            inner: reader,
            format: None,
        }
    }

    /// Construct a reader with specified format.
    pub fn with_format(reader: R, format: ImageFormat) -> Self {
        Reader {
            inner: reader,
            format: Some(format),
        }
    }

    /// Get the currently determined format.
    pub fn format(&self) -> Option<ImageFormat> {
        self.format
    }

    /// Supply the format as which to interpret the read image.
    pub fn set_format(&mut self, format: ImageFormat) {
        self.format = Some(format);
    }

    /// Remove the current information on the image format.
    ///
    /// Note that many operations require format information to be present and will return e.g. an
    /// `ImageError::UnsupportedError` when the image format has not been set.
    pub fn clear_format(&mut self) {
        self.format = None;
    }

    /// Unwrap the reader.
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl Reader<BufReader<File>> {
    /// Open a file to read, format will be guessed from path.
    ///
    /// This will not attempt any io operation on the opened file.
    ///
    /// If you want to inspect the content for a better guess on the format, which does not depend
    /// on file extensions, follow this call with a call to [`guess_format`].
    ///
    /// [`guess_format`]: #method.guess_format
    pub fn open<P>(path: P) -> io::Result<Self> where P: AsRef<Path> {
        Self::open_impl(path.as_ref())
    }

    fn open_impl(path: &Path) -> io::Result<Self> {
        let file = File::open(path)?;
        Ok(Reader {
            inner: BufReader::new(file),
            format: ImageFormat::from_path(path).ok(),
        })
    }
}

impl<R: BufRead + Seek> Reader<R> {
    /// Replace the format with a guess based on the content.
    ///
    /// If the guess fails, the format is unchanged. Error is for seek, hence io::Error
    /// and not ImageError.
    pub fn guess_format(&mut self) -> io::Result<()> {
        let mut start = [0; 16];

        // Save current offset, read start, restore offset.
        let cur = self.inner.seek(SeekFrom::Current(0))?;
        let len = io::copy(
            // Accept shorter files but read at most 16 bytes.
            &mut self.inner.by_ref().take(16),
            &mut Cursor::new(&mut start[..]))?;
        self.inner.seek(SeekFrom::Start(cur))?;

        if let Ok(format) = free_functions::guess_format(&start[..len as usize]) {
            self.format = Some(format);
        }
        Ok(())
    }

    /// Read the image dimensions.
    ///
    /// Uses the current format to construct the correct reader for the format.
    ///
    /// If no format was determined, returns an `ImageError::UnsupportedError`.
    pub fn dimensions(mut self) -> ImageResult<(u32, u32)> {
        let format = self.require_format()?;
        free_functions::image_dimensions_with_format_impl(self.inner, format)
    }

    /// Read the image (replaces `load`).
    ///
    /// Uses the current format to construct the correct reader for the format.
    ///
    /// If no format was determined, returns an `ImageError::UnsupportedError`.
    pub fn decode(mut self) -> ImageResult<DynamicImage> {
        let format = self.require_format()?;
        free_functions::load(self.inner, format)
    }

    fn require_format(&mut self) -> ImageResult<ImageFormat> {
        self.format.ok_or_else(||
            ImageError::UnsupportedError("Unable to determine image format".into()))
    }
}
<commit_msg>Split guessing and applying guessed format<commit_after>use std::fs::File;
use std::io::{self, BufRead, BufReader, Cursor, Read, Seek, SeekFrom};
use std::path::Path;

use dynimage::DynamicImage;
use image::ImageFormat;
use {ImageError, ImageResult};

use super::free_functions;

/// A multi-format image reader.
///
/// Wraps an input reader to facilitate automatic detection of an image's format, appropriate
/// decoding method, and dispatches into the set of supported [`ImageDecoder`] implementations.
///
/// ## Usage
///
/// Opening a file, deducing the format based on the file path automatically, and trying to decode
/// the image contained can be performed by constructing the reader and immediately consuming it.
///
/// ```no_run
/// # use image::ImageError;
/// # use image::io::Reader;
/// # fn main() -> Result<(), ImageError> {
/// let image = Reader::open("path/to/image.png")?
///     .decode()?;
/// # Ok(()) }
/// ```
///
/// It is also possible to make a guess based on the content. This is especially handy if the
/// source is some blob in memory and you have constructed the reader in another way. Here is an
/// example with a `pnm` black-and-white subformat that encodes its pixel matrix with ascii values.
///
/// ```no_run
/// # use image::ImageError;
/// # use image::io::Reader;
/// # fn main() -> Result<(), ImageError> {
/// use std::io::Cursor;
/// use image::ImageFormat;
///
/// let raw_data = b"P1 2 2\
///     0 1\
///     1 0";
///
/// let mut reader = Reader::new(Cursor::new(raw_data));
/// reader.guess_format().expect("Cursor io never fails");
/// assert_eq!(reader.format(), Some(ImageFormat::PNM));
///
/// let image = reader.decode()?;
/// # Ok(()) }
/// ```
///
/// As a final fallback or if only a specific format must be used, the reader always allows manual
/// specification of the supposed image format with [`set_format`].
///
/// [`set_format`]: #method.set_format
/// [`ImageDecoder`]: ../trait.ImageDecoder.html
pub struct Reader<R: Read> {
    /// The reader.
    inner: R,
    /// The format, if one has been set or deduced.
    format: Option<ImageFormat>,
}

impl<R: Read> Reader<R> {
    /// Create a new image reader without a preset format.
    ///
    /// It is possible to guess the format based on the content of the read object with
    /// [`guess_format`], or to set the format directly with [`set_format`].
    ///
    /// [`guess_format`]: #method.guess_format
    /// [`set_format`]: method.set_format
    pub fn new(reader: R) -> Self {
        Reader {
            inner: reader,
            format: None,
        }
    }

    /// Construct a reader with specified format.
    pub fn with_format(reader: R, format: ImageFormat) -> Self {
        Reader {
            inner: reader,
            format: Some(format),
        }
    }

    /// Get the currently determined format.
    pub fn format(&self) -> Option<ImageFormat> {
        self.format
    }

    /// Supply the format as which to interpret the read image.
    pub fn set_format(&mut self, format: ImageFormat) {
        self.format = Some(format);
    }

    /// Remove the current information on the image format.
    ///
    /// Note that many operations require format information to be present and will return e.g. an
    /// `ImageError::UnsupportedError` when the image format has not been set.
    pub fn clear_format(&mut self) {
        self.format = None;
    }

    /// Unwrap the reader.
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl Reader<BufReader<File>> {
    /// Open a file to read, format will be guessed from path.
    ///
    /// This will not attempt any io operation on the opened file.
    ///
    /// If you want to inspect the content for a better guess on the format, which does not depend
    /// on file extensions, follow this call with a call to [`guess_format`].
    ///
    /// [`guess_format`]: #method.guess_format
    pub fn open<P>(path: P) -> io::Result<Self> where P: AsRef<Path> {
        Self::open_impl(path.as_ref())
    }

    fn open_impl(path: &Path) -> io::Result<Self> {
        let file = File::open(path)?;
        Ok(Reader {
            inner: BufReader::new(file),
            format: ImageFormat::from_path(path).ok(),
        })
    }
}

impl<R: BufRead + Seek> Reader<R> {
    /// Make a format guess based on the content, replacing it on success.
    ///
    /// Returns `Ok` with the guess if no io error occurs. Additionally, replaces the current
    /// format if the guess was successful. If the guess was not unable to determine a format then
    /// the current format of the reader is unchanged.
    ///
    /// Returns an error if the underlying reader fails. The format is unchanged. The error is a
    /// `std::io::Error` and not `ImageError` since the only error case is an error when the
    /// underlying reader seeks.
    ///
    /// When an error occurs, the reader may not have been properly reset and it is potentially
    /// hazardous to continue with more io.
    ///
    /// ## Usage
    ///
    /// ```
    /// ```
    pub fn with_guessed_format(mut self) -> io::Result<Self> {
        let format = self.guess_format()?;
        // Replace format if found, keep current state if not.
        self.format = format.or(self.format);
        Ok(self)
    }

    /// Guess the format based on read data.
    pub fn guess_format(&mut self) -> io::Result<Option<ImageFormat>> {
        let mut start = [0; 16];

        // Save current offset, read start, restore offset.
        let cur = self.inner.seek(SeekFrom::Current(0))?;
        let len = io::copy(
            // Accept shorter files but read at most 16 bytes.
            &mut self.inner.by_ref().take(16),
            &mut Cursor::new(&mut start[..]))?;
        self.inner.seek(SeekFrom::Start(cur))?;

        Ok(free_functions::guess_format_impl(&start[..len as usize]))
    }

    /// Read the image dimensions.
    ///
    /// Uses the current format to construct the correct reader for the format.
    ///
    /// If no format was determined, returns an `ImageError::UnsupportedError`.
    pub fn into_dimensions(mut self) -> ImageResult<(u32, u32)> {
        let format = self.require_format()?;
        free_functions::image_dimensions_with_format_impl(self.inner, format)
    }

    /// Read the image (replaces `load`).
    ///
    /// Uses the current format to construct the correct reader for the format.
    ///
    /// If no format was determined, returns an `ImageError::UnsupportedError`.
    pub fn decode(mut self) -> ImageResult<DynamicImage> {
        let format = self.require_format()?;
        free_functions::load(self.inner, format)
    }

    fn require_format(&mut self) -> ImageResult<ImageFormat> {
        self.format.ok_or_else(||
            ImageError::UnsupportedError("Unable to determine image format".into()))
    }
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::fmt::{Debug, Error, Formatter};
use std::sync::{Arc, Mutex};

lazy_static! {
    static ref SYMBOLICATOR: Symbolicator = Symbolicator::new();
}

#[derive(Clone)]
struct Symbolicator(Arc<Mutex<InnerSymbolicator>>);

impl Symbolicator {
    fn new() -> Self {
        let inner = InnerSymbolicator::new();
        Self(Arc::new(Mutex::new(inner)))
    }

    pub fn symbolicate<S: Into<String>>(&self, string: S) -> Symbol {
        let string = string.into();
        let mut inner = self.0.lock().unwrap();
        if let Some(existing_id) = inner.symbols.get(&string) {
            return Symbol(*existing_id);
        }
        let next_id = inner.symbols.len() as u32;
        inner.symbols.insert(string, next_id);
        Symbol(next_id)
    }

    pub fn desymbolicate<S: AsRef<Symbol>>(&self, symbol: &S) -> Option<String> {
        let inner = self.0.lock().unwrap();
        let id = symbol.as_ref().0;
        for (key, value) in inner.symbols.iter() {
            if *value == id {
                return Some(key.clone());
            }
        }
        None
    }
}

type SymbolId = u32;

#[derive(Clone, PartialEq)]
pub struct Symbol(SymbolId);

impl AsRef<Symbol> for Symbol {
    fn as_ref(&self) -> &Symbol {
        &self
    }
}

#[cfg(not(test))]
impl Debug for Symbol {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        f.debug_tuple("Symbol")
            .field(&self.0)
            .field(&(*SYMBOLICATOR).desymbolicate(&self))
            .finish()
    }
}

#[cfg(test)]
impl Debug for Symbol {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        f.debug_tuple("Symbol").field(&self.0).finish()
    }
}

// Trick trait to enforce that the `Symbolicator` is thread-safe.
trait MustBeSendAndSync: Send + Sync {}

impl MustBeSendAndSync for Symbolicator {}

struct InnerSymbolicator {
    symbols: HashMap<String, SymbolId>,
}

impl InnerSymbolicator {
    pub fn new() -> Self {
        Self {
            symbols: HashMap::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::thread;

    use super::{Symbol, Symbolicator};
    use std::io::Write;

    #[test]
    fn it_symbolicates_and_desymbolicates() {
        let symbolicator = Symbolicator::new();
        let symbol = symbolicator.symbolicate("foo");
        assert_eq!(symbol, Symbol(0));
        assert_eq!(symbolicator.desymbolicate(&symbol), Some("foo".to_string()),);
        assert_eq!(symbolicator.desymbolicate(&Symbol(1)), None);
    }

    #[test]
    fn it_symbolicates_thread_safely() {
        let symbolicator = Symbolicator::new();

        // Spawn 10 of threads that will all race to symbolicate.
        let join_handles = (0..10).iter();
        for _ in 0..10 {
            let movable = symbolicator.clone();
            thread::spawn(move || {
                assert_eq!(movable.symbolicate("foo"), Symbol(0));
            });
        }

        // Spawn 10 of threads that will all race to desymbolicate.
        for _ in 0..10 {
            let movable = symbolicator.clone();
            thread::spawn(move || {
                assert_eq!(movable.desymbolicate(&Symbol(0)), Some("foo".to_string()));
            });
        }
    }
}
<commit_msg>Ensure all threads are joined in the test<commit_after>use std::collections::HashMap;
use std::fmt::{Debug, Error, Formatter};
use std::sync::{Arc, Mutex};

lazy_static! {
    static ref SYMBOLICATOR: Symbolicator = Symbolicator::new();
}

#[derive(Clone)]
struct Symbolicator(Arc<Mutex<InnerSymbolicator>>);

impl Symbolicator {
    fn new() -> Self {
        let inner = InnerSymbolicator::new();
        Self(Arc::new(Mutex::new(inner)))
    }

    pub fn symbolicate<S: Into<String>>(&self, string: S) -> Symbol {
        let string = string.into();
        let mut inner = self.0.lock().unwrap();
        if let Some(existing_id) = inner.symbols.get(&string) {
            return Symbol(*existing_id);
        }
        let next_id = inner.symbols.len() as u32;
        inner.symbols.insert(string, next_id);
        Symbol(next_id)
    }

    pub fn desymbolicate<S: AsRef<Symbol>>(&self, symbol: &S) -> Option<String> {
        let inner = self.0.lock().unwrap();
        let id = symbol.as_ref().0;
        for (key, value) in inner.symbols.iter() {
            if *value == id {
                return Some(key.clone());
            }
        }
        None
    }
}

type SymbolId = u32;

#[derive(Clone, PartialEq)]
pub struct Symbol(SymbolId);

impl AsRef<Symbol> for Symbol {
    fn as_ref(&self) -> &Symbol {
        &self
    }
}

#[cfg(not(test))]
impl Debug for Symbol {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        f.debug_tuple("Symbol")
            .field(&self.0)
            .field(&(*SYMBOLICATOR).desymbolicate(&self))
            .finish()
    }
}

#[cfg(test)]
impl Debug for Symbol {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        f.debug_tuple("Symbol").field(&self.0).finish()
    }
}

// Trick trait to enforce that the `Symbolicator` is thread-safe.
trait MustBeSendAndSync: Send + Sync {}

impl MustBeSendAndSync for Symbolicator {}

struct InnerSymbolicator {
    symbols: HashMap<String, SymbolId>,
}

impl InnerSymbolicator {
    pub fn new() -> Self {
        Self {
            symbols: HashMap::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::thread;

    use super::{Symbol, Symbolicator};
    use std::io::Write;

    #[test]
    fn it_symbolicates_and_desymbolicates() {
        let symbolicator = Symbolicator::new();
        let symbol = symbolicator.symbolicate("foo");
        assert_eq!(symbol, Symbol(0));
        assert_eq!(symbolicator.desymbolicate(&symbol), Some("foo".to_string()),);
        assert_eq!(symbolicator.desymbolicate(&Symbol(1)), None);
    }

    #[test]
    fn it_symbolicates_thread_safely() {
        let symbolicator = Symbolicator::new();

        // Spawn 10 of threads that will all race to symbolicate.
        let symbolicate_handles = (0..10)
            .into_iter()
            .map(|_| {
                let movable = symbolicator.clone();
                thread::spawn(move || {
                    assert_eq!(movable.symbolicate("foo"), Symbol(0));
                })
            })
            .collect::<Vec<thread::JoinHandle<()>>>();

        // Spawn 10 of threads that will all race to desymbolicate.
        let desymbolicate_handles = (0..10)
            .into_iter()
            .map(|_| {
                let movable = symbolicator.clone();
                thread::spawn(move || {
                    assert_eq!(movable.desymbolicate(&Symbol(0)), Some("foo".to_string()));
                })
            })
            .collect::<Vec<thread::JoinHandle<()>>>();

        for handle in symbolicate_handles
            .into_iter()
            .chain(desymbolicate_handles.into_iter())
        {
            handle.join().unwrap();
        }
    }
}
<|endoftext|>


<commit_before>/*
	Autor: Gustavo Michels de Camargo
	Projeto: Algoritmo estrural de um Grafo
*/

use std::{collections::HashMap};

// Matriz de Vector usada ara construir o Grafo.
type MatrizGrafo = Vec<Vec<isize>>;

// O dicionario serve para podermos dar entrada a qualquer String e ter como abstrair suas posições dentro.
// da matriz numerica, isso serve apenas para fins de uso, não requerer transcrever um Nodo com X para valor numerico.
#[derive(PartialEq, Eq, Clone, Debug)]
struct Grafo {
	matriz: MatrizGrafo,
	dicionario: HashMap<String, usize>,
	bicondicional: bool
}

trait Projeto {
	// Geral
	fn new(tamanho: usize, tipo: &str) -> Grafo;

	// Funções envolvendo o dicionario - Usuario
	fn usr_pegar_indice(&self, chave: String) -> usize;
	fn usr_pegar_chave(&self, indice: usize) -> String;

	// Usuario
	fn usr_adicionar_conexao(&mut self, a: String, b: String, valor: isize);
	fn usr_remover_conexao(&mut self, a: String, b: String);
	fn usr_numero_conexoes(&self, no: String) -> usize;
	fn usr_verificar_se_existe_conexao(&self, a: String, b: String) -> bool;
	fn usr_conexoes(&self, a: String) -> Vec<String>;

	// Maquina / uso para os Algoritmos
	fn adicionar_conexao(&mut self, a: usize, b: usize, valor: isize);
	fn remover_conexao(&mut self, a: usize, b: usize);
	fn numero_conexoes(&self, no: usize) -> usize;
	fn verificar_se_existe_conexao(&self, a: usize, b: usize) -> bool;
	fn conexoes(&self, a: usize) -> Vec<usize>;
}

// Este é a implementação da "Classe" de um grafo.
impl Projeto for Grafo {
	// Tamanho: Numero Maximo de Vertices que a matriz pode usar de 0 até tamanho.
	// Em notação matematica relativa a limites: [0, tamanho).
	// Toda função que começa com 'usr_'(usr = usuario) é a versão da função que deve ser usada para interagir diretamente com o usuario.
	// As funções de mesmo nome mas sem 'usr_' deve ser usada apenas dentro dos algoritmos, como o Dijkstra para menor caminho entre dois nos.
	// Fiz assim para otimizar processamento e descartar necessidade de acessar e
	// consultaro dicionario o tempo todo quando se apenas como Objetivo encontrar um menor caminho com Dijkstra por exemplo.

	// Apenas essa função foge a regra por ser universal
	fn new(tamanho: usize, tipo: &str) -> Grafo {
		Grafo {
			matriz: vec![vec![-1; tamanho]; tamanho],
			dicionario: HashMap::new(),
			bicondicional: match tipo  {
				"->" => false, // Condicional
				"<->" | _ => true // Bicondicional
			}
		}
	}

	// ---- Funções para uso direto do usuario ----

	// Retorna o indice da matriz relacionada a chave
	fn usr_pegar_indice(&self, chave: String) -> usize {
		if self.dicionario.contains_key(&chave) {
			return (&self.dicionario.get(&chave)).unwrap().clone();
		}

		return 0;
	}

	// Retorna a chave do dicionario relacionada ao valor do indice da matriz do grafo
	fn usr_pegar_chave(&self, indice: usize) -> String {
		for (key, value) in self.dicionario.iter() {
			if *value == indice {
				return (*key).clone();
			}
		}

		return "".to_string();
	}

	// Conecta Dois vertices
	fn usr_adicionar_conexao(&mut self, a: String, b: String, valor: isize) {
		if !self.dicionario.contains_key(&a){
			let num: usize = self.dicionario.len();
			self.dicionario.insert(a.to_owned(), num);
		}

		if !self.dicionario.contains_key(&b){
			let num: usize = self.dicionario.len();
			self.dicionario.insert(b.to_owned(), num);
		}

		let (valor_a, valor_b): (usize, usize) = (self.usr_pegar_indice(a), self.usr_pegar_indice(b));

		self.matriz[valor_a][valor_b] = valor;

		if self.bicondicional {
			self.matriz[valor_b][valor_a] = valor;
		}

	}

	fn usr_remover_conexao(&mut self, a: String, b: String) {
		let (valor_a, valor_b): (usize, usize) = (self.usr_pegar_indice(a), self.usr_pegar_indice(b));

		self.matriz[valor_a][valor_b]  = -1;
		self.matriz[valor_b][valor_a]  = -1;
	}

	// Retorba o numero de vertices na qual ele se conecta
	fn usr_numero_conexoes(&self, no: String) -> usize {
		self.matriz[self.usr_pegar_indice(no)].iter()
						.filter(|x| **x >= 0)
						.collect::<Vec<&isize>>()
						.len() as usize | 0
	}

	// Verifica se dois nos estão conectados
	fn usr_verificar_se_existe_conexao(&self, a: String, b: String) -> bool {
		self.matriz[self.usr_pegar_indice(a)][self.usr_pegar_indice(b)]  >= 0
	}

	fn usr_conexoes(&self, a: String) -> Vec<String> {
		let mut result: Vec<String> = Vec::new();
		let a_value: usize = self.usr_pegar_indice(a);

		for i in 0..self.matriz[a_value].len() {
			if a_value != i && self.matriz[a_value][i] > -1 {
				result.push(self.usr_pegar_chave(i));
			}
		}

		return result;
	}

	// ---- Funções para uso direto dos algoritmos (tem melhor perfomance) ----

	// Retorna um array dos indice de todos os nos na qual o no 'a' se conecta
	// Esera usar esta função apenas para usos proprios dentro do Grafo, como em algoritmos tipo dijkstra
	// Conecta Dois vertices
	fn adicionar_conexao(&mut self, a: usize, b: usize, valor: isize) {
		self.matriz[a][b] = valor;

		if self.bicondicional {
			self.matriz[b][a] = valor;
		}
	}

	fn remover_conexao(&mut self, a: usize, b: usize) {
		self.matriz[a][b]  = -1;
		self.matriz[b][a]  = -1;
	}

	// Retorba o numero de vertices na qual ele se conecta
	fn numero_conexoes(&self, no: usize) -> usize {
		self.matriz[no].iter()
						.filter(|x| **x >= 0)
						.collect::<Vec<&isize>>()
						.len() as usize | 0
	}

	fn verificar_se_existe_conexao(&self, a: usize, b: usize) -> bool {
		self.matriz[a][b]  >= 0
	}

	fn conexoes(&self, a: usize) -> Vec<usize> {
		let mut result: Vec<usize> = Vec::new();

		for i in 0..self.matriz[a].len() {
			if a != i && self.matriz[a][i] > -1 {
				result.push(i);
			}
		}
		return result;
	}

	// ---- Funções dos algoritmos ----

}

// Main
fn main() {
	// Grafo com no maximo mil vertices
	 // "->" =  Grafo condicional, "<->" = Grafo Bicondicional
	let mut grafo: Grafo = Grafo::new(1000, "->");

	grafo.usr_adicionar_conexao(0.to_string(), 1.to_string(), 1);
	grafo.usr_adicionar_conexao(1.to_string(), 2.to_string(), 1);
	grafo.usr_adicionar_conexao(2.to_string(), 3.to_string(), 1);
	grafo.usr_adicionar_conexao(3.to_string(), 0.to_string(), 1);

	println!("{:?}", grafo.conexoes(2));
}

#[cfg(test)]
mod test {
	use super::*;

	#[test]
	fn usr_numero_conexoes() {
		let mut grafo: Grafo = Grafo::new(1000, "->");

		for i in 1..1000 {
			grafo.usr_adicionar_conexao(0.to_string(), i.to_string(), 1);
		}

		assert_eq!(grafo.usr_numero_conexoes(0.to_string()), 999);
		assert_eq!(grafo.usr_numero_conexoes(0.to_string()), grafo.numero_conexoes(0));
	}

	#[test]
	fn numero_conexoes() {
		let mut grafo: Grafo = Grafo::new(1000, "<->");

		for i in 1..1000 {
			grafo.adicionar_conexao(0, i, 1);
		}

		assert_eq!(grafo.numero_conexoes(0), 999);
		assert_eq!(grafo.numero_conexoes(0), grafo.usr_numero_conexoes(0.to_string()));
	}
}
<commit_msg>Revisão dos comentarios<commit_after>/*
	Autor: Gustavo Michels de Camargo
	Projeto: Algoritmo estrural de um Grafo
*/

use std::{collections::HashMap};

// Matriz de Vector usada ara construir o Grafo.
type MatrizGrafo = Vec<Vec<isize>>;

// O dicionario serve para podermos dar entrada a qualquer String e ter como abstrair suas posições dentro.
// da matriz numerica, isso serve apenas para fins de uso, não requerer transcrever um Nodo com X para valor numerico.
#[derive(PartialEq, Eq, Clone, Debug)]
struct Grafo {
	matriz: MatrizGrafo,
	dicionario: HashMap<String, usize>,
	bicondicional: bool
}

trait Projeto {
	// Geral
	fn new(tamanho: usize, tipo: &str) -> Grafo;

	// Funções envolvendo o dicionario - Usuario
	fn usr_pegar_indice(&self, chave: String) -> usize;
	fn usr_pegar_chave(&self, indice: usize) -> String;

	// Usuario
	fn usr_adicionar_conexao(&mut self, a: String, b: String, valor: isize);
	fn usr_remover_conexao(&mut self, a: String, b: String);
	fn usr_numero_conexoes(&self, no: String) -> usize;
	fn usr_verificar_se_existe_conexao(&self, a: String, b: String) -> bool;
	fn usr_conexoes(&self, a: String) -> Vec<String>;

	// Maquina / uso para os Algoritmos
	fn adicionar_conexao(&mut self, a: usize, b: usize, valor: isize);
	fn remover_conexao(&mut self, a: usize, b: usize);
	fn numero_conexoes(&self, no: usize) -> usize;
	fn verificar_se_existe_conexao(&self, a: usize, b: usize) -> bool;
	fn conexoes(&self, a: usize) -> Vec<usize>;
}

// Este é a implementação da "Classe" de um grafo.
impl Projeto for Grafo {
	// Tamanho: Numero Maximo de Vertices que a matriz pode usar de 0 até tamanho.
	// Em notação matematica relativa a limites: [0, tamanho).
	// Toda função que começa com 'usr_'(usr = usuario) é a versão da função que deve ser usada para interagir diretamente com o usuario.
	// As funções de mesmo nome mas sem 'usr_' deve ser usada apenas dentro dos algoritmos, como o Dijkstra para menor caminho entre dois nos.
	// Fiz assim para otimizar processamento e descartar necessidade de acessar e
	// consultar o dicionario o tempo todo quando se apenas tem como Objetivo encontrar um menor caminho com Dijkstra por exemplo.

	// Apenas essa função foge a regra por ser universal
	fn new(tamanho: usize, tipo: &str) -> Grafo {
		Grafo {
			matriz: vec![vec![-1; tamanho]; tamanho],
			dicionario: HashMap::new(),
			bicondicional: match tipo  {
				"->" => false, // Condicional
				"<->" | _ => true // Bicondicional
			}
		}
	}

	// ---- Funções para uso direto do usuario ----

	// Retorna o indice da matriz relacionada a chave
	fn usr_pegar_indice(&self, chave: String) -> usize {
		if self.dicionario.contains_key(&chave) {
			return (&self.dicionario.get(&chave)).unwrap().clone();
		}

		return 0;
	}

	// Retorna a chave do dicionario relacionada ao valor do indice da matriz do grafo
	fn usr_pegar_chave(&self, indice: usize) -> String {
		for (key, value) in self.dicionario.iter() {
			if *value == indice {
				return (*key).clone();
			}
		}

		return "".to_string();
	}

	// Conecta Dois vertices
	fn usr_adicionar_conexao(&mut self, a: String, b: String, valor: isize) {
		if !self.dicionario.contains_key(&a){
			let num: usize = self.dicionario.len();
			self.dicionario.insert(a.to_owned(), num);
		}

		if !self.dicionario.contains_key(&b){
			let num: usize = self.dicionario.len();
			self.dicionario.insert(b.to_owned(), num);
		}

		let (valor_a, valor_b): (usize, usize) = (self.usr_pegar_indice(a), self.usr_pegar_indice(b));

		self.matriz[valor_a][valor_b] = valor;

		if self.bicondicional {
			self.matriz[valor_b][valor_a] = valor;
		}

	}

	fn usr_remover_conexao(&mut self, a: String, b: String) {
		let (valor_a, valor_b): (usize, usize) = (self.usr_pegar_indice(a), self.usr_pegar_indice(b));

		self.matriz[valor_a][valor_b]  = -1;
		self.matriz[valor_b][valor_a]  = -1;
	}

	// Retorba o numero de vertices na qual ele se conecta
	fn usr_numero_conexoes(&self, no: String) -> usize {
		self.matriz[self.usr_pegar_indice(no)].iter()
						.filter(|x| **x >= 0)
						.collect::<Vec<&isize>>()
						.len() as usize | 0
	}

	// Verifica se dois nos estão conectados
	fn usr_verificar_se_existe_conexao(&self, a: String, b: String) -> bool {
		self.matriz[self.usr_pegar_indice(a)][self.usr_pegar_indice(b)]  >= 0
	}

	fn usr_conexoes(&self, a: String) -> Vec<String> {
		let mut result: Vec<String> = Vec::new();
		let a_value: usize = self.usr_pegar_indice(a);

		for i in 0..self.matriz[a_value].len() {
			if a_value != i && self.matriz[a_value][i] > -1 {
				result.push(self.usr_pegar_chave(i));
			}
		}

		return result;
	}

	// ---- Funções para uso direto dos algoritmos (tem melhor perfomance) ----

	// Retorna um array dos indice de todos os nos na qual o no 'a' se conecta
	// Esera usar esta função apenas para usos proprios dentro do Grafo, como em algoritmos tipo dijkstra
	// Conecta Dois vertices
	fn adicionar_conexao(&mut self, a: usize, b: usize, valor: isize) {
		self.matriz[a][b] = valor;

		if self.bicondicional {
			self.matriz[b][a] = valor;
		}
	}

	fn remover_conexao(&mut self, a: usize, b: usize) {
		self.matriz[a][b]  = -1;
		self.matriz[b][a]  = -1;
	}

	// Retorba o numero de vertices na qual ele se conecta
	fn numero_conexoes(&self, no: usize) -> usize {
		self.matriz[no].iter()
						.filter(|x| **x >= 0)
						.collect::<Vec<&isize>>()
						.len() as usize | 0
	}

	fn verificar_se_existe_conexao(&self, a: usize, b: usize) -> bool {
		self.matriz[a][b]  >= 0
	}

	fn conexoes(&self, a: usize) -> Vec<usize> {
		let mut result: Vec<usize> = Vec::new();

		for i in 0..self.matriz[a].len() {
			if a != i && self.matriz[a][i] > -1 {
				result.push(i);
			}
		}
		return result;
	}

	// ---- Funções dos algoritmos ----

}

// Main
fn main() {
	// Grafo com no maximo mil vertices
	 // "->" =  Grafo condicional, "<->" = Grafo Bicondicional
	let mut grafo: Grafo = Grafo::new(1000, "->");

	grafo.usr_adicionar_conexao(0.to_string(), 1.to_string(), 1);
	grafo.usr_adicionar_conexao(1.to_string(), 2.to_string(), 1);
	grafo.usr_adicionar_conexao(2.to_string(), 3.to_string(), 1);
	grafo.usr_adicionar_conexao(3.to_string(), 0.to_string(), 1);

	println!("{:?}", grafo.conexoes(2));
}

#[cfg(test)]
mod test {
	use super::*;

	#[test]
	fn usr_numero_conexoes() {
		let mut grafo: Grafo = Grafo::new(1000, "->");

		for i in 1..1000 {
			grafo.usr_adicionar_conexao(0.to_string(), i.to_string(), 1);
		}

		assert_eq!(grafo.usr_numero_conexoes(0.to_string()), 999);
		assert_eq!(grafo.usr_numero_conexoes(0.to_string()), grafo.numero_conexoes(0));
	}

	#[test]
	fn numero_conexoes() {
		let mut grafo: Grafo = Grafo::new(1000, "<->");

		for i in 1..1000 {
			grafo.adicionar_conexao(0, i, 1);
		}

		assert_eq!(grafo.numero_conexoes(0), 999);
		assert_eq!(grafo.numero_conexoes(0), grafo.usr_numero_conexoes(0.to_string()));
	}
}
<|endoftext|>


<commit_before>// Github entities represented as structs.
use std::io;
use csv;
use rustc_serialize::json;

use format::split;

/// An Issue-to-be. It doesn't have number, state or any timestamp because
/// it is not yet created.
///
/// The flow is then:
///
/// create(NewIssue) -> Issue
#[derive(Debug, RustcDecodable, RustcEncodable)]
pub struct NewIssue {
    pub assignees: Vec<String>,
    pub body: String,
    pub labels: Vec<String>,
    pub title: String,
    pub milestone: Option<u32>,
}

// pub type NewIssues = Vec<NewIssue>;
pub struct NewIssues(Vec<NewIssue>);

impl NewIssues {
    fn new() -> Self {
        NewIssues(Vec::new())
    }

    fn push(&mut self, elem: NewIssue) {
        self.0.push(elem);
    }
}

impl IntoIterator for NewIssues {
    type Item = NewIssue;
    type IntoIter = ::std::vec::IntoIter<NewIssue>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl <T: io::Read>From<csv::Reader<T>> for NewIssues {
    fn from(mut records: csv::Reader<T>) -> Self {
        let mut issues: NewIssues = NewIssues::new();

        for record in records.decode() {
            let (title, body, labels, assignees, milestone):
                (String, String, String, String, Option<u32>) = record.unwrap();

            issues.push(NewIssue { assignees : split(assignees)
                                 , body : body
                                 , labels : split(labels)
                                 , title : title
                                 , milestone : milestone
                                 });
        }

        issues
    }
}

/// A partial representation of a Github Issue. The represented fields are the
/// only ones transported to the final CSV/Json output. Might be interesting
/// to add some more bits like the milestone.
#[derive(Debug, RustcDecodable, RustcEncodable)]
pub struct Issue {
    pub assignee: Option<User>,
    pub body: Option<String>,
    pub created_at: Option<String>,
    pub closed_at: Option<String>,
    pub labels: Labels,
    pub number: u32,
    pub state: Option<String>,
    pub title: Option<String>,
    pub user: Option<User>,
}

impl Issue {
    pub fn from_str(data: &str) -> Result<Issue, json::DecoderError> {
        json::decode(data)
    }
}

pub type Issues = Vec<Issue>;

pub type Labels = Vec<Label>;

#[derive(Debug, RustcDecodable, RustcEncodable)]
pub struct Label {
    pub name: String,
}

#[derive(Debug, RustcDecodable, RustcEncodable)]
pub struct User {
    pub login: String,
}
<commit_msg>refactor(update): Extract NewIssue from Record implementation<commit_after>// Github entities represented as structs.
use std::io;
use csv;
use rustc_serialize::json;

use format::split;

/// An Issue-to-be. It doesn't have number, state or any timestamp because
/// it is not yet created.
///
/// The flow is then:
///
/// create(NewIssue) -> Issue
#[derive(Debug, RustcDecodable, RustcEncodable)]
pub struct NewIssue {
    pub assignees: Vec<String>,
    pub body: String,
    pub labels: Vec<String>,
    pub title: String,
    pub milestone: Option<u32>,
}

type Record = (String, String, String, String, Option<u32>);

impl From<Record> for NewIssue {
    fn from(record: Record) -> Self {
        let (title, body, labels, assignees, milestone):
            (String, String, String, String, Option<u32>) = record;

        NewIssue { assignees : split(assignees)
                 , body : body
                 , labels : split(labels)
                 , title : title
                 , milestone : milestone
                 }
    }
}

// pub type NewIssues = Vec<NewIssue>;
pub struct NewIssues(Vec<NewIssue>);

impl NewIssues {
    fn new() -> Self {
        NewIssues(Vec::new())
    }

    fn push(&mut self, elem: NewIssue) {
        self.0.push(elem);
    }
}

impl IntoIterator for NewIssues {
    type Item = NewIssue;
    type IntoIter = ::std::vec::IntoIter<NewIssue>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl <T: io::Read>From<csv::Reader<T>> for NewIssues {
    fn from(mut records: csv::Reader<T>) -> Self {
        let mut issues: NewIssues = NewIssues::new();

        for record in records.decode::<Record>() {
            issues.push(NewIssue::from(record.unwrap()));
        }

        issues
    }
}

/// A partial representation of a Github Issue. The represented fields are the
/// only ones transported to the final CSV/Json output. Might be interesting
/// to add some more bits like the milestone.
#[derive(Debug, RustcDecodable, RustcEncodable)]
pub struct Issue {
    pub assignee: Option<User>,
    pub body: Option<String>,
    pub created_at: Option<String>,
    pub closed_at: Option<String>,
    pub labels: Labels,
    pub number: u32,
    pub state: Option<String>,
    pub title: Option<String>,
    pub user: Option<User>,
}

impl Issue {
    pub fn from_str(data: &str) -> Result<Issue, json::DecoderError> {
        json::decode(data)
    }
}

pub type Issues = Vec<Issue>;

pub type Labels = Vec<Label>;

#[derive(Debug, RustcDecodable, RustcEncodable)]
pub struct Label {
    pub name: String,
}

#[derive(Debug, RustcDecodable, RustcEncodable)]
pub struct User {
    pub login: String,
}
<|endoftext|>


<commit_before>use std::io;
use std::io::BufReader;
use std::io::prelude::*;
use std::env;
use std::process::exit;
use std::fs::File;

fn usage() {
  println!("Usage: cat input.csv | csv_to_json");
}

fn main() {
  let stdin = io::stdin();
  let mut filereader;
  let mut reader = &mut stdin.lock() as &mut BufRead;
  let args : Vec<String> = env::args().collect();

  if args.len() > 2 {
    usage();
    exit(1);
  } else if args.len() == 2 {
    let file = File::open(args[1].clone());
    if !file.is_ok() {
      usage();
      exit(1);
    }
    filereader = BufReader::new(file.unwrap());
    reader = &mut filereader;
  }

  let split_char = ',';

  let mut line = String::new();
  let _unused_size = reader.read_line(&mut line);

  let headers : Vec<&str> = line.trim().split(split_char).collect();

  let mut first = true;

  for line in reader.lines() {
    if first {
      print!("[");
      first = false;
    } else {
      println!(",");
    }

    // Opening brace (escaped).
    print!("{{");

    let line_str = line.unwrap();

    let mut first = true;
    let components : Vec<&str> = line_str.split(split_char).collect();
    for (header, component) in headers.iter().zip(components.iter()) {
      if !first {
        print!(",");
      } else {
        first = false;
      }
      print!("\"{}\": \"{}\"", header, component);
    }

    // Closing brace (escaped).
    print!("}}");
  }
  println!("]");
}
<commit_msg>Minor change to usage and style<commit_after>use std::io;
use std::io::BufReader;
use std::io::prelude::*;
use std::env;
use std::process;
use std::fs::File;

fn usage() {
  println!("Usage: cat input.csv | csv_to_json");
  println!("Usage: csv_to_json input.csv");
}

fn main() {
  let stdin = io::stdin();
  let mut filereader;
  let mut reader = &mut stdin.lock() as &mut BufRead;
  let args : Vec<String> = env::args().collect();

  if args.len() > 2 {
    usage();
    process::exit(1);
  } else if args.len() == 2 {
    let file = File::open(args[1].clone());
    if !file.is_ok() {
      usage();
      process::exit(1);
    }
    filereader = BufReader::new(file.unwrap());
    reader = &mut filereader;
  }

  let split_char = ',';

  let mut line = String::new();
  let _unused_size = reader.read_line(&mut line);

  let headers : Vec<&str> = line.trim().split(split_char).collect();

  let mut first = true;

  for line in reader.lines() {
    if first {
      print!("[");
      first = false;
    } else {
      println!(",");
    }

    // Opening brace (escaped).
    print!("{{");

    let line_str = line.unwrap();

    let mut first = true;
    let components : Vec<&str> = line_str.split(split_char).collect();
    for (header, component) in headers.iter().zip(components.iter()) {
      if !first {
        print!(",");
      } else {
        first = false;
      }
      print!("\"{}\": \"{}\"", header, component);
    }

    // Closing brace (escaped).
    print!("}}");
  }
  println!("]");
}
<|endoftext|>


<commit_before>//! Lua thread test.
//! Spawns a lua thread!

use std::time::Duration;
use std::thread;
use std::collections::BTreeMap;

use hlua::any::AnyLuaValue;
use hlua::any::AnyLuaValue::*;
use hlua::{Lua, LuaError};
use rustc_serialize::json::{Json, ToJson, Object};

use super::*;

fn wait_for_thread() {
    for i in 0..20 {
        if !thread_running() {
            thread::sleep_ms(200);
        }
        else { return; }
    }
    panic!("Thread didn't run!");
}

#[test]
fn activate_thread() {
    super::init();
}

#[test]
fn thread_exec_okay() {
    wait_for_thread();

    let hello_receiver = send(LuaQuery::Execute(
        "hello = 'hello world'".to_string())).unwrap();
    let hello_result = hello_receiver.recv().unwrap();
    assert!(hello_result.is_ok());
    assert_eq!(hello_result, LuaResponse::Pong);

    let assert_receiver = send(LuaQuery::Execute(
        "assert(hello == 'hello world')".to_string())).unwrap();
    let assert_result = assert_receiver.recv().unwrap();
    assert!(hello_result.is_ok());
    assert_eq!(assert_result, LuaResponse::Pong);
}

#[test]
fn thread_exec_err() {
    wait_for_thread();

    let assert_receiver = send(LuaQuery::Execute(
        "assert(true == false, 'Logic works')".to_string())).unwrap();
    let assert_result = assert_receiver.recv().unwrap();
    assert!(assert_result.is_err());
    assert!(!assert_result.is_ok());
    if let LuaResponse::Error(err) = assert_result {
        if let LuaError::ExecutionError(lua_err) = err {
            assert!(lua_err.contains("Logic works"));
        }
        else {
            panic!("thread_exec_err result was not an ExecutionError: {:?}",
                   err);
        }
    }
    else {
        panic!("thread_exec_err result was not an error: {:?}", assert_result);
    }
}

#[test]
fn thread_exec_file_ok() {
    wait_for_thread();

    let file_receiver = send(LuaQuery::ExecFile(
        "lib/test/lua-exec-file.lua".to_string())).unwrap();
    let file_result = file_receiver.recv().unwrap();
    if let LuaResponse::Error(err) = file_result {
        if let LuaError::ReadError(ioerr) = err {
            panic!("Lua thread was unable to execute file: {:?}", ioerr);
        }
        else {
            panic!("Unexpected error executing file: {:?}", err);
        }
    }
    assert!(file_result.is_ok());
    assert_eq!(file_result, LuaResponse::Pong);

    // Print the method from the file
    let test_receiver = send(LuaQuery::Execute(
        "confirm_file()".to_string())).unwrap();
    let test_result = test_receiver.recv().unwrap();
    assert!(test_result.is_ok());
    assert!(test_result == LuaResponse::Pong);
}

#[test]
fn thread_exec_file_err() {
    wait_for_thread();

    let run_receiver = send(LuaQuery::ExecFile(
        "lib/test/lua-bad-assert.lua".to_string())).unwrap();
    let run_result = run_receiver.recv().unwrap();
    assert!(run_result.is_err());
    match run_result {
        LuaResponse::Error(err) => {
            match err {
                LuaError::ExecutionError(ex) => {
                    assert!(ex.contains("Dude, 1 is totally equal to 0"));
                },
                _ => panic!("Got wrong hlua error type: {:?}", err)
            }
        },
        _ => panic!("Got wrong LuaResponse type: {:?}", run_result)
    }

    let syntax_receiver = send(LuaQuery::ExecFile(
        "lib/test/lua-syntax-err.txt".to_string())).unwrap();
    let syntax_result = syntax_receiver.recv().unwrap();
    assert!(syntax_result.is_err());
    match syntax_result {
        LuaResponse::Error(err) => {
            match err {
                LuaError::SyntaxError(serr) => {
                    assert!(serr.contains("expected"));
                },
                _ => panic!("Got wrong hlua error type: {:?}", err)
            }
        }
        _ => panic!("Got wrong LuaResponse type: {:?}", syntax_result)
    }
}

fn test_rust_exec() {
    wait_for_thread();
}

fn rust_lua_fn(lua: &mut Lua) -> AnyLuaValue {
    {
        let mut foo = lua.empty_array("foo");
        foo.set("bar", 12);
    }
    match lua.get::<AnyLuaValue, _>("foo") {
        Some(LuaArray(arr)) => AnyLuaValue::LuaBoolean(true),
        _ => AnyLuaValue::LuaBoolean(false)
    }
}

#[test]
fn convert_string() {
    let input = "Hello World".to_string();
    let json_input = Json::String(input.clone());
    assert_eq!(json_to_lua(json_input), LuaString(input));
}
#[test]
fn convert_numbers() {
    let lua_number = LuaNumber(42f64);
    assert_eq!(json_to_lua(Json::F64(42f64)), lua_number);
    assert_eq!(json_to_lua(Json::I64(42i64)), lua_number);
    assert_eq!(json_to_lua(Json::U64(42u64)), lua_number);
}

#[test]
fn convert_bool() {
    assert_eq!(json_to_lua(Json::Boolean(true)), LuaBoolean(true));
    assert_eq!(json_to_lua(Json::Boolean(false)), LuaBoolean(false));
}

#[test]
fn convert_array() {
    let json = Json::Array(
        vec![Json::Boolean(true), Json::F64(11f64),
             Json::String("Foo".to_string())]
    );
    let lua = LuaArray(vec![
        (LuaNumber(1f64), LuaBoolean(true)),
        (LuaNumber(2f64), LuaNumber(11f64)),
        (LuaNumber(3f64), LuaString("Foo".to_string()))
    ]);
    assert_eq!(json_to_lua(json), lua);
}

#[test]
fn convert_object() {
    // { name="foo", point: {x=0, y=1}, valid=false }
    // The fields are emitted in alphabetical order thanks to Json's
    // internal BTreeMap representation.

    let mut json_tree: Object = BTreeMap::new();
    let mut point_tree: Object = BTreeMap::new();
    point_tree.insert("x".to_string(), Json::U64(0u64));
    point_tree.insert("y".to_string(), Json::U64(1u64));
    json_tree.insert("point".to_string(), Json::Object(point_tree));
    json_tree.insert("name".to_string(), Json::String("foo".to_string()));
    json_tree.insert("valid".to_string(), Json::Boolean(false));

    let lua = LuaArray(vec![
        (LuaString("name".to_string()), LuaString("foo".to_string())),
        (LuaString("point".to_string()), LuaArray(vec![
            (LuaString("x".to_string()), LuaNumber(0f64)),
            (LuaString("y".to_string()), LuaNumber(1f64))
        ])),
        (LuaString("valid".to_string()), LuaBoolean(false)),
    ]);

    assert_eq!(json_to_lua(Json::Object(json_tree)), lua);
}
<commit_msg>Add test for RustFn<commit_after>//! Lua thread test.
//! Spawns a lua thread!

use std::time::Duration;
use std::thread;
use std::collections::BTreeMap;

use hlua::any::AnyLuaValue;
use hlua::any::AnyLuaValue::*;
use hlua::lua_tables::LuaTable;
use hlua::{Lua, LuaError};
use rustc_serialize::json::{Json, ToJson, Object};

use super::*;

fn wait_for_thread() {
    for i in 0..20 {
        if !thread_running() {
            thread::sleep_ms(200);
        }
        else { return; }
    }
    panic!("Thread didn't run!");
}

#[test]
fn activate_thread() {
    super::init();
}

#[test]
fn thread_exec_okay() {
    wait_for_thread();

    let hello_receiver = send(LuaQuery::Execute(
        "hello = 'hello world'".to_string())).unwrap();
    let hello_result = hello_receiver.recv().unwrap();
    assert!(hello_result.is_ok());
    assert_eq!(hello_result, LuaResponse::Pong);

    let assert_receiver = send(LuaQuery::Execute(
        "assert(hello == 'hello world')".to_string())).unwrap();
    let assert_result = assert_receiver.recv().unwrap();
    assert!(hello_result.is_ok());
    assert_eq!(assert_result, LuaResponse::Pong);
}

#[test]
fn thread_exec_err() {
    wait_for_thread();

    let assert_receiver = send(LuaQuery::Execute(
        "assert(true == false, 'Logic works')".to_string())).unwrap();
    let assert_result = assert_receiver.recv().unwrap();
    assert!(assert_result.is_err());
    assert!(!assert_result.is_ok());
    if let LuaResponse::Error(err) = assert_result {
        if let LuaError::ExecutionError(lua_err) = err {
            assert!(lua_err.contains("Logic works"));
        }
        else {
            panic!("thread_exec_err result was not an ExecutionError: {:?}",
                   err);
        }
    }
    else {
        panic!("thread_exec_err result was not an error: {:?}", assert_result);
    }
}

#[test]
fn thread_exec_file_ok() {
    wait_for_thread();

    let file_receiver = send(LuaQuery::ExecFile(
        "lib/test/lua-exec-file.lua".to_string())).unwrap();
    let file_result = file_receiver.recv().unwrap();
    if let LuaResponse::Error(err) = file_result {
        if let LuaError::ReadError(ioerr) = err {
            panic!("Lua thread was unable to execute file: {:?}", ioerr);
        }
        else {
            panic!("Unexpected error executing file: {:?}", err);
        }
    }
    assert!(file_result.is_ok());
    assert_eq!(file_result, LuaResponse::Pong);

    // Print the method from the file
    let test_receiver = send(LuaQuery::Execute(
        "confirm_file()".to_string())).unwrap();
    let test_result = test_receiver.recv().unwrap();
    assert!(test_result.is_ok());
    assert!(test_result == LuaResponse::Pong);
}

#[test]
fn thread_exec_file_err() {
    wait_for_thread();

    let run_receiver = send(LuaQuery::ExecFile(
        "lib/test/lua-bad-assert.lua".to_string())).unwrap();
    let run_result = run_receiver.recv().unwrap();
    assert!(run_result.is_err());
    match run_result {
        LuaResponse::Error(err) => {
            match err {
                LuaError::ExecutionError(ex) => {
                    assert!(ex.contains("Dude, 1 is totally equal to 0"));
                },
                _ => panic!("Got wrong hlua error type: {:?}", err)
            }
        },
        _ => panic!("Got wrong LuaResponse type: {:?}", run_result)
    }

    let syntax_receiver = send(LuaQuery::ExecFile(
        "lib/test/lua-syntax-err.txt".to_string())).unwrap();
    let syntax_result = syntax_receiver.recv().unwrap();
    assert!(syntax_result.is_err());
    match syntax_result {
        LuaResponse::Error(err) => {
            match err {
                LuaError::SyntaxError(serr) => {
                    assert!(serr.contains("expected"));
                },
                _ => panic!("Got wrong hlua error type: {:?}", err)
            }
        }
        _ => panic!("Got wrong LuaResponse type: {:?}", syntax_result)
    }
}

#[test]
fn test_rust_exec() {
    wait_for_thread();
    let rust_receiver = send(LuaQuery::ExecWithLua(rust_lua_fn)).unwrap();
    let rust_result = rust_receiver.recv().unwrap();
    assert!(rust_result.is_ok());

    match rust_result {
        LuaResponse::Variable(Some(var)) => {
            match var {
                AnyLuaValue::LuaBoolean(b) => {
                    if !b {
                        panic!("Rust function failed!");
                    }
                },
                _ => panic!("Rust function returned wrong AnyLuaValue")
            }
        },
        _ => panic!("Got wrong LuaResponse from Rust function!")
    }
}

fn rust_lua_fn(lua: &mut Lua) -> AnyLuaValue {
    {
        let mut foo = lua.empty_array("foo");
        foo.set("bar", 12.0);
    }
    let mut maybe_foo = lua.get::<LuaTable<_>, _>("foo");
    assert!(maybe_foo.is_some());
    let mut foo = maybe_foo.unwrap();
    assert!(foo.get::<f64, _>("bar").is_some());
    AnyLuaValue::LuaBoolean(true)
}

#[test]
fn convert_string() {
    let input = "Hello World".to_string();
    let json_input = Json::String(input.clone());
    assert_eq!(json_to_lua(json_input), LuaString(input));
}
#[test]
fn convert_numbers() {
    let lua_number = LuaNumber(42f64);
    assert_eq!(json_to_lua(Json::F64(42f64)), lua_number);
    assert_eq!(json_to_lua(Json::I64(42i64)), lua_number);
    assert_eq!(json_to_lua(Json::U64(42u64)), lua_number);
}

#[test]
fn convert_bool() {
    assert_eq!(json_to_lua(Json::Boolean(true)), LuaBoolean(true));
    assert_eq!(json_to_lua(Json::Boolean(false)), LuaBoolean(false));
}

#[test]
fn convert_array() {
    let json = Json::Array(
        vec![Json::Boolean(true), Json::F64(11f64),
             Json::String("Foo".to_string())]
    );
    let lua = LuaArray(vec![
        (LuaNumber(1f64), LuaBoolean(true)),
        (LuaNumber(2f64), LuaNumber(11f64)),
        (LuaNumber(3f64), LuaString("Foo".to_string()))
    ]);
    assert_eq!(json_to_lua(json), lua);
}

#[test]
fn convert_object() {
    // { name="foo", point: {x=0, y=1}, valid=false }
    // The fields are emitted in alphabetical order thanks to Json's
    // internal BTreeMap representation.

    let mut json_tree: Object = BTreeMap::new();
    let mut point_tree: Object = BTreeMap::new();
    point_tree.insert("x".to_string(), Json::U64(0u64));
    point_tree.insert("y".to_string(), Json::U64(1u64));
    json_tree.insert("point".to_string(), Json::Object(point_tree));
    json_tree.insert("name".to_string(), Json::String("foo".to_string()));
    json_tree.insert("valid".to_string(), Json::Boolean(false));

    let lua = LuaArray(vec![
        (LuaString("name".to_string()), LuaString("foo".to_string())),
        (LuaString("point".to_string()), LuaArray(vec![
            (LuaString("x".to_string()), LuaNumber(0f64)),
            (LuaString("y".to_string()), LuaNumber(1f64))
        ])),
        (LuaString("valid".to_string()), LuaBoolean(false)),
    ]);

    assert_eq!(json_to_lua(Json::Object(json_tree)), lua);
}
<|endoftext|>


<commit_before>
pub trait Prod {
    type Head;
    type Tail: Prod;

    fn split(self) -> (Self::Head, Self::Tail);
}

impl Prod for ! {
    type Head = !;
    type Tail = !;

    fn split(self) -> (Self::Head, Self::Tail) {
        unreachable!()
    }
}

impl Prod for () {
    type Head = ();
    type Tail = ();

    fn split(self) -> (Self::Head, Self::Tail) {
        ((), ())
    }
}

impl<A> Prod for (A,) {
    type Head = A;
    type Tail = ();

    fn split(self) -> (Self::Head, Self::Tail) {
        (self.0, ())
    }
}

impl<A, B> Prod for (A, B)
    where B: Prod
{
    type Head = A;
    type Tail = B;

    fn split(self) -> (Self::Head, Self::Tail) {
        self
    }
}

pub trait Pair<H, T> {
    type ProdTail: Prod<Head = T, Tail = ()>;
    type Output: Prod<Head = H, Tail = Self::ProdTail>;
}

impl<H, T> Pair<H, T> for (H, T) {
    type ProdTail = (T,);
    type Output = (H, Self::ProdTail);
}

#[cfg(test)]
mod tests {

    #[test]
    fn split() {
        use super::Prod;

        let x = (1, ("Hello", ()));
        let (a, (b, ())) = x.split();
        assert_eq!(a, 1);
        assert_eq!(b, "Hello");
    }
}
<commit_msg>Remove unnecessary scruff in meta::prod<commit_after>pub trait Prod {
    type Left;
    type Right;

    fn to_canonical(self) -> (Self::Left, Self::Right);
}

impl<A, B> Prod for (A, B) {
    type Left = A;
    type Right = B;

    fn to_canonical(self) -> (Self::Left, Self::Right) {
        self
    }
}

#[cfg(test)]
mod tests {

    #[test]
    fn split() {
        use super::Prod;

        let x = (1, ("Hello", ()));
        let (a, (b, ())) = x.to_canonical();
        assert_eq!(a, 1);
        assert_eq!(b, "Hello");
    }
}
<|endoftext|>


<commit_before>
#[allow(dead_code)]
pub fn multiples(upper_bound: i64) -> i64 {
    let range = 0..upper_bound;
    let divisible = range.filter(|x| x % 3 == 0 || x % 5 == 0);
    let mut sum = 0;
    for x in divisible {
        sum = sum + x;
    }
    sum
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn example() {
        assert_eq!(multiples(10), 23);
    }

    #[test]
    fn solution() {
        assert_eq!(multiples(1000), 233168);
    }
}
<commit_msg>functional solution with fold<commit_after>
#[allow(dead_code)]
pub fn multiples(upper_bound: i64) -> i64 {
    let range = 0..upper_bound;
    let divisible = range.filter(|x| x % 3 == 0 || x % 5 == 0);
    let mut sum = 0;
    for x in divisible {
        sum = sum + x;
    }
    sum
}

#[allow(dead_code)]
pub fn multiples_fun(upper_bound: i64) -> i64 {
    let divisible = (0..upper_bound).filter(|x| x % 3 == 0 || x % 5 == 0);
    divisible.fold(0, |sum, x| sum + x)
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn example() {
        assert_eq!(multiples(10), 23);
    }

    #[test]
    fn solution() {
        assert_eq!(multiples(1000), 233168);
    }

    #[test]
    fn example_fun() {
        assert_eq!(multiples_fun(10), 23);
    }

    #[test]
    fn solution_fun() {
        assert_eq!(multiples_fun(1000), 233168);
    }
}
<|endoftext|>


<commit_before>extern crate euclid;

use euclid::TypedRect;
use euclid::TypedSize2D;

use defs::*;

#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct Polyomino {
    pub squares: Vec<UPoint>,
}

#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
pub enum GridSegmentType {
    Perimeter,
    Internal,
}

pub struct GridSegment(pub UPoint, pub UPoint, pub GridSegmentType);

impl Polyomino {
    pub fn monomino() -> Polyomino {
        Polyomino {
            squares: vec![UPoint::new(0, 0)],
        }
    }

    pub fn has_position(&self, p: UPoint) -> bool {
        self.squares.contains(&p)
    }

    // TODO: This should be doing entire straight lines at once, not
    // just square by square

    // todo: The segment stuff could be more efficient, only building vecs
    // of the ones we want. Probably not a real issue.
    fn vertical_segments(&self) -> Vec<GridSegment> {
        // Vertical segments have a square to the right of them,
        // unless they're at the far-right of the polyominio.

        let mut res = vec![];

        for p in self.squares.iter().cloned() {
            let sort = if self.has_position(p - UVec::new(-1, 0)) {
                GridSegmentType::Internal
            } else {
                GridSegmentType::Perimeter
            };

            res.push(GridSegment(p, p + UVec::new(0, 1), sort));

            if !self.has_position(p + UVec::new(1, 0)) {
                // In this case we must be at the right-most side of the poly
                res.push(GridSegment(
                    p + UVec::new(1, 0),
                    p + UVec::new(1, 0) + UVec::new(0, 1),
                    GridSegmentType::Perimeter,
                ));
            }
        }

        res
    }

    fn horizontal_segments(&self) -> Vec<GridSegment> {
        // See above
        let mut res = vec![];

        for p in self.squares.iter().cloned() {
            let sort = if self.has_position(p - UVec::new(0, -1)) {
                GridSegmentType::Internal
            } else {
                GridSegmentType::Perimeter
            };

            res.push(GridSegment(p, p + UVec::new(1, 0), sort));

            if !self.has_position(p + UVec::new(0, 1)) {
                res.push(GridSegment(
                    p + UVec::new(0, 1),
                    p + UVec::new(0, 1) + UVec::new(1, 0),
                    GridSegmentType::Perimeter,
                ));
            }
        }

        res
    }

    pub fn segments(&self) -> Vec<GridSegment> {
        let mut r = self.vertical_segments();
        r.append(&mut self.horizontal_segments());
        r
    }

    pub fn square_rects(&self) -> Vec<TypedRect<i32, UniverseSpace>> {
        self.squares
            .iter()
            .map(|&s| TypedRect::new(s, TypedSize2D::new(1, 1)))
            .collect()
    }

    pub fn bounding_box(&self) -> TypedRect<i32, UniverseSpace> {
        let rects = self.square_rects();
        rects.iter().fold(rects[0], |a, b| a.union(b))
    }
}
<commit_msg>Fix segment logic<commit_after>extern crate euclid;

use euclid::TypedRect;
use euclid::TypedSize2D;

use defs::*;

#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct Polyomino {
    pub squares: Vec<UPoint>,
}

#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
pub enum GridSegmentType {
    Perimeter,
    Internal,
}

pub struct GridSegment(pub UPoint, pub UPoint, pub GridSegmentType);

impl Polyomino {
    pub fn monomino() -> Polyomino {
        Polyomino {
            squares: vec![UPoint::new(0, 0)],
        }
    }

    pub fn has_position(&self, p: UPoint) -> bool {
        self.squares.contains(&p)
    }

    // TODO: This should be doing entire straight lines at once, not
    // just square by square

    // todo: The segment stuff could be more efficient, only building vecs
    // of the ones we want. Probably not a real issue.
    fn vertical_segments(&self) -> Vec<GridSegment> {
        // Vertical segments have a square to the right of them,
        // unless they're at the far-right of the polyominio.

        let mut res = vec![];

        for p in self.squares.iter().cloned() {
            let sort = if self.has_position(p + UVec::new(-1, 0)) {
                GridSegmentType::Internal
            } else {
                GridSegmentType::Perimeter
            };

            res.push(GridSegment(p, p + UVec::new(0, 1), sort));

            if !self.has_position(p + UVec::new(1, 0)) {
                // In this case we must be at the right-most side of the poly
                res.push(GridSegment(
                    p + UVec::new(1, 0),
                    p + UVec::new(1, 0) + UVec::new(0, 1),
                    GridSegmentType::Perimeter,
                ));
            }
        }

        res
    }

    fn horizontal_segments(&self) -> Vec<GridSegment> {
        // See above
        let mut res = vec![];

        for p in self.squares.iter().cloned() {
            let sort = if self.has_position(p + UVec::new(0, -1)) {
                GridSegmentType::Internal
            } else {
                GridSegmentType::Perimeter
            };

            res.push(GridSegment(p, p + UVec::new(1, 0), sort));

            if !self.has_position(p + UVec::new(0, 1)) {
                res.push(GridSegment(
                    p + UVec::new(0, 1),
                    p + UVec::new(0, 1) + UVec::new(1, 0),
                    GridSegmentType::Perimeter,
                ));
            }
        }

        res
    }

    pub fn segments(&self) -> Vec<GridSegment> {
        let mut r = self.vertical_segments();
        r.append(&mut self.horizontal_segments());
        r
    }

    pub fn square_rects(&self) -> Vec<TypedRect<i32, UniverseSpace>> {
        self.squares
            .iter()
            .map(|&s| TypedRect::new(s, TypedSize2D::new(1, 1)))
            .collect()
    }

    pub fn bounding_box(&self) -> TypedRect<i32, UniverseSpace> {
        let rects = self.square_rects();
        rects.iter().fold(rects[0], |a, b| a.union(b))
    }
}
<|endoftext|>