native-solver 0.2.0

Heads-up postflop No-Limit Hold'em solver: hand evaluator, ranges, betting trees, and combo-vectorized CFR / CFR+ / DCFR.
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
//! Poker hand strength: [`evaluate_5`] for exactly five cards and
//! [`evaluate_7`] for the best five of seven (two hole cards and a board).
//!
//! Both return a [`HandStrength`]; stronger hands compare greater, and equal
//! strengths split the pot.
//!
//! ```
//! use native_solver::{evaluate_7, Card, HandCategory};
//!
//! let cards = |s: &str| -> Vec<Card> { s.split(' ').map(|c| c.parse().unwrap()).collect() };
//! let board = cards("Ks Th 7s 4d 2s");
//! let hand = |hole: &str| {
//!     let all: Vec<Card> = cards(hole).into_iter().chain(board.iter().copied()).collect();
//!     evaluate_7(all.try_into().unwrap())
//! };
//! assert!(hand("As 9s") > hand("Kd Kc")); // a flush beats a set
//! assert_eq!(hand("As 9s").category(), HandCategory::Flush);
//! ```

// Implementation notes.
//
// `evaluate_5` is table-driven for speed, since CFR calls it an enormous
// number of times. Every 5-card hand falls into one of two cases:
//
// - **All 5 ranks distinct**: straight/flush/high-card only (a repeated
//   rank is impossible here, so no pair-or-better). Which of the 13
//   ranks are present is a 13-bit bitmask (0..8192); `TABLES.straight_high`
//   and `TABLES.high_card_tiebreak`, precomputed once and indexed directly
//   by that bitmask, give the answer with no branching or sorting.
// - **A rank repeats**: pair or better. Two cards can never share both
//   rank and suit, so a repeated rank makes a flush structurally
//   impossible — the hand's category is fully determined by the
//   *multiset* of ranks alone. Assigning each rank a distinct prime and
//   multiplying the 5 cards' primes gives a product that's unique per
//   multiset (unique prime factorization), so `TABLES.paired` (keyed by
//   that product) looks the score up directly.
//
// Both tables are built once, lazily, from `evaluate_5_reference` — the
// original correctness-first implementation (grouping + sorting, checked
// all 21 5-card subsets' worth of hand types by hand in earlier
// milestones) — kept around purely as the oracle for table generation and
// for the exhaustive cross-check test below. `evaluate_5` and
// `evaluate_5_reference` are checked equal across all C(52,5) = 2,598,960
// possible 5-card hands, not just a handful of examples.

use crate::card::Card;
use std::collections::HashMap;
use std::sync::OnceLock;

const CAT_HIGH_CARD: u32 = 0;
const CAT_PAIR: u32 = 1;
const CAT_TWO_PAIR: u32 = 2;
const CAT_THREE_KIND: u32 = 3;
const CAT_STRAIGHT: u32 = 4;
const CAT_FLUSH: u32 = 5;
const CAT_FULL_HOUSE: u32 = 6;
const CAT_FOUR_KIND: u32 = 7;
const CAT_STRAIGHT_FLUSH: u32 = 8;

/// Hand categories, ordered from weakest to strongest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum HandCategory {
    /// No pair or better.
    HighCard,
    /// One pair.
    Pair,
    /// Two pairs.
    TwoPair,
    /// Three cards of one rank.
    ThreeOfAKind,
    /// Five consecutive ranks, including the ace-low wheel.
    Straight,
    /// Five cards of one suit.
    Flush,
    /// Three of one rank and a pair of another.
    FullHouse,
    /// Four cards of one rank.
    FourOfAKind,
    /// A straight in one suit, including the royal flush.
    StraightFlush,
}

