hearts 0.1.1

Cards, tricks, and a rules-driven state machine for the card game Hearts
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
//! One deal of Hearts, from the pass to the last trick.
//!
//! A [`Round`] is a runtime-checked state machine.  Accessors expose the
//! whole position — including all four hands and every pass, so bots and UIs
//! enforce their own information hygiene — and action methods mutate it,
//! returning [`RoundError`] on illegal moves.
//!
//! The flow of a round:
//!
//! 1. **Passing** ([`Phase::Passing`], skipped on a
//!    [hold](crate::seat::PassDirection::Hold) deal): each seat
//!    [`pass`](Round::pass)es exactly three cards, in any order of seats.
//!    The fourth submission triggers the exchange atomically.
//! 2. **Tricks** ([`Phase::Playing`]): the holder of the 2♣ leads it to the
//!    first trick; play proceeds clockwise under the rules of Hearts —
//!    follow suit if able; no penalty card on the first trick unless the
//!    hand allows nothing else; no heart led until hearts are broken.
//! 3. The thirteenth trick ends the round ([`Phase::Finished`]) with a
//!    [`RoundResult`] tallying each seat's penalty points.

use crate::hand::{Card, Hand};
use crate::seat::{PassDirection, Seat};
use crate::trick::Trick;
use crate::{Rules, Suit};
use core::fmt;
use thiserror::Error;

/// The phase of a [`Round`]
///
/// UIs are expected to match on all phases, so this enum is exhaustive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Phase {
    /// Seats are choosing three cards to pass
    Passing,
    /// Tricks are being played
    Playing,
    /// The round is over; see [`Round::result`]
    Finished,
}

impl fmt::Display for Phase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Passing => "passing",
            Self::Playing => "playing",
            Self::Finished => "finished",
        })
    }
}

/// Error indicating an impossible penalty tally
///
/// The four penalty counts of a round always sum to 26, and whoever took the
/// Q♠ holds at least 13 of them.
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, Hash)]
#[error("Round points must sum to 26 with at least 13 for the Q♠ taker")]
pub struct InvalidResult(pub [u8; 4]);

/// The outcome of a round: each seat's raw penalty points
///
/// A result records facts — the points as taken, moon unapplied — and
/// [`RoundResult::scores`] prices them under a [`Rules`].  The counts always
/// sum to 26 and the Q♠ taker holds at least 13; construction and
/// deserialization validate this.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(try_from = "[u8; 4]", into = "[u8; 4]")
)]
pub struct RoundResult {
    points: [u8; 4],
}

impl RoundResult {
    /// Create a result from raw penalty points by seat
    ///
    /// # Panics
    ///
    /// When the tally is impossible; see [`RoundResult::try_new`].  In const
    /// contexts, this is a compile-time error.
    #[must_use]
    #[inline]
    pub const fn new(points: [u8; 4]) -> Self {
        match Self::try_new(points) {
            Ok(result) => result,
            Err(_) => panic!("round points must sum to 26 with at least 13 for the Q♠ taker"),
        }
    }

    /// Try to create a result from raw penalty points by seat
    ///
    /// # Errors
    ///
    /// When the points do not sum to 26, or nobody holds the 13 points of
    /// the Q♠.
    #[inline]
    pub const fn try_new(points: [u8; 4]) -> Result<Self, InvalidResult> {
        let sum = points[0] as u16 + points[1] as u16 + points[2] as u16 + points[3] as u16;
        let max = {
            let ab = if points[0] > points[1] {
                points[0]
            } else {
                points[1]
            };
            let cd = if points[2] > points[3] {
                points[2]
            } else {
                points[3]
            };
            if ab > cd { ab } else { cd }
        };
        if sum == 26 && max >= 13 {
            Ok(Self { points })
        } else {
            Err(InvalidResult(points))
        }
    }

    /// Raw penalty points by seat, moon unapplied; they sum to 26
    #[must_use]
    #[inline]
    pub const fn points(self) -> [u8; 4] {
        self.points
    }

