<commit_before>use crate::value::de::{MapDeserializer, MapRefDeserializer, SeqDeserializer, SeqRefDeserializer};
use crate::value::Value;
use crate::Error;
use serde::de::value::{BorrowedStrDeserializer, StrDeserializer};
use serde::de::{
    Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error as _, VariantAccess, Visitor,
};
use serde::ser::{Serialize, SerializeMap, Serializer};
use std::cmp::Ordering;
use std::fmt::{self, Debug};
use std::hash::{Hash, Hasher};

/// A representation of YAML's `!Tag` syntax, used for enums.
///
/// Refer to the example code on [`TaggedValue`] for an example of deserializing
/// tagged values.
#[derive(Clone)]
pub struct Tag {
    pub(crate) string: String,
}

/// A `Tag` + `Value` representing a tagged YAML scalar, sequence, or mapping.
///
/// ```
/// use serde_yaml::value::TaggedValue;
/// use std::collections::BTreeMap;
///
/// let yaml = "
///     scalar: !Thing x
///     sequence_flow: !Thing [first]
///     sequence_block: !Thing
///       - first
///     mapping_flow: !Thing {k: v}
///     mapping_block: !Thing
///       k: v
/// ";
///
/// let data: BTreeMap<String, TaggedValue> = serde_yaml::from_str(yaml).unwrap();
/// assert!(data["scalar"].tag == "Thing");
/// assert!(data["sequence_flow"].tag == "Thing");
/// assert!(data["sequence_block"].tag == "Thing");
/// assert!(data["mapping_flow"].tag == "Thing");
/// assert!(data["mapping_block"].tag == "Thing");
///
/// // The leading '!' in tags are not significant. The following is also true.
/// assert!(data["scalar"].tag == "!Thing");
/// ```
#[derive(Clone, PartialEq, PartialOrd, Hash, Debug)]
pub struct TaggedValue {
    #[allow(missing_docs)]
    pub tag: Tag,
    #[allow(missing_docs)]
    pub value: Value,
}

impl Tag {
    /// Create tag.
    ///
    /// The leading '!' is not significant. It may be provided, but does not
    /// have to be. The following are equivalent:
    ///
    /// ```
    /// use serde_yaml::value::Tag;
    ///
    /// assert_eq!(Tag::new("!Thing"), Tag::new("Thing"));
    ///
    /// let tag = Tag::new("Thing");
    /// assert!(tag == "Thing");
    /// assert!(tag == "!Thing");
    ///
    /// let tag = Tag::new("!Thing");
    /// assert!(tag == "Thing");
    /// assert!(tag == "!Thing");
    /// ```
    ///
    /// Such a tag would serialize to `!Thing` in YAML regardless of whether a
    /// '!' was included in the call to `Tag::new`.
    pub fn new(string: impl Into<String>) -> Self {
        Tag {
            string: string.into(),
        }
    }
}

impl Value {
    pub(crate) fn untag(self) -> Self {
        let mut cur = self;
        while let Value::Tagged(tagged) = cur {
            cur = tagged.value;
        }
        cur
    }

    pub(crate) fn untag_ref(&self) -> &Self {
        let mut cur = self;
        while let Value::Tagged(tagged) = cur {
            cur = &tagged.value;
        }
        cur
    }

    pub(crate) fn untag_mut(&mut self) -> &mut Self {
        let mut cur = self;
        while let Value::Tagged(tagged) = cur {
            cur = &mut tagged.value;
        }
        cur
    }
}

pub(crate) fn nobang(maybe_banged: &str) -> &str {
    maybe_banged.strip_prefix('!').unwrap_or(maybe_banged)
}

impl Eq for Tag {}

impl PartialEq for Tag {
    fn eq(&self, other: &Tag) -> bool {
        PartialEq::eq(nobang(&self.string), nobang(&other.string))
    }
}

impl<T> PartialEq<T> for Tag
where
    T: ?Sized + AsRef<str>,
{
    fn eq(&self, other: &T) -> bool {
        PartialEq::eq(nobang(&self.string), nobang(other.as_ref()))
    }
}

impl Ord for Tag {
    fn cmp(&self, other: &Self) -> Ordering {
        Ord::cmp(nobang(&self.string), nobang(&other.string))
    }
}

impl PartialOrd for Tag {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        PartialOrd::partial_cmp(nobang(&self.string), nobang(&other.string))
    }
}

impl Hash for Tag {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        nobang(&self.string).hash(hasher);
    }
}

impl Debug for Tag {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "!{}", nobang(&self.string))
    }
}

impl Serialize for TaggedValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(1))?;
        map.serialize_entry(&format_args!("!{}", nobang(&self.tag.string)), &self.value)?;
        map.end()
    }
}

impl<'de> Deserialize<'de> for TaggedValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct TaggedValueVisitor;

        impl<'de> Visitor<'de> for TaggedValueVisitor {
            type Value = TaggedValue;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a YAML value with a !Tag")
            }

            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
            where
                A: EnumAccess<'de>,
            {
                let (tag, contents) = data.variant::<String>()?;
                let tag = Tag::new(tag);
                let value = contents.newtype_variant()?;
                Ok(TaggedValue { tag, value })
            }
        }

        deserializer.deserialize_any(TaggedValueVisitor)
    }
}

impl<'de> EnumAccess<'de> for TaggedValue {
    type Error = Error;
    type Variant = Value;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error>
    where
        V: DeserializeSeed<'de>,
    {
        let tag = StrDeserializer::<Error>::new(nobang(&self.tag.string));
        let value = seed.deserialize(tag)?;
        Ok((value, self.value))
    }
}

impl<'de> VariantAccess<'de> for Value {
    type Error = Error;

    fn unit_variant(self) -> Result<(), Error> {
        Deserialize::deserialize(self)
    }

    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error>
    where
        T: DeserializeSeed<'de>,
    {
        seed.deserialize(self)
    }

    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
    where
        V: Visitor<'de>,
    {
        if let Value::Sequence(v) = self {
            Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
        } else {
            Err(Error::invalid_type(self.unexpected(), &"tuple variant"))
        }
    }

    fn struct_variant<V>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Error>
    where
        V: Visitor<'de>,
    {
        if let Value::Mapping(v) = self {
            Deserializer::deserialize_any(MapDeserializer::new(v), visitor)
        } else {
            Err(Error::invalid_type(self.unexpected(), &"struct variant"))
        }
    }
}

impl<'de> EnumAccess<'de> for &'de TaggedValue {
    type Error = Error;
    type Variant = &'de Value;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error>
    where
        V: DeserializeSeed<'de>,
    {
        let tag = BorrowedStrDeserializer::<Error>::new(nobang(&self.tag.string));
        let value = seed.deserialize(tag)?;
        Ok((value, &self.value))
    }
}

impl<'de> VariantAccess<'de> for &'de Value {
    type Error = Error;

    fn unit_variant(self) -> Result<(), Error> {
        Deserialize::deserialize(self)
    }

    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error>
    where
        T: DeserializeSeed<'de>,
    {
        seed.deserialize(self)
    }

    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
    where
        V: Visitor<'de>,
    {
        if let Value::Sequence(v) = self {
            Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
        } else {
            Err(Error::invalid_type(self.unexpected(), &"tuple variant"))
        }
    }

    fn struct_variant<V>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Error>
    where
        V: Visitor<'de>,
    {
        if let Value::Mapping(v) = self {
            Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor)
        } else {
            Err(Error::invalid_type(self.unexpected(), &"struct variant"))
        }
    }
}
<commit_msg>Implement Display trait for serde_yaml::value::tagged::Tag<commit_after>use crate::value::de::{MapDeserializer, MapRefDeserializer, SeqDeserializer, SeqRefDeserializer};
use crate::value::Value;
use crate::Error;
use serde::de::value::{BorrowedStrDeserializer, StrDeserializer};
use serde::de::{
    Deserialize, DeserializeSeed, Deserializer, EnumAccess, Error as _, VariantAccess, Visitor,
};
use serde::ser::{Serialize, SerializeMap, Serializer};
use std::cmp::Ordering;
use std::fmt::{self, Debug, Display};
use std::hash::{Hash, Hasher};

/// A representation of YAML's `!Tag` syntax, used for enums.
///
/// Refer to the example code on [`TaggedValue`] for an example of deserializing
/// tagged values.
#[derive(Clone)]
pub struct Tag {
    pub(crate) string: String,
}

/// A `Tag` + `Value` representing a tagged YAML scalar, sequence, or mapping.
///
/// ```
/// use serde_yaml::value::TaggedValue;
/// use std::collections::BTreeMap;
///
/// let yaml = "
///     scalar: !Thing x
///     sequence_flow: !Thing [first]
///     sequence_block: !Thing
///       - first
///     mapping_flow: !Thing {k: v}
///     mapping_block: !Thing
///       k: v
/// ";
///
/// let data: BTreeMap<String, TaggedValue> = serde_yaml::from_str(yaml).unwrap();
/// assert!(data["scalar"].tag == "Thing");
/// assert!(data["sequence_flow"].tag == "Thing");
/// assert!(data["sequence_block"].tag == "Thing");
/// assert!(data["mapping_flow"].tag == "Thing");
/// assert!(data["mapping_block"].tag == "Thing");
///
/// // The leading '!' in tags are not significant. The following is also true.
/// assert!(data["scalar"].tag == "!Thing");
/// ```
#[derive(Clone, PartialEq, PartialOrd, Hash, Debug)]
pub struct TaggedValue {
    #[allow(missing_docs)]
    pub tag: Tag,
    #[allow(missing_docs)]
    pub value: Value,
}

impl Tag {
    /// Create tag.
    ///
    /// The leading '!' is not significant. It may be provided, but does not
    /// have to be. The following are equivalent:
    ///
    /// ```
    /// use serde_yaml::value::Tag;
    ///
    /// assert_eq!(Tag::new("!Thing"), Tag::new("Thing"));
    ///
    /// let tag = Tag::new("Thing");
    /// assert!(tag == "Thing");
    /// assert!(tag == "!Thing");
    /// assert!(tag.to_string() == "!Thing");
    ///
    /// let tag = Tag::new("!Thing");
    /// assert!(tag == "Thing");
    /// assert!(tag == "!Thing");
    /// assert!(tag.to_string() == "!Thing");
    /// ```
    ///
    /// Such a tag would serialize to `!Thing` in YAML regardless of whether a
    /// '!' was included in the call to `Tag::new`.
    pub fn new(string: impl Into<String>) -> Self {
        Tag {
            string: string.into(),
        }
    }
}

impl Value {
    pub(crate) fn untag(self) -> Self {
        let mut cur = self;
        while let Value::Tagged(tagged) = cur {
            cur = tagged.value;
        }
        cur
    }

