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
//! # StaticId
//!
//! This library provides an extremely memory-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.
//! - Exceptional memory efficiency: Each `StaticId` is represented by a single 64-bit pointer.
//! - Ultra-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.
//!
//! ## Limitations
//!
//! - The `code` component of a `StaticId` cannot exceed 32 bytes.
//! - The `venue` component of a `StaticId` cannot exceed 16 bytes.
//! 
//! ## Usage
//!
//! ```rust
//! use static_id::StaticId;
//!
//! let id = StaticId::from_str("AAPL", "NASDAQ");
//! assert_eq!(id.get_id().code.as_str(), "AAPL");
//! assert_eq!(id.get_id().venue.as_str(), "NASDAQ");
//!
//! // Fast equality check (compares only 8 bytes)
//! let id2 = StaticId::from_str("AAPL", "NASDAQ");
//! assert_eq!(id, id2);
//! ```
//!
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)]
pub struct IdCore {
    pub code: Code,
    pub venue: Venue,
}

#[derive(Debug, Clone, Copy)]
pub struct StaticId {
    id_ptr: &'static IdCore,
}

impl PartialEq for StaticId {
    fn eq(&self, other: &Self) -> bool {
        ptr_eq(self.id_ptr, other.id_ptr)
    }
}

impl Hash for StaticId {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.id_ptr.hash(state);
    }
}


//static ID_CACHE: Lazy<DashMap<IdCore, &'static IdCore>> = Lazy::new(DashMap::new);
static ID_CACHE: Lazy<Mutex<FxHashMap<IdCore, &'static IdCore>>> = Lazy::new(|| Mutex::new(FxHashMap::default()));

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()    
    }
}

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_lengths() {
        let id1 = StaticId::from_str("ABC", "NYSE");
        let id2 = StaticId::from_str("XYZ", "NASDAQ");
        let id3 = StaticId::from_str("ABC", "NASDAQ");
        let id4 = StaticId::from_str("XYZ", "NASDAQ");

        assert_eq!(id1.len(), 7);
        assert_eq!(id2.len(), 9);
        assert_eq!(id3.len(), 9);
        assert_eq!(id4.len(), 9);

        assert_eq!(StaticId::cache_len(), 3);
    }

    #[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 arc_id = Arc::new(id);

        let mut threads = Vec::new();
        for _ in 0..10 {
            let id_clone = arc_id.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);
                }
            }));
        }

        for t in threads {
            t.join().unwrap();
        }
        
        assert_eq!(StaticId::cache_len(), 1);
    }
}