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
#[cfg(test)]
mod test;

use crate::contract::Strain;
use core::fmt;
use core::ops::{BitAnd, BitOr, BitXor, Index, IndexMut, Not, Sub};
use rand::prelude::SliceRandom as _;

/// A suit of playing cards
///
/// Suits are convertible to [`Strain`]s since suits form a subset of strains.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum Suit {
    /// ♣, convertible to [`Strain::Clubs`]
    Clubs,
    /// ♦, convertible to [`Strain::Diamonds`]
    Diamonds,
    /// ♥, convertible to [`Strain::Hearts`]
    Hearts,
    /// ♠, convertible to [`Strain::Spades`]
    Spades,
}

impl Suit {
    /// Suits in ascending order, the order in this crate
    pub const ASCENDING: [Self; 4] = [Self::Clubs, Self::Diamonds, Self::Hearts, Self::Spades];

    /// Suits in descending order, the order in [`dds_bridge_sys`]
    pub const DESCENDING: [Self; 4] = [Self::Spades, Self::Hearts, Self::Diamonds, Self::Clubs];
}

impl From<Suit> for Strain {
    fn from(suit: Suit) -> Self {
        match suit {
            Suit::Clubs => Self::Clubs,
            Suit::Diamonds => Self::Diamonds,
            Suit::Hearts => Self::Hearts,
            Suit::Spades => Self::Spades,
        }
    }
}

/// Position at the table
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Seat {
    /// Dealer of Board 1, partner of [`Seat::South`]
    North,
    /// Dealer of Board 2, partner of [`Seat::West`]
    East,
    /// Dealer of Board 3, partner of [`Seat::North`]
    South,
    /// Dealer of Board 4, partner of [`Seat::East`]
    West,
}

/// A playing card
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Card {
    /// The suit of the card
    pub suit: Suit,

    /// The rank of the card
    ///
    /// The rank is a number from 2 to 14.  J, Q, K, A are denoted as 11, 12,
    /// 13, 14 respectively.
    pub rank: u8,
}

impl Card {
    /// Create a card from suit and rank
    #[must_use]
    pub const fn new(suit: Suit, rank: u8) -> Self {
        Self { suit, rank }
    }
}

/// A bitset whose size is known at compile time
pub trait SmallSet<T>: Copy + Eq + BitAnd + BitOr + BitXor + Not + Sub {
    /// The empty set
    const EMPTY: Self;

    /// The set containing all possible values
    const ALL: Self;

    /// The number of elements in the set
    #[must_use]
    fn len(self) -> usize;

    /// Whether the set is empty
    #[must_use]
    fn is_empty(self) -> bool {
        self == Self::EMPTY
    }

    /// Whether the set contains a value
    fn contains(self, value: T) -> bool;

    /// Insert a value into the set
    fn insert(&mut self, value: T) -> bool;

    /// Remove a value from the set
    fn remove(&mut self, value: T) -> bool;

    /// Toggle a value in the set
    fn toggle(&mut self, value: T) -> bool;
}

/// A set of cards of the same suit
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Holding(u16);

impl SmallSet<u8> for Holding {
    const EMPTY: Self = Self(0);
    const ALL: Self = Self(0x7FFC);

    fn len(self) -> usize {
        self.0.count_ones() as usize
    }

    fn contains(self, rank: u8) -> bool {
        self.0 & 1 << rank != 0
    }

    fn insert(&mut self, rank: u8) -> bool {
        let insertion = 1 << rank & Self::ALL.0;
        let inserted = insertion & !self.0 != 0;
        self.0 |= insertion;
        inserted
    }

    fn remove(&mut self, rank: u8) -> bool {
        let removed = self.contains(rank);
        self.0 &= !(1 << rank);
        removed
    }

    fn toggle(&mut self, rank: u8) -> bool {
        self.0 ^= 1 << rank & Self::ALL.0;
        self.contains(rank)
    }
}

impl Holding {
    /// As a bitset of ranks
    #[must_use]
    pub const fn to_bits(self) -> u16 {
        self.0
    }

    /// Create a holding from a bitset of ranks
    #[must_use]
    pub const fn from_bits(bits: u16) -> Self {
        Self(bits & Self::ALL.0)
    }
}

impl BitAnd for Holding {
    type Output = Self;

    fn bitand(self, rhs: Self) -> Self {
        Self(self.0 & rhs.0)
    }
}

impl BitOr for Holding {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
    }
}

impl BitXor for Holding {
    type Output = Self;

    fn bitxor(self, rhs: Self) -> Self {
        Self(self.0 ^ rhs.0)
    }
}

impl Not for Holding {
    type Output = Self;

    fn not(self) -> Self {
        Self::ALL ^ self
    }
}

impl Sub for Holding {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self {
        self & !rhs
    }
}

impl fmt::Display for Holding {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for rank in (2..15).rev() {
            if self.contains(rank) {
                use fmt::Write;
                f.write_char(b"23456789TJQKA"[rank as usize - 2] as char)?;
            }
        }
        Ok(())
    }
}