/// The strength of a five-card poker hand; stronger hands compare greater.
///
/// [`evaluate_5`] and [`evaluate_7`] return it. Equal strengths split the
/// pot.
///
/// ```
/// use native_solver::{evaluate_5, Card, HandCategory};
///
/// let hand = |s: &str| -> [Card; 5] {
///     let cards: Vec<Card> = s.split(' ').map(|c| c.parse().unwrap()).collect();
///     cards.try_into().unwrap()
/// };
/// let flush = evaluate_5(hand("Ah 9h 7h 4h 2h"));
/// let straight = evaluate_5(hand("9h 8d 7s 6h 5c"));
/// assert!(flush > straight);
/// assert_eq!(flush.category(), HandCategory::Flush);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HandStrength(pub(crate) u32);

impl HandStrength {
    /// The hand's category, e.g. [`HandCategory::Flush`].
    pub fn category(self) -> HandCategory {
        category_of(self.0)
    }
}

/// The category packed into the top bits of an internal score.
fn category_of(score: u32) -> HandCategory {
    match score >> 20 {
        CAT_HIGH_CARD => HandCategory::HighCard,
        CAT_PAIR => HandCategory::Pair,
        CAT_TWO_PAIR => HandCategory::TwoPair,
        CAT_THREE_KIND => HandCategory::ThreeOfAKind,
        CAT_STRAIGHT => HandCategory::Straight,
        CAT_FLUSH => HandCategory::Flush,
        CAT_FULL_HOUSE => HandCategory::FullHouse,
        CAT_FOUR_KIND => HandCategory::FourOfAKind,
        CAT_STRAIGHT_FLUSH => HandCategory::StraightFlush,
        other => unreachable!("invalid hand category bits: {other}"),
    }
}

/// Pack up to 5 tiebreak ranks (most significant first) into the low 20
/// bits of a score, in the same bit positions `pack` uses.
fn pack_ranks(ranks: &[u8]) -> u32 {
    let mut bits = 0u32;
    for (i, &r) in ranks.iter().enumerate() {
        bits |= (r as u32) << (16 - i * 4);
    }
    bits
}

/// Pack a category and up to 5 tiebreak ranks (most significant first) into
/// a single comparable score: higher score always beats lower score.
fn pack(category: u32, ranks: &[u8]) -> u32 {
    (category << 20) | pack_ranks(ranks)
}

/// Ranks (descending, unique) that make up a straight, if any. `ranks_desc`
/// must already be sorted descending and deduplicated.
fn straight_high(ranks_desc: &[u8]) -> Option<u8> {
    if ranks_desc.len() != 5 {
        return None;
    }
    // Wheel: A-2-3-4-5, i.e. rank indices 12,3,2,1,0. High card is the "5" (index 3).
    if ranks_desc == [12, 3, 2, 1, 0] {
        return Some(3);
    }
    for w in ranks_desc.windows(2) {
        if w[0] != w[1] + 1 {
            return None;
        }
    }
    Some(ranks_desc[0])
}