    /// The seat that shot the moon — took all 26 points — if any
    #[must_use]
    pub fn shooter(self) -> Option<Seat> {
        Seat::ALL
            .into_iter()
            .find(|&s| self.points[s as usize] == 26)
    }

    /// Points charged to each seat under the given rules
    ///
    /// A shot moon charges 26 to each opponent and nothing to the shooter.
    /// The rules do not affect the pricing yet; the parameter reserves room
    /// for the moon add/subtract variant.
    #[must_use]
    pub fn scores(self, _rules: &Rules) -> [u16; 4] {
        match self.shooter() {
            Some(shooter) => {
                let mut scores = [26; 4];
                scores[shooter as usize] = 0;
                scores
            }
            None => self.points.map(u16::from),
        }
    }
}

impl From<RoundResult> for [u8; 4] {
    #[inline]
    fn from(result: RoundResult) -> Self {
        result.points
    }
}

impl TryFrom<[u8; 4]> for RoundResult {
    type Error = InvalidResult;

    #[inline]
    fn try_from(points: [u8; 4]) -> Result<Self, InvalidResult> {
        Self::try_new(points)
    }
}

/// Error returned when constructing a [`Round`] from an invalid deal
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DealError {
    /// Each seat is dealt exactly 13 cards
    #[error("Each seat is dealt exactly 13 cards")]
    WrongHandSize,

    /// A card appears in more than one hand
    #[error("A card appears in more than one hand")]
    RepeatedCard,

    /// A hand holds a bit that is not a card (see
    /// [`Hand::from_bits_retain`])
    #[error("A hand holds a bit that is not a card")]
    UnknownCard,
}

/// Error returned when a [`Round`] action is illegal
#[derive(Debug, Error, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RoundError {
    /// The action does not belong to the current phase
    #[error("This action is not available in the {0} phase")]
    WrongPhase(Phase),

    /// The seat tried to play out of turn
    #[error("It is not {0}'s turn")]
    NotYourTurn(Seat),

    /// The seat has already passed its three cards
    #[error("{0} has already passed")]
    AlreadyPassed(Seat),

    /// A pass is exactly three cards
    #[error("A pass is exactly 3 cards, not {0}")]
    WrongPassCount(usize),

    /// The card is not in the acting seat's hand
    #[error("{0} is not in the hand")]
    NotInHand(Card),

    /// The first trick is led with the 2♣
    #[error("The first trick is led with the 2♣")]
    MustLeadTwoOfClubs,

    /// The hand can follow the led suit
    #[error("The led suit {0} must be followed")]
    MustFollowSuit(Suit),

    /// Hearts cannot be led until a heart has been played
    #[error("Hearts cannot be led until a heart has been played")]
    HeartsNotBroken,

    /// No penalty card on the first trick while the hand allows anything else
    #[error("{0} cannot be played on the first trick")]
    FirstTrickPenalty(Card),

    /// The card set holds a bit that is not a card (see
    /// [`Hand::from_bits_retain`])
    #[error("The card set holds a bit that is not a card")]
    UnknownCard,
}

/// One deal of Hearts
///
/// See the [module documentation](self) for the flow.  Construct with
/// [`Round::from_deal`] or, under the `rand` feature, [`Round::deal`].
///
/// With the `serde` feature, a `Round` serializes to a plain snapshot of its
/// position, and deserialization *replays* the recorded history through the
/// state machine — a corrupt snapshot is rejected, never trusted.
#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serde",
    derive(serde::Serialize, serde::Deserialize),
    serde(into = "repr::RoundRepr", try_from = "repr::RoundRepr")
)]
pub struct Round {
    rules: Rules,
    direction: PassDirection,
    hands: [Hand; 4],
    /// Chosen passes, retained for the whole round; a seat's cards leave its
    /// hand when it passes and land with the receiver on the exchange.
    passes: [Option<Hand>; 4],
    phase: Phase,
    /// The trick in progress; `Some` exactly during [`Phase::Playing`].
    current: Option<Trick>,
    /// Completed tricks in play order.
    tricks: Vec<Trick>,
    result: Option<RoundResult>,
}

