borderless 0.1.2

SDK for borderless packages
Documentation
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
mod iterator;
mod keyvalue;
mod proxy;

use super::hashmap::keyvalue::KeyValue;
use super::hashmap::proxy::{
    Entry as EntryProxy, Key as KeyProxy, Value as ValueProxy, ValueMut as ValueMutProxy,
};
use crate::__private::registers::REGISTER_CURSOR;
use crate::__private::storage_traits::private::Sealed;
use crate::__private::{
    read_field, read_register, storage_cursor, storage_remove, storage_traits, write_field,
};
use crate::collections::hashmap::iterator::{HashMapIt, Keys, Values};
use nohash_hasher::IntMap;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use std::cell::{OnceCell, RefCell};
use std::collections::HashSet;
use std::fmt::{Debug, Formatter};
use std::hash::Hash;
use std::marker::PhantomData;
use std::rc::Rc;
use xxhash_rust::xxh64::Xxh64;

// Enforces determinism when hashing keys
pub(crate) const SEED: u64 = 12345;

enum CacheOp {
    Update,
    Remove,
}

pub struct HashMap<K, V> {
    base_key: u64,
    cache: RefCell<IntMap<u64, Rc<RefCell<KeyValue<K, V>>>>>,
    operations: IntMap<u64, CacheOp>,
    entries: usize,
    db_keys: OnceCell<Vec<u64>>,
}

impl<K, V> Sealed for HashMap<K, V> {}

impl<K, V> storage_traits::ToPayload for HashMap<K, V>
where
    K: Serialize + DeserializeOwned + Hash + Eq,
    V: Serialize + DeserializeOwned,
{
    fn to_payload(&self, path: &str) -> anyhow::Result<Option<String>> {
        use serde_json::to_string as to_str;
        // Remove leading '/' if present
        let path = path.strip_prefix('/').unwrap_or(path);

        let (path, remainder) = match path.split_once('/') {
            Some((path, remainder)) => (path, remainder),
            None => (path, ""),
        };

        if !path.is_empty() {
            // Try to deserialize key (complex key types will fail)
            let key: K = match serde_json::from_str(path) {
                Ok(key) => key,
                Err(_) => return Ok(None),
            };

            // Nest to the next to_payload()
            return self
                .get(key)
                .map_or(Ok(None), |val| (*val).to_payload(remainder));
        };
        // We build the json output manually to save performance
        let n_items = self.len();
        if n_items == 0 {
            return Ok(Some("{}".to_string()));
        }
        let first = self.iter().next().unwrap(); // We checked empty
        let complex_key = matches!(serde_json::to_value(first.key())?, Value::Object(_));

        let entries: Vec<String> = self
            .iter()
            .map(|item| {
                let k = to_str(item.key()).expect("Key serialization error");
                let v = to_str(item.value()).expect("Value serialization error");

                if complex_key {
                    format!("[{}, {}]", k, v)
                } else {
                    let k = to_str(&k).unwrap(); // Escape key
                    format!("{}: {}", k, v)
                }
            })
            .collect();

        let body = entries.join(",");

        let out = if complex_key {
            format!("[{}]", body)
        } else {
            format!("{{{}}}", body)
        };

        Ok(Some(out))
    }
}

impl<K, V> Debug for HashMap<K, V>
where
    K: Serialize + DeserializeOwned + Hash + Eq + Debug,
    V: Serialize + DeserializeOwned + Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        // Use the Rust's built-in debug_map helper
        let mut dm = f.debug_map();
        for entry in self.iter() {
            let (k, v) = &*entry;
            dm.entry(k, v);
        }
        dm.finish()
    }
}

impl<K, V> storage_traits::Storeable for HashMap<K, V>
where
    K: Serialize + DeserializeOwned + Hash + Eq,
    V: Serialize + DeserializeOwned,
{
    fn decode(base_key: u64) -> Self {
        Self::open(base_key)
    }

    fn parse_value(value: Value, base_key: u64) -> anyhow::Result<Self> {
        let mut out = Self::new(base_key);

        match value.clone() {
            Value::Array(_) => {
                // A HashMap with a complex key type is serialized as an array of [key, value]
                let pairs: Vec<(K, V)> = serde_json::from_value(value)?;
                for (k, v) in pairs {
                    out.insert(k, v);
                }
            }
            Value::Object(_) => {
                // A HashMap with a simple key type is serialized as a regular HashMap
                let map: std::collections::HashMap<K, V> = serde_json::from_value(value)?;
                for pair in map {
                    out.insert(pair.0, pair.1);
                }
            }
            _ => unreachable!(),
        }
        Ok(out)
    }

    fn commit(self, _base_key: u64) {
        self.commit()
    }
}