/// Slow, case-by-case [`evaluate_5`], kept as a test and benchmark oracle.
///
/// Not part of the documented API; it may change without notice.
#[doc(hidden)]
pub fn evaluate_5_reference(cards: [Card; 5]) -> u32 {
    let mut rank_counts = [0u8; 13];
    let mut suit_counts = [0u8; 4];
    for &c in &cards {
        rank_counts[c.rank() as usize] += 1;
        suit_counts[c.suit() as usize] += 1;
    }
    let is_flush = suit_counts.contains(&5);

    let mut ranks_desc: Vec<u8> = (0..13u8).filter(|&r| rank_counts[r as usize] > 0).collect();
    ranks_desc.sort_unstable_by(|a, b| b.cmp(a));
    let straight = straight_high(&ranks_desc);

    if is_flush {
        if let Some(high) = straight {
            return pack(CAT_STRAIGHT_FLUSH, &[high]);
        }
    }

    let mut groups: Vec<(u8, u8)> = (0..13u8)
        .filter(|&r| rank_counts[r as usize] > 0)
        .map(|r| (rank_counts[r as usize], r))
        .collect();
    groups.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1)));

    match groups[0].0 {
        4 => pack(CAT_FOUR_KIND, &[groups[0].1, groups[1].1]),
        3 if groups[1].0 >= 2 => pack(CAT_FULL_HOUSE, &[groups[0].1, groups[1].1]),
        3 => pack(CAT_THREE_KIND, &[groups[0].1, groups[1].1, groups[2].1]),
        2 if groups[1].0 == 2 => pack(CAT_TWO_PAIR, &[groups[0].1, groups[1].1, groups[2].1]),
        2 => pack(
            CAT_PAIR,
            &[groups[0].1, groups[1].1, groups[2].1, groups[3].1],
        ),
        _ if is_flush => {
            let ranks: Vec<u8> = groups.iter().map(|g| g.1).collect();
            pack(CAT_FLUSH, &ranks)
        }
        _ if straight.is_some() => pack(CAT_STRAIGHT, &[straight.unwrap()]),
        _ => {
            let ranks: Vec<u8> = groups.iter().map(|g| g.1).collect();
            pack(CAT_HIGH_CARD, &ranks)
        }
    }
}

/// One prime per rank (2..=A); the product of a 5-card hand's rank primes
/// is unique per rank *multiset* (unique prime factorization), so it's a
/// perfect key for the paired-hand lookup table.
const RANK_PRIMES: [u64; 13] = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41];

struct Tables {
    /// Indexed by the 13-bit "which ranks are present" bitmask (only
    /// entries with exactly 5 bits set are meaningful): `Some(high)` if
    /// those 5 ranks form a straight.
    straight_high: Vec<Option<u8>>,
    /// Same indexing; packed tiebreak ranks for the non-straight case
    /// (used for both flush and high-card, which share the same ordering).
    high_card_tiebreak: Vec<u32>,
    /// Rank-prime product -> full packed score, for every 5-rank multiset
    /// that has at least one repeat (pair or better). A repeated rank
    /// makes a flush structurally impossible, so the category is fully
    /// determined by the multiset alone.
    paired: HashMap<u64, u32>,
}

static TABLES: OnceLock<Tables> = OnceLock::new();

fn tables() -> &'static Tables {
    TABLES.get_or_init(build_tables)
}

fn build_tables() -> Tables {
    let mut straight_high_table = vec![None; 8192];
    let mut high_card_tiebreak = vec![0u32; 8192];
    for mask in 0u16..8192 {
        if mask.count_ones() != 5 {
            continue;
        }
        let ranks_desc: Vec<u8> = (0..13u8).rev().filter(|&r| mask & (1 << r) != 0).collect();
        straight_high_table[mask as usize] = straight_high(&ranks_desc);
        high_card_tiebreak[mask as usize] = pack_ranks(&ranks_desc);
    }

    let mut paired = HashMap::new();
    for ranks in rank_multisets_with_repeat() {
        let hand = representative_hand(&ranks);
        let score = evaluate_5_reference(hand);
        let product: u64 = ranks.iter().map(|&r| RANK_PRIMES[r as usize]).product();
        paired.insert(product, score);
    }

    Tables {
        straight_high: straight_high_table,
        high_card_tiebreak,
        paired,
    }
}

/// Every non-increasing sequence of 5 ranks (0..13) with at least one
/// repeated value — i.e. every possible 5-card rank multiset that isn't
/// all-distinct (and excluding 5-of-a-kind, which is impossible with only
/// 4 suits per rank). There are C(17,5) - C(13,5) - 13 = 6188 - 1287 - 13
/// = 4888 of them.
fn rank_multisets_with_repeat() -> Vec<[u8; 5]> {
    let mut out = Vec::new();
    for r0 in 0..13u8 {
        for r1 in 0..=r0 {
            for r2 in 0..=r1 {
                for r3 in 0..=r2 {
                    for r4 in 0..=r3 {
                        let ranks = [r0, r1, r2, r3, r4];
                        let mut counts = [0u8; 13];
                        for &r in &ranks {
                            counts[r as usize] += 1;
                        }
                        let max_count = counts.iter().copied().max().unwrap();
                        if (2..=4).contains(&max_count) {
                            out.push(ranks);
                        }
                    }
                }
            }
        }
    }
    out
}

