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
//! This module represents a basic, rule-agnostic 32-cards system.

extern crate rand;

use self::rand::{thread_rng,Rng};
use std::num::Wrapping;
use std::string::ToString;
use rustc_serialize;

/// One of the four Suits: Heart, Spade, Diamond, Club
#[derive(PartialEq,Clone,Copy)]
pub struct Suit(pub u32);

/// The Heart suit
pub const HEART: Suit = Suit(1 << 0);
/// The Spade suit
pub const SPADE: Suit = Suit(1 << 8);
/// The Diamond suit
pub const DIAMOND: Suit = Suit(1 << 16);
/// The Club suit
pub const CLUB: Suit = Suit(1 << 24);


impl rustc_serialize::Encodable for Suit {
    fn encode<S: rustc_serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        match *self {
            HEART | SPADE | DIAMOND | CLUB => self.0.encode(s),
            _ => "??".encode(s),
        }
    }
}

impl Suit {
    /// Returns the suit corresponding to the number:
    ///
    /// * `0`: Heart
    /// * `1`: Spade
    /// * `2`: Diamond
    /// * `3`: Club
    /// * `>=4`: panics
    pub fn from_n(n: u32) -> Self {
        if n >= 4 { panic!("Bad suit number"); }
        Suit(1 << 8*n)
    }

    /// Returns a UTF-8 character representing the suit.
    pub fn to_string(self) -> String {
        match self {
            HEART => "",
            SPADE => "",
            DIAMOND => "",
            CLUB => "",
            _ => "?",
        }.to_string()
    }
}


/// Rank of a card in a suit
#[derive(PartialEq,Clone,Copy)]
pub struct Rank(pub u32);
/// 7
pub const RANK_7: Rank = Rank(1 << 0);
/// 8
pub const RANK_8: Rank = Rank(1 << 1);
/// 9
pub const RANK_9: Rank = Rank(1 << 2);
/// Jack
pub const RANK_J: Rank = Rank(1 << 3);
/// Queen
pub const RANK_Q: Rank = Rank(1 << 4);
/// King
pub const RANK_K: Rank = Rank(1 << 5);
/// 10
pub const RANK_X: Rank = Rank(1 << 6);
/// Ace
pub const RANK_A: Rank = Rank(1 << 7);
/// Bit mask over all ranks
pub const RANK_MASK: Rank = Rank(255);

impl Rank {

    /// Returns the rank corresponding to the given number:
    /// * `0`: 7
    /// * `1`: 8
    /// * `2`: 9
    /// * `3`: J
    /// * `4`: Q
    /// * `5`: K
    /// * `6`: X
    /// * `7`: A
    /// * `>=8`: panics
    pub fn from_n(n: u32) -> Self {
        if n >= 8 { panic!("Invalid rank number: {}", n); }
        Rank(1 << n)
    }

    /// Returns a character representing the given rank
    pub fn to_string(self) -> String {
        match self {
            RANK_7 => "7",
            RANK_8 => "8",
            RANK_9 => "9",
            RANK_J => "J",
            RANK_Q => "Q",
            RANK_K => "K",
            RANK_X => "X",
            RANK_A => "A",
            _ => "?",
        }.to_string()
    }
}

/// Represents a single card
#[derive(PartialEq,Clone,Copy)]
pub struct Card(pub u32);

impl rustc_serialize::Encodable for Card {
    fn encode<S: rustc_serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        self.0.encode(s)
    }
}


impl Card {
    /// Returns the card number (from 0 to 31)
    pub fn id(self) -> u32 {
        let mut i = 0;
        let Card(mut v) = self;
        while v != 0 {
            i+=1;
            v = v>>1;
        }

        i-1
    }

    /// Returns the card corresponding to the given number
    pub fn from_id(id: u32) -> Self {
        if id > 31 { panic!("invalid card id"); }
        Card(1 << id)
    }

    /// Returns the card's rank
    pub fn rank(self) -> Rank {
        let Card(mut v) = self;
        let mut r: u32 = 0;
        let Rank(mask) = RANK_MASK;

        r |= mask & v;
        v = v >> 8;
        r |= mask & v;
        v = v >> 8;
        r |= mask & v;
        v = v >> 8;
        r |= v;

        Rank(r)
    }

    /// Returns the card's suit
    pub fn suit(self) -> Suit {
        let Card(v) = self;
        let Rank(r) = self.rank();
        Suit(v / r)
    }

    /// Returns a string representation of the card
    pub fn to_string(self) -> String {
        let r = self.rank();
        let s = self.suit();
        r.to_string() + &s.to_string()
    }

    /// Creates a card from the given suit and rank
    pub fn new(suit: Suit, rank: Rank) -> Self {
        let Suit(s) = suit;
        let Rank(r) = rank;

        Card(s * r)
    }
}


#[test]
fn card_test() {
    for i in 0..32 {
        let card = Card::from_id(i);
        assert!(i == card.id());
    }

    for s in 0..4 {
        let suit = Suit::from_n(s);
        for r in 0..8 {
            let rank = Rank::from_n(r);
            let card = Card::new(suit, rank);
            assert!(card.rank() == rank);
            assert!(card.suit() == suit);
        }
    }
}

/// Represents an unordered set of cards
#[derive(PartialEq,Clone,Copy)]
pub struct Hand(pub u32);

