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
use core::fmt;
use std::cmp::Ordering;

use bincode::{Decode, Encode};
use serde::{Deserialize, Serialize};

#[derive(
    Default, Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Encode, Decode,
)]
pub enum Player {
    #[default]
    Player1,
    Player2,
    Player3,
    Player4,
}

impl Player {
    pub const MAX_PLAYERS: usize = 4;

    pub fn to_num(self) -> u8 {
        match self {
            Self::Player1 => 1,
            Self::Player2 => 2,
            Self::Player3 => 3,
            Self::Player4 => 4,
        }
    }

    fn next(self) -> Option<Self> {
        self.to_num()
            .checked_add(1)
            .and_then(|num| Self::try_from(num).ok())
    }
}

impl fmt::Display for Player {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "player {}", self.to_num())
    }
}

impl PartialOrd for Player {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Player {
    fn cmp(&self, other: &Self) -> Ordering {
        self.to_num().partial_cmp(&other.to_num()).unwrap()
    }
}

impl TryFrom<u8> for Player {
    type Error = String;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            1 => Ok(Player::Player1),
            2 => Ok(Player::Player2),
            3 => Ok(Player::Player3),
            4 => Ok(Player::Player4),
            value => Err(format!(
                "Player number must be between 1 and 4, got {value}."
            )),
        }
    }
}

pub struct PlayerRange {
    start: Player,
    stop: Player,
    current: Option<Player>,
}

impl PlayerRange {
    /// Returns inclusive player range from first player to `stop`.
    pub fn up_to(stop: Player) -> Self {
        Self::new(Player::Player1, stop)
    }

    /// # Arguments
    ///
    /// * `start` - first player, inclusive.
    ///
    /// * `stop` - last player, inclusive.
    pub fn new(start: Player, stop: Player) -> Self {
        assert!(start <= stop);
        Self {
            start,
            stop,
            current: Some(start),
        }
    }

    pub fn contains(&self, player: Player) -> bool {
        self.start <= player && player <= self.stop
    }
}

impl Iterator for PlayerRange {
    type Item = Player;

    fn next(&mut self) -> Option<Self::Item> {
        match self.current {
            Some(current) => {
                if current == self.stop {
                    self.current = None;
                } else {
                    self.current = current.next();
                }

                Some(current)
            }
            None => {
                self.current = Some(self.start);
                None
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let size = match self.current {
            Some(current) => 1 + (self.stop.to_num() - current.to_num()) as usize,
            None => 0,
        };
        (size, Some(size))
    }
}

impl ExactSizeIterator for PlayerRange {}

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

    #[test]
    fn test_range() {
        let mut range = PlayerRange::new(Player::Player2, Player::Player4);

        assert_eq!(range.next(), Some(Player::Player2));
        assert_eq!(range.next(), Some(Player::Player3));
        assert_eq!(range.next(), Some(Player::Player4));
        assert_eq!(range.next(), None);

        assert_eq!(range.next(), Some(Player::Player2));
        assert_eq!(range.next(), Some(Player::Player3));
        assert_eq!(range.next(), Some(Player::Player4));
        assert_eq!(range.next(), None);
    }

    #[test]
    fn test_range_up_to() {
        let mut range = PlayerRange::up_to(Player::Player3);
        assert_eq!(range.next(), Some(Player::Player1));
        assert_eq!(range.next(), Some(Player::Player2));
        assert_eq!(range.next(), Some(Player::Player3));
        assert_eq!(range.next(), None);
    }
}