impl Clone for Round {
    fn clone(&self) -> Self {
        Self {
            rules: self.rules,
            direction: self.direction,
            hands: self.hands,
            passes: self.passes,
            phase: self.phase,
            current: self.current,
            tricks: self.tricks.clone(),
            result: self.result,
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.rules = source.rules;
        self.direction = source.direction;
        self.hands = source.hands;
        self.passes = source.passes;
        self.phase = source.phase;
        self.current = source.current;
        self.tricks.clone_from(&source.tricks);
        self.result = source.result;
    }
}

/// The seat holding the 2♣, who leads the first trick
// The expect is unreachable: the hands partition the deck by construction.
fn opening_leader(hands: &[Hand; 4]) -> Seat {
    Seat::ALL
        .into_iter()
        .find(|&seat| hands[seat as usize].contains(Card::TWO_OF_CLUBS))
        .expect("the four hands partition the deck, so one holds the 2♣")
}

impl Round {
    /// Construct a round from a fixed deal of four 13-card hands
    ///
    /// Hands are indexed by seat.  A [hold](PassDirection::Hold) deal skips
    /// the passing phase and starts with the 2♣ holder to lead.
    ///
    /// # Errors
    ///
    /// When the hands are not 13 cards each, any card appears twice, or a
    /// hand smuggles non-card bits (via [`Hand::from_bits_retain`]).
    pub fn from_deal(
        rules: Rules,
        direction: PassDirection,
        hands: [Hand; 4],
    ) -> Result<Self, DealError> {
        let mut seen = Hand::EMPTY;
        for hand in hands {
            if hand.len() != 13 {
                return Err(DealError::WrongHandSize);
            }
            if !(seen & hand).is_empty() {
                return Err(DealError::RepeatedCard);
            }
            seen |= hand;
        }
        // 52 disjoint set bits cover the deck exactly when none of them is
        // an invalid (non-card) bit.
        if seen != Hand::ALL {
            return Err(DealError::UnknownCard);
        }

        let passing = !matches!(direction, PassDirection::Hold);
        Ok(Self {
            rules,
            direction,
            passes: [None; 4],
            phase: if passing {
                Phase::Passing
            } else {
                Phase::Playing
            },
            current: if passing {
                None
            } else {
                Some(Trick::new(opening_leader(&hands)))
            },
            hands,
            tricks: Vec::with_capacity(13),
            result: None,
        })
    }

    /// Shuffle and deal a fresh round: 13 cards to each seat
    // The deal is disjoint by construction, so `from_deal` cannot fail.
    #[allow(clippy::missing_panics_doc)]
    #[cfg(feature = "rand")]
    #[must_use]
    pub fn deal(
        rules: Rules,
        direction: PassDirection,
        rng: &mut (impl rand::Rng + ?Sized),
    ) -> Self {
        let mut deck = crate::deck::Deck::ALL;
        let hands = [
            deck.draw(rng, 13),
            deck.draw(rng, 13),
            deck.draw(rng, 13),
            deck.take(),
        ];
        Self::from_deal(rules, direction, hands).expect("a fresh deck deals disjoint cards")
    }

    /// The rules of this round
    #[must_use]
    #[inline]
    pub const fn rules(&self) -> &Rules {
        &self.rules
    }

    /// The pass direction of this round
    #[must_use]
    #[inline]
    pub const fn direction(&self) -> PassDirection {
        self.direction
    }

    /// The current phase
    #[must_use]
    #[inline]
    pub const fn phase(&self) -> Phase {
        self.phase
    }

    /// The hand of a seat
    ///
    /// All hands are visible by design; bots enforce their own information
    /// hygiene.
    #[must_use]
    #[inline]
    pub const fn hand(&self, seat: Seat) -> Hand {
        self.hands[seat as usize]
    }

    /// The cards a seat has chosen to pass, or `None` if it has not passed
    ///
    /// Retained for the whole round (always `None` on a hold deal).  Visible
    /// by design; bots enforce their own information hygiene.
    #[must_use]
    #[inline]
    pub const fn passed(&self, seat: Seat) -> Option<Hand> {
        self.passes[seat as usize]
    }

