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(feature = "utoipa", derive(utoipa::ToSchema))]
12pub enum InstrumentType {
13    #[default]
14    Spot,
15    Perp,
16}
17
18impl InstrumentType {
19    pub const ALL: [Self; 2] = [Self::Spot, Self::Perp];
20
21    pub const fn to_id(&self) -> i32 {
22        match self {
23            Self::Spot => 1,
24            Self::Perp => 2,
25        }
26    }
27
28    pub const fn is_spot(&self) -> bool {
29        match self {
30            Self::Spot => true,
31            Self::Perp => false,
32        }
33    }
34
35    pub const fn is_perp(&self) -> bool {
36        match self {
37            Self::Spot => false,
38            Self::Perp => true,
39        }
40    }
41}
42
43impl Display for InstrumentType {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            Self::Spot => write!(f, "spot"),
47            Self::Perp => write!(f, "perp"),
48        }
49    }
50}
51
52impl TryFrom<i32> for InstrumentType {
53    type Error = InstrumentTypeError;
54    fn try_from(value: i32) -> Result<Self, Self::Error> {
55        match value {
56            1 => Ok(Self::Spot),
57            2 => Ok(Self::Perp),
58            _ => Err(InstrumentTypeError::Unknown),
59        }
60    }
61}
62
63impl FromStr for InstrumentType {
64    type Err = InstrumentTypeError;
65
66    fn from_str(s: &str) -> Result<Self, Self::Err> {
67        match s {
68            "spot" => Ok(Self::Spot),
69            "perp" => Ok(Self::Perp),
70            _ => Err(InstrumentTypeError::Unknown),
71        }
72    }
73}