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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
#![allow(dead_code)]

use {
    std::{
        sync::atomic::{AtomicU64, Ordering},
        ops::{Index, IndexMut, Deref, DerefMut},
        collections::{HashMap},
        sync::Once,
        fmt,
        cmp,
    }
};


impl LiveIdInterner {
    pub fn add(&mut self, val: &str) {
        self.id_to_string.insert(LiveId::from_str(val), val.to_string());
    }
    
    pub fn contains(&mut self, val: &str) -> bool {
        self.id_to_string.contains_key(&LiveId::from_str(val))
    }
    
    pub fn with<F, R>(f: F) -> R
    where
    F: FnOnce(&mut Self) -> R,
    {
        static mut IDMAP: Option<LiveIdInterner> = None;
        static ONCE: Once = Once::new();
        ONCE.call_once( || unsafe {
            let mut map = LiveIdInterner {
                //alloc: 0,
                id_to_string: HashMap::new()
            };
            // pre-seed list for debugging purposes
            let fill = [
                "default",
                "exp",
                "void",
                "true",
                "false",
                "use",
                "#",
                "$",
                "@",
                "^",
                "^=",
                "|",
                "||",
                "|=",
                "%",
                "%=",
                "!=",
                "!",
                "&&",
                "*=",
                "*",
                "+=",
                "+",
                ",",
                "-=",
                "->",
                "-",
                "..",
                "...",
                "..=",
                ".",
                "/=",
                "/",
                "::",
                ":",
                ";",
                "<=",
                "<",
                "<<",
                "<<=",
                "==",
                "=",
                ">=",
                "=>",
                ">",
                ">>",
                ">>=",
                "?",
                "tracks",
                "state",
                "state_id",
                "user",
                "play",
                "ended"
            ];
            for item in &fill {
                if map.contains(item) {
                    eprintln!("WE HAVE AN ID COLLISION!");
                }
                map.add(item);
            }
            IDMAP = Some(map)
        });
        f(unsafe {IDMAP.as_mut().unwrap()})
    }
}

#[derive(Clone, Default, Eq, Hash, Copy, PartialEq)]
pub struct LiveId(pub u64);

pub const LIVE_ID_SEED:u64 = 0xd6e8_feb8_6659_fd93;

impl LiveId {
    pub fn empty() -> Self {
        Self (0)
    }
    pub fn from_lo_hi(lo:u32, hi:u32)->Self{
        Self( (lo as u64) | ((hi as u64)<<32) )
    }
    pub fn lo(&self)->u32{
        (self.0&0xffff_ffff) as u32
    }
    pub fn hi(&self)->u32{
        (self.0>>32) as u32
    }
    
    pub fn seeded()->Self{
        Self(LIVE_ID_SEED)
    }
    
    pub fn is_unique(&self) -> bool {
        (self.0 & 0x8000_0000_0000_0000) == 0 && self.0 != 0
    }
    
    pub fn is_ident(&self) -> bool {
        (self.0 & 0x8000_0000_0000_0000) != 0
    }
    
    pub fn is_empty(&self) -> bool {
        self.0 == 0
    }

    pub fn get_value(&self) -> u64 {
        self.0
    }
    
    // from https://nullprogram.com/blog/2018/07/31/
    // i have no idea what im doing with start value and finalisation.
    pub const fn from_bytes(seed:u64, id_bytes: &[u8], start: usize, end: usize) -> Self {
        let mut x = seed;
        let mut i = start;
        while i < end {
            x = x.overflowing_add(id_bytes[i] as u64).0;
            x ^= x >> 32;
            x = x.overflowing_mul(0xd6e8_feb8_6659_fd93).0;
            x ^= x >> 32;
            x = x.overflowing_mul(0xd6e8_feb8_6659_fd93).0;
            x ^= x >> 32;
            i += 1;
        }
        // mark high bit as meaning that this is a hash id
        Self ((x & 0x7fff_ffff_ffff_ffff) | 0x8000_0000_0000_0000)
    }
    
    pub const fn from_str(id_str: &str) -> Self {
        let bytes = id_str.as_bytes();
        Self::from_bytes(LIVE_ID_SEED, bytes, 0, bytes.len())
    }
    