    /// The trick in progress; `Some` exactly during [`Phase::Playing`]
    #[must_use]
    #[inline]
    pub const fn current_trick(&self) -> Option<Trick> {
        self.current
    }

    /// The completed tricks in play order
    #[must_use]
    #[inline]
    pub fn tricks(&self) -> &[Trick] {
        &self.tricks
    }

    /// The seat to play, or `None` outside [`Phase::Playing`]
    ///
    /// During the passing phase seats act in any order; see
    /// [`Round::passed`] for who still owes a pass.
    #[must_use]
    pub fn turn(&self) -> Option<Seat> {
        self.current.and_then(Trick::current)
    }

    /// Every card played so far, including the trick in progress
    #[must_use]
    pub fn played(&self) -> Hand {
        let tricks = self
            .tricks
            .iter()
            .fold(Hand::EMPTY, |acc, t| acc | t.cards());
        self.current.map_or(tricks, |t| tricks | t.cards())
    }

    /// Whether a heart has been played, allowing hearts to be led
    #[must_use]
    pub fn hearts_broken(&self) -> bool {
        self.tricks
            .iter()
            .copied()
            .chain(self.current)
            .any(|trick| trick.plays().any(|(_, card)| card.suit == Suit::Hearts))
    }

    /// The cards a seat has taken in its won tricks
    #[must_use]
    pub fn taken(&self, seat: Seat) -> Hand {
        self.tricks
            .iter()
            .filter(|t| t.winner() == Some(seat))
            .fold(Hand::EMPTY, |acc, t| acc | t.cards())
    }

    /// The penalty points a seat has taken so far
    #[must_use]
    pub fn points_taken(&self, seat: Seat) -> u8 {
        self.taken(seat).points()
    }

    /// The outcome, or `None` while the round is in play
    #[must_use]
    #[inline]
    pub const fn result(&self) -> Option<RoundResult> {
        self.result
    }

    const fn expect_phase(&self, phase: Phase) -> Result<(), RoundError> {
        if self.phase as u8 == phase as u8 {
            Ok(())
        } else {
            Err(RoundError::WrongPhase(self.phase))
        }
    }

    /// The cards `seat` may legally play right now
    ///
    /// Empty when it is not `seat`'s turn to play; otherwise a non-empty
    /// subset of its hand:
    ///
    /// - Leading the first trick: the 2♣ alone.
    /// - Leading later tricks: the whole hand, minus hearts until broken —
    ///   unless only hearts remain.
    /// - Following: the led suit if the hand has it, otherwise anything —
    ///   minus penalty cards on the first trick, unless only penalties
    ///   remain.
    #[must_use]
    pub fn legal_plays(&self, seat: Seat) -> Hand {
        /// The preferred set, falling back when the rule cannot be obeyed
        fn or_else(preferred: Hand, fallback: Hand) -> Hand {
            if preferred.is_empty() {
                fallback
            } else {
                preferred
            }
        }

        let Some(trick) = self.current else {
            return Hand::EMPTY;
        };
        if trick.current() != Some(seat) {
            return Hand::EMPTY;
        }

        let hand = self.hands[seat as usize];
        match trick.suit() {
            // Leading
            None => {
                if self.tricks.is_empty() {
                    Hand::TWO_OF_CLUBS
                } else if self.hearts_broken() {
                    hand
                } else {
                    or_else(hand - Hand::HEARTS, hand)
                }
            }
            // Following
            Some(led) => {
                let mut follow = Hand::EMPTY;
                follow[led] = hand[led];
                if !follow.is_empty() {
                    follow
                } else if self.tricks.is_empty() {
                    or_else(hand - Hand::PENALTIES, hand)
                } else {
                    hand
                }
            }
        }
    }

