playin-cards 0.2.0

♠ Library for French-suited playing cards
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]
#![doc(html_logo_url = "https://codeberg.org/pezcore/playin-cards/raw/branch/main/icon.svg")]
//! # Usage
//! The main interface is the [`Card`] which represents a single playing card
//! which may be one of the cards in a standard 52-card deck of playing cards,
//! or a Joker which may be either black or red. A [`Card`] instance can be
//! easily be parsed from a 2-`char` `str` with one of `A23456789TJQK` as the
//! first char and one of `SsCcDdHh♥♣♠♦` as the second char.
//!
//! `Card` can also be formatted as a 2-`char` Unicode string such `A♣`, `5♥`,
//! `J♠` with the [`Display`] trait or as a single-`char` Unicode card char such
//! as `🃑`, `🂵`, `🂫` with the [`UpperHex`] trait.

#[allow(unused_imports)]
use std::fmt::{Display, UpperHex};

use itertools::Itertools;
use strum::EnumIter;
use strum::IntoEnumIterator;

/// number of cards in a standard 52-card deck of French-suited playing cards
pub const CARDS_PER_DECK: u8 = 52;

/// A French-suited playing card
///
/// The card is represented by either `Joker`, which has only a `Color` or a
/// `Regular` which represents a normal card from a standard 52-card deck,
/// comprised of a [`Rank`] and a [`Suit`]
///
/// ## Parsing
///
/// `Card` can easily be parsed from a 2-`char` `str` representation where the
/// first char represents the [`Rank`] as one of `A23456789TJQK`) and the
/// second char represents the [`Suit`] as one of `SsCcDdHh♠♥♣♦`
/// ```
/// use playin_cards::{Card::*, Rank::*, Suit::*};
///
/// // Parse a Card instance from a 2-char ASCII string:
/// assert_eq!("AS".parse(), Ok(Regular{rank: Ace, suit: Spades}));
/// assert_eq!("3D".parse(), Ok(Regular{rank: Three, suit: Diamonds}));
/// assert_eq!("JC".parse(), Ok(Regular{rank: Jack, suit: Clubs}));
/// assert_eq!("9H".parse(), Ok(Regular{rank: Nine, suit: Hearts}));
///
/// // A Card can also be parsed from Unicode representation:
/// assert_eq!("A♣".parse(), Ok(Regular{rank: Ace, suit: Clubs}));
/// assert_eq!("5♠".parse(), Ok(Regular{rank: Five, suit: Spades}));
/// assert_eq!("8♥".parse(), Ok(Regular{rank: Eight, suit: Hearts}));
/// ```
///
/// ## Formatting
/// `Card` can be formatted as a 2-`char` Unicode `str` using [`Display`] or as
/// a single-`char` Unicode `str` using [`UpperHex`]
///
/// ```
/// use playin_cards::{Card::*, Rank::*, Suit::*};
///
/// // `Display` uses ASCII for rank and Unicode for Suit:
/// assert_eq!(format!("{}", Regular{rank: Ace, suit: Clubs}),     "A♣");
/// assert_eq!(format!("{}", Regular{rank: King, suit: Diamonds}), "K♦");
/// assert_eq!(format!("{}", Regular{rank: Ace, suit: Clubs}),     "A♣");
///
/// // `UpperHex` uses Unicode card chars
/// assert_eq!(format!("{:X}", Regular{rank: Ace, suit: Clubs}), "🃑");
/// ```
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Card {
    /// Regular playing card from a standard 52-card deck.
    Regular { rank: Rank, suit: Suit },
    /// A Joker
    Joker(Color),
}