/// A concrete 5-card hand with the given ranks (assigning increasing
/// suits to repeats of the same rank, which never collides since a rank
/// repeats at most 4 times).
fn representative_hand(ranks: &[u8; 5]) -> [Card; 5] {
    let mut next_suit = [0u8; 13];
    let mut cards = [Card(0); 5];
    for (i, &r) in ranks.iter().enumerate() {
        let s = next_suit[r as usize];
        next_suit[r as usize] += 1;
        cards[i] = Card(r * 4 + s);
    }
    cards
}

/// The strength of an exact five-card hand.
///
/// The five cards must be distinct; repeated cards give a meaningless
/// result and may panic.
pub fn evaluate_5(cards: [Card; 5]) -> HandStrength {
    HandStrength(score_5(cards))
}

/// [`evaluate_5`] as a raw score, for the solver's hot paths.
pub(crate) fn score_5(cards: [Card; 5]) -> u32 {
    debug_assert!(
        crate::card::CardSet::from_cards(&cards).len() == 5,
        "evaluate_5 needs five distinct cards"
    );
    let t = tables();

    let mut suit_counts = [0u8; 4];
    let mut rank_mask: u16 = 0;
    let mut has_repeat = false;
    for &c in &cards {
        let r = c.rank();
        suit_counts[c.suit() as usize] += 1;
        let bit = 1u16 << r;
        if rank_mask & bit != 0 {
            has_repeat = true;
        }
        rank_mask |= bit;
    }
    let is_flush = suit_counts.contains(&5);

    if !has_repeat {
        if let Some(high) = t.straight_high[rank_mask as usize] {
            let cat = if is_flush {
                CAT_STRAIGHT_FLUSH
            } else {
                CAT_STRAIGHT
            };
            return pack(cat, &[high]);
        }
        let cat = if is_flush { CAT_FLUSH } else { CAT_HIGH_CARD };
        return (cat << 20) | t.high_card_tiebreak[rank_mask as usize];
    }

    let product: u64 = cards
        .iter()
        .map(|&c| RANK_PRIMES[c.rank() as usize])
        .product();
    *t.paired
        .get(&product)
        .expect("every 5-card rank multiset is precomputed in `paired`")
}

/// All 21 ways to choose 5 indices out of 7.
#[cfg(test)]
const COMBOS_7_CHOOSE_5: [[usize; 5]; 21] = [
    [0, 1, 2, 3, 4],
    [0, 1, 2, 3, 5],
    [0, 1, 2, 3, 6],
    [0, 1, 2, 4, 5],
    [0, 1, 2, 4, 6],
    [0, 1, 2, 5, 6],
    [0, 1, 3, 4, 5],
    [0, 1, 3, 4, 6],
    [0, 1, 3, 5, 6],
    [0, 1, 4, 5, 6],
    [0, 2, 3, 4, 5],
    [0, 2, 3, 4, 6],
    [0, 2, 3, 5, 6],
    [0, 2, 4, 5, 6],
    [0, 3, 4, 5, 6],
    [1, 2, 3, 4, 5],
    [1, 2, 3, 4, 6],
    [1, 2, 3, 5, 6],
    [1, 2, 4, 5, 6],
    [1, 3, 4, 5, 6],
    [2, 3, 4, 5, 6],
];

/// The strength of the best five-card hand out of seven cards, e.g. two hole
/// cards and a five-card board.
///
/// The seven cards must be distinct; repeated cards give a meaningless
/// result and may panic.
pub fn evaluate_7(cards: [Card; 7]) -> HandStrength {
    HandStrength(score_7(cards))
}

