Skip to main content

bybit/
util.rs

1use std::collections::BTreeMap;
2use std::time::{SystemTime, UNIX_EPOCH};
3
4pub fn build_query(parameters: BTreeMap<String, String>) -> String {
5  let mut request = String::new();
6  for (key, value) in parameters {
7    let param = format!("{}={}&", key, value);
8    request.push_str(param.as_ref());
9  }
10  request.pop();
11  request
12}
13
14pub fn get_timestamp(time: SystemTime) -> u64 {
15  time
16    .duration_since(UNIX_EPOCH)
17    .expect("Time went backwards")
18    .as_millis() as u64
19}
20
21pub fn is_start_time_valid(start_time: &u64) -> bool {
22  let current_time = SystemTime::now()
23    .duration_since(UNIX_EPOCH)
24    .unwrap()
25    .as_secs();
26
27  start_time <= &current_time
28}
29
30pub fn vec_to_string_array(vector: Vec<String>) -> String {
31  format!(
32    "[{}]",
33    vector
34      .iter()
35      .map(|s| format!("\"{}\"", s))
36      .collect::<Vec<_>>()
37      .join(",")
38  )
39}
40
41pub fn vec_to_string(vector: Vec<String>) -> String {
42  format!(
43    "{}",
44    vector
45      .iter()
46      .map(|s| format!("{}", s))
47      .collect::<Vec<_>>()
48      .join(",")
49  )
50}
51
52#[macro_export]
53macro_rules! create_enum_with_fmt {
54  // We handle the first variant separately, then the remaining variants in a list.
55  // This way, we can easily assign the first variant as the enum's default.
56  (
57    $name:ident, {
58      $first_variant:ident => $first_display:expr
59      $(, $variant:ident => $display:expr)* $(,)?
60    }
61  ) => {
62    #[derive(Serialize, Deserialize, Debug, Clone, Copy, Default)]
63    pub enum $name {
64      #[default]
65      $first_variant,
66      $($variant),*
67    }
68
69    impl $name {
70      /// Convert a 1-based index to the corresponding variant.
71      /// Returns `None` if index is out of range.
72      pub fn from_int(value: i32) -> Option<Self> {
73        // Check the first variant
74        let mut index = 1;
75        if index == 1 {
76          return Some($name::$first_variant);
77        }
78        // Start indexing for the rest of the variants at 2
79        $(
80        index += 1;
81        if value == index {
82          return Some($name::$variant);
83        }
84        )*
85        None
86      }
87    }
88
89    impl std::fmt::Display for $name {
90      fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        match self {
92          $name::$first_variant => write!(f, "{}", $first_display),
93          $(
94          $name::$variant => write!(f, "{}", $display),
95          )*
96        }
97      }
98    }
99
100    impl $name {
101      pub fn as_str(&self) -> &str {
102        match self {
103          $name::$first_variant => $first_display,
104          $(
105          $name::$variant => $display,
106          )*
107        }
108      }
109    }
110  }
111}