/// A hand of playing cards
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Hand([Holding; 4]);

impl Index<Suit> for Hand {
    type Output = Holding;

    fn index(&self, suit: Suit) -> &Holding {
        &self.0[suit as usize]
    }
}

impl IndexMut<Suit> for Hand {
    fn index_mut(&mut self, suit: Suit) -> &mut Holding {
        &mut self.0[suit as usize]
    }
}

impl Hand {
    /// As a bitset of cards
    #[must_use]
    pub const fn to_bits(self) -> u64 {
        unsafe { core::mem::transmute(self.0) }
    }

    /// Create a hand from a bitset of cards
    ///
    /// This function removes invalid cards.
    #[must_use]
    pub const fn from_bits(bits: u64) -> Self {
        Self(unsafe { core::mem::transmute(bits & Self::ALL.to_bits()) })
    }

    /// Create a hand from a bitset of cards without checking
    ///
    /// # Safety
    /// The bitset must not contain invalid cards.
    #[must_use]
    pub const unsafe fn from_bits_unchecked(bits: u64) -> Self {
        Self(core::mem::transmute(bits))
    }
}

impl SmallSet<Card> for Hand {
    const EMPTY: Self = Self([Holding::EMPTY; 4]);
    const ALL: Self = Self([Holding::ALL; 4]);

    fn len(self) -> usize {
        self.to_bits().count_ones() as usize
    }

    fn contains(self, card: Card) -> bool {
        self[card.suit].contains(card.rank)
    }

    fn insert(&mut self, card: Card) -> bool {
        self[card.suit].insert(card.rank)
    }

    fn remove(&mut self, card: Card) -> bool {
        self[card.suit].remove(card.rank)
    }

    fn toggle(&mut self, card: Card) -> bool {
        self[card.suit].toggle(card.rank)
    }
}

impl fmt::Display for Hand {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}.{}.{}.{}",
            self[Suit::Spades],
            self[Suit::Hearts],
            self[Suit::Diamonds],
            self[Suit::Clubs]
        )
    }
}

impl BitAnd for Hand {
    type Output = Self;

    fn bitand(self, rhs: Self) -> Self {
        // SAFETY: safe when both operands are valid
        unsafe { Self::from_bits_unchecked(self.to_bits() & rhs.to_bits()) }
    }
}

impl BitOr for Hand {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self {
        // SAFETY: safe when both operands are valid
        unsafe { Self::from_bits_unchecked(self.to_bits() | rhs.to_bits()) }
    }
}

impl BitXor for Hand {
    type Output = Self;

    fn bitxor(self, rhs: Self) -> Self {
        // SAFETY: safe when both operands are valid
        unsafe { Self::from_bits_unchecked(self.to_bits() ^ rhs.to_bits()) }
    }
}

impl Not for Hand {
    type Output = Self;

    fn not(self) -> Self {
        Self::ALL ^ self
    }
}

impl Sub for Hand {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self {
        self & !rhs
    }
}

/// A deal of four hands
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Deal([Hand; 4]);

impl Index<Seat> for Deal {
    type Output = Hand;

    fn index(&self, seat: Seat) -> &Hand {
        &self.0[seat as usize]
    }
}

impl IndexMut<Seat> for Deal {
    fn index_mut(&mut self, seat: Seat) -> &mut Hand {
        &mut self.0[seat as usize]
    }
}

impl fmt::Display for Deal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "N:{} {} {} {}",
            self[Seat::North],
            self[Seat::East],
            self[Seat::South],
            self[Seat::West]
        )
    }
}

/// A deck of playing cards
#[derive(Debug, Clone, Default)]
struct Deck {
    /// The cards in the deck
    cards: Vec<Card>,
}

impl Deck {
    /// Create a standard 52-card deck
    #[must_use]
    fn standard_52() -> Self {
        Self {
            cards: Suit::ASCENDING
                .into_iter()
                .flat_map(|x| core::iter::repeat(x).zip(2..=14))
                .map(|(suit, rank)| Card::new(suit, rank))
                .collect(),
        }
    }

    /// Deal the deck into four hands
    #[must_use]
    fn deal(&self) -> Deal {
        let mut deal = Deal::default();

        for (index, card) in self.cards.iter().enumerate() {
            #[allow(clippy::cast_possible_truncation)]
            deal[unsafe { core::mem::transmute((index & 0x3) as u8) }].insert(*card);
        }

        deal
    }

    /// Shuffle the deck
    fn shuffle(&mut self, rng: &mut (impl rand::Rng + ?Sized)) {
        self.cards.shuffle(rng);
    }
}

impl Deal {
    /// Create a deal from a shuffled standard 52-card deck
    pub fn new(rng: &mut (impl rand::Rng + ?Sized)) -> Self {
        let mut deck = Deck::standard_52();
        deck.shuffle(rng);
        deck.deal()
    }
}