    pub(crate) fn untag_ref(&self) -> &Self {
        let mut cur = self;
        while let Value::Tagged(tagged) = cur {
            cur = &tagged.value;
        }
        cur
    }

    pub(crate) fn untag_mut(&mut self) -> &mut Self {
        let mut cur = self;
        while let Value::Tagged(tagged) = cur {
            cur = &mut tagged.value;
        }
        cur
    }
}

pub(crate) fn nobang(maybe_banged: &str) -> &str {
    maybe_banged.strip_prefix('!').unwrap_or(maybe_banged)
}

impl Eq for Tag {}

impl PartialEq for Tag {
    fn eq(&self, other: &Tag) -> bool {
        PartialEq::eq(nobang(&self.string), nobang(&other.string))
    }
}

impl<T> PartialEq<T> for Tag
where
    T: ?Sized + AsRef<str>,
{
    fn eq(&self, other: &T) -> bool {
        PartialEq::eq(nobang(&self.string), nobang(other.as_ref()))
    }
}

impl Ord for Tag {
    fn cmp(&self, other: &Self) -> Ordering {
        Ord::cmp(nobang(&self.string), nobang(&other.string))
    }
}

impl PartialOrd for Tag {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        PartialOrd::partial_cmp(nobang(&self.string), nobang(&other.string))
    }
}

impl Hash for Tag {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        nobang(&self.string).hash(hasher);
    }
}

impl Debug for Tag {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "!{}", nobang(&self.string))
    }
}

impl Display for Tag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "!{}", nobang(&self.string))
    }
}

impl Serialize for TaggedValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(1))?;
        map.serialize_entry(&format_args!("!{}", nobang(&self.tag.string)), &self.value)?;
        map.end()
    }
}

impl<'de> Deserialize<'de> for TaggedValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct TaggedValueVisitor;

        impl<'de> Visitor<'de> for TaggedValueVisitor {
            type Value = TaggedValue;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a YAML value with a !Tag")
            }

            fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
            where
                A: EnumAccess<'de>,
            {
                let (tag, contents) = data.variant::<String>()?;
                let tag = Tag::new(tag);
                let value = contents.newtype_variant()?;
                Ok(TaggedValue { tag, value })
            }
        }

        deserializer.deserialize_any(TaggedValueVisitor)
    }
}

impl<'de> EnumAccess<'de> for TaggedValue {
    type Error = Error;
    type Variant = Value;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error>
    where
        V: DeserializeSeed<'de>,
    {
        let tag = StrDeserializer::<Error>::new(nobang(&self.tag.string));
        let value = seed.deserialize(tag)?;
        Ok((value, self.value))
    }
}

impl<'de> VariantAccess<'de> for Value {
    type Error = Error;

    fn unit_variant(self) -> Result<(), Error> {
        Deserialize::deserialize(self)
    }

    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error>
    where
        T: DeserializeSeed<'de>,
    {
        seed.deserialize(self)
    }

    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
    where
        V: Visitor<'de>,
    {
        if let Value::Sequence(v) = self {
            Deserializer::deserialize_any(SeqDeserializer::new(v), visitor)
        } else {
            Err(Error::invalid_type(self.unexpected(), &"tuple variant"))
        }
    }

    fn struct_variant<V>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Error>
    where
        V: Visitor<'de>,
    {
        if let Value::Mapping(v) = self {
            Deserializer::deserialize_any(MapDeserializer::new(v), visitor)
        } else {
            Err(Error::invalid_type(self.unexpected(), &"struct variant"))
        }
    }
}

impl<'de> EnumAccess<'de> for &'de TaggedValue {
    type Error = Error;
    type Variant = &'de Value;

    fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error>
    where
        V: DeserializeSeed<'de>,
    {
        let tag = BorrowedStrDeserializer::<Error>::new(nobang(&self.tag.string));
        let value = seed.deserialize(tag)?;
        Ok((value, &self.value))
    }
}

impl<'de> VariantAccess<'de> for &'de Value {
    type Error = Error;

    fn unit_variant(self) -> Result<(), Error> {
        Deserialize::deserialize(self)
    }

    fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error>
    where
        T: DeserializeSeed<'de>,
    {
        seed.deserialize(self)
    }

    fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error>
    where
        V: Visitor<'de>,
    {
        if let Value::Sequence(v) = self {
            Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor)
        } else {
            Err(Error::invalid_type(self.unexpected(), &"tuple variant"))
        }
    }

    fn struct_variant<V>(
        self,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Error>
    where
        V: Visitor<'de>,
    {
        if let Value::Mapping(v) = self {
            Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor)
        } else {
            Err(Error::invalid_type(self.unexpected(), &"struct variant"))
        }
    }
}
<|endoftext|>


<commit_before>//! Decode Cryptographic Control (CC) packets.

use consts::CRYPTO_CONTROL_BYTES;
use util::slice_u16;

/// Buffer of bytes that represent a crypto control packet.
pub type Buf = [u8; CRYPTO_CONTROL_BYTES];

/// Information necessary to decrypt an encrypted message.
pub struct CryptoControlFields(Buf);

impl CryptoControlFields {
    /// Create a new `CryptoControlFields` decoder from the given bytes.
    pub fn new(buf: Buf) -> Self { CryptoControlFields(buf) }

    /// Initialization vector used internally by associated crypto algorithm.
    pub fn init(&self) -> &[u8] { &self.0[..9] }
    /// Type of crypto algorithm in use, if any.
    pub fn alg(&self) -> CryptoAlgorithm { CryptoAlgorithm::from_bits(self.0[9]) }
    /// Encryption key to use.
    pub fn key(&self) -> u16 { slice_u16(&self.0[10..]) }
}

/// Type of cryptographic algorithm.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum CryptoAlgorithm {
    Accordion,
    BatonEven,
    Firefly,
    Mayfly,
    Saville,
    BatonOdd,
    Unencrypted,
    Des,
    TripleDES,
    Aes,
    Other(u8),
}

impl CryptoAlgorithm {
    /// Parse the given 8 bits into a crypto algorithm.
    pub fn from_bits(bits: u8) -> CryptoAlgorithm {
        use self::CryptoAlgorithm::*;

        match bits {
            0x00 => Accordion,
            0x01 => BatonEven,
            0x02 => Firefly,
            0x03 => Mayfly,
            0x04 => Saville,
            0x41 => BatonOdd,
            0x80 => Unencrypted,
            0x81 => Des,
            0x83 => TripleDES,
            0x84 => Aes,
            b => Other(b),
        }
    }
}

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

    #[test]
    fn test_cypto() {
        let c = CryptoControlFields::new([
            0, 0, 0, 1, 0, 0, 0, 2, 0,
            0b10000100,
            0xDE, 0xAD,
        ]);

        assert_eq!(c.init(), &[0,0,0,1,0,0,0,2,0]);
        assert_eq!(c.alg(), Aes);
        assert_eq!(c.key(), 0xDEAD);
    }
}
<commit_msg>s/TripleDES/TripleDes/<commit_after>//! Decode Cryptographic Control (CC) packets.

use consts::CRYPTO_CONTROL_BYTES;
use util::slice_u16;

/// Buffer of bytes that represent a crypto control packet.
pub type Buf = [u8; CRYPTO_CONTROL_BYTES];

/// Information necessary to decrypt an encrypted message.
pub struct CryptoControlFields(Buf);

impl CryptoControlFields {
    /// Create a new `CryptoControlFields` decoder from the given bytes.
    pub fn new(buf: Buf) -> Self { CryptoControlFields(buf) }

    /// Initialization vector used internally by associated crypto algorithm.
    pub fn init(&self) -> &[u8] { &self.0[..9] }
    /// Type of crypto algorithm in use, if any.
    pub fn alg(&self) -> CryptoAlgorithm { CryptoAlgorithm::from_bits(self.0[9]) }
    /// Encryption key to use.
    pub fn key(&self) -> u16 { slice_u16(&self.0[10..]) }
}

/// Type of cryptographic algorithm.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum CryptoAlgorithm {
    Accordion,
    BatonEven,
    Firefly,
    Mayfly,
    Saville,
    BatonOdd,
    Unencrypted,
    Des,
    TripleDes,
    Aes,
    Other(u8),
}

impl CryptoAlgorithm {
    /// Parse the given 8 bits into a crypto algorithm.
    pub fn from_bits(bits: u8) -> CryptoAlgorithm {
        use self::CryptoAlgorithm::*;

        match bits {
            0x00 => Accordion,
            0x01 => BatonEven,
            0x02 => Firefly,
            0x03 => Mayfly,
            0x04 => Saville,
            0x41 => BatonOdd,
            0x80 => Unencrypted,
            0x81 => Des,
            0x83 => TripleDes,
            0x84 => Aes,
            b => Other(b),
        }
    }
}

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

    #[test]
    fn test_cypto() {
        let c = CryptoControlFields::new([
            0, 0, 0, 1, 0, 0, 0, 2, 0,
            0b10000100,
            0xDE, 0xAD,
        ]);

        assert_eq!(c.init(), &[0,0,0,1,0,0,0,2,0]);
        assert_eq!(c.alg(), Aes);
        assert_eq!(c.key(), 0xDEAD);
    }
}
<|endoftext|>


<commit_before>//! The module for the automatic map generation

use noise::{Brownian2, Seed, open_simplex2};

// TODO pick:
// use core::*;
// use core::{Map, Tile, TileMap};
use core::*;

/// A map
///
/// Note: It's chunked into big chunks and small chunks.
///       Small chunks keeps the noise data. Big chunks
///       determines the overlay layer.
pub struct MapGenerator<'a> {
  seed: &'a Seed,
}

/// Types of big chunks
pub enum BChunkType {
  /// Reserved for history, empty per default, but gets opened as the game is
  /// played. Manually designed.
  History,
  /// Automatic map generated chunk
  Auto,
  /// Manually random generated chunk
  Manually,
  /// Empty chunk
  Empty,
}

// TODO: Find out how to prevent double islands (manually generated islands)