    /// Pass three cards face down
    ///
    /// Seats pass in any order; each may act once.  The fourth submission
    /// performs the exchange atomically — every seat receives from its
    /// [giver](PassDirection::giver) — and play begins with the
    /// (post-exchange) holder of the 2♣.  The 2♣ itself may be passed.
    ///
    /// # Errors
    ///
    /// [`RoundError::WrongPhase`] outside the passing phase (hold deals
    /// never enter it), [`RoundError::AlreadyPassed`],
    /// [`RoundError::WrongPassCount`] unless exactly three cards,
    /// [`RoundError::NotInHand`] for cards the seat does not hold, and
    /// [`RoundError::UnknownCard`] for non-card bits smuggled via
    /// [`Hand::from_bits_retain`].
    pub fn pass(&mut self, seat: Seat, cards: Hand) -> Result<(), RoundError> {
        self.expect_phase(Phase::Passing)?;
        if self.passes[seat as usize].is_some() {
            return Err(RoundError::AlreadyPassed(seat));
        }
        if cards.contains_unknown_bits() {
            return Err(RoundError::UnknownCard);
        }
        if cards.len() != 3 {
            return Err(RoundError::WrongPassCount(cards.len()));
        }
        if let Some(card) = (cards - self.hands[seat as usize]).into_iter().next() {
            return Err(RoundError::NotInHand(card));
        }

        self.hands[seat as usize] -= cards;
        self.passes[seat as usize] = Some(cards);

        if self.passes.iter().all(Option::is_some) {
            for giver in Seat::ALL {
                // All four passes are in; the unwrap cannot fail.
                if let Some(passed) = self.passes[giver as usize] {
                    self.hands[self.direction.receiver(giver) as usize] |= passed;
                }
            }
            self.phase = Phase::Playing;
            self.current = Some(Trick::new(opening_leader(&self.hands)));
        }
        Ok(())
    }

    /// Play a card to the current trick
    ///
    /// A completed trick is swept automatically: its winner leads the next,
    /// and the thirteenth trick finishes the round with its
    /// [`result`](Round::result).
    ///
    /// # Errors
    ///
    /// [`RoundError::WrongPhase`] outside the playing phase,
    /// [`RoundError::NotYourTurn`], [`RoundError::NotInHand`], and the rule
    /// errors [`RoundError::MustLeadTwoOfClubs`],
    /// [`RoundError::MustFollowSuit`], [`RoundError::HeartsNotBroken`], and
    /// [`RoundError::FirstTrickPenalty`] — exactly when the card is outside
    /// [`Round::legal_plays`].
    // The expects are unreachable: `Playing` implies a live, incomplete
    // trick, and thirteen complete tricks tally exactly 26 points.
    #[allow(clippy::missing_panics_doc)]
    pub fn play(&mut self, seat: Seat, card: Card) -> Result<(), RoundError> {
        self.expect_phase(Phase::Playing)?;
        let mut trick = self.current.expect("a playing round has a live trick");
        if trick.current() != Some(seat) {
            return Err(RoundError::NotYourTurn(seat));
        }

        let hand = self.hands[seat as usize];
        if !hand.contains(card) {
            return Err(RoundError::NotInHand(card));
        }
        let first = self.tricks.is_empty();
        match trick.suit() {
            // Leading
            None => {
                if first && card != Card::TWO_OF_CLUBS {
                    return Err(RoundError::MustLeadTwoOfClubs);
                }
                if card.suit == Suit::Hearts
                    && !self.hearts_broken()
                    && !(hand - Hand::HEARTS).is_empty()
                {
                    return Err(RoundError::HeartsNotBroken);
                }
            }
            // Following
            Some(led) => {
                if card.suit != led && !hand[led].is_empty() {
                    return Err(RoundError::MustFollowSuit(led));
                }
                if first && card.points() > 0 && !(hand - Hand::PENALTIES).is_empty() {
                    return Err(RoundError::FirstTrickPenalty(card));
                }
            }
        }

        self.hands[seat as usize].remove(card);
        trick
            .play(card)
            .expect("the current trick is never complete");

        if trick.is_complete() {
            let winner = trick.winner().expect("a complete trick has a winner");
            self.tricks.push(trick);
            if self.tricks.len() == 13 {
                let mut points = [0u8; 4];
                for taken in &self.tricks {
                    let winner = taken.winner().expect("a complete trick has a winner");
                    points[winner as usize] += taken.points();
                }
                self.current = None;
                self.phase = Phase::Finished;
                self.result =
                    Some(RoundResult::try_new(points).expect("thirteen tricks tally 26 points"));
            } else {
                self.current = Some(Trick::new(winner));
            }
        } else {
            self.current = Some(trick);
        }
        Ok(())
    }
}

/// The serialized form of a [`Round`], validated by replay
///
/// The history of a round is fully ordered — the retained passes plus every
/// trick in play order — so deserialization reconstructs the pre-pass deal
/// and re-drives the real state machine over it.  No rule logic is
/// duplicated: a snapshot is valid exactly when its history is legal and
/// lands on the snapshotted position.
#[cfg(feature = "serde")]
mod repr {
    use super::{DealError, Phase, Round, RoundError, RoundResult};
    use crate::Rules;
    use crate::hand::Hand;
    use crate::seat::{PassDirection, Seat};
    use crate::trick::Trick;
    use thiserror::Error;

