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
use std::iter::repeat_with;
use std::ops::{Index, IndexMut};

use enum_map::Enum as _;
use itertools::izip;

use crate::enums::EnumSequence as _;
use crate::zones::tableau;

pub trait Deal {
    type Index;
    type Iter: Iterator<Item = Self::Index>;

    fn deal(self) -> Self::Iter;
}

pub trait Dealable {
    type Item;
    type Iter: Iterator<Item = Self::Item>;

    fn deal_out<D, T>(self, deal: D, piles: &mut T) -> Self::Iter
    where
        D: Deal,
        T: Index<D::Index> + IndexMut<D::Index>,
        T::Output: Extend<Self::Item>;
}

impl<I> Dealable for I
where
    I: IntoIterator,
{
    type Item = I::Item;
    type Iter = I::IntoIter;

    fn deal_out<D, T>(self, deal: D, piles: &mut T) -> Self::Iter
    where
        D: Deal,
        T: Index<D::Index> + IndexMut<D::Index>,
        T::Output: Extend<Self::Item>,
    {
        let mut iter = self.into_iter();

        // We zip with the Id first, because zip will poll each iterator in sequence and stop early
        // if one is empty. If we polled iter first we'd drop an item at the end.
        for (id, card) in izip!(deal.deal(), &mut iter) {
            piles[id].extend_one(card);
        }

        iter
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Tableau;

impl Deal for Tableau {
    type Index = tableau::Index;
    type Iter = impl Iterator<Item = tableau::Index>;

    fn deal(self) -> Self::Iter {
        repeat_with(tableau::Index::values_iter)
            .take(tableau::Index::LENGTH)
            .enumerate()
            .flat_map(|(offset, values_iter)| values_iter.skip(offset))
    }
}