    pub const fn str_append(self, id_str: &str) -> Self {
        let bytes = id_str.as_bytes();
        Self::from_bytes(self.0, bytes, 0, bytes.len())
    }

    pub const fn bytes_append(self, bytes: &[u8]) -> Self {
        Self::from_bytes(self.0, bytes, 0, bytes.len())
    }
    
    pub const fn id_append(self, id: LiveId) -> Self {
        let bytes = id.0.to_be_bytes();
        Self::from_bytes(self.0, &bytes, 0, bytes.len())
    }
    
    pub const fn from_str_num(id_str: &str, num:u64) -> Self {
        let bytes = id_str.as_bytes();
        let id = Self::from_bytes(LIVE_ID_SEED, bytes, 0, bytes.len());
        Self::from_bytes(id.0, &num.to_be_bytes(), 0, 8)
    }
    
    pub const fn from_num(seed:u64, num:u64) -> Self {
        Self::from_bytes(seed, &num.to_be_bytes(), 0, 8)
    }
    
    pub fn from_str_with_lut(id_str: &str) -> Result<Self,
    String> {
        let id = Self::from_str(id_str);
        LiveIdInterner::with( | idmap | {
            if let Some(stored) = idmap.id_to_string.get(&id) {
                if stored != id_str {
                    return Err(stored.clone())
                }
            }
            else {
                idmap.id_to_string.insert(id, id_str.to_string());
            }
            Ok(id)
        })
    }
    
    pub fn from_str_num_with_lut(id_str: &str, num:u64) -> Result<Self,
    String> {
        let id = Self::from_str_num(id_str, num);
        LiveIdInterner::with( | idmap | {
            idmap.id_to_string.insert(id, format!("{}{}",id_str, num));
            Ok(id)
        })
    }
    
    pub fn as_string<F, R>(&self, f: F) -> R
    where F: FnOnce(Option<&str>) -> R
    {
        LiveIdInterner::with( | idmap | {
            match idmap.id_to_string.get(self){
                Some(v)=>f(Some(v)),
                None=>f(None)
            }
        })
    }

    pub fn unique() -> Self {
        LiveId(UNIQUE_LIVE_ID.fetch_add(1, Ordering::SeqCst))
    }
}

pub (crate) static UNIQUE_LIVE_ID: AtomicU64 = AtomicU64::new(1);

impl Ord for LiveId {
    fn cmp(&self, other: &LiveId) -> cmp::Ordering {
        LiveIdInterner::with( | idmap | {
            if let Some(id1) = idmap.id_to_string.get(self) {
                if let Some(id2) = idmap.id_to_string.get(other) {
                    return id1.cmp(id2)
                }
            }
            cmp::Ordering::Equal
        })
    }
}

impl PartialOrd for LiveId {
    fn partial_cmp(&self, other: &LiveId) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Debug for LiveId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for LiveId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if *self == LiveId::empty() {
            write!(f, "0")
        }
        else if self.is_unique(){
            write!(f, "UniqueId {}", self.0)
        }
        else{
            self.as_string( | string | {
                if let Some(id) = string {
                    write!(f, "{}", id)
                }
                else {
                    write!(f, "IdNotFound {:016x}", self.0)
                }
            })
        }
    }
}

impl fmt::LowerHex for LiveId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}


pub struct LiveIdInterner {
    //alloc: u64,
    id_to_string: HashMap<LiveId, String>,
}

// ----------------------------------------------------------------------------

// Idea taken from the `nohash_hasher` crate.
#[derive(Default)]
pub struct LiveIdHasher(u64);

impl std::hash::Hasher for LiveIdHasher {
    fn write(&mut self, _: &[u8]) {
        unreachable!("Invalid use of IdHasher");
    }
    
    fn write_u8(&mut self, _n: u8) {
        unreachable!("Invalid use of IdHasher");
    }
    fn write_u16(&mut self, _n: u16) {
        unreachable!("Invalid use of IdHasher");
    }
    fn write_u32(&mut self, _n: u32) {
        unreachable!("Invalid use of IdHasher");
    }
    