/// The highest set bit of a non-empty 13-bit rank mask, as a rank.
fn top_rank(mask: u16) -> u32 {
    15 - mask.leading_zeros()
}

/// Packs the `count` highest ranks of `mask`, highest first, starting at
/// nibble `first` of the tiebreak (nibble 0 is the most significant).
fn pack_top_ranks(mut mask: u16, count: usize, first: usize) -> u32 {
    let mut bits = 0;
    for i in first..first + count {
        let rank = top_rank(mask);
        bits |= rank << (16 - i * 4);
        mask &= !(1 << rank);
    }
    bits
}

/// The high card of the best straight among the ranks of `mask`, if any.
/// The wheel (A-2-3-4-5) counts as five-high.
fn best_straight_high(mask: u16) -> Option<u32> {
    // Bit 0 is the ace playing low; rank `r` sits at bit `r + 1`.
    let low_ace = (mask << 1) | (mask >> 12 & 1);
    let runs = low_ace & low_ace >> 1 & low_ace >> 2 & low_ace >> 3 & low_ace >> 4;
    // A run starting at bit `i` ends on rank `i + 3`.
    (runs != 0).then(|| top_rank(runs) + 3)
}

/// [`evaluate_7`] as a raw score, for the solver's hot paths.
///
/// Reads the best five-card hand directly from rank and suit counts. Equal to
/// the maximum of [`score_5`] over all 21 five-card subsets.
pub(crate) fn score_7(cards: [Card; 7]) -> u32 {
    let mut suits = [0u16; 4];
    // Ranks held at least once, twice, three and four times.
    let (mut any, mut pairs, mut trips, mut quads) = (0u16, 0u16, 0u16, 0u16);
    for card in cards {
        let bit = 1u16 << card.rank();
        suits[card.suit() as usize] |= bit;
        quads |= trips & bit;
        trips |= pairs & bit;
        pairs |= any & bit;
        any |= bit;
    }

    // Five cards of one suit leave room for at most one more card of any of
    // their ranks plus one other, so a flush rules out quads and full houses.
    for flush in suits {
        if flush.count_ones() >= 5 {
            return match best_straight_high(flush) {
                Some(high) => (CAT_STRAIGHT_FLUSH << 20) | (high << 16),
                None => (CAT_FLUSH << 20) | pack_top_ranks(flush, 5, 0),
            };
        }
    }
    if quads != 0 {
        let quad = top_rank(quads);
        return (CAT_FOUR_KIND << 20) | (quad << 16) | pack_top_ranks(any & !(1 << quad), 1, 1);
    }
    if trips != 0 {
        let trip = top_rank(trips);
        let others = pairs & !(1 << trip);
        if others != 0 {
            return (CAT_FULL_HOUSE << 20) | (trip << 16) | (top_rank(others) << 12);
        }
    }
    if let Some(high) = best_straight_high(any) {
        return (CAT_STRAIGHT << 20) | (high << 16);
    }
    if trips != 0 {
        let trip = top_rank(trips);
        return (CAT_THREE_KIND << 20) | (trip << 16) | pack_top_ranks(any & !(1 << trip), 2, 1);
    }
    if pairs != 0 {
        let high = top_rank(pairs);
        let lower = pairs & !(1 << high);
        if lower != 0 {
            let low = top_rank(lower);
            let kickers = any & !(1 << high) & !(1 << low);
            return (CAT_TWO_PAIR << 20)
                | (high << 16)
                | (low << 12)
                | pack_top_ranks(kickers, 1, 2);
        }
        return (CAT_PAIR << 20) | (high << 16) | pack_top_ranks(any & !(1 << high), 3, 1);
    }
    (CAT_HIGH_CARD << 20) | pack_top_ranks(any, 5, 0)
}

