hearts 0.1.1

Cards, tricks, and a rules-driven state machine for the card game Hearts
Documentation
//! The four seats of Hearts and the pass-direction cycle.

use core::fmt;
use core::str::FromStr;
use thiserror::Error;

/// One of the four seats, named by compass point as in bridge
///
/// Play proceeds clockwise, i.e. to the [`left`](Self::left).  Seats index
/// per-seat arrays via `seat as usize`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum Seat {
    /// The north seat
    North = 0,
    /// The east seat
    East = 1,
    /// The south seat
    South = 2,
    /// The west seat
    West = 3,
}

impl Seat {
    /// All four seats in clockwise order
    pub const ALL: [Self; 4] = [Self::North, Self::East, Self::South, Self::West];

    /// The seat to the left (clockwise), the next seat in turn order
    #[must_use]
    #[inline]
    pub const fn left(self) -> Self {
        match self {
            Self::North => Self::East,
            Self::East => Self::South,
            Self::South => Self::West,
            Self::West => Self::North,
        }
    }

    /// The seat to the right (counterclockwise), the previous seat in turn
    /// order
    #[must_use]
    #[inline]
    pub const fn right(self) -> Self {
        match self {
            Self::North => Self::West,
            Self::East => Self::North,
            Self::South => Self::East,
            Self::West => Self::South,
        }
    }

    /// The seat across the table
    #[must_use]
    #[inline]
    pub const fn across(self) -> Self {
        match self {
            Self::North => Self::South,
            Self::East => Self::West,
            Self::South => Self::North,
            Self::West => Self::East,
        }
    }

    /// Uppercase letter, the compass initial
    #[must_use]
    #[inline]
    pub const fn letter(self) -> char {
        match self {
            Self::North => 'N',
            Self::East => 'E',
            Self::South => 'S',
            Self::West => 'W',
        }
    }
}

impl fmt::Display for Seat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::North => "North",
            Self::East => "East",
            Self::South => "South",
            Self::West => "West",
        })
    }
}

/// Error returned when parsing a [`Seat`] fails
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
#[error("Invalid seat: expected one of N, E, S, W or a compass name")]
pub struct ParseSeatError;

impl FromStr for Seat {
    type Err = ParseSeatError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_uppercase().as_str() {
            "N" | "NORTH" => Ok(Self::North),
            "E" | "EAST" => Ok(Self::East),
            "S" | "SOUTH" => Ok(Self::South),
            "W" | "WEST" => Ok(Self::West),
            _ => Err(ParseSeatError),
        }
    }
}

/// Where each seat passes its three cards before play
///
/// The standard rotation cycles left, right, across, hold with each deal;
/// see [`CYCLE`](Self::CYCLE) and [`from_deal_index`](Self::from_deal_index).
/// On a hold deal nobody passes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u8)]
pub enum PassDirection {
    /// Pass to the seat on the left
    Left = 0,
    /// Pass to the seat on the right
    Right = 1,
    /// Pass to the seat across the table
    Across = 2,
    /// Keep the dealt hand; no passing
    Hold = 3,
}

impl PassDirection {
    /// The standard four-deal rotation, in order
    pub const CYCLE: [Self; 4] = [Self::Left, Self::Right, Self::Across, Self::Hold];

    /// The direction of the `n`th deal (0-based) under the standard rotation
    #[must_use]
    #[inline]
    pub const fn from_deal_index(n: u32) -> Self {
        Self::CYCLE[n as usize % 4]
    }

    /// The seat that receives `giver`'s cards (the giver itself on a hold)
    #[must_use]
    #[inline]
    pub const fn receiver(self, giver: Seat) -> Seat {
        match self {
            Self::Left => giver.left(),
            Self::Right => giver.right(),
            Self::Across => giver.across(),
            Self::Hold => giver,
        }
    }

    /// The seat whose cards `receiver` gets (the receiver itself on a hold)
    #[must_use]
    #[inline]
    pub const fn giver(self, receiver: Seat) -> Seat {
        match self {
            Self::Left => receiver.right(),
            Self::Right => receiver.left(),
            Self::Across => receiver.across(),
            Self::Hold => receiver,
        }
    }
}

impl fmt::Display for PassDirection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Left => "left",
            Self::Right => "right",
            Self::Across => "across",
            Self::Hold => "hold",
        })
    }
}

/// Error returned when parsing a [`PassDirection`] fails
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
#[error("Invalid pass direction: expected left, right, across, or hold")]
pub struct ParsePassDirectionError;

impl FromStr for PassDirection {
    type Err = ParsePassDirectionError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_ascii_lowercase().as_str() {
            "left" => Ok(Self::Left),
            "right" => Ok(Self::Right),
            "across" => Ok(Self::Across),
            "hold" => Ok(Self::Hold),
            _ => Err(ParsePassDirectionError),
        }
    }
}

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

    #[test]
    fn seat_geometry() {
        for seat in Seat::ALL {
            assert_eq!(seat.left().right(), seat);
            assert_eq!(seat.right().left(), seat);
            assert_eq!(seat.across().across(), seat);
            assert_eq!(seat.left().left(), seat.across());
            assert_ne!(seat.left(), seat);
        }
        assert_eq!(Seat::North.left(), Seat::East);
        assert_eq!(Seat::ALL[Seat::West as usize], Seat::West);
    }

    #[test]
    fn pass_direction_cycle() {
        assert_eq!(PassDirection::from_deal_index(0), PassDirection::Left);
        assert_eq!(PassDirection::from_deal_index(5), PassDirection::Right);
        assert_eq!(
            PassDirection::from_deal_index(u32::MAX),
            PassDirection::Hold
        );

        for direction in PassDirection::CYCLE {
            for seat in Seat::ALL {
                assert_eq!(direction.giver(direction.receiver(seat)), seat);
                assert_eq!(direction.receiver(direction.giver(seat)), seat);
            }
        }
        assert_eq!(PassDirection::Left.receiver(Seat::North), Seat::East);
        assert_eq!(PassDirection::Hold.receiver(Seat::North), Seat::North);
    }

    #[test]
    fn parsing() {
        for seat in Seat::ALL {
            assert_eq!(seat.to_string().parse(), Ok(seat));
            assert_eq!(seat.letter().to_string().parse(), Ok(seat));
        }
        assert_eq!("north".parse(), Ok(Seat::North));
        assert_eq!("NE".parse::<Seat>(), Err(ParseSeatError));

        for direction in PassDirection::CYCLE {
            assert_eq!(direction.to_string().parse(), Ok(direction));
        }
        assert_eq!("ACROSS".parse(), Ok(PassDirection::Across));
        assert_eq!("up".parse::<PassDirection>(), Err(ParsePassDirectionError));
    }
}