/// Ranks of a standard French-suited playing card
///
/// ## Numeric Values and Ordering
///
/// Numeric values of `Rank` instance are only exposed through the variant's discriminants, which
/// are ordered in "Aces high" order (23456789TJQKA) and offset to match the name of the rank:
/// ```
/// use playin_cards::Rank;
/// assert_eq!(Rank::Two as u8, 2);
/// assert_eq!(Rank::Six as u8, 6);
/// assert_eq!(Rank::King as u8, 13);
/// assert_eq!(Rank::Ace as u8, 14);
/// ```
///
/// [`Rank`] also implements [`Ord`] in Aces high order. If any other ordering is needed, explicit
/// comparison logic must be implemented. For example, the following listing implements a custom
/// ordering where odd-numbered ranks are always considered less than even-numbered ranks but
/// otherwise follow Aces-high ordering.
///
/// ```rust
/// use std::cmp::Ordering;
/// use playin_cards::Rank::*;
///
/// let mut ranks = [Ace, Two, Three, Four, Five, Six, Seven];
///
/// // Sort an array of Rank using a custom ordering
/// ranks.sort_by(|&r1, &r2| match (r1 as u8 & 1 == 0, r2 as u8 & 1 == 0) {
///     (true, false) => Ordering::Greater,
///     (false, true) => Ordering::Less,
///     _ => r1.cmp(&r2),
/// });
///
/// assert_eq!(ranks, [Three, Five, Seven, Two, Four, Six, Ace]);
/// ```
///
///
/// ## Conversions
///
/// `Rank` is bidirectionally convertible with `char` via `From` and `TryFrom`. The character set
/// used to convert to and from `Rank` is given by [`Rank::ALLOWED_CHARS`]
///
/// ```
/// use playin_cards::{Rank, ParseError};
///
/// // get the char corresponding to a `Rank` instance
/// assert_eq!(char::from(Rank::King), 'K');
/// assert_eq!(char::from(Rank::Five), '5');
/// assert_eq!(char::from(Rank::Jack), 'J');
///
/// // parse a single `char` to a `Rank`
/// assert_eq!(Rank::try_from('Q'), Ok(Rank::Queen));
/// assert_eq!(Rank::try_from('4'), Ok(Rank::Four));
/// assert_eq!(Rank::try_from('T'), Ok(Rank::Ten));
/// assert_eq!(Rank::try_from('A'), Ok(Rank::Ace));
///
/// // Parsing fails if an invalid char is used
/// assert_eq!(Rank::try_from('Y'), Err(ParseError::InvalidChar));
/// ```
///
/// ## Iteration
/// Thanks to [`strum`], the variants of [`Rank`] can be iterated over:
/// ```
/// use playin_cards::Rank;
/// use strum::IntoEnumIterator;
///
/// let mut rankiter = Rank::iter();
/// assert_eq!(rankiter.next(), Some(Rank::Two));
/// assert_eq!(rankiter.next(), Some(Rank::Three));
/// assert_eq!(rankiter.next(), Some(Rank::Four));
/// assert_eq!(rankiter.next(), Some(Rank::Five));
/// // You get the point...
///
/// ```
#[repr(u8)]
#[derive(EnumIter, Debug, Ord, PartialOrd, PartialEq, Clone, Copy, Eq, Hash)]
pub enum Rank {
    Two = 2,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King,
    Ace,
}

/// Suits of a standard French-suited playing card
///
/// ## Conversions
/// `Suit` is bidirectionally convertible with `char`:
/// ```
/// use playin_cards::Suit;
/// // Converting Suit -> char uses Unicode
/// assert_eq!(char::from(Suit::Spades),   '♠');
/// assert_eq!(char::from(Suit::Hearts),   '♥');
/// assert_eq!(char::from(Suit::Diamonds), '♦');
/// assert_eq!(char::from(Suit::Clubs),    '♣');
/// // Converting char -> Suit allows uppercase ASCII, lowercase ASCII, or
/// // Unicode
/// assert_eq!(Suit::try_from('S'), Ok(Suit::Spades)); // Uppercase
/// assert_eq!(Suit::try_from('s'), Ok(Suit::Spades)); // Lowercase
/// assert_eq!(Suit::try_from('♠'), Ok(Suit::Spades)); // Unicode
/// ```
/// ## Iteration
/// Thanks to [`strum`], the variants of [`Suit`] can be iterated over:
/// ```
/// use playin_cards::Suit;
/// use strum::IntoEnumIterator;
///
/// let mut suititer = Suit::iter();
/// assert_eq!(suititer.next(), Some(Suit::Hearts));
/// assert_eq!(suititer.next(), Some(Suit::Diamonds));
/// assert_eq!(suititer.next(), Some(Suit::Spades));
/// assert_eq!(suititer.next(), Some(Suit::Clubs));
///
/// ```
#[derive(EnumIter, Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Suit {
    Hearts,
    Diamonds,
    Spades,
    Clubs,
}

/// Color of a [`Suit`] or [`Card`]. Either Red or Black
#[derive(Debug, PartialEq, Clone, Copy, Eq, Hash)]
pub enum Color {
    Red,
    Black,
}

mod format;
mod parse;

pub use parse::ParseError;

impl Suit {
    /// Set of allowed chars which can be converted to [`Suit`] with
    /// [`TryFrom<char>`]
    pub const ALLOWED_CHARS: &'static str = "SsCcHhDd♠♣♥♦";

    /// Return the color of the `Suit`
    pub fn color(self) -> Color {
        match self {
            Suit::Hearts | Suit::Diamonds => Color::Red,
            Suit::Spades | Suit::Clubs => Color::Black,
        }
    }
}

