mod.rs 18.3 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A storage hash map that allows to associate keys with values.

mod impls;
mod iter;
mod storage;

#[cfg(test)]
mod tests;

24
25
26
#[cfg(all(test, feature = "ink-fuzz-tests"))]
mod fuzz_tests;

27
28
29
30
31
32
33
34
pub use self::iter::{
    Iter,
    IterMut,
    Keys,
    Values,
    ValuesMut,
};
use crate::{
35
36
37
38
39
40
    collections::Stash,
    lazy::lazy_hmap::{
        Entry as LazyEntry,
        LazyHashMap,
        OccupiedEntry as LazyOccupiedEntry,
        VacantEntry as LazyVacantEntry,
41
    },
42
    traits::PackedLayout,
43
44
45
46
47
};
use core::{
    borrow::Borrow,
    cmp::Eq,
};
48
49
50
51
52
use ink_env::hash::{
    Blake2x256,
    CryptoHash,
    HashOutput,
};
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
use ink_prelude::borrow::ToOwned;
use ink_primitives::Key;

/// The index type within a hashmap.
///
/// # Note
///
/// Used for key indices internal to the hashmap.
type KeyIndex = u32;

/// A hash map operating on the contract storage.
///
/// Stores a mapping between keys and values.
///
/// # Note
///
/// Unlike Rust's standard `HashMap` that uses the [`core::hash::Hash`] trait
/// in order to hash its keys the storage hash map uses the [`scale::Encode`]
/// encoding in order to hash its keys using a built-in cryptographic
/// hash function provided by the chain runtime.
///
/// The main difference between the lower-level `LazyHashMap` and the
/// `storage::HashMap` is that the latter is aware of its associated keys and
/// values and operates on those instances directly as opposed to `Option`
/// instances of them. Also it provides a more high-level and user focused
/// API.
///
/// Users should generally prefer using this storage hash map over the low-level
/// `LazyHashMap` for direct usage in their smart contracts.
#[derive(Debug)]
83
pub struct HashMap<K, V, H = Blake2x256>
84
85
86
where
    K: Ord + Clone + PackedLayout,
    V: PackedLayout,
87
88
    H: CryptoHash,
    Key: From<<H as HashOutput>::Type>,
89
90
91
92
93
94
95
96
97
98
99
{
    /// The keys of the storage hash map.
    keys: Stash<K>,
    /// The values of the storage hash map.
    values: LazyHashMap<K, ValueEntry<V>, H>,
}

/// An entry within the storage hash map.
///
/// Stores the value as well as the index to its associated key.
#[derive(Debug, scale::Encode, scale::Decode)]
100
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
101
102
103
104
105
106
107
struct ValueEntry<V> {
    /// The value stored in this entry.
    value: V,
    /// The index of the key associated with this value.
    key_index: KeyIndex,
}

108
109
/// An occupied entry that holds the value.
pub struct OccupiedEntry<'a, K, V>
110
111
112
113
where
    K: Ord + Clone + PackedLayout,
    V: PackedLayout,
{
114
115
116
117
    /// A reference to the `Stash` instance, containing the keys.
    keys: &'a mut Stash<K>,
    /// The `LazyHashMap::OccupiedEntry`.
    values_entry: LazyOccupiedEntry<'a, K, ValueEntry<V>>,
118
119
120
}

/// A vacant entry with previous and next vacant indices.
121
pub struct VacantEntry<'a, K, V>
122
123
124
125
where
    K: Ord + Clone + PackedLayout,
    V: PackedLayout,
{
126
127
128
129
    /// A reference to the `Stash` instance, containing the keys.
    keys: &'a mut Stash<K>,
    /// The `LazyHashMap::VacantEntry`.
    values_entry: LazyVacantEntry<'a, K, ValueEntry<V>>,
130
131
132
133
134
135
}