// TODO: Use Vec2 in this methods:
impl<'a> MapGenerator<'a> {
  /// Creates a new map
  pub fn new(seed: &'a Seed) -> MapGenerator<'a> {
    MapGenerator {
      seed: seed,
    }
  }

  // TODO: Add some sort of cache

  /// Get the noise value at a given point
  pub fn get_noise_value(&self, coord: Vec2<i64>) -> f64 {
    let noise = Brownian2::new(open_simplex2, 4).wavelength(32.0);
    noise.apply(&self.seed, &[coord.x() as f64, coord.y() as f64])
    // Todo: Add some sort of converter method
  }

  /// Get big chunk coordinates
  pub fn get_bchunk(coord: Vec2<i64>) -> Vec2<i64> {
    // TODO: Chunk size 64?
    Vec2(((coord.x() as f64) / 64.0).floor() as i64,
         ((coord.y() as f64) / 64.0).floor() as i64)
  }

  /// Get the chunk type of the big chunk at (x, y)
  pub fn get_bchunk_type(&self, coord: Vec2<i64>) -> BChunkType {
    let noise = Brownian2::new(open_simplex2, 4).wavelength(32.0);
    let noise_val =
      noise.apply(&self.seed, &[coord.x() as f64, coord.y() as f64]);
    if noise_val > 0.3 {
      BChunkType::Empty // Too many too few?
    } else if noise_val > 0.1 {
      BChunkType::Auto
    } else if noise_val > 0.05 {
      BChunkType::History
    } else {
      BChunkType::Manually
    }
  }

  /// Get overlay value (used for customizing the noise)
  pub fn get_overlay_value(&self, coord: Vec2<i64>) -> f64 {
    let Vec2(x, y) = coord;

    // Center chunk coordinate
    let Vec2(cx, cy) = MapGenerator::get_bchunk(coord) + Vec2(32, 32);
    let chunk_type = self.get_bchunk_type(Vec2(cx, cy));
    let chunk_int = self.seed.get2([cx, cy]);
    let chunk_value = (chunk_int as f64) / (usize::max_value() as f64);
    match chunk_type {
      BChunkType::Empty => 0.0,
      BChunkType::Auto => {
        // This is why we need vector math, kids.
        // TODO: Use vec math here

        use std::f64;

        // TODO: Make more shapes.
        let elip_dist = (((cx - x) * (cx - x) + (cy - y) * (cy - y)) as f64)
                        .sqrt();
        let angle = chunk_value * f64::consts::PI * 2.0;
        let (cirx, ciry) = (angle.sin() + cx as f64,
                            angle.cos() + cy as f64);
        let sec_dist = ((cirx - x as f64) * (cirx - x as f64)
                       + (ciry - y as f64) * (ciry - y as f64)).sqrt();
        let dist = sec_dist.max(elip_dist);

        let res = 1.0 - dist / 25.0;

        if res > 0.0 {
          res
        } else {
          0.0
        }
      },
      _ => 0.0,
    }
  }
}

impl<'a> TileMap for MapGenerator<'a> {

  // Add foreground/background
  /// Get the tile at a given point
  fn get_tile(&self, coord: Vec2<i64>) -> Block {
    let val = (self.get_noise_value(coord)
               + self.get_overlay_value(coord)) / 2.0;

    // Temporary map gen. Proof of concept.
    if val > 0.9 {
      Block::new(Tile::Water, Tile::Grass, Tile::Tree)
    } else {
      Block::new(Tile::Water, Tile::None, Tile::None)
    }
  }
}
<commit_msg>Add cache, NOTE: Is not finished yet.<commit_after>//! The module for the automatic map generation

use noise::{Brownian2, Seed, open_simplex2};

// TODO pick:
// use core::*;
// use core::{Map, Tile, TileMap};
use core::*;

pub const CHUNK_SIZE: i64 = 64;

/// A map
///
/// Note: It's chunked into big chunks and small chunks.
///       Small chunks keeps the noise data. Big chunks
///       determines the overlay layer.
pub struct MapGenerator<'a> {
  seed: &'a Seed,
}

/// Types of big chunks
pub enum BChunkType {
  /// Reserved for history, empty per default, but gets opened as the game is
  /// played. Manually designed.
  History,
  /// Automatic map generated chunk
  Auto,
  /// Manually random generated chunk
  Manually,
  /// Empty chunk
  Empty,
}

// TODO: Find out how to prevent double islands (manually generated islands)

// TODO: Use Vec2 in this methods:
impl<'a> MapGenerator<'a> {
  /// Creates a new map
  pub fn new(seed: &'a Seed) -> MapGenerator<'a> {
    MapGenerator {
      seed: seed,
    }
  }

  // TODO: Add some sort of cache

  /// Get the noise value at a given point
  pub fn get_noise_value(&self, coord: Vec2<i64>) -> f64 {
    let noise = Brownian2::new(open_simplex2, 4).wavelength(32.0);
    noise.apply(&self.seed, &[coord.x() as f64, coord.y() as f64])
    // Todo: Add some sort of converter method
  }

  /// Get big chunk coordinates
  pub fn get_bchunk(coord: Vec2<i64>) -> Vec2<i64> {
    // TODO: Chunk size 64?
    Vec2(((coord.x() as f64) / (CHUNK_SIZE as f64)).floor() as i64,
         ((coord.y() as f64) / (CHUNK_SIZE as f64)).floor() as i64)
  }

  /// Get the chunk type of the big chunk at (x, y)
  pub fn get_bchunk_type(&self, coord: Vec2<i64>) -> BChunkType {
    let noise = Brownian2::new(open_simplex2, 4).wavelength(32.0);
    let noise_val =
      noise.apply(&self.seed, &[coord.x() as f64, coord.y() as f64]);
    if noise_val > 0.3 {
      BChunkType::Empty // Too many too few?
    } else if noise_val > 0.1 {
      BChunkType::Auto
    } else if noise_val > 0.05 {
      BChunkType::History
    } else {
      BChunkType::Manually
    }
  }

  /// Get overlay value (used for customizing the noise)
  pub fn get_overlay_value(&self, coord: Vec2<i64>) -> f64 {
    let Vec2(x, y) = coord;

    // Center chunk coordinate
    let Vec2(cx, cy) = MapGenerator::get_bchunk(coord) + Vec2(32, 32);
    let chunk_type = self.get_bchunk_type(Vec2(cx, cy));
    let chunk_int = self.seed.get2([cx, cy]);
    let chunk_value = (chunk_int as f64) / (usize::max_value() as f64);
    match chunk_type {
      BChunkType::Empty => 0.0,
      BChunkType::Auto => {
        // This is why we need vector math, kids.
        // TODO: Use vec math here

        use std::f64;

        // TODO: Make more shapes.
        let elip_dist = (((cx - x) * (cx - x) + (cy - y) * (cy - y)) as f64)
                        .sqrt();
        let angle = chunk_value * f64::consts::PI * 2.0;
        let (cirx, ciry) = (angle.sin() + cx as f64,
                            angle.cos() + cy as f64);
        let sec_dist = ((cirx - x as f64) * (cirx - x as f64)
                       + (ciry - y as f64) * (ciry - y as f64)).sqrt();
        let dist = sec_dist.max(elip_dist);

        let res = 1.0 - dist / 25.0;

        if res > 0.0 {
          res
        } else {
          0.0
        }
      },
      _ => 0.0,
    }
  }
}

impl<'a> TileMap for MapGenerator<'a> {

  // TODO: Rename to get block?
  /// Get the tile at a given point
  fn get_tile(&self, coord: Vec2<i64>) -> Block {
    let val = (self.get_noise_value(coord)
               + self.get_overlay_value(coord)) / 2.0;

    // Temporary map gen. Proof of concept.
    if val > 0.9 {
      Block::new(Tile::Water, Tile::Grass, Tile::Tree)
    } else {
      Block::new(Tile::Water, Tile::None, Tile::None)
    }
  }
}
<|endoftext|>


<commit_before>use std::sync::Arc;
use error::Error;

use super::{Request, Response, IronResult};

pub trait Handler: Send + Sync {
    fn call(&self, &mut Request) -> IronResult<Response>;

    fn catch(&self, &mut Request, Box<Error>) -> (Response, IronResult<()>);
}

pub trait BeforeMiddleware: Send + Sync {
    fn before(&self, &mut Request) -> IronResult<()>;

    fn catch(&self, _: &mut Request, err: Box<Error>) -> IronResult<()> {
        Err(err)
    }
}

pub trait AfterMiddleware: Send + Sync {
    fn after(&self, &mut Request, &mut Response) -> IronResult<()>;

    // This response was generated by the `catch` function of Handlers and is abnormal in some way.
    fn catch(&self, _: &mut Request, _: &mut Response, err: Box<Error>) -> IronResult<()> {
        Err(err)
    }
}

pub trait AroundMiddleware: Handler {
    fn around(&mut self, handler: Box<Handler + Send + Sync>);
}

pub trait Chain: Handler {
    fn new<H: Handler>(H) -> Self;

    fn link<B, A>(&mut self, (B, A)) where A: AfterMiddleware, B: BeforeMiddleware;

    fn link_before<B>(&mut self, B) where B: BeforeMiddleware;

    fn link_after<A>(&mut self, A) where A: AfterMiddleware;

    fn around<A>(&mut self, A) where A: AroundMiddleware;
}

pub struct ChainBuilder {
    befores: Vec<Box<BeforeMiddleware + Send + Sync>>,
    afters: Vec<Box<AfterMiddleware + Send + Sync>>,
    handler: Box<Handler + Send + Sync>
}

impl Chain for ChainBuilder {
    fn new<H: Handler>(handler: H) -> ChainBuilder {
        ChainBuilder {
            befores: vec![],
            afters: vec![],
            handler: box handler as Box<Handler + Send + Sync>
        }
    }

    fn link<B, A>(&mut self, link: (B, A))
    where A: AfterMiddleware, B: BeforeMiddleware {
        let (before, after) = link;
        self.befores.push(box before as Box<BeforeMiddleware + Send + Sync>);
        self.afters.push(box after as Box<AfterMiddleware + Send + Sync>);
    }

    fn link_before<B>(&mut self, before: B) where B: BeforeMiddleware {
        self.befores.push(box before as Box<BeforeMiddleware + Send + Sync>);
    }

    fn link_after<A>(&mut self, after: A) where A: AfterMiddleware {
        self.afters.push(box after as Box<AfterMiddleware + Send + Sync>);
    }

    fn around<A>(&mut self, mut around: A) where A: AroundMiddleware {
        use std::mem;

        let old = mem::replace(&mut self.handler, box Nop as Box<Handler + Send + Sync>);
        around.around(old);
        self.handler = box around as Box<Handler + Send + Sync>;
    }
}

impl Handler for ChainBuilder {
    fn call(&self, req: &mut Request) -> IronResult<Response> {
        let before_result = helpers::run_befores(req, self.befores.as_slice(), None);

        let (res, err) = match before_result {
            Ok(()) => match self.handler.call(req) {
                Ok(res) => (res, None),
                Err(e) => helpers::run_handler_catch(req, e, &self.handler)
            },
            Err(e) => helpers::run_handler_catch(req, e, &self.handler)
        };

        helpers::run_afters(req, res, err, self.afters.as_slice())
    }

