1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
//! # StaticId
//!
//! This Rust library provides a cache-efficient implementation of `StaticId` for handling
//! interned identifiers with optimal performance.
//!
//! ## Features
//!
//! - `StaticId`: A highly optimized, interned identifier type combining a code and a venue, e.g., for financial products
//! - Exceptional cache efficiency: Each `StaticId` is represented by a single 64-bit pointer
//! - Fast comparisons: Equality checks and hashing operations only compare 8 bytes, regardless of the actual string length
//! - Lazy evaluation: The actual string data is only accessed during serialization
//! - Serialization and deserialization support using Serde
//!
//! ## How this works
//!
//! - **Compact Representation**: Each StaticId is stored as a single 64-bit pointer, regardless of
//! the length of the underlying strings. Duplicate values are not allocated in memory; instead,
//! the actual ID value exists in memory once, and each ID owns only a pointer to that memory location.
//! - **Fast Comparisons**: Equality checks and hash computations only compare the 64-bit pointers,
//! making these operations extremely fast and constant-time. Most operations after creation, such
//! as hashing and comparison, use only 8 bytes and are likely to be cache-efficient.
//! - **Lazy Evaluation**: The actual string data is only accessed when necessary (e.g., during
//! serialization or debugging), minimizing unnecessary memory access. Users should be aware that
//! these operations might be slower as they may require accessing the actual value from memory.
//! - **Creation Overhead**: To ensure uniqueness, there's a slight overhead during initial creation
//! (approximately 15 ns per object creation). This trade-off allows for significant performance
//! gains in subsequent operations.
//! - **Input Constraints**: For clarity and efficiency, the input values are limited: 'code' is
//! restricted to 32 characters, and 'venue' to 16 characters.
//!
//! ## Limitations
//!
//! - The `code` component of a `StaticId` cannot exceed 32 bytes.
//! - The `venue` component of a `StaticId` cannot exceed 16 bytes.
//! - Attempting to create a `StaticId` with components exceeding these limits will result in truncation.
//! - Accessing the data (e.g., during serialization or debugging) may be slow.
//!
//! ## Usage
//!
//! `StaticId` combines a `Code` (up to 32 bytes) and a `Venue` (up to 16 bytes) into an interned identifier:
//!
//! ```rust
//! use static_id::StaticId;
//!
//! // Create from string slices
//! let id = StaticId::from_str("AAPL", "NASDAQ");
//!
//! // Create from byte slices
//! let id_bytes = StaticId::from_bytes(b"AAPL", b"NASDAQ");
//!
//! assert_eq!(id.get_id().code.as_str(), "AAPL");
//! assert_eq!(id.get_id().venue.as_str(), "NASDAQ");
//!
//! // Get the length of the combined code and venue
//! println!("Length: {}", id.len()); // Outputs the sum of code and venue lengths
//!
//! // Get the number of unique StaticIds in the cache
//! println!("Cache size: {}", StaticId::cache_len());
//!
//! // Fast equality check (compares only 8 bytes)
//! let id2 = StaticId::from_str("AAPL", "NASDAQ");
//! assert_eq!(id, id2);
//!
//! println!("ID: {}", id); // => APPL@NASDAQ
//!
//! // Memory usage
//! println!("Size of StaticId: {} bytes", std::mem::size_of::<StaticId>()); // Outputs: 8 bytes
//! ```
//!
//! ## License
//!
//! This project is licensed under [LICENSE NAME] - see the [LICENSE.md](LICENSE.md) file for details.
//!
//! ## Contributing
//!
//! Contributions are welcome! Please feel free to submit a Pull Request.
pub mod symbol;
use once_cell::sync::Lazy;
use rustc_hash::FxHashMap;
use std::{
hash::Hash,
hash::Hasher,
ptr::eq as ptr_eq
};
use std::sync::Mutex;
use serde::{Serialize, Deserialize};
//use dashmap::{
// DashMap,
// mapref::entry::Entry as DashEntry,
//};
pub use symbol::Symbol;
pub type Code = Symbol<32>;
pub type Venue = Symbol<16>;
#[derive(PartialEq, Eq, Hash, Clone, Serialize, Deserialize, Debug, Default)]
pub struct IdCore {
pub code: Code,
pub venue: Venue,
}
#[derive(Debug, Clone, Copy)]
pub struct StaticId {
id_ptr: &'static IdCore,
}
impl Default for StaticId {
fn default() -> Self {
*DEFAULT_ID
}
}
impl std::fmt::Display for StaticId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}@{}", self.id_ptr.code, self.id_ptr.venue)
}
}
impl PartialEq for StaticId {
fn eq(&self, other: &Self) -> bool {
ptr_eq(self.id_ptr, other.id_ptr)
}
}
impl Eq for StaticId {}
impl Hash for StaticId {
fn hash<H: Hasher>(&self, state: &mut H) {
self.id_ptr.hash(state);
}
}
static ID_CACHE: Lazy<Mutex<FxHashMap<IdCore, &'static IdCore>>> = Lazy::new(|| Mutex::new(FxHashMap::default()));
static DEFAULT_ID: Lazy<StaticId> = Lazy::new(|| StaticId::from_str("", ""));
impl StaticId {
#[inline]
#[must_use]
pub fn from_str(code: &str, venue: &str) -> Self {
let id = IdCore {
code: Symbol::from(code),
venue: Symbol::from(venue),
};
let mut cache = ID_CACHE.lock().unwrap();
let interned = cache.entry(id.clone()).or_insert_with(|| Box::leak(Box::new(id)));
StaticId { id_ptr: interned }
}
#[inline]
#[must_use]
pub fn from_bytes(code: &[u8], venue: &[u8]) -> Self {
let id = IdCore {
code: Symbol::from(code),
venue: Symbol::from(venue),
};
let mut cache = ID_CACHE.lock().unwrap();
let interned = cache.entry(id.clone()).or_insert_with(|| Box::leak(Box::new(id)));
StaticId { id_ptr: interned }
}
#[inline]
pub fn cache_len() -> usize {
ID_CACHE.lock().unwrap().len()
}
#[inline]
pub fn get_id(&self) -> &IdCore {
self.id_ptr
}
#[inline]
pub fn len(&self) -> usize {
self.id_ptr.code.len() + self.id_ptr.venue.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.id_ptr.code.is_empty() && self.id_ptr.venue.is_empty()
}
#[inline]
pub fn upper_bound_len(&self) -> usize {
self.id_ptr.code.upper_bound() + self.id_ptr.venue.upper_bound()
}
#[inline]
#[must_use]
pub fn code_str(&self) -> &str {
self.id_ptr.code.as_str()
}
#[inline]
#[must_use]
pub fn venue_str(&self) -> &str {
self.id_ptr.venue.as_str()
}
}
impl Serialize for StaticId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
IdCore {
code: self.id_ptr.code,
venue: self.id_ptr.venue,
}.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for StaticId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let id: IdCore = IdCore::deserialize(deserializer)?;
Ok(StaticId::from_str(id.code.as_str(), id.venue.as_str()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem::size_of;
#[test]
fn test_static_id_equality() {
let id1 = StaticId::from_str("ABC", "NYSE");
let id2 = StaticId::from_str("ABC", "NYSE");
let id3 = StaticId::from_str("XYZ", "NASDAQ");
assert_eq!(id1, id2);
assert_ne!(id1, id3);
}
#[test]
fn test_static_id_reuse() {
let id1 = StaticId::from_str("ABC", "NYSE");
let id2 = StaticId::from_str("ABC", "NYSE");
assert!(std::ptr::eq(id1.id_ptr, id2.id_ptr));
}
#[test]
fn test_serialization() {
let id = StaticId::from_str("ABC", "NYSE");
let serialized = serde_json::to_string(&id).unwrap();
let deserialized: StaticId = serde_json::from_str(&serialized).unwrap();
assert_eq!(id, deserialized);
}
#[test]
fn test_static_id_size() {
let size = size_of::<StaticId>();
println!("Size of StaticId: {} bytes", size);
#[cfg(target_pointer_width = "64")]
assert_eq!(size, 8, "On 64-bit systems, StaticId should be 8 bytes");
#[cfg(target_pointer_width = "32")]
assert_eq!(size, 4, "On 32-bit systems, StaticId should be 4 bytes");
}
#[test]
fn test_debug() {
let id = StaticId::from_str("ABC", "NYSE");
println!("{:?}", id);
}
#[test]
fn test_multi_threaded() {
use std::thread;
use std::sync::Arc;
std::thread::sleep(std::time::Duration::from_secs(3));
ID_CACHE.lock().unwrap().clear();
let id = StaticId::from_str("ABC", "NYSE");
let map = Arc::new(Mutex::new(FxHashMap::default()));
map.lock().unwrap().insert(id, 1);
let arc_id = Arc::new(id);
let mut threads = Vec::new();
for _ in 0..10 {
let id_clone = arc_id.clone();
let map_clone = map.clone();
threads.push(thread::spawn(move || {
for _ in 0..100_000 {
let id_thd = StaticId::from_str("ABC", "NYSE");
assert_eq!(*id_clone, id_thd);
let map_locked = map_clone.lock().unwrap();
let x = map_locked.get(&id_thd).unwrap();
assert_eq!(*x, 1);
}
}));
}
for t in threads {
t.join().unwrap();
}
assert_eq!(StaticId::cache_len(), 1);
}
#[test]
fn test_default() {
let id = StaticId::default();
println!("{:?}", id);
assert_eq!(id, *DEFAULT_ID);
}
#[test]
fn test_hashmap() {
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert(StaticId::from_str("AAPL", "NASDAQ"), 100);
map.insert(StaticId::from_str("GOOGL", "NASDAQ"), 200);
assert_eq!(map.get(&StaticId::from_str("AAPL", "NASDAQ")), Some(&100));
assert_eq!(map.get(&StaticId::from_str("GOOGL", "NASDAQ")), Some(&200));
}
#[test]
fn test_as_str() {
let id = StaticId::from_str("AAPL", "NASDAQ");
assert_eq!(id.code_str(), "AAPL");
assert_eq!(id.venue_str(), "NASDAQ");
}
#[test]
fn test_display() {
let id = StaticId::from_str("AAPL", "NASDAQ");
println!("{}", id);
assert_eq!(id.to_string(), "AAPL@NASDAQ");
}
}