/// An entry within the stash.
///
/// The vacant entries within a storage stash form a doubly linked list of
/// vacant entries that is used to quickly re-use their vacant storage.
136
pub enum Entry<'a, K: 'a, V: 'a>
137
138
139
140
141
where
    K: Ord + Clone + PackedLayout,
    V: PackedLayout,
{
    /// A vacant entry that holds the index to the next and previous vacant entry.
142
    Vacant(VacantEntry<'a, K, V>),
143
    /// An occupied entry that holds the value.
144
    Occupied(OccupiedEntry<'a, K, V>),
145
146
}

147
148
149
150
impl<K, V, H> HashMap<K, V, H>
where
    K: Ord + Clone + PackedLayout,
    V: PackedLayout,
151
152
    H: CryptoHash,
    Key: From<<H as HashOutput>::Type>,
153
154
155
156
157
158
159
160
161
{
    /// Creates a new empty storage hash map.
    pub fn new() -> Self {
        Self {
            keys: Stash::new(),
            values: LazyHashMap::new(),
        }
    }

162
    /// Returns the number of key-value pairs stored in the hash map.
163
164
165
166
    pub fn len(&self) -> u32 {
        self.keys.len()
    }

167
168
169
170
171
172
    /// Returns the number of key-value pairs stored in the cache.
    #[cfg(test)]
    pub(crate) fn len_cached_entries(&self) -> u32 {
        self.keys.len()
    }

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
    /// Returns `true` if the hash map is empty.
    pub fn is_empty(&self) -> bool {
        self.keys.is_empty()
    }

    /// Returns an iterator yielding shared references to all key/value pairs
    /// of the hash map.
    ///
    /// # Note
    ///
    /// - Avoid unbounded iteration over big storage hash maps.
    /// - Prefer using methods like `Iterator::take` in order to limit the number
    ///   of yielded elements.
    pub fn iter(&self) -> Iter<K, V, H> {
        Iter::new(self)
    }

    /// Returns an iterator yielding exclusive references to all key/value pairs
    /// of the hash map.
    ///
    /// # Note
    ///
    /// - Avoid unbounded iteration over big storage hash maps.
    /// - Prefer using methods like `Iterator::take` in order to limit the number
    ///   of yielded elements.
    pub fn iter_mut(&mut self) -> IterMut<K, V, H> {
        IterMut::new(self)
    }

    /// Returns an iterator yielding shared references to all values of the hash map.
    ///
    /// # Note
    ///
    /// - Avoid unbounded iteration over big storage hash maps.
    /// - Prefer using methods like `Iterator::take` in order to limit the number
    ///   of yielded elements.
    pub fn values(&self) -> Values<K, V, H> {
        Values::new(self)
    }

    /// Returns an iterator yielding shared references to all values of the hash map.
    ///
    /// # Note
    ///
    /// - Avoid unbounded iteration over big storage hash maps.
    /// - Prefer using methods like `Iterator::take` in order to limit the number
    ///   of yielded elements.
    pub fn values_mut(&mut self) -> ValuesMut<K, V, H> {
        ValuesMut::new(self)
    }

    /// Returns an iterator yielding shared references to all keys of the hash map.
    ///
    /// # Note
    ///
    /// - Avoid unbounded iteration over big storage hash maps.
    /// - Prefer using methods like `Iterator::take` in order to limit the number
    ///   of yielded elements.
    pub fn keys(&self) -> Keys<K> {
        Keys::new(self)
    }
}

impl<K, V, H> HashMap<K, V, H>
where
    K: Ord + Clone + PackedLayout,
    V: PackedLayout,
240
241
    H: CryptoHash,
    Key: From<<H as HashOutput>::Type>,
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
{
    fn clear_cells(&self) {
        if self.values.key().is_none() {
            // We won't clear any storage if we are in lazy state since there
            // probably has not been any state written to storage, yet.
            return
        }
        for key in self.keys() {
            // It might seem wasteful to clear all entries instead of just
            // the occupied ones. However this spares us from having one extra
            // read for every element in the storage stash to filter out vacant
            // entries. So this is actually a trade-off and at the time of this
            // implementation it is unclear which path is more efficient.
            //
            // The bet is that clearing a storage cell is cheaper than reading one.
            self.values.clear_packed_at(key);
        }
    }
}

impl<K, V, H> HashMap<K, V, H>
where
    K: Ord + Eq + Clone + PackedLayout,
    V: PackedLayout,
266
267
    H: CryptoHash,
    Key: From<<H as HashOutput>::Type>,
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
{
    /// Inserts a key-value pair into the map.
    ///
    /// Returns the previous value associated with the same key if any.
    /// If the map did not have this key present, `None` is returned.
    ///
    /// # Note
    ///
    /// - If the map did have this key present, the value is updated,
    ///   and the old value is returned. The key is not updated, though;
    ///   this matters for types that can be `==` without being identical.
    pub fn insert(&mut self, key: K, new_value: V) -> Option<V> {
        if let Some(occupied) = self.values.get_mut(&key) {
            // Update value, don't update key.
            let old_value = core::mem::replace(&mut occupied.value, new_value);
            return Some(old_value)
        }
        // At this point we know that `key` does not yet exist in the map.
        let key_index = self.keys.put(key.to_owned());
        self.values.put(
            key,
            Some(ValueEntry {
                value: new_value,
                key_index,
            }),
        );
        None
    }

    /// Removes the key/value pair from the map associated with the given key.
    ///
    /// - Returns the removed value if any.
    ///
    /// # Note
    ///
    /// The key may be any borrowed form of the map's key type,
    /// but `Hash` and `Eq` on the borrowed form must match those for the key type.
    pub fn take<Q>(&mut self, key: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Ord + scale::Encode + ToOwned<Owned = K>,
    {
        let entry = self.values.put_get(key, None)?;
        self.keys
            .take(entry.key_index)
            .expect("`key_index` must point to a valid key entry");
        Some(entry.value)
    }

    /// Returns a shared reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the map's key type,
    /// but `Hash` and `Eq` on the borrowed form must match those for the key type.
    pub fn get<Q>(&self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: Ord + scale::Encode + ToOwned<Owned = K>,
    {
        self.values.get(key).map(|entry| &entry.value)
    }

    /// Returns a mutable reference to the value corresponding to the key.
    ///
    /// The key may be any borrowed form of the map's key type,
    /// but `Hash` and `Eq` on the borrowed form must match those for the key type.
    pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    where
        K: Borrow<Q>,
        Q: Ord + scale::Encode + ToOwned<Owned = K>,
    {
        self.values.get_mut(key).map(|entry| &mut entry.value)
    }

    /// Returns `true` if there is an entry corresponding to the key in the map.
    pub fn contains_key<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Ord + PartialEq<K> + Eq + scale::Encode + ToOwned<Owned = K>,
    {
        // We do not check if the given key is equal to the queried key which is
        // what normally a hash map implementation does because we do not resolve
        // or prevent collisions in this hash map implementation at any level.
        // Having a collision is virtually impossible since we
351
        // are using a keyspace of `2^256` bit.
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
        self.values.get(key).is_some()
    }

    /// Defragments storage used by the storage hash map.
    ///
    /// Returns the number of storage cells freed this way.
    ///
    /// A `max_iterations` parameter of `None` means that there is no limit
    /// to the number of iterations performed. This is generally not advised.
    ///
    /// # Note
    ///
    /// This frees storage that is held but not necessary for the hash map to hold.
    /// This operation might be expensive, especially for big `max_iteration`
    /// parameters. The `max_iterations` parameter can be used to limit the
    /// expensiveness for this operation and instead free up storage incrementally.
    pub fn defrag(&mut self, max_iterations: Option<u32>) -> u32 {
        // This method just defrags the underlying `storage::Stash` used to
        // store the keys as it can sometimes take a lot of unused storage
        // if many keys have been removed at some point. Some hash map
        // implementations might even prefer to perform this operation with a
        // limit set to 1 after every successful removal.
        if let Some(0) = max_iterations {
            // Bail out early if the iteration limit is set to 0 anyways to
376
            // completely avoid doing work in this case.
377
378
379
380
381
382
383
384
385
386
387
388
            return 0
        }
        let len_vacant = self.keys.capacity() - self.keys.len();
        let max_iterations = max_iterations.unwrap_or(len_vacant);
        let values = &mut self.values;
        let callback = |old_index, new_index, key: &K| {
            let value_entry = values.get_mut(key).expect("key must be valid");
            debug_assert_eq!(value_entry.key_index, old_index);
            value_entry.key_index = new_index;
        };
        self.keys.defrag(Some(max_iterations), callback)
    }
389
390

    /// Gets the given key's corresponding entry in the map for in-place manipulation.
391
392
393
394
    pub fn entry(&mut self, key: K) -> Entry<K, V> {
        let entry = self.values.entry(key);
        match entry {
            LazyEntry::Occupied(o) => {
395
                Entry::Occupied(OccupiedEntry {
396
397
398
399
400
401
402
403
                    keys: &mut self.keys,
                    values_entry: o,
                })
            }
            LazyEntry::Vacant(v) => {
                Entry::Vacant(VacantEntry {
                    keys: &mut self.keys,
                    values_entry: v,
404
405
406
407
408
409
                })
            }
        }
    }
}

410
impl<'a, K, V> Entry<'a, K, V>
411
412
413
414
415
416
417
where
    K: Ord + Clone + PackedLayout,
    V: PackedLayout + core::fmt::Debug + core::cmp::Eq + Default,
{
    /// Returns a reference to this entry's key.
    pub fn key(&self) -> &K {
        match self {
418
419
            Entry::Occupied(entry) => entry.values_entry.key(),
            Entry::Vacant(entry) => entry.values_entry.key(),
420
421
422
423
424
425
426
        }
    }

    /// Ensures a value is in the entry by inserting the default value if empty, and returns
    /// a reference to the value in the entry.
    pub fn or_default(self) -> &'a V {
        match self {
427
            Entry::Occupied(entry) => &mut entry.values_entry.into_mut().value,
428
429
430
431
432
433
434
435
            Entry::Vacant(entry) => entry.insert(V::default()),
        }
    }

    /// Ensures a value is in the entry by inserting the default if empty, and returns
    /// a mutable reference to the value in the entry.
    pub fn or_insert(self, default: V) -> &'a mut V {
        match self {
436
            Entry::Occupied(entry) => &mut entry.values_entry.into_mut().value,
437
438
439
440
441
442
443
444
445
446
447
            Entry::Vacant(entry) => entry.insert(default),
        }
    }

    /// Ensures a value is in the entry by inserting the result of the default function if empty,
    /// and returns mutable references to the key and value in the entry.
    pub fn or_insert_with<F>(self, default: F) -> &'a mut V
    where
        F: FnOnce() -> V,
    {
        match self {
448
            Entry::Occupied(entry) => &mut entry.values_entry.into_mut().value,
449
450
451
452
453
454
455
456
457
458
459
460
            Entry::Vacant(entry) => Entry::insert(default(), entry),
        }
    }

    /// Ensures a value is in the entry by inserting, if empty, the result of the default
    /// function, which takes the key as its argument, and returns a mutable reference to
    /// the value in the entry.
    pub fn or_insert_with_key<F>(self, default: F) -> &'a mut V
    where
        F: FnOnce(&K) -> V,
    {
        match self {
461
            Entry::Occupied(entry) => &mut entry.values_entry.into_mut().value,
462
            Entry::Vacant(entry) => Entry::insert(default(entry.key()), entry),
463
464
465
466
467
468
469
470
471
472
473
474
        }
    }

    /// Provides in-place mutable access to an occupied entry before any
    /// potential inserts into the map.
    pub fn and_modify<F>(self, f: F) -> Self
    where
        F: FnOnce(&mut V),
    {
        match self {
            Entry::Occupied(mut entry) => {
                {
475
476
                    let v = entry.values_entry.get_mut();
                    f(&mut v.value);
477
478
479
480
481
482
483
484
                }
                Entry::Occupied(entry)
            }
            Entry::Vacant(entry) => Entry::Vacant(entry),
        }
    }

    /// Inserts `value` into `entry`.
485
486
    fn insert(value: V, entry: VacantEntry<'a, K, V>) -> &'a mut V {
        entry.insert(value)
487
488
489
    }
}

490
impl<'a, K, V> VacantEntry<'a, K, V>
491
492
493
494
where
    K: Ord + Clone + PackedLayout,
    V: PackedLayout,
{
495
    /// Gets a reference to the key that would be used when inserting a value through the `VacantEntry`.
496
    pub fn key(&self) -> &K {
497
        self.values_entry.key()
498
499
500
501
    }

    /// Take ownership of the key.
    pub fn into_key(self) -> K {
502
        self.values_entry.into_key()
503
504
    }

505
    /// Sets the value of the entry with the `VacantEntry`s key, and returns a mutable reference to it.
506
507
    pub fn insert(self, value: V) -> &'a mut V {
        // At this point we know that `key` does not yet exist in the map.
508
509
510
511
512
        let key_index = self.keys.put(self.key().to_owned());
        &mut self
            .values_entry
            .insert(ValueEntry { value, key_index })
            .value
513
514
515
    }
}

516
impl<'a, K, V> OccupiedEntry<'a, K, V>
517
518
519
520
521
522
where
    K: Ord + Clone + PackedLayout,
    V: PackedLayout,
{
    /// Gets a reference to the key in the entry.
    pub fn key(&self) -> &K {
523
        self.values_entry.key()
524
525
526
527
    }

    /// Take the ownership of the key and value from the map.
    pub fn remove_entry(self) -> (K, V) {
528
529
530
531
        let k = self.values_entry.key().to_owned();
        let v = self.values_entry.remove();
        self.keys
            .take(v.key_index)
532
            .expect("`key_index` must point to a valid key entry");
533
        (k, v.value)
534
535
536
537
    }

    /// Gets a reference to the value in the entry.
    pub fn get(&self) -> &V {
538
        &self.values_entry.get().value
539
540
541
542
543
544
545
    }

    /// Gets a mutable reference to the value in the entry.
    ///
    /// If you need a reference to the `OccupiedEntry` which may outlive the destruction of the
    /// `Entry` value, see `into_mut`.
    pub fn get_mut(&mut self) -> &mut V {
546
        &mut self.values_entry.get_mut().value
547
548
549
550
    }

    /// Sets the value of the entry, and returns the entry's old value.
    pub fn insert(&mut self, new_value: V) -> V {
551
        core::mem::replace(&mut self.values_entry.get_mut().value, new_value)
552
553
554
555
556
557
558
    }

    /// Takes the value out of the entry, and returns it.
    pub fn remove(self) -> V {
        self.remove_entry().1
    }

559
    /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry
560
561
    /// with a lifetime bound to the map itself.
    pub fn into_mut(self) -> &'a mut V {
562
        &mut self.values_entry.into_mut().value
563
    }
564
}