    fn catch(&self, req: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        let before_result = helpers::run_befores(req, self.befores.as_slice(), Some(err));

        let (res, err) = match before_result {
            Ok(()) => match self.handler.call(req) {
                Ok(res) => (res, None),
                Err(e) => helpers::run_handler_catch(req, e, &self.handler)
            },
            Err(e) => helpers::run_handler_catch(req, e, &self.handler)
        };

        match helpers::run_afters(req, res, err, self.afters.as_slice()) {
            Ok(res) => (res, Ok(())),
            // FIXME: Make 500
            Err(err) => (Response::new(), Err(err))
        }
    }
}

impl Handler for fn(&mut Request) -> IronResult<Response> {
    fn call(&self, req: &mut Request) -> IronResult<Response> {
        self.call(req)
    }

    fn catch(&self, _: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        // FIXME: Make Response a 500
        (Response::new(), Err(err))
    }
}

pub struct Nop;

impl Handler for Nop {
    fn call(&self, _: &mut Request) -> IronResult<Response> {
        Ok(Response::new())
    }

    fn catch(&self, _: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        // FIXME: Make Response a 500
        (Response::new(), Err(err))
    }
}

impl Handler for Box<Handler + Send + Sync> {
    fn call(&self, req: &mut Request) -> IronResult<Response> {
        self.call(req)
    }

    fn catch(&self, req: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        self.catch(req, err)
    }
}

impl Handler for Arc<Box<Handler + Send + Sync>> {
    fn call(&self, req: &mut Request) -> IronResult<Response> {
        self.call(req)
    }

    fn catch(&self, req: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        self.catch(req, err)
    }
}

mod helpers {
    use super::super::{Request, Response, IronResult};
    use super::{AfterMiddleware, BeforeMiddleware, Handler};
    use error::Error;

    pub fn run_befores(req: &mut Request, befores: &[Box<BeforeMiddleware>], err: Option<Box<Error>>) -> IronResult<()> {
        match err {
            Some(mut e) => {
                for (i, before) in befores.iter().enumerate() {
                    match before.catch(req, e) {
                        Ok(_) => return run_befores(req, befores, None),
                        Err(new) => e = new
                    }
                }
                Err(e)
            },

            None => {
                for (i, before) in befores.iter().enumerate() {
                    match before.before(req) {
                        Ok(_) => (),
                        Err(err) => return run_befores(req, befores.slice_from(i), Some(err))
                    }
                }
                Ok(())
            }
        }
    }

    pub fn run_afters(req: &mut Request, mut res: Response, err: Option<Box<Error>>,
                  afters: &[Box<AfterMiddleware>]) -> IronResult<Response> {
        match err {
            Some(mut e) => {
                for (i, after) in afters.iter().enumerate() {
                    match after.catch(req, &mut res, e) {
                        Ok(_) => return run_afters(req, res, None, afters),
                        Err(new) => e = new
                    }
                }
                Err(e)
            },

            None => {
                for (i, after) in afters.iter().enumerate() {
                    match after.after(req, &mut res) {
                        Ok(_) => (),
                        Err(err) => return run_afters(req, res, Some(err), afters.slice_from(i))
                    }
                }
                Ok(res)
            }
        }
    }

    pub fn run_handler_catch(req: &mut Request, err: Box<Error>,
                         handler: &Box<Handler>) -> (Response, Option<Box<Error>>) {
        match handler.catch(req, err) {
            (res, Ok(())) => (res, None),
            (res, Err(e)) => (res, Some(e))
        }
    }
}

<commit_msg>(doc) Documented Handler.<commit_after>use std::sync::Arc;
use error::Error;

use super::{Request, Response, IronResult};

/// `Handler`s are responsible for handling requests by creating Responses from Requests.
///
/// By default, bare functions and variants of Chain implement `Handler`.
///
/// `Handler`s are allowed to return errors, and if they do, their `catch` method is called and the
/// error is propagated to `AfterMiddleware`.
pub trait Handler: Send + Sync {
    /// Produce a `Response` from a Request, with the possibility of error.
    ///
    /// If this returns an Err, `catch` is called with the error.
    fn call(&self, &mut Request) -> IronResult<Response>;

    /// If `Handler`'s call method produces an Err, then this method is called
    /// to produce a `Response` and possibly handle the error.
    ///
    /// If the passed-in error is not handled, it should be returned as the second
    /// item in the returned tuple. If it is handled, then `Ok(())` can be returned
    /// instead to indicate that all is good with the Response.
    fn catch(&self, &mut Request, Box<Error>) -> (Response, IronResult<()>);
}

pub trait BeforeMiddleware: Send + Sync {
    fn before(&self, &mut Request) -> IronResult<()>;

    fn catch(&self, _: &mut Request, err: Box<Error>) -> IronResult<()> {
        Err(err)
    }
}

pub trait AfterMiddleware: Send + Sync {
    fn after(&self, &mut Request, &mut Response) -> IronResult<()>;

    // This response was generated by the `catch` function of Handlers and is abnormal in some way.
    fn catch(&self, _: &mut Request, _: &mut Response, err: Box<Error>) -> IronResult<()> {
        Err(err)
    }
}

pub trait AroundMiddleware: Handler {
    fn around(&mut self, handler: Box<Handler + Send + Sync>);
}

pub trait Chain: Handler {
    fn new<H: Handler>(H) -> Self;

    fn link<B, A>(&mut self, (B, A)) where A: AfterMiddleware, B: BeforeMiddleware;

    fn link_before<B>(&mut self, B) where B: BeforeMiddleware;

    fn link_after<A>(&mut self, A) where A: AfterMiddleware;

    fn around<A>(&mut self, A) where A: AroundMiddleware;
}

pub struct ChainBuilder {
    befores: Vec<Box<BeforeMiddleware + Send + Sync>>,
    afters: Vec<Box<AfterMiddleware + Send + Sync>>,
    handler: Box<Handler + Send + Sync>
}

impl Chain for ChainBuilder {
    fn new<H: Handler>(handler: H) -> ChainBuilder {
        ChainBuilder {
            befores: vec![],
            afters: vec![],
            handler: box handler as Box<Handler + Send + Sync>
        }
    }

    fn link<B, A>(&mut self, link: (B, A))
    where A: AfterMiddleware, B: BeforeMiddleware {
        let (before, after) = link;
        self.befores.push(box before as Box<BeforeMiddleware + Send + Sync>);
        self.afters.push(box after as Box<AfterMiddleware + Send + Sync>);
    }

    fn link_before<B>(&mut self, before: B) where B: BeforeMiddleware {
        self.befores.push(box before as Box<BeforeMiddleware + Send + Sync>);
    }

    fn link_after<A>(&mut self, after: A) where A: AfterMiddleware {
        self.afters.push(box after as Box<AfterMiddleware + Send + Sync>);
    }

    fn around<A>(&mut self, mut around: A) where A: AroundMiddleware {
        use std::mem;

        let old = mem::replace(&mut self.handler, box Nop as Box<Handler + Send + Sync>);
        around.around(old);
        self.handler = box around as Box<Handler + Send + Sync>;
    }
}

impl Handler for ChainBuilder {
    fn call(&self, req: &mut Request) -> IronResult<Response> {
        let before_result = helpers::run_befores(req, self.befores.as_slice(), None);

        let (res, err) = match before_result {
            Ok(()) => match self.handler.call(req) {
                Ok(res) => (res, None),
                Err(e) => helpers::run_handler_catch(req, e, &self.handler)
            },
            Err(e) => helpers::run_handler_catch(req, e, &self.handler)
        };

        helpers::run_afters(req, res, err, self.afters.as_slice())
    }

    fn catch(&self, req: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        let before_result = helpers::run_befores(req, self.befores.as_slice(), Some(err));

        let (res, err) = match before_result {
            Ok(()) => match self.handler.call(req) {
                Ok(res) => (res, None),
                Err(e) => helpers::run_handler_catch(req, e, &self.handler)
            },
            Err(e) => helpers::run_handler_catch(req, e, &self.handler)
        };

        match helpers::run_afters(req, res, err, self.afters.as_slice()) {
            Ok(res) => (res, Ok(())),
            // FIXME: Make 500
            Err(err) => (Response::new(), Err(err))
        }
    }
}

impl Handler for fn(&mut Request) -> IronResult<Response> {
    fn call(&self, req: &mut Request) -> IronResult<Response> {
        self.call(req)
    }

    fn catch(&self, _: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        // FIXME: Make Response a 500
        (Response::new(), Err(err))
    }
}

pub struct Nop;

impl Handler for Nop {
    fn call(&self, _: &mut Request) -> IronResult<Response> {
        Ok(Response::new())
    }

    fn catch(&self, _: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        // FIXME: Make Response a 500
        (Response::new(), Err(err))
    }
}

impl Handler for Box<Handler + Send + Sync> {
    fn call(&self, req: &mut Request) -> IronResult<Response> {
        self.call(req)
    }

    fn catch(&self, req: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        self.catch(req, err)
    }
}

impl Handler for Arc<Box<Handler + Send + Sync>> {
    fn call(&self, req: &mut Request) -> IronResult<Response> {
        self.call(req)
    }

    fn catch(&self, req: &mut Request, err: Box<Error>) -> (Response, IronResult<()>) {
        self.catch(req, err)
    }
}

mod helpers {
    use super::super::{Request, Response, IronResult};
    use super::{AfterMiddleware, BeforeMiddleware, Handler};
    use error::Error;

    pub fn run_befores(req: &mut Request, befores: &[Box<BeforeMiddleware>], err: Option<Box<Error>>) -> IronResult<()> {
        match err {
            Some(mut e) => {
                for (i, before) in befores.iter().enumerate() {
                    match before.catch(req, e) {
                        Ok(_) => return run_befores(req, befores, None),
                        Err(new) => e = new
                    }
                }
                Err(e)
            },

            None => {
                for (i, before) in befores.iter().enumerate() {
                    match before.before(req) {
                        Ok(_) => (),
                        Err(err) => return run_befores(req, befores.slice_from(i), Some(err))
                    }
                }
                Ok(())
            }
        }
    }

    pub fn run_afters(req: &mut Request, mut res: Response, err: Option<Box<Error>>,
                  afters: &[Box<AfterMiddleware>]) -> IronResult<Response> {
        match err {
            Some(mut e) => {
                for (i, after) in afters.iter().enumerate() {
                    match after.catch(req, &mut res, e) {
                        Ok(_) => return run_afters(req, res, None, afters),
                        Err(new) => e = new
                    }
                }
                Err(e)
            },

            None => {
                for (i, after) in afters.iter().enumerate() {
                    match after.after(req, &mut res) {
                        Ok(_) => (),
                        Err(err) => return run_afters(req, res, Some(err), afters.slice_from(i))
                    }
                }
                Ok(res)
            }
        }
    }