impl rustc_serialize::Encodable for Hand {
    fn encode<S: rustc_serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        self.0.encode(s)
    }
}

impl Hand {
    /// Returns an empty hand.
    pub fn new() -> Self {
        Hand(0)
    }

    /// Add `card` to `self`.
    ///
    /// No effect if `self` already contains `card`.
    pub fn add(&mut self, card: Card) -> &mut Hand {
        self.0 |= card.0;
        self
    }

    /// Removes `card` from `self`.
    ///
    /// No effect if `self` does not contains `card`.
    pub fn remove(&mut self, card: Card) {
        self.0 &= !card.0;
    }

    /// Remove all cards from `self`.
    pub fn clean(&mut self) {
        *self = Hand::new();
    }

    /// Returns `true` if `self` contains `card`.
    pub fn has(self, card: Card) -> bool {
        (self.0 & card.0) != 0
    }

    /// Returns `true` if the hand contains any card of the given suit.
    pub fn has_any(self, suit: Suit) -> bool {
        (self.0 & (RANK_MASK.0 * suit.0)) != 0
    }

    /// Returns `true` if `self` contains no card.
    pub fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Returns a card from `self`.
    ///
    /// Returns an invalid card if `self` is empty.
    pub fn get_card(self) -> Card {
        if self.is_empty() {
            return Card(0);
        }

        let Hand(h) = self;
        // Finds the rightmost bit, shifted to the left by 1.
        // let n = 1 << (h.trailing_zeroes());
        let n = Wrapping(h ^ (h - 1)) + Wrapping(1);
        if n.0 == 0 {
            // We got an overflow. This means the desired bit it the leftmost one.
            Card::from_id(31)
        } else {
            // We just need to shift it back.
            Card(n.0 >> 1)
        }
    }

    /// Returns the cards contained in `self` as a `Vec`.
    pub fn list(self) -> Vec<Card> {
        let mut cards = Vec::new();
        let mut h = self;

        while !h.is_empty() {
            let c = h.get_card();
            h.remove(c);
            cards.push(c);
        }

        cards
    }

    /// Returns the number of cards in `self`.
    pub fn size(self) -> usize {
        self.list().len()
    }
}

impl ToString for Hand {
    /// Returns a string representation of `self`.
    fn to_string(&self) -> String {
        let mut s = "[".to_string();

        for c in (*self).list().iter() {
            s = s + &c.to_string();
            s = s +",";
        }

        s + "]"
    }
}

#[test]
fn hand_test() {
    let mut hand = Hand::new();

    let cards: Vec<Card> = vec![
        Card::new(HEART, RANK_7),
        Card::new(HEART, RANK_8),
        Card::new(SPADE, RANK_9),
        Card::new(SPADE, RANK_J),
        Card::new(CLUB, RANK_Q),
        Card::new(CLUB, RANK_K),
        Card::new(DIAMOND, RANK_X),
        Card::new(DIAMOND, RANK_A),
    ];

    assert!(hand.is_empty());

    for card in cards.iter() {
        assert!(!hand.has(*card));
        hand.add(*card);
        assert!(hand.has(*card));
    }

    assert!(hand.size() == cards.len());

    for card in cards.iter() {
        assert!(hand.has(*card));
        hand.remove(*card);
        assert!(!hand.has(*card));
    }
}

/// A deck of cards.
pub struct Deck{
    cards: Vec<Card>,
}


impl Deck {
    /// Returns a full, sorted deck of 32 cards.
    pub fn new() -> Self {
        let mut d = Deck{cards:Vec::with_capacity(32)};

        for i in 0..32 {
            d.cards.push(Card::from_id(i));
        }

        d
    }

    /// Shuffle this deck.
    pub fn shuffle(&mut self) {
        thread_rng().shuffle(&mut self.cards[..]);
    }

    /// Draw the top card from the deck.
    ///
    /// # Panics
    /// If `self` is empty.
    pub fn draw(&mut self) -> Card {
        self.cards.pop().expect("deck is empty")
    }

    /// Returns `true` if this deck is empty.
    pub fn is_empty(&self) -> bool {
        self.cards.is_empty()
    }

    /// Returns the number of cards left in this deck.
    pub fn len(&self) -> usize {
        self.cards.len()
    }

    /// Deal `n` cards to each hand.
    ///
    /// # Panics
    /// If `self.len() < 4 * n`
    pub fn deal_each(&mut self, hands: &mut [Hand; 4], n: usize) {
        if self.len() < 4*n {
            panic!("Deck has too few cards!");
        }

        for hand in hands.iter_mut() {
            for _ in 0..n {
                hand.add(self.draw());
            }
        }
    }
}

impl ToString for Deck {
    fn to_string(&self) -> String {
        let mut s = "[".to_string();

        for c in self.cards.iter() {
            s = s + &c.to_string();
            s = s +",";
        }

        s + "]"
    }
}

#[test]
fn test_deck() {
    let mut deck = Deck::new();
    deck.shuffle();

    assert!(deck.len() == 32);

    let mut count = [0; 32];
    while !deck.is_empty() {
        let card = deck.draw();
        count[card.id() as usize] += 1;
    }

    for c in count.iter() {
        assert!(*c == 1);
    }
}