    #[inline(always)]
    fn write_u64(&mut self, n: u64) {
        self.0 = n;
    }
    
    fn write_usize(&mut self, _n: usize) {
        unreachable!("Invalid use of IdHasher");
    }
    
    fn write_i8(&mut self, _n: i8) {
        unreachable!("Invalid use of IdHasher");
    }
    fn write_i16(&mut self, _n: i16) {
        unreachable!("Invalid use of IdHasher");
    }
    fn write_i32(&mut self, _n: i32) {
        unreachable!("Invalid use of IdHasher");
    }
    fn write_i64(&mut self, _n: i64) {
        unreachable!("Invalid use of IdHasher");
    }
    fn write_isize(&mut self, _n: isize) {
        unreachable!("Invalid use of IdHasher");
    }
    
    #[inline(always)]
    fn finish(&self) -> u64 {
        self.0
    }
}

#[derive(Copy, Clone, Default)]
pub struct LiveIdHasherBuilder {}

impl std::hash::BuildHasher for LiveIdHasherBuilder {
    type Hasher = LiveIdHasher;
    
    #[inline(always)]
    fn build_hasher(&self) -> LiveIdHasher {
        LiveIdHasher::default()
    }
}

#[derive(Clone, Debug)]
pub struct LiveIdMap<K, V> {
    map: HashMap<K, V, LiveIdHasherBuilder>,
    //alloc_set: HashSet<K, LiveIdHasherBuilder>
}

impl<K, V> Default for LiveIdMap<K, V>
where K: std::cmp::Eq + std::hash::Hash + Copy + From<LiveId> + std::fmt::Debug {
    fn default() -> Self {
        Self {
            map: HashMap::with_hasher(LiveIdHasherBuilder {}),
            //alloc_set: HashSet::with_hasher(LiveIdHasherBuilder {})
        }
    }
}
/*
impl<K, V> LiveIdMap<K, V>
where K: std::cmp::Eq + std::hash::Hash + Copy + From<LiveId> + std::fmt::Debug
{
    pub fn new() -> Self {Self::default()}
    
    pub fn alloc_key(&mut self) -> K {
        loop {
            let new_id = LiveId::unique().into();
            if self.map.get(&new_id).is_none() && !self.alloc_set.contains(&new_id) {
                self.alloc_set.insert(new_id);
                return new_id
            }
        }
    }
    
    pub fn insert_unique(&mut self, value: V) -> K {
        loop {
            let new_id = LiveId::unique().into();
            if self.alloc_set.contains(&new_id) {
                continue
            }
            match self.map.entry(new_id) {
                Entry::Occupied(_) => continue,
                Entry::Vacant(v) => {
                    
                    v.insert(value);
                    return new_id
                }
            }
        }
    }
    
    pub fn insert(&mut self, k: impl Into<K>, value: V) {
        let k = k.into();
        self.alloc_set.remove(&k);
        match self.map.entry(k) {
            Entry::Occupied(_) => panic!("Item {:?} already inserted",k),
            Entry::Vacant(v) => v.insert(value)
        };
    }
}
*/
impl<K, V> Deref for LiveIdMap<K, V>
where K: std::cmp::Eq + std::hash::Hash + Copy + From<LiveId>
{
    type Target = HashMap<K, V, LiveIdHasherBuilder>;
    fn deref(&self) -> &Self::Target {&self.map}
}

impl<K, V> DerefMut for LiveIdMap<K, V>
where K: std::cmp::Eq + std::hash::Hash + Copy + From<LiveId>
{
    fn deref_mut(&mut self) -> &mut Self::Target {&mut self.map}
}

impl<K, V> Index<K> for LiveIdMap<K, V>
where K: std::cmp::Eq + std::hash::Hash + Copy + From<LiveId>
{
    type Output = V;
    fn index(&self, index: K) -> &Self::Output {
        self.map.get(&index).unwrap()
    }
}

impl<K, V> IndexMut<K> for LiveIdMap<K, V>
where K: std::cmp::Eq + std::hash::Hash + Copy + From<LiveId>
{
    fn index_mut(&mut self, index: K) -> &mut Self::Output {
        self.map.get_mut(&index).unwrap()
    }
}