    pub fn run_handler_catch(req: &mut Request, err: Box<Error>,
                         handler: &Box<Handler>) -> (Response, Option<Box<Error>>) {
        match handler.catch(req, err) {
            (res, Ok(())) => (res, None),
            (res, Err(e)) => (res, Some(e))
        }
    }
}

<|endoftext|>


<commit_before>use super::mode;
use super::util;
use std::collections::Deque;
use std::collections::RingBuf;

#[deriving(Clone)]
#[deriving(Show)]
enum DOC {
    Nil,
    Append(Box<Doc>, Box<Doc>),
    Group(Box<Doc>),
    Nest(uint, Box<Doc>),
    Newline,
    Text(String),
}

pub type Doc = DOC;
type Cmd<'a> = (uint,mode::Mode,&'a Doc);

fn fitting(mut cmds:RingBuf<Cmd>, mut rem:int) -> bool {
    let mut fits = true;

    loop {
        if rem < 0 {
            fits = false;
            break;
        }
        match cmds.pop_front() {
            None => {
                break;
            },
            Some((ind, mode, doc)) => match doc {
                &Nil => {
                },
                &Append(box ref ldoc, box ref rdoc) => {
                    cmds.push_front((ind, mode, rdoc));
                    cmds.push_front((ind, mode, ldoc));
                },
                &Group(box ref doc) => {
                    cmds.push_front((ind, mode, doc));
                },
                &Nest(off, box ref doc) => {
                    cmds.push_front((ind + off, mode, doc));
                },
                &Newline => {
                    fits = true;
                },
                &Text(ref str) => {
                    rem -= str.len() as int;
                },
            }
        }
    }

    fits
}

impl Doc {

    fn best(&self, width:uint) -> String {
        let mut pos = 0u;
        let mut cmds = RingBuf::new();
        let mut result = String::new();

        cmds.push((0, mode::Break, self));

        loop {
            match cmds.pop_front() {
                None => {
                    break;
                },
                Some((ind, mode, doc)) => match doc {
                    &Nil => {
                    },
                    &Append(box ref ldoc, box ref rdoc) => {
                        cmds.push_front((ind, mode, rdoc));
                        cmds.push_front((ind, mode, ldoc));
                    },
                    &Group(box ref doc) => match mode {
                        mode::Flat => {
                            cmds.push_front((ind, mode::Flat, doc));
                        },
                        mode::Break => {
                            // FIXME: fitting() modifies cmds so we must either
                            // take a clone and pass it or rewrite fitting()
                            // to modify a separate cmd stack and only observe
                            // this one.
                            let mut cmds_dup = cmds.clone();
                            let next = (ind, mode::Flat, doc);
                            cmds_dup.push_front(next);
                            if fitting(cmds_dup, width as int - pos as int) {
                                cmds.push_front(next);
                            } else {
                                cmds.push_front((ind, mode::Break, doc));
                            }
                        }
                    },
                    &Nest(off, box ref doc) => {
                        cmds.push_front((ind + off, mode, doc));
                    },
                    &Newline => {
                        result.push_str(util::string::nl_spaces(ind).as_slice());
                        pos = ind;
                    },
                    &Text(ref str) => {
                        result.push_str(str.as_slice());
                        pos += str.len();
                    },
                }
            }
        }

        result
    }

    #[inline]
    pub fn nil() -> Doc {
        Nil
    }

    #[inline]
    pub fn append(self, that:Doc) -> Doc {
        match self {
            Nil => {
                that
            },
            ldoc => match that {
                Nil => {
                    ldoc
                },
                rdoc => {
                    Append(box ldoc, box rdoc)
                },
            }
        }
    }

    #[inline]
    pub fn as_string<T:ToString>(t:T) -> Doc {
        Doc::text(t.to_string())
    }

    #[inline]
    pub fn concat(ds:&[Doc]) -> Doc {
        ds.iter().fold(Nil, |a, b| a.append(b.clone()))
    }

    #[inline]
    pub fn group(self) -> Doc {
        Group(box self)
    }

    #[inline]
    pub fn nest(self, off:uint) -> Doc {
        Nest(off, box self)
    }

    #[inline]
    pub fn newline() -> Doc {
        Newline
    }

    #[inline]
    pub fn render(&self, width:uint) -> String {
        self.best(width)
    }

    #[inline]
    pub fn text<T:Str>(str:T) -> Doc {
        Text(String::from_str(str.as_slice()))
    }

}
<commit_msg>Inline fitting; best replaces render<commit_after>use super::mode;
use super::util;
use std::collections::Deque;
use std::collections::RingBuf;

#[deriving(Clone)]
#[deriving(Show)]
enum DOC {
    Nil,
    Append(Box<Doc>, Box<Doc>),
    Group(Box<Doc>),
    Nest(uint, Box<Doc>),
    Newline,
    Text(String),
}

pub type Doc = DOC;
type Cmd<'a> = (uint,mode::Mode,&'a Doc);

#[inline(always)]
fn fitting(mut cmds:RingBuf<Cmd>, mut rem:int) -> bool {
    let mut fits = true;

    loop {
        if rem < 0 {
            fits = false;
            break;
        }
        match cmds.pop_front() {
            None => {
                break;
            },
            Some((ind, mode, doc)) => match doc {
                &Nil => {
                },
                &Append(box ref ldoc, box ref rdoc) => {
                    cmds.push_front((ind, mode, rdoc));
                    cmds.push_front((ind, mode, ldoc));
                },
                &Group(box ref doc) => {
                    cmds.push_front((ind, mode, doc));
                },
                &Nest(off, box ref doc) => {
                    cmds.push_front((ind + off, mode, doc));
                },
                &Newline => {
                    fits = true;
                },
                &Text(ref str) => {
                    rem -= str.len() as int;
                },
            }
        }
    }

    fits
}

impl Doc {

    #[inline]
    pub fn nil() -> Doc {
        Nil
    }

    #[inline]
    pub fn append(self, that:Doc) -> Doc {
        match self {
            Nil => {
                that
            },
            ldoc => match that {
                Nil => {
                    ldoc
                },
                rdoc => {
                    Append(box ldoc, box rdoc)
                },
            }
        }
    }

    #[inline]
    pub fn as_string<T:ToString>(t:T) -> Doc {
        Doc::text(t.to_string())
    }

    #[inline]
    pub fn concat(ds:&[Doc]) -> Doc {
        ds.iter().fold(Nil, |a, b| a.append(b.clone()))
    }

    #[inline]
    pub fn group(self) -> Doc {
        Group(box self)
    }

    #[inline]
    pub fn nest(self, off:uint) -> Doc {
        Nest(off, box self)
    }

    #[inline]
    pub fn newline() -> Doc {
        Newline
    }

    #[inline]
    pub fn render(&self, width:uint) -> String {
        let mut pos = 0u;
        let mut cmds = RingBuf::new();
        let mut result = String::new();

        cmds.push((0, mode::Break, self));

        loop {
            match cmds.pop_front() {
                None => {
                    break;
                },
                Some((ind, mode, doc)) => match doc {
                    &Nil => {
                    },
                    &Append(box ref ldoc, box ref rdoc) => {
                        cmds.push_front((ind, mode, rdoc));
                        cmds.push_front((ind, mode, ldoc));
                    },
                    &Group(box ref doc) => match mode {
                        mode::Flat => {
                            cmds.push_front((ind, mode::Flat, doc));
                        },
                        mode::Break => {
                            // FIXME: fitting() modifies cmds so we must either
                            // take a clone and pass it or rewrite fitting()
                            // to modify a separate cmd stack and only observe
                            // this one.
                            let mut cmds_dup = cmds.clone();
                            let next = (ind, mode::Flat, doc);
                            cmds_dup.push_front(next);
                            if fitting(cmds_dup, width as int - pos as int) {
                                cmds.push_front(next);
                            } else {
                                cmds.push_front((ind, mode::Break, doc));
                            }
                        }
                    },
                    &Nest(off, box ref doc) => {
                        cmds.push_front((ind + off, mode, doc));
                    },
                    &Newline => {
                        result.push_str(util::string::nl_spaces(ind).as_slice());
                        pos = ind;
                    },
                    &Text(ref str) => {
                        result.push_str(str.as_slice());
                        pos += str.len();
                    },
                }
            }
        }

        result
    }

    #[inline]
    pub fn text<T:Str>(str:T) -> Doc {
        Text(String::from_str(str.as_slice()))
    }

}
<|endoftext|>


<commit_before>extern mod redis;

use std::io::process;
use std::io::io_error;
use std::libc::SIGTERM;

pub static SERVER_PORT: int = 38991;

struct RedisServer {
    priv process: process::Process,
}

impl RedisServer {

    fn new() -> RedisServer {
        let mut process = process::Process::new(process::ProcessConfig {
            program: "redis-server",
            args: [~"-"],
            env: None,
            cwd: None,
            io: [process::CreatePipe(true, false),
                 process::Ignored,
                 process::Ignored],
        }).unwrap();
        let input = format!("
            port {port}
        ", port=SERVER_PORT);
        process.io[0].get_mut_ref().write(input.as_bytes());
        process.io[0] = None;
        RedisServer { process: process }
    }
}

impl Drop for RedisServer {

    fn drop(&mut self) {
        io_error::cond.trap(|_e| {}).inside(|| {
            self.process.signal(SIGTERM as int);
        });
        let rv = self.process.wait();
        assert!(rv.success());
    }
}

struct TestContext {
    server: RedisServer,
    client: redis::Client,
}

impl TestContext {

    fn new() -> TestContext {
        let url = format!("redis://127.0.0.1:{port}/0", port=SERVER_PORT);
        let server = RedisServer::new();

        let mut client;
        loop {
            match redis::Client::open(url) {
                Ok(x) => { client = x; break; }
                Err(redis::ConnectionRefused) => { std::io::timer::sleep(10); }
                _ => { fail!("Error on connect"); }
            }
        }

        client.get_connection().unwrap().flushdb();
        TestContext {
            server: server,
            client: client,
        }
    }

    fn connection(&self) -> redis::Connection {
        self.client.get_connection().unwrap()
    }
}

#[test]
fn test_ping() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    assert!(con.ping() == true);
}

#[test]
fn test_info() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    let info = con.info();
    assert!(*info.find(&~"tcp_port").unwrap() == SERVER_PORT.to_str());
}

#[test]
fn test_basics() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    con.set("foo", "bar");
    assert!(con.get("foo") == Some(~"bar"));
    con.del("foo");
    assert!(con.get("foo") == None);
}

#[test]
fn test_types() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    con.set("foo", 42);
    con.set("bar", "test");
    assert!(con.get_type("foo") == redis::StringType);
    assert!(con.get_type("bar") == redis::StringType);
    assert!(con.get("foo") == Some(~"42"));
    assert!(con.get_as::<int>("foo") == Some(42));
    assert!(con.get("bar") == Some(~"test"));
    assert!(con.exists("foo") == true);
    assert!(con.exists("invalid") == false);
}

#[test]
fn test_script() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    let script = redis::Script::new("
        return tonumber(ARGV[1]) + 1;
    ");
    assert!(con.call_script(&script, [], [redis::StrArg("42")]) == redis::Int(43));
}

