Skip to main content

ctrader_connector/common/
ids.rs

1//! Typed identifiers.
2//!
3//! Each kind of identifier is its own type, so an order id cannot be passed where a position id
4//! is expected. The server numbers entities from one; zero and negative values are rejected.
5
6use std::fmt;
7use std::str::FromStr;
8
9use crate::common::errors::ValueError;
10
11macro_rules! id {
12    ($(#[$doc:meta])* $name:ident, $kind:literal) => {
13        $(#[$doc])*
14        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
15        pub struct $name(i64);
16
17        impl $name {
18            /// Wraps a value received from or sent to the server.
19            ///
20            /// # Errors
21            ///
22            /// Returns [`ValueError::InvalidId`] when the value is zero or negative.
23            pub fn new(value: i64) -> Result<Self, ValueError> {
24                if value > 0 {
25                    Ok(Self(value))
26                } else {
27                    Err(ValueError::InvalidId {
28                        kind: $kind,
29                        value: value.to_string(),
30                    })
31                }
32            }
33
34            /// Returns the value as the wire carries it.
35            #[must_use]
36            pub const fn get(self) -> i64 {
37                self.0
38            }
39        }
40
41        impl TryFrom<i64> for $name {
42            type Error = ValueError;
43
44            fn try_from(value: i64) -> Result<Self, Self::Error> {
45                Self::new(value)
46            }
47        }
48
49        impl From<$name> for i64 {
50            fn from(id: $name) -> Self {
51                id.0
52            }
53        }
54
55        impl FromStr for $name {
56            type Err = ValueError;
57
58            fn from_str(text: &str) -> Result<Self, Self::Err> {
59                let invalid = || ValueError::InvalidId {
60                    kind: $kind,
61                    value: text.to_owned(),
62                };
63                Self::new(text.parse().map_err(|_| invalid())?).map_err(|_| invalid())
64            }
65        }
66
67        impl fmt::Display for $name {
68            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69                self.0.fmt(f)
70            }
71        }
72    };
73}
74
75id!(
76    /// Identifier of a trading account.
77    AccountId,
78    "account id"
79);
80id!(
81    /// Identifier of a tradable symbol.
82    SymbolId,
83    "symbol id"
84);
85id!(
86    /// Identifier of an order.
87    OrderId,
88    "order id"
89);
90id!(
91    /// Identifier of a position.
92    PositionId,
93    "position id"
94);
95id!(
96    /// Identifier of a deal.
97    DealId,
98    "deal id"
99);
100id!(
101    /// Identifier of a change in the history of the balance of an account.
102    CashFlowId,
103    "cash flow id"
104);
105
106id!(
107    /// Identifier of an asset, such as a currency.
108    AssetId,
109    "asset id"
110);
111id!(
112    /// Identifier of a category of symbols.
113    SymbolCategoryId,
114    "symbol category id"
115);
116
117#[cfg(test)]
118mod tests {
119    use std::collections::HashSet;
120
121    use super::{
122        AccountId, AssetId, CashFlowId, DealId, OrderId, PositionId, SymbolCategoryId, SymbolId,
123    };
124    use crate::common::errors::ValueError;
125
126    macro_rules! id_tests {
127        ($($module:ident: $name:ident, $kind:literal;)*) => {$(
128            mod $module {
129                use super::*;
130
131                fn invalid(value: &str) -> ValueError {
132                    ValueError::InvalidId {
133                        kind: $kind,
134                        value: value.to_owned(),
135                    }
136                }
137
138                #[test]
139                fn positive_values_round_trip() -> Result<(), ValueError> {
140                    for value in [1, 42, i64::MAX] {
141                        let id = $name::new(value)?;
142                        assert_eq!(id.get(), value);
143                        assert_eq!(i64::from(id), value);
144                        assert_eq!($name::try_from(value), Ok(id));
145                        assert_eq!(id.to_string(), value.to_string());
146                        assert_eq!(id.to_string().parse(), Ok(id));
147                    }
148                    Ok(())
149                }
150
151                #[test]
152                fn zero_and_negative_values_are_rejected() {
153                    for value in [0, -1, i64::MIN] {
154                        let text = value.to_string();
155                        assert_eq!($name::new(value), Err(invalid(&text)));
156                        assert_eq!($name::try_from(value), Err(invalid(&text)));
157                        assert_eq!(text.parse::<$name>(), Err(invalid(&text)));
158                    }
159                }
160
161                #[test]
162                fn text_that_is_not_a_number_is_rejected() {
163                    for text in ["", " 7", "7.0", "seven", "9223372036854775808"] {
164                        assert_eq!(text.parse::<$name>(), Err(invalid(text)));
165                    }
166                }
167
168                #[test]
169                fn rejection_names_the_kind() {
170                    assert_eq!(
171                        invalid("0").to_string(),
172                        concat!($kind, " must be a positive integer, got 0")
173                    );
174                }
175
176                #[test]
177                fn ids_order_and_hash_by_value() -> Result<(), ValueError> {
178                    let low = $name::new(1)?;
179                    let high = $name::new(2)?;
180                    assert!(low < high);
181                    let set: HashSet<_> = [low, high, low].into_iter().collect();
182                    assert_eq!(set.len(), 2);
183                    Ok(())
184                }
185            }
186        )*};
187    }
188
189    id_tests! {
190        account: AccountId, "account id";
191        symbol: SymbolId, "symbol id";
192        order: OrderId, "order id";
193        position: PositionId, "position id";
194        deal: DealId, "deal id";
195        cash_flow: CashFlowId, "cash flow id";
196        asset: AssetId, "asset id";
197        symbol_category: SymbolCategoryId, "symbol category id";
198    }
199}