/// [`score_7`] as originally defined: the best of all 21 five-card subsets.
#[cfg(test)]
fn score_7_reference(cards: [Card; 7]) -> u32 {
    COMBOS_7_CHOOSE_5
        .iter()
        .map(|combo| {
            let five = [
                cards[combo[0]],
                cards[combo[1]],
                cards[combo[2]],
                cards[combo[3]],
                cards[combo[4]],
            ];
            score_5(five)
        })
        .max()
        .expect("21 combos is never empty")
}

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

    fn hand5(cards: &str) -> [Card; 5] {
        let parsed: Vec<Card> = cards
            .split_whitespace()
            .map(|c| c.parse::<Card>().unwrap())
            .collect();
        parsed.try_into().unwrap()
    }

    fn hand7(cards: &str) -> [Card; 7] {
        let parsed: Vec<Card> = cards
            .split_whitespace()
            .map(|c| c.parse::<Card>().unwrap())
            .collect();
        parsed.try_into().unwrap()
    }

    /// Visits every 7-card hand whose lowest card index is `offset`, or
    /// `offset` plus a multiple of `stride`.
    fn for_each_7_card_hand(stride: u8, offset: u8, mut visit: impl FnMut([Card; 7])) {
        for a in (offset..52).step_by(stride as usize) {
            for b in a + 1..52 {
                for c in b + 1..52 {
                    for d in c + 1..52 {
                        for e in d + 1..52 {
                            for f in e + 1..52 {
                                for g in f + 1..52 {
                                    visit([a, b, c, d, e, f, g].map(Card));
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn evaluate_7_matches_best_of_21_on_a_sample() {
        // Every 61st hand of the full enumeration: about two million.
        let (mut index, mut checked) = (0u32, 0u32);
        for offset in 0..46 {
            for_each_7_card_hand(52, offset, |hand| {
                if index % 61 == 0 {
                    assert_eq!(score_7(hand), score_7_reference(hand), "{hand:?}");
                    checked += 1;
                }
                index += 1;
            });
        }
        assert_eq!(index, 133_784_560);
        assert_eq!(checked, 2_193_190);
    }

    #[test]
    fn evaluate_7_does_not_depend_on_card_order() {
        let hand = hand7("As Ah Kd Kc 7s 7d 2c");
        let expected = score_7_reference(hand);
        let mut rotated = hand;
        for _ in 0..7 {
            rotated.rotate_left(1);
            assert_eq!(score_7(rotated), expected);
            let mut swapped = rotated;
            swapped.swap(0, 4);
            assert_eq!(score_7(swapped), expected);
        }
    }

    /// All 133,784,560 hands; about a minute of CPU time. Run with
    /// `cargo test --release evaluate_7_matches_best_of_21_for_every_hand -- --ignored`.
    #[test]
    #[ignore = "exhaustive: about a minute of CPU time"]
    fn evaluate_7_matches_best_of_21_for_every_hand() {
        use rayon::prelude::*;
        let hands: u64 = (0u8..46)
            .into_par_iter()
            .map(|offset| {
                let mut hands = 0u64;
                for_each_7_card_hand(52, offset, |hand| {
                    assert_eq!(score_7(hand), score_7_reference(hand), "{hand:?}");
                    hands += 1;
                });
                hands
            })
            .sum();
        assert_eq!(hands, 133_784_560);
    }

    #[test]
    fn categorizes_each_hand_type() {
        assert_eq!(
            evaluate_5(hand5("As Ks Qs Js Ts")).category(),
            HandCategory::StraightFlush
        );
        assert_eq!(
            evaluate_5(hand5("5s 4s 3s 2s As")).category(),
            HandCategory::StraightFlush
        ); // wheel
        assert_eq!(
            evaluate_5(hand5("Ah Ad As Ac Kh")).category(),
            HandCategory::FourOfAKind
        );
        assert_eq!(
            evaluate_5(hand5("Ah Ad As Kh Kd")).category(),
            HandCategory::FullHouse
        );
        assert_eq!(
            evaluate_5(hand5("Ah 9h 7h 4h 2h")).category(),
            HandCategory::Flush
        );
        assert_eq!(
            evaluate_5(hand5("9h 8d 7s 6h 5c")).category(),
            HandCategory::Straight
        );
        assert_eq!(
            evaluate_5(hand5("Ah Ad As Kh Qd")).category(),
            HandCategory::ThreeOfAKind
        );
        assert_eq!(
            evaluate_5(hand5("Ah Ad Kh Kd Qc")).category(),
            HandCategory::TwoPair
        );
        assert_eq!(
            evaluate_5(hand5("Ah Ad Kh Qd Jc")).category(),
            HandCategory::Pair
        );
        assert_eq!(
            evaluate_5(hand5("Ah Kd Qh Jd 9c")).category(),
            HandCategory::HighCard
        );
    }

    #[test]
    fn wheel_straight_loses_to_six_high_straight() {
        let wheel = evaluate_5(hand5("5s 4s 3d 2c As"));
        let six_high = evaluate_5(hand5("6s 5d 4d 3c 2h"));
        assert!(six_high > wheel);
    }

    #[test]
    fn higher_trips_beats_lower_trips_in_full_house() {
        let aces_full = evaluate_5(hand5("Ah Ad As Kh Kd"));
        let kings_full = evaluate_5(hand5("Kh Kd Ks Ah Ad"));
        assert!(aces_full > kings_full);
    }

    #[test]
    fn flush_beats_straight_beats_trips() {
        let flush = evaluate_5(hand5("Ah 9h 7h 4h 2h"));
        let straight = evaluate_5(hand5("9h 8d 7s 6h 5c"));
        let trips = evaluate_5(hand5("Ah Ad As Kh Qd"));
        assert!(flush > straight);
        assert!(straight > trips);
    }

    #[test]
    fn evaluate_7_picks_best_two_pair_from_three_pairs() {
        // Board AA KK QQ, hole cards 2 3: best hand should be AAKKQ (top two pair), not AAQQ or KKQQ.
        let best = evaluate_7(hand7("2c 3d Ah Ad Kh Kd Qh"));
        let expected = evaluate_5(hand5("Ah Ad Kh Kd Qh"));
        assert_eq!(best, expected);
        assert_eq!(best.category(), HandCategory::TwoPair);
    }

    #[test]
    fn evaluate_7_finds_straight_using_board_and_hole_cards() {
        // Hole: 9h 8d, board: 7s 6h 5c 2d 2s -> best is 9-high straight.
        let best = evaluate_7(hand7("9h 8d 7s 6h 5c 2d 2s"));
        assert_eq!(best.category(), HandCategory::Straight);
        let expected = evaluate_5(hand5("9h 8d 7s 6h 5c"));
        assert_eq!(best, expected);
    }

    /// Cross-checks the table-driven `evaluate_5` against the original
    /// grouping-based `evaluate_5_reference` for every one of the
    /// C(52,5) = 2,598,960 possible 5-card hands — not just a handful of
    /// hand-picked examples.
    #[test]
    fn evaluate_5_matches_reference_for_every_possible_hand() {
        let mut checked = 0u64;
        for a in 0u8..52 {
            for b in (a + 1)..52 {
                for c in (b + 1)..52 {
                    for d in (c + 1)..52 {
                        for e in (d + 1)..52 {
                            let hand = [a, b, c, d, e].map(Card);
                            let fast = score_5(hand);
                            let reference = evaluate_5_reference(hand);
                            assert_eq!(fast, reference, "mismatch for hand {hand:?}");
                            checked += 1;
                        }
                    }
                }
            }
        }
        assert_eq!(checked, 2_598_960);
    }
}