#[test]
fn test_blpop() {
    let ctx = TestContext::new();
    let client = ctx.client;
    let (port, chan) = Chan::new();

    do spawn {
        let mut con = client.get_connection().unwrap();
        let rv = con.blpop(["q"], 5.0);
        assert!(rv == Some((~"q", ~"awesome")));
        chan.send(());
    }

    do spawn {
        let mut con = client.get_connection().unwrap();
        con.rpush("q", "awesome");
    }

    port.recv();
}

#[test]
fn test_scan() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();

    for x in range(0, 100) {
        con.set(format!("key:{}", x), x);
    }

    let mut found = [false, .. 100];
    for item in con.scan("key:*") {
        let mut iter = item.split(':');
        if iter.next().is_none() {
            continue;
        }
        match iter.next() {
            Some(value) => {
                found[from_str::<uint>(value).unwrap()] = true;
            }
            None => {},
        }
    }

    for x in range(0, 100) {
        assert!(found[x] == true);
    }
}
<commit_msg>Sleep less, do more work<commit_after>extern mod redis;

use std::io::process;
use std::io::io_error;
use std::libc::SIGTERM;

pub static SERVER_PORT: int = 38991;

struct RedisServer {
    priv process: process::Process,
}

impl RedisServer {

    fn new() -> RedisServer {
        let mut process = process::Process::new(process::ProcessConfig {
            program: "redis-server",
            args: [~"-"],
            env: None,
            cwd: None,
            io: [process::CreatePipe(true, false),
                 process::Ignored,
                 process::Ignored],
        }).unwrap();
        let input = format!("
            port {port}
        ", port=SERVER_PORT);
        process.io[0].get_mut_ref().write(input.as_bytes());
        process.io[0] = None;
        RedisServer { process: process }
    }
}

impl Drop for RedisServer {

    fn drop(&mut self) {
        io_error::cond.trap(|_e| {}).inside(|| {
            self.process.signal(SIGTERM as int);
        });
        let rv = self.process.wait();
        assert!(rv.success());
    }
}

struct TestContext {
    server: RedisServer,
    client: redis::Client,
}

impl TestContext {

    fn new() -> TestContext {
        let url = format!("redis://127.0.0.1:{port}/0", port=SERVER_PORT);
        let server = RedisServer::new();

        let mut client;
        loop {
            match redis::Client::open(url) {
                Ok(x) => { client = x; break; }
                Err(redis::ConnectionRefused) => { std::io::timer::sleep(1); }
                _ => { fail!("Error on connect"); }
            }
        }

        client.get_connection().unwrap().flushdb();
        TestContext {
            server: server,
            client: client,
        }
    }

    fn connection(&self) -> redis::Connection {
        self.client.get_connection().unwrap()
    }
}

#[test]
fn test_ping() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    assert!(con.ping() == true);
}

#[test]
fn test_info() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    let info = con.info();
    assert!(*info.find(&~"tcp_port").unwrap() == SERVER_PORT.to_str());
}

#[test]
fn test_basics() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    con.set("foo", "bar");
    assert!(con.get("foo") == Some(~"bar"));
    con.del("foo");
    assert!(con.get("foo") == None);
}

#[test]
fn test_types() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    con.set("foo", 42);
    con.set("bar", "test");
    assert!(con.get_type("foo") == redis::StringType);
    assert!(con.get_type("bar") == redis::StringType);
    assert!(con.get("foo") == Some(~"42"));
    assert!(con.get_as::<int>("foo") == Some(42));
    assert!(con.get("bar") == Some(~"test"));
    assert!(con.exists("foo") == true);
    assert!(con.exists("invalid") == false);
}

#[test]
fn test_script() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();
    let script = redis::Script::new("
        return tonumber(ARGV[1]) + 1;
    ");
    assert!(con.call_script(&script, [], [redis::StrArg("42")]) == redis::Int(43));
}

#[test]
fn test_blpop() {
    let ctx = TestContext::new();
    let client = ctx.client;
    let (port, chan) = Chan::new();

    do spawn {
        let mut con = client.get_connection().unwrap();
        let rv = con.blpop(["q"], 5.0);
        assert!(rv == Some((~"q", ~"awesome")));
        chan.send(());
    }

    do spawn {
        let mut con = client.get_connection().unwrap();
        con.rpush("q", "awesome");
    }

    port.recv();
}

#[test]
fn test_scan() {
    let ctx = TestContext::new();
    let mut con = ctx.connection();

    for x in range(0, 100) {
        con.set(format!("key:{}", x), x);
    }

    let mut found = [false, .. 100];
    for item in con.scan("key:*") {
        let mut iter = item.split(':');
        if iter.next().is_none() {
            continue;
        }
        match iter.next() {
            Some(value) => {
                found[from_str::<uint>(value).unwrap()] = true;
            }
            None => {},
        }
    }

    for x in range(0, 100) {
        assert!(found[x] == true);
    }
}
<|endoftext|>


<commit_before>extern crate chan;
extern crate rand;

use ::bincode;
use ::bincode::serde::{serialize_into, deserialize_from, DeserializeError};
use ::model;
use ::model::types::{Board, Player, PlayerType, SubField};
use ::net::{self, types};
use ::net::types::{MessageType};
use ::util;
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use term_painter::ToStyle;
use term_painter::Color::*;

#[derive(Debug)]
enum CurrentPlayer {
    Host,
    Client,
}

/// Initialize and prepare game
pub fn init(name: String, size: u8, board: Vec<SubField>) {
    let listener = TcpListener::bind((types::LOCALHOST, types::DEFAULT_PORT)).unwrap();

    // accept one incoming connection
    let (client_conn, _) = listener.accept().unwrap();
    let mut client_stream = client_conn.try_clone().unwrap();

    // welcome client
    serialize_into(
        &mut client_stream,
        &(types::MessageType::Welcome(
            "Welcome stranger, let me sink your ships!".to_string(),
            name.clone())
        ),
        bincode::SizeLimit::Infinite
    );

    // add CTRL+C system hook, so that connection partner is informed about disconnect
    let mut client_stream_clone = client_stream.try_clone().unwrap();
    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();
    ::ctrlc::set_handler(move || {
        net::send(&mut client_stream_clone.try_clone().unwrap(), MessageType::Quit);
        client_stream_clone.shutdown(Shutdown::Both).expect("shutdown call failed");
    }).expect("Error setting Ctrl+C handler");

    // wait for client to send his name
    let recv: Result<types::MessageType, DeserializeError> =
        deserialize_from(&mut client_stream, bincode::SizeLimit::Infinite);
    let client_name = match recv {
        Ok(received) => {
            match received {
                MessageType::Login(name) => {
                    name
                },
                MessageType::Quit => {
                    println!("Client closed connection.");
                    return
                },
                _ => {
                    // unexpected packet

                    "".to_string()
                },
            }
        },
        Err(_) => {
            println!("ERROR hit me");
            "".to_string()
        },
    };

    // create players
    let host = Player {
        own_board: board.clone(),
        op_board: Board::init(),
        player_type: PlayerType::Human,
        name: name,
        capacity: Board::targets(&board),
    };

    let client = Player {
        own_board: Board::init(),
        op_board: Board::init(),
        player_type: PlayerType::Human,
        name: client_name,
        capacity: Board::targets(&Board::init()),
    };

    // start game
    start(host, client, client_stream);

    println!("\n{}", Yellow.paint("Bye."));
}

