rusty_common/strings.rs
1//! SmartString type aliases for memory efficiency
2//!
3//! This module provides optimized SmartString types for common use cases in HFT systems.
4//! SmartString is used for strings that are typically less than 24 bytes, which includes
5//! most symbols, exchange names, currency codes, and other short identifiers.
6
7pub use smartstring::alias::String as SmartString;
8use std::fmt::{self, Write};
9
10/// Safe formatting into SmartString for HFT systems
11///
12/// This function formats arguments into a SmartString, returning a static
13/// error message on formatting failure instead of panicking. This is critical
14/// for HFT systems where panics are unacceptable.
15///
16/// # Examples
17/// ```
18/// let msg = safe_format(format_args!("Error: {}", "connection failed"));
19/// ```
20#[inline]
21pub fn safe_format(args: fmt::Arguments) -> SmartString {
22 let mut s = SmartString::new();
23 match write!(s, "{args}") {
24 Ok(_) => s,
25 Err(_) => SmartString::from("<formatting error>"),
26 }
27}
28
29/// Exchange name (e.g., "binance", "coinbase")
30pub type ExchangeName = SmartString;
31
32/// Currency code (e.g., "USD", "EUR", "KRW")
33pub type CurrencyCode = SmartString;
34
35/// Order ID (typically short identifiers or UUIDs)
36pub type OrderId = SmartString;
37
38/// Client order ID
39pub type ClientOrderId = SmartString;
40
41/// Trade ID
42pub type TradeId = SmartString;
43
44/// Account ID
45pub type AccountId = SmartString;
46
47/// API key identifier
48pub type ApiKey = SmartString;
49
50/// Short message or status
51pub type StatusMessage = SmartString;
52
53/// Create an ExchangeName from a string slice
54#[inline]
55pub fn exchange_name(s: &str) -> ExchangeName {
56 s.into()
57}
58
59/// Create a CurrencyCode from a string slice
60#[inline]
61#[must_use]
62pub fn currency_code(s: &str) -> CurrencyCode {
63 s.into()
64}
65
66/// Create an OrderId from a string slice
67#[inline]
68pub fn order_id(s: &str) -> OrderId {
69 s.into()
70}
71
72/// Safe formatting macro that returns a SmartString
73///
74/// This macro is like format! but returns a SmartString and never panics.
75/// On formatting failure, it returns "<formatting error>".
76///
77/// # Examples
78/// ```
79/// let msg = safe_format!("Error code: {}", 42);
80/// let err = safe_format!("Failed to connect: {}", e);
81/// ```
82#[macro_export]
83macro_rules! safe_format {
84 ($($arg:tt)*) => {
85 $crate::strings::safe_format(format_args!($($arg)*))
86 };
87}