impl Card {
    /// Return the color of the `Card` which is just the color of its `Suit`
    pub fn color(self) -> Color {
        match self {
            Self::Regular { rank: _, suit } => suit.color(),
            Self::Joker(color) => color,
        }
    }

    /// Return `true` if this card is a Joker, otherwise return `false`
    pub fn is_joker(self) -> bool {
        match self {
            Self::Regular { rank: _, suit: _ } => false,
            Self::Joker(_) => true,
        }
    }
}

impl Rank {
    /// Set of allowed chars which can be converted to [`Rank`] with
    /// [`TryFrom<char>`]
    pub const ALLOWED_CHARS: &'static str = "A23456789TJQK";

    /// Return true if and only if `self` is of adjacent rank to `other`. Two and Ace are
    /// considered adjacent.
    pub fn is_adjacent(self, other: Self) -> bool {
        matches!((self as u8).abs_diff(other as u8), 1 | 12)
    }
}

impl From<(Rank, Suit)> for Card {
    fn from((rank, suit): (Rank, Suit)) -> Self {
        Self::Regular { rank, suit }
    }
}

/// Generate an (unshuffled) [shoe](https://en.wikipedia.org/wiki/Shoe_(cards))
///
/// Return an unshuffled shoe containing `n_decks` decks. If `with_jokers`
/// `true`, Each deck has 54 cards, all the cards in a standard 52-card deck,
/// and 2 Jokers, one Black and one Red. If `with_jokers` is `false`, each deck
/// only contains the 52 cards in a standard deck.
pub fn gen_shoe(n_decks: u8, with_jokers: bool) -> Vec<Card> {
    let extra_cards: u8 = if with_jokers { 2 } else { 0 };
    // total number of cards in the shoe
    let total_cards = n_decks as usize * (CARDS_PER_DECK + extra_cards) as usize;

    // preallocate memory for the shoe
    let mut output = Vec::with_capacity(total_cards);
    for _ in 0..n_decks {
        let deck_iter = Rank::iter().cartesian_product(Suit::iter()).map(Card::from);
        output.extend(deck_iter);
        if with_jokers {
            output.extend([Card::Joker(Color::Red), Card::Joker(Color::Black)]);
        }
    }
    output
}

#[cfg(test)]
mod test {
    use super::*;
    use itertools::Itertools;
    use std::collections::HashMap;
    use strum::IntoEnumIterator;