/// Starting the game with given parameters
fn start(mut host: Player, mut client: Player, mut stream: TcpStream) {
    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                    Request initial board configuration from host                          //
    ///////////////////////////////////////////////////////////////////////////////////////////////

    if host.capacity == 0 {
        net::send(
            &mut stream,
            MessageType::Text("Server is setting its ships, please wait :)".to_string())
        );
        println!("Please set your ships:");
        ::model::place_ships(&mut host);
    }
    model::print_boards(&host);

    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                    Request initial board configuration from client                        //
    ///////////////////////////////////////////////////////////////////////////////////////////////
    net::send(&mut stream, MessageType::RequestBoard);

    loop {
        let recv: Result<types::MessageType, DeserializeError> =
        deserialize_from(&mut stream, bincode::SizeLimit::Infinite);
        match recv {
            Ok(received) => {
                match received {
                    MessageType::Board(vec) => {
                        client.own_board = vec;
                        break;
                    },
                    MessageType::Quit => {
                        println!("Client closed connection.");
                        return
                    },
                    _ => continue,
                }
            },
            Err(_) => {
                println!("ERROR board");
                net::send(&mut stream, MessageType::Quit);
                stream.shutdown(Shutdown::Both).expect("shutdown call failed");
                return
            },
        };
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                              Choose random start player                                   //
    ///////////////////////////////////////////////////////////////////////////////////////////////
    let mut current_player = match choose_player(&host, &client).name == host.name {
        true => CurrentPlayer::Host,
        false => CurrentPlayer::Client,
    };
    println!("Starting player: {:?}", current_player);

    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                             Take turns while not ended                                    //
    ///////////////////////////////////////////////////////////////////////////////////////////////
    loop {
        match current_player {
            CurrentPlayer::Host => {
                // inform Client that its the turn of Host
                net::send(&mut stream, MessageType::TurnHost);

                // wait for input from Host
                println!("{}", Yellow.paint("It's your turn!"));
                let mut coord;
                loop {
                    println!("{}", Yellow.paint("Please enter a valid coordinate: "));
                    coord = util::read_string();
                    if ::model::valid_coordinate(&coord) {
                        break;
                    }
                    print!("{}", Red.paint("Invalid coordinate! "));
                }
                // modify boards
                let coord_id = Board::get_index(&coord);
                match ::model::match_move(&mut host, &mut client, coord_id) {
                    SubField::Hit => {
                        net::send(&mut stream, MessageType::Hit(coord_id));
                        model::print_boards(&host);
                    }
                    SubField::Miss => {
                        net::send(&mut stream, MessageType::Miss(coord_id));
                        model::print_boards(&host);
                        current_player = CurrentPlayer::Client;
                    }
                    _ => {}
                }

                // if Host won: send message to Client, end game
                if ::model::game_over(&client) {
                    net::send(&mut stream, MessageType::Lost);
                    println!("{}", Yellow.paint("Congratulations, you won the game :)"));
                    break;
                }
            }
            CurrentPlayer::Client => {
                println!(
                    "{} {} {}",
                    Cyan.paint("Wait for"),
                    Yellow.paint(&client.name),
                    Cyan.paint("to finish turn!"),
                );
                // inform Client that its his turn
                net::send(&mut stream, MessageType::RequestCoord);
                // wait for input from Client
                let recv: Result<types::MessageType, DeserializeError> =
                    deserialize_from(&mut stream, bincode::SizeLimit::Infinite);
                let coordinate = match recv {
                    Ok(received) => {
                        match received {
                            MessageType::Shoot(coord) => {
                                coord
                            },
                            MessageType::Quit => {
                                println!("Client closed connection.");
                                return
                            },
                            _ => {
                                // unexpected packet
                                "".to_string()
                            },
                        }
                    },
                    Err(_) => {
                        println!("ERROR coord");
                        return
                    },
                };

                // modify boards
                let coord_id = Board::get_index(&coordinate);
                match ::model::match_move(&mut client, &mut host, coord_id) {
                    SubField::Hit => {
                        println!("{} hit one of your ships!", client.name);
                        net::send(&mut stream, MessageType::Hit(coord_id));
                        model::print_boards(&host);
                    }
                    SubField::Miss => {
                        println!("{} missed your ships.", client.name);
                        net::send(&mut stream, MessageType::Miss(coord_id));
                        model::print_boards(&host);
                        current_player = CurrentPlayer::Host;
                    }
                    _ => {}
                }

                // if Client won: send message to Client, end game
                if ::model::game_over(&host) {
                    net::send(&mut stream, MessageType::Won);
                    println!("{}", Yellow.paint("You lost :("));
                    break;
                }
            }
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                                  Quit game                                                //
    ///////////////////////////////////////////////////////////////////////////////////////////////
    net::send(&mut stream, MessageType::Quit);
}

/// Randomly choose host or client player to start guessing
fn choose_player<'a>(p1: &'a Player, p2: &'a Player) -> &'a Player {
    use self::rand::distributions::{IndependentSample, Range};
    let between = Range::new(0, 2);
    let mut rng = rand::thread_rng();
    match between.ind_sample(&mut rng) {
        0 => &p1,
        _ => &p2,
    }
}
<commit_msg>Fix capacity bug<commit_after>extern crate chan;
extern crate rand;

use ::bincode;
use ::bincode::serde::{serialize_into, deserialize_from, DeserializeError};
use ::model;
use ::model::types::{Board, Player, PlayerType, SubField};
use ::net::{self, types};
use ::net::types::{MessageType};
use ::util;
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use term_painter::ToStyle;
use term_painter::Color::*;

#[derive(Debug)]
enum CurrentPlayer {
    Host,
    Client,
}

/// Initialize and prepare game
pub fn init(name: String, size: u8, board: Vec<SubField>) {
    let listener = TcpListener::bind((types::LOCALHOST, types::DEFAULT_PORT)).unwrap();

    // accept one incoming connection
    let (client_conn, _) = listener.accept().unwrap();
    let mut client_stream = client_conn.try_clone().unwrap();

    // welcome client
    serialize_into(
        &mut client_stream,
        &(types::MessageType::Welcome(
            "Welcome stranger, let me sink your ships!".to_string(),
            name.clone())
        ),
        bincode::SizeLimit::Infinite
    );

    // add CTRL+C system hook, so that connection partner is informed about disconnect
    let mut client_stream_clone = client_stream.try_clone().unwrap();
    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();
    ::ctrlc::set_handler(move || {
        net::send(&mut client_stream_clone.try_clone().unwrap(), MessageType::Quit);
        client_stream_clone.shutdown(Shutdown::Both).expect("shutdown call failed");
    }).expect("Error setting Ctrl+C handler");

    // wait for client to send his name
    let recv: Result<types::MessageType, DeserializeError> =
        deserialize_from(&mut client_stream, bincode::SizeLimit::Infinite);
    let client_name = match recv {
        Ok(received) => {
            match received {
                MessageType::Login(name) => {
                    name
                },
                MessageType::Quit => {
                    println!("Client closed connection.");
                    return
                },
                _ => {
                    // unexpected packet

                    "".to_string()
                },
            }
        },
        Err(_) => {
            println!("ERROR hit me");
            "".to_string()
        },
    };

    // create players
    let host = Player {
        own_board: board.clone(),
        op_board: Board::init(),
        player_type: PlayerType::Human,
        name: name,
        capacity: Board::targets(&board),
    };

    let client = Player {
        own_board: Board::init(),
        op_board: Board::init(),
        player_type: PlayerType::Human,
        name: client_name,
        capacity: Board::targets(&Board::init()),
    };

    // start game
    start(host, client, client_stream);

    println!("\n{}", Yellow.paint("Bye."));
}

/// Starting the game with given parameters
fn start(mut host: Player, mut client: Player, mut stream: TcpStream) {
    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                    Request initial board configuration from host                          //
    ///////////////////////////////////////////////////////////////////////////////////////////////

    if host.capacity == 0 {
        net::send(
            &mut stream,
            MessageType::Text("Server is setting its ships, please wait :)".to_string())
        );
        println!("Please set your ships:");
        ::model::place_ships(&mut host);
    }
    model::print_boards(&host);

    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                    Request initial board configuration from client                        //
    ///////////////////////////////////////////////////////////////////////////////////////////////
    net::send(&mut stream, MessageType::RequestBoard);

    loop {
        let recv: Result<types::MessageType, DeserializeError> =
        deserialize_from(&mut stream, bincode::SizeLimit::Infinite);
        match recv {
            Ok(received) => {
                match received {
                    MessageType::Board(vec) => {
                        client.own_board = vec.clone();
                        client.capacity = Board::targets(&vec);
                        break;
                    },
                    MessageType::Quit => {
                        println!("Client closed connection.");
                        return
                    },
                    _ => continue,
                }
            },
            Err(_) => {
                println!("ERROR board");
                net::send(&mut stream, MessageType::Quit);
                stream.shutdown(Shutdown::Both).expect("shutdown call failed");
                return
            },
        };
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                              Choose random start player                                   //
    ///////////////////////////////////////////////////////////////////////////////////////////////
    let mut current_player = match choose_player(&host, &client).name == host.name {
        true => CurrentPlayer::Host,
        false => CurrentPlayer::Client,
    };
    println!("Starting player: {:?}", current_player);

    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                             Take turns while not ended                                    //
    ///////////////////////////////////////////////////////////////////////////////////////////////
    loop {
        match current_player {
            CurrentPlayer::Host => {
                // inform Client that its the turn of Host
                net::send(&mut stream, MessageType::TurnHost);

                // wait for input from Host
                println!("{}", Yellow.paint("It's your turn!"));
                let mut coord;
                loop {
                    println!("{}", Yellow.paint("Please enter a valid coordinate: "));
                    coord = util::read_string();
                    if ::model::valid_coordinate(&coord) {
                        break;
                    }
                    print!("{}", Red.paint("Invalid coordinate! "));
                }
                // modify boards
                let coord_id = Board::get_index(&coord);
                match ::model::match_move(&mut host, &mut client, coord_id) {
                    SubField::Hit => {
                        net::send(&mut stream, MessageType::Hit(coord_id));
                        model::print_boards(&host);
                    }
                    SubField::Miss => {
                        net::send(&mut stream, MessageType::Miss(coord_id));
                        model::print_boards(&host);
                        current_player = CurrentPlayer::Client;
                    }
                    _ => {}
                }

                // if Host won: send message to Client, end game
                if ::model::game_over(&client) {
                    net::send(&mut stream, MessageType::Lost);
                    println!("{}", Yellow.paint("Congratulations, you won the game :)"));
                    break;
                }
            }
            CurrentPlayer::Client => {
                println!(
                    "{} {} {}",
                    Cyan.paint("Wait for"),
                    Yellow.paint(&client.name),
                    Cyan.paint("to finish turn!"),
                );
                // inform Client that its his turn
                net::send(&mut stream, MessageType::RequestCoord);
                // wait for input from Client
                let recv: Result<types::MessageType, DeserializeError> =
                    deserialize_from(&mut stream, bincode::SizeLimit::Infinite);
                let coordinate = match recv {
                    Ok(received) => {
                        match received {
                            MessageType::Shoot(coord) => {
                                coord
                            },
                            MessageType::Quit => {
                                println!("Client closed connection.");
                                return
                            },
                            _ => {
                                // unexpected packet
                                "".to_string()
                            },
                        }
                    },
                    Err(_) => {
                        println!("ERROR coord");
                        return
                    },
                };

                // modify boards
                let coord_id = Board::get_index(&coordinate);
                match ::model::match_move(&mut client, &mut host, coord_id) {
                    SubField::Hit => {
                        println!("{} hit one of your ships!", client.name);
                        net::send(&mut stream, MessageType::Hit(coord_id));
                        model::print_boards(&host);
                    }
                    SubField::Miss => {
                        println!("{} missed your ships.", client.name);
                        net::send(&mut stream, MessageType::Miss(coord_id));
                        model::print_boards(&host);
                        current_player = CurrentPlayer::Host;
                    }
                    _ => {}
                }

                // if Client won: send message to Client, end game
                if ::model::game_over(&host) {
                    net::send(&mut stream, MessageType::Won);
                    println!("{}", Yellow.paint("You lost :("));
                    break;
                }
            }
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    //                                  Quit game                                                //
    ///////////////////////////////////////////////////////////////////////////////////////////////
    net::send(&mut stream, MessageType::Quit);
}

/// Randomly choose host or client player to start guessing
fn choose_player<'a>(p1: &'a Player, p2: &'a Player) -> &'a Player {
    use self::rand::distributions::{IndependentSample, Range};
    let between = Range::new(0, 2);
    let mut rng = rand::thread_rng();
    match between.ind_sample(&mut rng) {
        0 => &p1,
        _ => &p2,
    }
}
<|endoftext|>


<commit_before>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://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 crate::{
    conversion::{
        analysis::tdef::TypedefAnalysis, api::Api, apivec::ApiVec,
        convert_error::ConvertErrorWithContext,
    },
    types::QualifiedName,
};

use super::pod::PodPhase;
/// Where we find a typedef pointing at something we can't represent,
/// e.g. because it uses too many template parameters, break the link.
/// Use the typedef as a first-class type.
pub(crate) fn replace_hopeless_typedef_targets(apis: ApiVec<PodPhase>) -> ApiVec<PodPhase> {
    let ignored_types: HashSet<QualifiedName> = apis
        .iter()
        .filter_map(|api| match api {
            Api::IgnoredItem { .. } => Some(api.name()),
            _ => None,
        })
        .cloned()
        .collect();
    let ignored_forward_declarations: HashSet<QualifiedName> = apis
        .iter()
        .filter_map(|api| match api {
            Api::ForwardDeclaration { err: Some(_), .. } => Some(api.name()),
            _ => None,
        })
        .cloned()
        .collect();
    // Convert any Typedefs which depend on these things into OpaqueTypedefs
    // instead.
    // And, after this point we no longer need special knowledge of forward
    // declarations with errors, so just convert them into regular IgnoredItems too.
    apis.into_iter()
        .map(|api| match api {
            Api::Typedef {
                analysis: TypedefAnalysis { ref deps, .. },
                ..
            } if !ignored_types.is_disjoint(deps) => Api::OpaqueTypedef {
                name: api.name_info().clone(),
                forward_declaration: false,
            },
            Api::Typedef {
                analysis: TypedefAnalysis { ref deps, .. },
                ..
            } if !ignored_forward_declarations.is_disjoint(deps) => Api::OpaqueTypedef {
                name: api.name_info().clone(),
                forward_declaration: true,
            },
            Api::ForwardDeclaration {
                name,
                err: Some(ConvertErrorWithContext(err, ctx)),
            } => Api::IgnoredItem { name, err, ctx },
            _ => api,
        })
        .collect()
}
<commit_msg>Fix merge problem.<commit_after>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use indexmap::set::IndexSet as HashSet;

use crate::{
    conversion::{
        analysis::tdef::TypedefAnalysis, api::Api, apivec::ApiVec,
        convert_error::ConvertErrorWithContext,
    },
    types::QualifiedName,
};

use super::pod::PodPhase;
/// Where we find a typedef pointing at something we can't represent,
/// e.g. because it uses too many template parameters, break the link.
/// Use the typedef as a first-class type.
pub(crate) fn replace_hopeless_typedef_targets(apis: ApiVec<PodPhase>) -> ApiVec<PodPhase> {
    let ignored_types: HashSet<QualifiedName> = apis
        .iter()
        .filter_map(|api| match api {
            Api::IgnoredItem { .. } => Some(api.name()),
            _ => None,
        })
        .cloned()
        .collect();
    let ignored_forward_declarations: HashSet<QualifiedName> = apis
        .iter()
        .filter_map(|api| match api {
            Api::ForwardDeclaration { err: Some(_), .. } => Some(api.name()),
            _ => None,
        })
        .cloned()
        .collect();
    // Convert any Typedefs which depend on these things into OpaqueTypedefs
    // instead.
    // And, after this point we no longer need special knowledge of forward
    // declarations with errors, so just convert them into regular IgnoredItems too.
    apis.into_iter()
        .map(|api| match api {
            Api::Typedef {
                analysis: TypedefAnalysis { ref deps, .. },
                ..
            } if !ignored_types.is_disjoint(deps) => Api::OpaqueTypedef {
                name: api.name_info().clone(),
                forward_declaration: false,
            },
            Api::Typedef {
                analysis: TypedefAnalysis { ref deps, .. },
                ..
            } if !ignored_forward_declarations.is_disjoint(deps) => Api::OpaqueTypedef {
                name: api.name_info().clone(),
                forward_declaration: true,
            },
            Api::ForwardDeclaration {
                name,
                err: Some(ConvertErrorWithContext(err, ctx)),
            } => Api::IgnoredItem { name, err, ctx },
            _ => api,
        })
        .collect()
}
<|endoftext|>


<commit_before>use std::rc::*;

use super::treenode::*;
use super::tree_ref::*;

pub trait TreeNodeBuilder {
    ///
    /// Sets the children of a tree node to a set of tree node references
    ///
    fn set_children_refs<'a>(&mut self, new_children: &'a Vec<Rc<TreeNode>>);
}

type ChildList = Rc<Vec<Rc<TreeNode>>>;

impl<T: MutableTreeNode> TreeNodeBuilder for T {
    fn set_children_refs<'a>(&mut self, new_children: &'a Vec<Rc<TreeNode>>) {
        let num_new_children = new_children.len();

        if num_new_children > 0 {
            // Build the final child node backwards
            let mut new_child = new_children[num_new_children-1].with_no_sibling();

            for child_num in (0..(num_new_children-1)).rev() {
                new_child = new_children[child_num].with_sibling_ref(&new_child);
            }

            self.set_child(new_child);
        } else {
            // No children
            self.clear_child();
        }
    }
}

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

    #[test]
    fn can_build_tree() {
        let mut root = BasicTree::new("test", ());
        let child_list = vec!["child1".to_tree_node(), "child2".to_tree_node(), "child3".to_tree_node()];

        root.set_children_refs(&child_list);

        assert!(root.get_child_ref().is_some());
        assert!(root.get_child_ref().map(|x| x.get_tag() == "child1").unwrap_or(false));
        assert!(root.get_child_ref().and_then(|x| x.get_sibling_ref()).map(|x| x.get_tag() == "child2").unwrap_or(false));
        assert!(root.get_child_ref().and_then(|x| x.get_sibling_ref()).and_then(|x| x.get_sibling_ref()).map(|x| x.get_tag() == "child3").unwrap_or(false));
        assert!(root.get_child_ref().and_then(|x| x.get_sibling_ref()).and_then(|x| x.get_sibling_ref()).and_then(|x| x.get_sibling_ref()).is_none());
    }
}
<commit_msg>Use the indexer to get the tree's children instead<commit_after>use std::rc::*;

use super::treenode::*;
use super::tree_ref::*;

pub trait TreeNodeBuilder {
    ///
    /// Sets the children of a tree node to a set of tree node references
    ///
    fn set_children_refs<'a>(&mut self, new_children: &'a Vec<Rc<TreeNode>>);
}

type ChildList = Rc<Vec<Rc<TreeNode>>>;

impl<T: MutableTreeNode> TreeNodeBuilder for T {
    fn set_children_refs<'a>(&mut self, new_children: &'a Vec<Rc<TreeNode>>) {
        let num_new_children = new_children.len();

        if num_new_children > 0 {
            // Build the final child node backwards
            let mut new_child = new_children[num_new_children-1].with_no_sibling();

            for child_num in (0..(num_new_children-1)).rev() {
                new_child = new_children[child_num].with_sibling_ref(&new_child);
            }

            self.set_child(new_child);
        } else {
            // No children
            self.clear_child();
        }
    }
}

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

    #[test]
    fn can_build_tree() {
        let mut root = BasicTree::new("test", ());
        let child_list = vec!["child1".to_tree_node(), "child2".to_tree_node(), "child3".to_tree_node()];

        root.set_children_refs(&child_list);

        assert!(root.get_child_ref().is_some());
        assert!(root.get_child_ref_at(0).map(|x| x.get_tag() == "child1").unwrap_or(false));
        assert!(root.get_child_ref_at(1).map(|x| x.get_tag() == "child2").unwrap_or(false));
        assert!(root.get_child_ref_at(2).map(|x| x.get_tag() == "child3").unwrap_or(false));
        assert!(root.get_child_ref_at(3).is_none());
    }
}
<|endoftext|>