    /// Error rejecting a corrupt [`Round`](super::Round) snapshot
    #[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
    #[non_exhaustive]
    pub enum InvalidRound {
        /// The snapshot does not reconstruct a legal deal
        #[error("The snapshot does not reconstruct a legal deal: {0}")]
        Deal(#[from] DealError),
        /// The recorded history is not a legal sequence of actions
        #[error("The recorded history is not a legal sequence of actions: {0}")]
        History(#[from] RoundError),
        /// The replayed history does not land on the snapshotted position
        #[error("The snapshot does not match its replayed history")]
        Mismatch,
    }

    #[derive(Clone, serde::Serialize, serde::Deserialize)]
    pub struct RoundRepr {
        rules: Rules,
        direction: PassDirection,
        hands: [Hand; 4],
        passes: [Option<Hand>; 4],
        phase: Phase,
        current: Option<Trick>,
        tricks: Vec<Trick>,
        result: Option<RoundResult>,
    }

    impl From<Round> for RoundRepr {
        fn from(round: Round) -> Self {
            Self {
                rules: round.rules,
                direction: round.direction,
                hands: round.hands,
                passes: round.passes,
                phase: round.phase,
                current: round.current,
                tricks: round.tricks,
                result: round.result,
            }
        }
    }

    impl RoundRepr {
        /// Each trick of the snapshot, the one in progress last
        fn history(&self) -> impl Iterator<Item = &Trick> {
            self.tricks.iter().chain(&self.current)
        }

        /// Undo the snapshot back to its pre-pass deal
        ///
        /// A seat's original hand is its current hand plus everything it
        /// played and passed, minus what it received.  On corrupt input
        /// this yields garbage hands, which the replay then rejects.
        fn pre_pass_hands(&self) -> [Hand; 4] {
            let mut played = [Hand::EMPTY; 4];
            for trick in self.history() {
                for (seat, card) in trick.plays() {
                    played[seat as usize].insert(card);
                }
            }
            Seat::ALL.map(|seat| {
                let passed = self.passes[seat as usize].unwrap_or(Hand::EMPTY);
                let giver = self.direction.giver(seat);
                let received = self.passes[giver as usize].unwrap_or(Hand::EMPTY);
                (self.hands[seat as usize] | played[seat as usize] | passed) - received
            })
        }
    }

    impl TryFrom<RoundRepr> for Round {
        type Error = InvalidRound;

        fn try_from(repr: RoundRepr) -> Result<Self, InvalidRound> {
            let mut round = Round::from_deal(repr.rules, repr.direction, repr.pre_pass_hands())?;
            for seat in Seat::ALL {
                if let Some(cards) = repr.passes[seat as usize] {
                    round.pass(seat, cards)?;
                }
            }
            for trick in repr.history() {
                for (seat, card) in trick.plays() {
                    round.play(seat, card)?;
                }
            }

            if round.hands != repr.hands
                || round.phase != repr.phase
                || round.current != repr.current
                || round.tricks != repr.tricks
                || round.result != repr.result
            {
                return Err(InvalidRound::Mismatch);
            }
            Ok(round)
        }
    }
}

#[cfg(feature = "serde")]
pub use repr::InvalidRound;