pragma_common/
instrument_type.rs

1use std::{fmt::Display, str::FromStr};
2
3#[derive(Debug, thiserror::Error)]
4pub enum InstrumentTypeError {
5    #[error("Unknown instrument_type")]
6    Unknown,
7}
8
9#[derive(Debug, Default, PartialEq, Eq, Hash, Clone, Copy)]
10#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize,))]
11#[cfg_attr(
12    feature = "borsh",
13    derive(borsh::BorshSerialize, borsh::BorshDeserialize)
14)]
15#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
16pub enum InstrumentType {
17    #[default]
18    Spot,
19    Perp,
20}
21
22impl InstrumentType {
23    pub const ALL: [Self; 2] = [Self::Spot, Self::Perp];
24
25    pub const fn to_id(&self) -> i32 {
26        match self {
27            Self::Spot => 1,
28            Self::Perp => 2,
29        }
30    }
31
32    pub const fn is_spot(&self) -> bool {
33        match self {
34            Self::Spot => true,
35            Self::Perp => false,
36        }
37    }
38
39    pub const fn is_perp(&self) -> bool {
40        match self {
41            Self::Spot => false,
42            Self::Perp => true,
43        }
44    }
45
46    pub const fn from_str_const(s: &str) -> Option<Self> {
47        match s.as_bytes() {
48            b"spot" | b"SPOT" | b"Spot" => Some(Self::Spot),
49            b"perp" | b"PERP" | b"Perp" => Some(Self::Perp),
50            _ => None,
51        }
52    }
53}
54
55impl Display for InstrumentType {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        match self {
58            Self::Spot => write!(f, "spot"),
59            Self::Perp => write!(f, "perp"),
60        }
61    }
62}
63
64impl TryFrom<i32> for InstrumentType {
65    type Error = InstrumentTypeError;
66    fn try_from(value: i32) -> Result<Self, Self::Error> {
67        match value {
68            1 => Ok(Self::Spot),
69            2 => Ok(Self::Perp),
70            _ => Err(InstrumentTypeError::Unknown),
71        }
72    }
73}
74
75impl FromStr for InstrumentType {
76    type Err = InstrumentTypeError;
77
78    fn from_str(s: &str) -> Result<Self, Self::Err> {
79        match s {
80            "spot" => Ok(Self::Spot),
81            "perp" => Ok(Self::Perp),
82            _ => Err(InstrumentTypeError::Unknown),
83        }
84    }
85}