pragma_common/
instrument_type.rs1use 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
47impl Display for InstrumentType {
48 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49 match self {
50 Self::Spot => write!(f, "spot"),
51 Self::Perp => write!(f, "perp"),
52 }
53 }
54}
55
56impl TryFrom<i32> for InstrumentType {
57 type Error = InstrumentTypeError;
58 fn try_from(value: i32) -> Result<Self, Self::Error> {
59 match value {
60 1 => Ok(Self::Spot),
61 2 => Ok(Self::Perp),
62 _ => Err(InstrumentTypeError::Unknown),
63 }
64 }
65}
66
67impl FromStr for InstrumentType {
68 type Err = InstrumentTypeError;
69
70 fn from_str(s: &str) -> Result<Self, Self::Err> {
71 match s {
72 "spot" => Ok(Self::Spot),
73 "perp" => Ok(Self::Perp),
74 _ => Err(InstrumentTypeError::Unknown),
75 }
76 }
77}