    #[rustfmt::skip]
    pub const FULL_DECK_CARDS: [Card; 52] = [
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Ace },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Two },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Three },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Four },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Five },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Six },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Seven },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Eight },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Nine },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Ten },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Jack },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::Queen },
        Card::Regular{ suit: Suit::Hearts, rank: Rank::King },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Ace },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Two },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Three },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Four },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Five },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Six },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Seven },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Eight },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Nine },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Ten },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Jack },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::Queen },
        Card::Regular{ suit: Suit::Diamonds, rank: Rank::King },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Ace },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Two },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Three },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Four },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Five },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Six },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Seven },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Eight },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Nine },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Ten },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Jack },
        Card::Regular{ suit: Suit::Spades, rank: Rank::Queen },
        Card::Regular{ suit: Suit::Spades, rank: Rank::King },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Ace },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Two },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Three },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Four },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Five },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Six },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Seven },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Eight },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Nine },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Ten },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Jack },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::Queen },
        Card::Regular{ suit: Suit::Clubs, rank: Rank::King },
    ];

    #[test]
    /// Tests that all Ranks cast to their respective values of u8
    fn rank_cast_u8() {
        assert_eq!(Rank::Ace as u8, 14, "Ace as u8 was not 14");
        assert_eq!(Rank::Two as u8, 2, "Two as u8 was not 2");
        assert_eq!(Rank::Three as u8, 3, "Three as u8 was not 3");
        assert_eq!(Rank::Four as u8, 4, "Four as u8 was not 4");
        assert_eq!(Rank::Five as u8, 5, "Five as u8 was not 5");
        assert_eq!(Rank::Six as u8, 6, "Six as u8 was not 6");
        assert_eq!(Rank::Seven as u8, 7, "Seven as u8 was not 7");
        assert_eq!(Rank::Eight as u8, 8, "Eight as u8 was not 8");
        assert_eq!(Rank::Nine as u8, 9, "Nine as u8 was not 9");
        assert_eq!(Rank::Ten as u8, 10, "Ten as u8 was not 10");
        assert_eq!(Rank::Jack as u8, 11, "Jack as u8 was not 11");
        assert_eq!(Rank::Queen as u8, 12, "Queen as u8 was not 12");
        assert_eq!(Rank::King as u8, 13, "King as u8 was not 13");
    }
    #[test]
    fn suit_colors() {
        assert_eq!(Suit::Spades.color(), Color::Black);
        assert_eq!(Suit::Hearts.color(), Color::Red);
        assert_eq!(Suit::Clubs.color(), Color::Black);
        assert_eq!(Suit::Diamonds.color(), Color::Red);
    }
    #[test]
    fn card_colors() {
        for card in FULL_DECK_CARDS[..26].iter() {
            assert_eq!(
                card.color(),
                Color::Red,
                "{} incorrectly identified as Red",
                card
            );
        }
        for card in FULL_DECK_CARDS[26..].iter() {
            assert_eq!(
                card.color(),
                Color::Black,
                "{} incorrectly identified as Black",
                card
            );
        }
        assert_eq!(Card::Joker(Color::Black).color(), Color::Black);
        assert_eq!(Card::Joker(Color::Red).color(), Color::Red);
    }
    #[test]
    fn is_joker() {
        for card in FULL_DECK_CARDS.iter() {
            assert!(!card.is_joker(), "{} incorrectly identified as joker", card)
        }
        assert!(Card::Joker(Color::Black).is_joker());
        assert!(Card::Joker(Color::Red).is_joker());
    }
    fn count(shoe: &[Card]) -> HashMap<Card, u16> {
        let mut map = HashMap::new();
        for &card in shoe {
            *map.entry(card).or_insert(0) += 1;
        }
        map
    }
    fn test_shoe(n: u8, w_jokers: bool) {
        let shoe = gen_shoe(n, w_jokers);
        let n_jokers = if w_jokers { 2 * n } else { 0 } as usize;
        assert_eq!(shoe.len(), CARDS_PER_DECK as usize * n as usize + n_jokers);
        let map = count(&shoe);
        for (rank, suit) in Rank::iter().cartesian_product(Suit::iter()) {
            assert_eq!(map.get(&Card::Regular { rank, suit }), Some(&(n as u16)));
        }
        if w_jokers {
            assert_eq!(map.get(&Card::Joker(Color::Black)), Some(&(n as u16)));
            assert_eq!(map.get(&Card::Joker(Color::Red)), Some(&(n as u16)));
        }
    }
    /// Assert that there is exactly 1 of each card in the results of `gen_shoe`.
    #[test]
    fn gen_shoe_no_jokers_single() {
        test_shoe(1, false);
    }
    /// Assert that there is exactly N of each card in the results of `gen_shoe`.
    #[test]
    fn gen_shoe_no_jokers_multi() {
        test_shoe(6, false);
    }
    #[test]
    fn gen_shoe_w_jokers() {
        test_shoe(1, true);
    }
    #[test]
    fn gen_shoe_w_jokers_multi() {
        test_shoe(4, true);
    }

    #[rustfmt::skip]
    #[test]
    fn is_adjacent() {
        for (r1, r2) in Rank::iter().cartesian_product(Rank::iter()) {
            match (r1, r2) {
                (Rank::Ace, Rank::Two) | (Rank::Two, Rank::Ace) => assert!(r1.is_adjacent(r2)),
                (Rank::Two, Rank::Three) | (Rank::Three, Rank::Two) => assert!(r1.is_adjacent(r2)),
                (Rank::Three, Rank::Four) | (Rank::Four, Rank::Three) => assert!(r1.is_adjacent(r2)),
                (Rank::Four, Rank::Five) | (Rank::Five, Rank::Four) => assert!(r1.is_adjacent(r2)),
                (Rank::Five, Rank::Six) | (Rank::Six, Rank::Five) => assert!(r1.is_adjacent(r2)),
                (Rank::Six, Rank::Seven) | (Rank::Seven, Rank::Six) => assert!(r1.is_adjacent(r2)),
                (Rank::Seven, Rank::Eight) | (Rank::Eight, Rank::Seven) => assert!(r1.is_adjacent(r2)),
                (Rank::Eight, Rank::Nine) | (Rank::Nine, Rank::Eight) => assert!(r1.is_adjacent(r2)),
                (Rank::Nine, Rank::Ten) | (Rank::Ten, Rank::Nine) => assert!(r1.is_adjacent(r2)),
                (Rank::Ten, Rank::Jack) | (Rank::Jack, Rank::Ten) => assert!(r1.is_adjacent(r2)),
                (Rank::Jack, Rank::Queen) | (Rank::Queen, Rank::Jack) => assert!(r1.is_adjacent(r2)),
                (Rank::Queen, Rank::King) | (Rank::King, Rank::Queen) => assert!(r1.is_adjacent(r2)),
                (Rank::King, Rank::Ace) | (Rank::Ace, Rank::King) => assert!(r1.is_adjacent(r2)),
                _ => assert!(!r1.is_adjacent(r2)),
            }
        }
    }
}