Skip to main content

native_solver/
card.rs

1//! Cards and card sets. A [`Card`] is one of the 52 cards of a standard
2//! deck; a [`CardSet`] is a set of cards packed into a bitmask for fast
3//! membership and removal checks.
4
5use std::fmt;
6use std::str::FromStr;
7
8/// Rank characters, low to high: 2..=9, T, J, Q, K, A.
9pub const RANKS: &str = "23456789TJQKA";
10/// Suit characters: clubs, diamonds, hearts, spades.
11pub const SUITS: &str = "cdhs";
12
13/// One of the 52 cards, stored as its index `rank * 4 + suit`.
14///
15/// Every [`Card`] value is valid: it can only be built from an index in
16/// `0..52`, a rank and suit in range, or parsed from text.
17///
18/// ```
19/// use native_solver::Card;
20///
21/// let card: Card = "As".parse()?;
22/// assert_eq!((card.rank(), card.suit()), (12, 3));
23/// assert_eq!(card.to_string(), "As");
24/// assert_eq!(Card::new(12, 3), Some(card));
25/// # Ok::<(), native_solver::CardParseError>(())
26/// ```
27#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
28pub struct Card(pub(crate) u8);
29
30impl Card {
31    /// The card with the given rank and suit, or `None` if either is out of range.
32    ///
33    /// `rank` is in `0..13` (0 = "2", 12 = "A") and `suit` in `0..4` (clubs,
34    /// diamonds, hearts, spades).
35    pub const fn new(rank: u8, suit: u8) -> Option<Card> {
36        if rank < 13 && suit < 4 {
37            Some(Card(rank * 4 + suit))
38        } else {
39            None
40        }
41    }
42
43    /// The card with index `index` in `0..52` (`rank * 4 + suit`), or `None`
44    /// if the index is out of range.
45    pub const fn from_index(index: u8) -> Option<Card> {
46        if index < 52 {
47            Some(Card(index))
48        } else {
49            None
50        }
51    }
52
53    /// The index `rank * 4 + suit`, in `0..52`.
54    pub const fn index(self) -> u8 {
55        self.0
56    }
57
58    /// Rank index in `0..13` (0 = "2", 12 = "A").
59    pub const fn rank(self) -> u8 {
60        self.0 / 4
61    }
62
63    /// Suit index in `0..4`: clubs, diamonds, hearts, spades.
64    pub const fn suit(self) -> u8 {
65        self.0 % 4
66    }
67
68    /// All 52 cards in index order.
69    pub fn all() -> impl Iterator<Item = Card> {
70        (0..52).map(Card)
71    }
72}
73
74impl fmt::Display for Card {
75    /// Two characters: rank then suit, e.g. `As`, `Td`, `2c`.
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        let r = RANKS.as_bytes()[self.rank() as usize] as char;
78        let s = SUITS.as_bytes()[self.suit() as usize] as char;
79        write!(f, "{r}{s}")
80    }
81}
82
83impl fmt::Debug for Card {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        write!(f, "Card({self})")
86    }
87}
88
89/// Why a card string could not be parsed; each variant carries the input.
90#[derive(Debug, Clone, PartialEq, Eq)]
91#[non_exhaustive]
92pub enum CardParseError {
93    /// Not exactly two characters.
94    Length(String),
95    /// The first character is not one of `23456789TJQKA`.
96    Rank(String),
97    /// The second character is not one of `cdhs`.
98    Suit(String),
99}
100
101impl fmt::Display for CardParseError {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self {
104            Self::Length(s) => write!(f, "invalid card string: {s:?}"),
105            Self::Rank(s) => write!(f, "invalid rank in card {s:?}"),
106            Self::Suit(s) => write!(f, "invalid suit in card {s:?}"),
107        }
108    }
109}
110
111impl std::error::Error for CardParseError {}
112
113impl FromStr for Card {
114    type Err = CardParseError;
115
116    /// Parses the two-character notation, e.g. `"As"`, `"Td"`, `"2c"`. Rank
117    /// and suit are case-insensitive.
118    ///
119    /// # Errors
120    /// Returns a [`CardParseError`] naming the part that is wrong: the
121    /// length, the rank, or the suit.
122    fn from_str(s: &str) -> Result<Card, CardParseError> {
123        let chars: Vec<char> = s.chars().collect();
124        if chars.len() != 2 {
125            return Err(CardParseError::Length(s.into()));
126        }
127        let rank = RANKS
128            .find(chars[0].to_ascii_uppercase())
129            .ok_or_else(|| CardParseError::Rank(s.into()))? as u8;
130        let suit = SUITS
131            .find(chars[1].to_ascii_lowercase())
132            .ok_or_else(|| CardParseError::Suit(s.into()))? as u8;
133        Ok(Card(rank * 4 + suit))
134    }
135}
136
137/// A set of cards, packed as a 52-bit mask (bit `card.index()` per card).
138///
139/// ```
140/// use native_solver::{Card, CardSet};
141///
142/// let board: Vec<Card> = ["Ks", "Th", "7s"].iter().map(|s| s.parse()).collect::<Result<_, _>>()?;
143/// let dead = CardSet::from_cards(&board);
144/// assert!(dead.contains("Ks".parse()?));
145/// assert_eq!(dead.len(), 3);
146/// # Ok::<(), native_solver::CardParseError>(())
147/// ```
148#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
149pub struct CardSet(pub(crate) u64);
150
151impl CardSet {
152    /// The empty set.
153    pub const EMPTY: CardSet = CardSet(0);
154
155    /// The set holding exactly `cards`.
156    pub fn from_cards(cards: &[Card]) -> CardSet {
157        cards.iter().copied().collect()
158    }
159
160    /// Whether `card` is in the set.
161    pub const fn contains(self, card: Card) -> bool {
162        self.0 & (1 << card.0) != 0
163    }
164
165    /// Adds `card`; returns whether it was newly added.
166    pub fn insert(&mut self, card: Card) -> bool {
167        let added = !self.contains(card);
168        self.0 |= 1 << card.0;
169        added
170    }
171
172    /// Whether the two sets share no card.
173    pub const fn is_disjoint(self, other: CardSet) -> bool {
174        self.0 & other.0 == 0
175    }
176
177    /// The cards in either set.
178    pub const fn union(self, other: CardSet) -> CardSet {
179        CardSet(self.0 | other.0)
180    }
181
182    /// The number of cards in the set.
183    pub const fn len(self) -> usize {
184        self.0.count_ones() as usize
185    }
186
187    /// Whether the set is empty.
188    pub const fn is_empty(self) -> bool {
189        self.0 == 0
190    }
191
192    /// The cards in the set, in index order.
193    pub fn iter(self) -> impl Iterator<Item = Card> {
194        Card::all().filter(move |&card| self.contains(card))
195    }
196}
197
198impl From<Card> for CardSet {
199    fn from(card: Card) -> CardSet {
200        CardSet(1 << card.0)
201    }
202}
203
204impl FromIterator<Card> for CardSet {
205    fn from_iter<I: IntoIterator<Item = Card>>(cards: I) -> CardSet {
206        let mut set = CardSet::EMPTY;
207        set.extend(cards);
208        set
209    }
210}
211
212impl Extend<Card> for CardSet {
213    fn extend<I: IntoIterator<Item = Card>>(&mut self, cards: I) {
214        for card in cards {
215            self.insert(card);
216        }
217    }
218}
219
220impl std::ops::BitOr for CardSet {
221    type Output = CardSet;
222
223    fn bitor(self, other: CardSet) -> CardSet {
224        self.union(other)
225    }
226}
227
228/// Raw `u64` mask helpers for the solver's hot paths, which keep card sets
229/// as plain bitmasks.
230pub(crate) fn bit(card: Card) -> u64 {
231    1 << card.0
232}
233
234/// The raw mask of `cards`.
235pub(crate) fn mask_of(cards: &[Card]) -> u64 {
236    cards.iter().fold(0, |mask, &card| mask | bit(card))
237}
238
239/// Whether the raw `mask` contains `card`.
240pub(crate) fn mask_has(mask: u64, card: Card) -> bool {
241    mask & bit(card) != 0
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    fn card(s: &str) -> Card {
249        s.parse().unwrap()
250    }
251
252    #[test]
253    fn parse_errors_say_which_part_is_wrong() {
254        assert_eq!("A".parse::<Card>(), Err(CardParseError::Length("A".into())));
255        assert_eq!("Xs".parse::<Card>(), Err(CardParseError::Rank("Xs".into())));
256        assert_eq!("Ax".parse::<Card>(), Err(CardParseError::Suit("Ax".into())));
257        assert_eq!(
258            CardParseError::Rank("Xs".into()).to_string(),
259            "invalid rank in card \"Xs\""
260        );
261        assert_eq!("aS".parse::<Card>(), "As".parse::<Card>());
262    }
263
264    #[test]
265    fn parses_and_formats_round_trip() {
266        for s in ["As", "Kh", "Td", "2c", "9s"] {
267            assert_eq!(card(s).to_string(), s);
268        }
269        assert_eq!(format!("{:?}", card("Td")), "Card(Td)");
270    }
271
272    #[test]
273    fn rank_and_suit_indices() {
274        assert_eq!((card("As").rank(), card("As").suit()), (12, 3));
275        assert_eq!((card("2c").rank(), card("2c").suit()), (0, 0));
276        assert_eq!(card("As").index(), 51);
277    }
278
279    #[test]
280    fn constructors_reject_out_of_range_values() {
281        assert_eq!(Card::new(12, 3), Some(card("As")));
282        assert_eq!(Card::new(13, 0), None);
283        assert_eq!(Card::new(0, 4), None);
284        assert_eq!(Card::from_index(51), Some(card("As")));
285        assert_eq!(Card::from_index(52), None);
286        assert_eq!(Card::all().count(), 52);
287        assert!(Card::all().all(|c| Card::from_index(c.index()) == Some(c)));
288    }
289
290    #[test]
291    fn rejects_invalid_cards() {
292        assert!("Xs".parse::<Card>().is_err());
293        assert!("A".parse::<Card>().is_err());
294        assert!("Azz".parse::<Card>().is_err());
295    }
296
297    #[test]
298    fn card_set_operations() {
299        let mut set = CardSet::from_cards(&[card("As"), card("Kh")]);
300        assert!(set.contains(card("As")) && set.contains(card("Kh")));
301        assert!(!set.contains(card("Td")));
302        assert_eq!(set.len(), 2);
303        assert!(set.insert(card("Td")));
304        assert!(!set.insert(card("Td")));
305        assert_eq!(
306            set.iter().collect::<Vec<_>>(),
307            [card("Td"), card("Kh"), card("As")]
308        );
309        assert!(set.is_disjoint(CardSet::from(card("2c"))));
310        assert!(!set.is_disjoint(CardSet::from(card("As")) | CardSet::from(card("2c"))));
311        assert!(CardSet::EMPTY.is_empty());
312    }
313}