impl<K, V> HashMap<K, V>
where
    K: Serialize + DeserializeOwned + Hash + Eq,
    V: Serialize + DeserializeOwned,
{
    pub(crate) fn new(base_key: u64) -> Self {
        HashMap {
            base_key,
            cache: RefCell::default(),
            operations: IntMap::default(),
            entries: 0,
            db_keys: OnceCell::default(),
        }
    }

    pub(crate) fn open(base_key: u64) -> Self {
        // Read number of entries from the DB
        let entries = read_field::<usize>(base_key, 0).unwrap();
        HashMap {
            base_key,
            cache: RefCell::default(),
            operations: IntMap::default(),
            entries,
            db_keys: OnceCell::default(),
        }
    }

    pub fn len(&self) -> usize {
        self.entries
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn contains_key(&self, sub_key: K) -> bool {
        let sub_key = Self::hash_key(&sub_key);
        self.read(sub_key).is_some()
    }

    pub fn remove(&mut self, key: K) -> Option<V> {
        let internal_key = Self::hash_key(&key);
        // Check if key is present
        self.read(internal_key)?;
        // Decrease number of entries
        self.entries = self.entries.saturating_sub(1);
        // Flag key as removed
        self.operations.insert(internal_key, CacheOp::Remove);
        // Remove value from cache
        let mut cache = self.cache.borrow_mut();
        cache.remove(&internal_key).and_then(Self::extract_cell)
    }

    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        let internal_key = Self::hash_key(&key);
        if self.read(internal_key).is_none() {
            // Increase number of entries
            self.entries = self.entries.saturating_add(1);
        }
        // Flag key as modified
        self.operations.insert(internal_key, CacheOp::Update);
        // Insert new value
        let mut cache = self.cache.borrow_mut();
        // Create pair
        let pair = KeyValue::new(key, value);
        let cell = Rc::new(RefCell::new(pair));
        // Insert new KeyPair into the cache
        cache
            .insert(internal_key, cell)
            .and_then(Self::extract_cell)
    }

    pub fn get(&self, key: K) -> Option<ValueProxy<'_, K, V>> {
        let internal_key = Self::hash_key(&key);
        match self.read(internal_key) {
            None => None,
            Some(cell) => {
                let proxy = ValueProxy {
                    cell_ptr: cell,
                    _back_ref: PhantomData,
                };
                Some(proxy)
            }
        }
    }

    pub fn get_mut(&mut self, key: K) -> Option<ValueMutProxy<'_, K, V>> {
        let internal_key = Self::hash_key(&key);
        match self.read(internal_key) {
            None => None,
            Some(cell) => {
                // NOTE: Mark the node as changed, because the user could totally do that.
                self.flag_write(internal_key);
                let proxy = ValueMutProxy {
                    cell_ptr: cell,
                    _back_ref: PhantomData,
                };
                Some(proxy)
            }
        }
    }

    pub fn clear(&mut self) {
        // Discard local changes
        self.operations.clear();
        self.cache = RefCell::default();
        // Flag keys to be removed
        // TODO Enhance to avoid cloning the keys
        let db_keys: Vec<u64> = self.db_keys().to_vec();
        for key in db_keys {
            self.operations.insert(key, CacheOp::Remove);
        }
        // Update counter of total entries
        self.entries = 0;
    }

    pub fn iter(&self) -> HashMapIt<K, V> {
        HashMapIt::new(self)
    }

    pub fn keys(&self) -> Keys<K, V> {
        // Return Keys iterator
        Keys::new(self)
    }

    pub fn values(&self) -> Values<K, V> {
        // Return Values iterator
        Values::new(self)
    }

    fn commit(self) {
        // Store the entries counter in the DB
        write_field(self.base_key, 0, &self.entries);

        // Sync the in-memory mirror with the DB state
        for (key, op) in &self.operations {
            match op {
                CacheOp::Update => {
                    let cache = self.cache.borrow();
                    let cell = cache.get(key).expect("Cache corruption");
                    write_field(self.base_key, *key, cell.as_ref());
                }
                CacheOp::Remove => storage_remove(self.base_key, *key),
            }
        }
    }

    fn read(&self, key: u64) -> Option<Rc<RefCell<KeyValue<K, V>>>> {
        // Deleted keys (but still not commited) must return None
        // as the DB still contains them
        if let Some(CacheOp::Remove) = self.operations.get(&key) {
            return None;
        }
        // Check first the in-memory copy
        if let Some(cell) = self.cache.borrow().get(&key) {
            return Some(cell.clone());
        }
        // Fallback to DB
        match read_field::<KeyValue<K, V>>(self.base_key, key) {
            None => None,
            Some(keypair) => {
                let cell = Rc::new(RefCell::new(keypair));
                // Add value to the in-memory mirror
                self.cache.borrow_mut().insert(key, cell.clone());
                Some(cell)
            }
        }
    }

    fn flag_write(&mut self, key: u64) {
        self.operations.insert(key, CacheOp::Update);
    }

    fn get_entry(&self, internal_key: u64) -> Option<EntryProxy<'_, K, V>> {
        // Create entry proxy object
        match self.read(internal_key) {
            None => None,
            Some(cell) => {
                let key = EntryProxy {
                    cell_ptr: cell,
                    _back_ref: PhantomData,
                };
                Some(key)
            }
        }
    }

    fn get_key(&self, internal_key: u64) -> Option<KeyProxy<'_, K, V>> {
        // Create key proxy object
        match self.read(internal_key) {
            None => None,
            Some(cell) => {
                let key = KeyProxy {
                    cell_ptr: cell,
                    _back_ref: PhantomData,
                };
                Some(key)
            }
        }
    }

    fn get_value(&self, internal_key: u64) -> Option<ValueProxy<'_, K, V>> {
        // Create value proxy object
        match self.read(internal_key) {
            None => None,
            Some(cell) => {
                let key = ValueProxy {
                    cell_ptr: cell,
                    _back_ref: PhantomData,
                };
                Some(key)
            }
        }
    }

    fn db_keys(&self) -> &Vec<u64> {
        self.db_keys.get_or_init(|| {
            // Load entries from DB
            let entries = storage_cursor(self.base_key) as usize;

            // Load DB keys
            let mut db_keys: Vec<u64> = Vec::with_capacity(entries);
            for i in 0..entries {
                // Read content from register
                let bytes = read_register(REGISTER_CURSOR.saturating_add(i as u64))
                    .expect("Fail to read register");
                // Convert into the sub-key
                let arr: [u8; 8] = bytes.as_slice().try_into().expect("Slice length error");
                let sub_key = u64::from_le_bytes(arr);
                // Push key into the vector
                db_keys.push(sub_key);
            }
            db_keys
        })
    }

    fn internal_keys(&self) -> HashSet<u64> {
        let cache = self.cache.borrow();
        cache.keys().chain(self.db_keys().iter()).cloned().collect()
    }

    fn extract_cell(rc: Rc<RefCell<KeyValue<K, V>>>) -> Option<V> {
        let old_cell = Rc::try_unwrap(rc).ok().expect("Rc strong counter > 1");
        Some(old_cell.into_inner().pair.1)
    }

    fn hash_key(key: &K) -> u64 {
        let mut h = Xxh64::new(SEED);
        key.hash(&mut h);
        h.digest()
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[cfg(test)]
mod tests {
    use crate::__private::dev::rand;
    use crate::collections::hashmap::HashMap;
    use anyhow::Context;
    use std::collections::HashMap as StdHashMap;

    const KEY: u64 = 123456;
    const N: u64 = 5000;

    #[test]
    fn is_empty() -> anyhow::Result<()> {
        let map: HashMap<u64, u64> = HashMap::new(KEY);
        assert!(map.is_empty(), "HashMap must be empty");
        Ok(())
    }

    #[test]
    fn clear() -> anyhow::Result<()> {
        let mut map: HashMap<u64, u64> = HashMap::new(KEY);
        for i in 0..N {
            let random = rand(0, u64::MAX);
            map.insert(i, random);
        }
        map.clear();
        // Check integrity
        assert!(map.is_empty(), "HashMap must be empty");
        Ok(())
    }

    #[test]
    fn len() -> anyhow::Result<()> {
        let mut map: HashMap<u64, u64> = HashMap::new(KEY);
        for i in 0..N {
            // Check integrity
            assert_eq!(map.len(), i as usize, "Length mismatch");
            let random = rand(0, u64::MAX);
            map.insert(i, random);
        }
        Ok(())
    }

    #[test]
    fn contains_key() -> anyhow::Result<()> {
        let mut map: HashMap<u64, u64> = HashMap::new(KEY);
        for i in 0..N {
            let random = rand(0, u64::MAX);
            map.insert(i, random);
        }
        // Check integrity
        let target: u64 = 30000;
        assert!(!map.contains_key(target), "HashMap contains wrong key");
        map.insert(target, 0);
        assert!(map.contains_key(target), "HashMap must contain the key");
        map.remove(target);
        assert!(!map.contains_key(target), "HashMap contains wrong key");
        Ok(())
    }

    #[test]
    fn insert() -> anyhow::Result<()> {
        let mut map: HashMap<u64, u64> = HashMap::new(KEY);
        // A trusted reference used to know what the correct behavior should be
        let mut oracle = StdHashMap::<u64, u64>::with_capacity(N as usize);

        for i in 0..N {
            let random = rand(0, u64::MAX);
            map.insert(i, random);
            oracle.insert(i, random);
        }
        // Check integrity
        for i in 0..N {
            let val = map.get(i).context("Get({i}) must return some value")?;
            assert_eq!(oracle.get(&i), Some(&*val), "Element mismatch")
        }
        Ok(())
    }

    #[test]
    fn remove() -> anyhow::Result<()> {
        let mut map: HashMap<u64, u64> = HashMap::new(KEY);
        // A trusted reference used to know what the correct behavior should be
        let mut oracle = StdHashMap::<u64, u64>::with_capacity(N as usize);

        for i in 0..N {
            let random = rand(0, u64::MAX);
            map.insert(i, random);
            oracle.insert(i, random);
        }
        // Check integrity
        for i in 0..N {
            let x = map.remove(i);
            let y = oracle.remove(&i);
            assert_eq!(x, y, "Element mismatch")
        }
        Ok(())
    }

    #[test]
    fn iter() -> anyhow::Result<()> {
        let mut map: HashMap<u64, u64> = HashMap::new(KEY);
        // A trusted reference used to know what the correct behavior should be
        let mut oracle = StdHashMap::<u64, u64>::with_capacity(N as usize);

        for i in 0..N {
            let random = rand(0, u64::MAX);
            map.insert(i, random);
            oracle.insert(i, random);
        }

        // Collect and sort both key-lists
        let mut hashmap_pairs: Vec<(u64, u64)> = map.iter().map(|e| *e).collect();
        let mut oracle_pairs: Vec<(u64, u64)> = oracle.iter().map(|(k, v)| (*k, *v)).collect();
        hashmap_pairs.sort_unstable();
        oracle_pairs.sort_unstable();
        // Check integrity
        assert_eq!(hashmap_pairs, oracle_pairs);
        Ok(())
    }

    #[test]
    fn keys() -> anyhow::Result<()> {
        let mut map: HashMap<u64, u64> = HashMap::new(KEY);
        // A trusted reference used to know what the correct behavior should be
        let mut oracle = StdHashMap::<u64, u64>::with_capacity(N as usize);

        for i in 0..N {
            let random = rand(0, u64::MAX);
            map.insert(i, random);
            oracle.insert(i, random);
        }

        // Collect and sort both key-lists
        let mut hashmap_keys: Vec<u64> = map.keys().map(|p| *p).collect();
        let mut oracle_keys: Vec<u64> = oracle.keys().cloned().collect();
        hashmap_keys.sort_unstable();
        oracle_keys.sort_unstable();
        // Check integrity
        assert_eq!(hashmap_keys, oracle_keys);
        Ok(())
    }

    #[test]
    fn values() -> anyhow::Result<()> {
        let mut map: HashMap<u64, u64> = HashMap::new(KEY);
        // A trusted reference used to know what the correct behavior should be
        let mut oracle = StdHashMap::<u64, u64>::with_capacity(N as usize);

        for i in 0..N {
            let random = rand(0, u64::MAX);
            map.insert(i, random);
            oracle.insert(i, random);
        }

        // Collect and sort both values-lists
        let mut hashmap_values: Vec<u64> = map.values().map(|p| *p).collect();
        let mut oracle_values: Vec<u64> = oracle.values().cloned().collect();
        hashmap_values.sort_unstable();
        oracle_values.sort_unstable();
        // Check integrity
        assert_eq!(hashmap_values, oracle_values);
        Ok(())
    }

    #[test]
    fn cursor() -> anyhow::Result<()> {
        let mut map: HashMap<u64, u64> = HashMap::new(KEY);
        // A trusted reference used to know what the correct behavior should be
        let mut oracle = StdHashMap::<u64, u64>::with_capacity(N as usize);

        for i in 0..N {
            let random = rand(0, u64::MAX);
            map.insert(i, random);
            oracle.insert(i, random);
        }
        // Commit changes to DB
        map.commit();

        // Reopen map
        let mut map: HashMap<u64, u64> = HashMap::open(KEY);
        // Insert new elements
        let m = N * 2;
        for i in N..m {
            let random = rand(0, u64::MAX);
            map.insert(i, random);
            oracle.insert(i, random);
        }

        // Collect and sort both values-lists
        let mut map_keys: Vec<u64> = map.keys().map(|p| *p).collect();
        let mut oracle_keys: Vec<u64> = oracle.keys().cloned().collect();
        map_keys.sort_unstable();
        oracle_keys.sort_unstable();
        // Check integrity
        assert_eq!(map_keys, oracle_keys, "Integrity check failed");
        Ok(())
    }
}