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
use anyhow::{bail, Result};
#[cfg(feature = "netidx")]
use derive::FromValue;
#[cfg(feature = "netidx")]
use netidx_derive::Pack;
use serde::{Deserialize, Serialize};
use std::str::FromStr;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "juniper", derive(juniper::GraphQLEnum))]
#[cfg_attr(feature = "netidx", derive(Pack, FromValue))]
pub enum OptionType {
    #[serde(alias = "Call", alias = "call", alias = "CALL")]
    Call,
    #[serde(alias = "Put", alias = "put", alias = "PUT")]
    Put,
}

impl FromStr for OptionType {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "CALL" => Ok(Self::Call),
            "PUT" => Ok(Self::Put),
            _ => Err(anyhow::anyhow!("invalid format: {s}")),
        }
    }
}

impl OptionType {
    pub fn flip(&self) -> Self {
        match self {
            Self::Call => Self::Put,
            Self::Put => Self::Call,
        }
    }

    pub fn to_char(&self) -> char {
        match self {
            Self::Call => 'C',
            Self::Put => 'P',
        }
    }

    pub fn from_char(c: char) -> Result<Self> {
        match c {
            'C' => Ok(Self::Call),
            'P' => Ok(Self::Put),
            _ => bail!("invalid option char: {}", c),
        }
    }

    pub fn to_str_uppercase(&self) -> &'static str {
        match self {
            Self::Call => "CALL",
            Self::Put => "PUT",
        }
    }

    pub fn from_str_uppercase(s: &str) -> Result<Self> {
        match s {
            "CALL" => Ok(Self::Call),
            "PUT" => Ok(Self::Put),
            _ => bail!("invalid format: {}", s),
        }
    }

    pub fn to_str_lowercase(&self) -> &'static str {
        match self {
            Self::Call => "call",
            Self::Put => "put",
        }
    }

    pub fn from_str_lowercase(s: &str) -> Result<Self> {
        match s {
            "call" => Ok(Self::Call),
            "put" => Ok(Self::Put),
            _ => bail!("invalid format: {}", s),
        }
    }
}