summaryrefslogtreecommitdiff
path: root/protocol/src/actions.rs
blob: defe1f98c5f13114d41fcc331ce1b82f6c145823 (plain)
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 core::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

use crate::contract::LevelAndSuit;

#[derive(PartialEq, Eq, Clone, Copy, Serialize, Deserialize)]
pub enum Bid {
    Pass,
    Double,
    Redouble,
    Raise(LevelAndSuit),
}

impl Bid {
    pub fn as_raise(&self) -> Option<LevelAndSuit> {
        match self {
            Bid::Raise(raise) => Some(*raise),
            _ => None,
        }
    }
}

impl fmt::Display for Bid {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Bid::Pass => write!(f, "Pass"),
            Bid::Double => write!(f, "Double"),
            Bid::Redouble => write!(f, "Redouble"),
            Bid::Raise(x) => write!(f, "{}", x),
        }
    }
}

impl fmt::Debug for Bid {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter<'_>,
    ) -> std::result::Result<(), std::fmt::Error> {
        match self {
            Bid::Pass => write!(f, "Pass"),
            Bid::Double => write!(f, "Double"),
            Bid::Redouble => write!(f, "Redouble"),
            Bid::Raise(x) => write!(f, "Raise({})", x),
        }
    }
}

impl FromStr for Bid {
    type Err = anyhow::Error;
    fn from_str(
        s: &str,
    ) -> std::result::Result<Self, <Self as std::str::FromStr>::Err> {
        match s.trim().to_ascii_lowercase().as_str() {
            "pass" => Ok(Bid::Pass),
            "double" => Ok(Bid::Double),
            "redouble" => Ok(Bid::Redouble),
            x => Ok(Bid::Raise(x.parse()?)),
        }
    }
}