1
// This file is part of hnefatafl-copenhagen.
2
//
3
// hnefatafl-copenhagen is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU Affero General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// hnefatafl-copenhagen is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU Affero General Public License for more details.
12
//
13
// You should have received a copy of the GNU Affero General Public License
14
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
15

            
16
use std::{fmt, str::FromStr};
17

            
18
use serde::{Deserialize, Serialize};
19

            
20
#[derive(
21
    Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize,
22
)]
23
pub enum Role {
24
    #[default]
25
    Attacker,
26
    Defender,
27
    Roleless,
28
}
29

            
30
impl Role {
31
    #[must_use]
32
51819242
    pub fn opposite(&self) -> Self {
33
51819242
        match self {
34
35518320
            Self::Attacker => Self::Defender,
35
16300922
            Self::Defender => Self::Attacker,
36
            Self::Roleless => Self::Roleless,
37
        }
38
51819242
    }
39
}
40

            
41
impl fmt::Display for Role {
42
48
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43
48
        match self {
44
24
            Role::Attacker => write!(f, "attacker"),
45
24
            Role::Defender => write!(f, "defender"),
46
            Role::Roleless => write!(f, "roleless"),
47
        }
48
48
    }
49
}
50

            
51
impl FromStr for Role {
52
    type Err = anyhow::Error;
53

            
54
876
    fn from_str(string: &str) -> anyhow::Result<Self> {
55
876
        let string = string.to_lowercase();
56

            
57
876
        match string.as_str() {
58
876
            "a" | "attacker" => Ok(Self::Attacker),
59
480
            "d" | "defender" => Ok(Self::Defender),
60
            _ => Err(anyhow::Error::msg(format!(
61
                "Error trying to convert '{string}' to a Role!"
62
            ))),
63
        }
64
876
    }
65
}