<commit_before>#![warn(clippy::filetype_is_file)]

fn main() -> std::io::Result<()> {
    use std::fs;
    use std::ops::BitOr;

    // !filetype.is_dir()
    if fs::metadata("foo.txt")?.file_type().is_file() {
        // read file
    }

    // positive of filetype.is_dir()
    if !fs::metadata("foo.txt")?.file_type().is_file() {
        // handle dir
    }

    // false positive of filetype.is_dir()
    if !fs::metadata("foo.txt")?.file_type().is_file().bitor(true) {
        // ...
    }

    Ok(())
}<commit_msg>format codebase.<commit_after>#![warn(clippy::filetype_is_file)]

fn main() -> std::io::Result<()> {
    use std::fs;
    use std::ops::BitOr;

    // !filetype.is_dir()
    if fs::metadata("foo.txt")?.file_type().is_file() {
        // read file
    }

    // positive of filetype.is_dir()
    if !fs::metadata("foo.txt")?.file_type().is_file() {
        // handle dir
    }

    // false positive of filetype.is_dir()
    if !fs::metadata("foo.txt")?.file_type().is_file().bitor(true) {
        // ...
    }

    Ok(())
}
<|endoftext|>


<commit_before>use std::env;

fn newmat(x: usize, y: usize) -> Vec<Vec<f64>> {
  let inner = vec![0_f64; y];
  vec![inner; x]
}

fn matgen(n: usize) -> Vec<Vec<f64>> {
  let mut a = newmat(n, n);
  let tmp = 1_f64 / (n as f64) / (n as f64);
  for i in 0..n {
    for j in 0..n {
      let val = tmp * (i as f64 - j as f64) * (i as f64 + j as f64);
      a[i][j] = val;
    }
  }
  a
}

fn matmul(a: Vec<Vec<f64>>, b: Vec<Vec<f64>>) -> Vec<Vec<f64>> {
  let m = a.len();
  let n = a[0].len();
  let p = b[0].len();

  let mut b2 = newmat(n, p);
  for i in 0..n {
    for j in 0..p {
      b2[j][i] = b[i][j];
    }
  }

  let mut c = newmat(m, p);
  for i in 0..m {
    for j in 0..p {
      let mut s = 0_f64;
      let ref ai = a[i];
      let ref b2j = b2[j];
      for k in 0..n {
        s += ai[k] * b2j[k];
      }
      c[i][j] = s;
    }
  }

  c
}

fn main() {
  let mut n = 100;
  if env::args().len() > 1 {
    let arg1 = env::args().nth(1).unwrap();
    n = arg1.parse().unwrap();
  }
  n = n / 2 * 2;

  let a = matgen(n);
  let b = matgen(n);
  let c = matmul(a, b);
  println!("{}", c[n / 2][n / 2]);
}
<commit_msg>Matmul with less indexing and more iterators<commit_after>// rustc -C opt-level=3 -C lto

fn new_mat(x: usize, y: usize) -> Vec<Vec<f64>> {
    vec![vec![0f64; y]; x]
}

fn mat_gen(n: usize) -> Vec<Vec<f64>> {
    let mut m = new_mat(n, n);
    let tmp = 1f64 / (n as f64) / (n as f64);

    for i in 0 .. n {
        for j in 0 .. n {
            m[i][j] = tmp * (i as f64 - j as f64) * (i as f64 + j as f64);
        }
    }
    m
}

#[inline(never)]
fn mat_mul(a: &[Vec<f64>], b: &[Vec<f64>]) -> Vec<Vec<f64>> {
    let m = a.len();
    let n = a[0].len();
    let p = b[0].len();

    let mut b2 = new_mat(n, p);
    for i in 0 .. n {
        for j in 0 .. p {
            b2[j][i] = b[i][j];
        }
    }

    let mut c = new_mat(m, p);

    for (i, ci) in c.iter_mut().enumerate() {
        for (cij, b2j) in ci.iter_mut().zip(&b2) {
            *cij = a[i].iter().zip(b2j).map(|(&x, y)| x * y).sum();
        }
    }

    c
}

fn main() {
    let n = std::env::args()
            .nth(1)
            .unwrap_or("1500".into())
            .parse::<usize>()
            .unwrap() / 2 * 2;

    let a = mat_gen(n);
    let b = mat_gen(n);
    let c = mat_mul(&a, &b);

    println!("{}", c[n / 2][n / 2]);
}<|endoftext|>