lazy_array.rs 28.9 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
//
// 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.

use super::{
16
    CacheCell,
17
    EntryState,
18
    StorageEntry,
19
};
20
use crate::traits::{
21
22
    clear_packed_root,
    pull_packed_root_opt,
23
    ExtKeyPtr,
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
    KeyPtr,
    PackedLayout,
    SpreadLayout,
};
use core::{
    fmt,
    fmt::Debug,
    mem,
    ptr::NonNull,
};
use ink_primitives::Key;

/// The index type used in the lazy storage chunk.
pub type Index = u32;

/// A lazy storage array that spans over N storage cells.
///
/// Storage data structure to emulate storage arrays: `[T; N]`.
///
/// # Note
///
/// Computes operations on the underlying N storage cells in a lazy fashion.
/// Due to the size constraints the `LazyArray` is generally more efficient
/// than the [`LazyMap`](`super::LazyIndexMap`) for most use cases with limited elements.
///
/// This is mainly used as low-level storage primitives by other high-level
/// storage primitives in order to manage the contract storage for a whole
/// chunk of storage cells.
52
pub struct LazyArray<T, const N: usize> {
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    /// The offset key for the N cells.
    ///
    /// If the lazy chunk has been initialized during contract initialization
    /// the key will be `None` since there won't be a storage region associated
    /// to the lazy chunk which prevents it from lazily loading elements. This,
    /// however, is only checked at contract runtime. We might incorporate
    /// compile-time checks for this particular use case later on.
    key: Option<Key>,
    /// The subset of currently cached entries of the lazy storage chunk.
    ///
    /// An entry is cached as soon as it is loaded or written.
    cached_entries: EntryArray<T, N>,
}

67
68
#[cfg(feature = "std")]
const _: () = {
69
    use crate::traits::StorageLayout;
70
    use ink_metadata::layout::{
71
72
73
74
75
        ArrayLayout,
        CellLayout,
        Layout,
        LayoutKey,
    };
76
    use scale_info::TypeInfo;
77

78
    impl<T, const N: usize> StorageLayout for LazyArray<T, N>
79
    where
80
        T: TypeInfo + 'static,
81
82
    {
        fn layout(key_ptr: &mut KeyPtr) -> Layout {
83
            let capacity = N as u32;
84
85
86
87
88
89
90
91
92
93
94
95
            Layout::Array(ArrayLayout::new(
                LayoutKey::from(key_ptr.advance_by(capacity as u64)),
                capacity,
                1,
                Layout::Cell(CellLayout::new::<T>(LayoutKey::from(
                    key_ptr.advance_by(0),
                ))),
            ))
        }
    }
};

96
struct DebugEntryArray<'a, T, const N: usize>(&'a EntryArray<T, N>)
97
where
98
    T: Debug;
99

100
impl<'a, T, const N: usize> Debug for DebugEntryArray<'a, T, N>
101
102
103
104
105
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_map()
106
107
108
109
110
111
            .entries(
                self.0
                    .iter()
                    .enumerate()
                    .filter_map(|(key, entry)| entry.as_ref().map(|entry| (key, entry))),
            )
112
113
114
115
            .finish()
    }
}

116
impl<T, const N: usize> Debug for LazyArray<T, N>
117
118
119
120
121
122
123
124
125
126
127
128
129
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("LazyArray")
            .field("key", &self.key)
            .field("cached_entries", &DebugEntryArray(&self.cached_entries))
            .finish()
    }
}

#[test]
fn debug_impl_works() {
130
    let mut larray = <LazyArray<i32, 4>>::new();
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
    // Empty imap.
    assert_eq!(
        format!("{:?}", &larray),
        "LazyArray { key: None, cached_entries: {} }",
    );
    // Filled imap.
    larray.put(0, Some(1));
    larray.put(2, Some(2));
    larray.put(3, None);
    assert_eq!(
        format!("{:?}", &larray),
        "LazyArray { \
            key: None, \
            cached_entries: {\
                0: Entry { \
                    value: Some(1), \
                    state: Mutated \
                }, \
                2: Entry { \
                    value: Some(2), \
                    state: Mutated \
                }, \
                3: Entry { \
                    value: None, \
                    state: Mutated \
                }\
            } \
        }",
    );
}

/// Returns the capacity for an array with the given array length.
163
164
fn array_capacity<T, const N: usize>() -> u32 {
    N as u32
165
166
167
168
}

/// The underlying array cache for the [`LazyArray`].
#[derive(Debug)]
169
pub struct EntryArray<T, const N: usize> {
170
    /// The cache entries of the entry array.
171
    entries: [CacheCell<Option<StorageEntry<T>>>; N],
172
173
174
175
}

#[derive(Debug)]
pub struct EntriesIter<'a, T> {
176
    iter: core::slice::Iter<'a, CacheCell<Option<StorageEntry<T>>>>,
177
178
179
}

impl<'a, T> EntriesIter<'a, T> {
180
    pub fn new<const N: usize>(entry_array: &'a EntryArray<T, N>) -> Self {
181
182
183
184
185
186
187
        Self {
            iter: entry_array.entries.iter(),
        }
    }
}

impl<'a, T> Iterator for EntriesIter<'a, T> {
188
    type Item = &'a Option<StorageEntry<T>>;
189
190

    fn next(&mut self) -> Option<Self::Item> {
191
        self.iter.next().map(|cell| cell.as_inner())
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.iter.count()
    }
}

impl<'a, T> DoubleEndedIterator for EntriesIter<'a, T> {
    fn next_back(&mut self) -> Option<Self::Item> {
208
        self.iter.next_back().map(|cell| cell.as_inner())
209
210
211
212
213
    }
}

impl<'a, T> ExactSizeIterator for EntriesIter<'a, T> {}

214
impl<T, const N: usize> EntryArray<T, N> {
215
216
217
    /// Creates a new entry array cache.
    pub fn new() -> Self {
        Self {
218
            entries: array_init::array_init(|_| Default::default()),
219
220
221
222
        }
    }
}

223
impl<T, const N: usize> Default for EntryArray<T, N> {
224
225
226
227
228
    fn default() -> Self {
        Self::new()
    }
}

229
impl<T, const N: usize> EntryArray<T, N> {
230
231
232
233
234
235
236
237
238
239
    /// Returns the constant capacity of the lazy array.
    #[inline]
    pub fn capacity() -> u32 {
        array_capacity::<T, N>()
    }

    /// Puts the the new value into the indexed slot and
    /// returns the old value if any.
    fn put(&self, at: Index, new_value: Option<T>) -> Option<T> {
        mem::replace(
240
            unsafe { self.entries[at as usize].get_ptr().as_mut() },
241
            Some(StorageEntry::new(new_value, EntryState::Mutated)),
242
        )
243
        .map(StorageEntry::into_value)
244
245
246
247
        .flatten()
    }

    /// Inserts a new entry into the cache and returns an exclusive reference to it.
248
249
250
251
252
253
    unsafe fn insert_entry(
        &self,
        at: Index,
        new_entry: StorageEntry<T>,
    ) -> NonNull<StorageEntry<T>> {
        let entry: &mut Option<StorageEntry<T>> =
254
            &mut *CacheCell::get_ptr(&self.entries[at as usize]).as_ptr();
255
256
257
258
259
260
261
262
        *entry = Some(new_entry);
        entry
            .as_mut()
            .map(NonNull::from)
            .expect("just inserted the entry")
    }

    /// Returns an exclusive reference to the entry at the given index if any.
263
    unsafe fn get_entry_mut(&self, at: Index) -> Option<&mut StorageEntry<T>> {
264
265
266
        if at >= Self::capacity() {
            return None
        }
267
        (&mut *CacheCell::get_ptr(&self.entries[at as usize]).as_ptr()).as_mut()
268
269
270
271
272
273
274
275
    }

    /// Returns an iterator that yields shared references to all cached entries.
    pub fn iter(&self) -> EntriesIter<T> {
        EntriesIter::new(self)
    }
}

276
impl<T, const N: usize> LazyArray<T, N>
277
278
279
280
281
282
283
284
285
286
287
288
where
    T: PackedLayout,
{
    /// Clears the underlying storage of the entry at the given index.
    ///
    /// # Safety
    ///
    /// For performance reasons this does not synchronize the lazy array's
    /// memory-side cache which invalidates future accesses the cleared entry.
    /// Care should be taken when using this API.
    ///
    /// The general use of this API is to streamline `Drop` implementations of
289
    /// high-level abstractions that build upon this low-level data structure.
290
291
292
293
294
295
296
    pub fn clear_packed_at(&self, index: Index) {
        let root_key = self.key_at(index).expect("cannot clear in lazy state");
        if <T as SpreadLayout>::REQUIRES_DEEP_CLEAN_UP {
            // We need to load the entity before we remove its associated contract storage
            // because it requires a deep clean-up which propagates clearing to its fields,
            // for example in the case of `T` being a `storage::Box`.
            let entity = self.get(index).expect("cannot clear a non existing entity");
297
            clear_packed_root::<T>(entity, &root_key);
298
299
300
        } else {
            // The type does not require deep clean-up so we can simply clean-up
            // its associated storage cell and be done without having to load it first.
301
            ink_env::clear_contract_storage(&root_key);
302
303
304
305
        }
    }
}

306
impl<T, const N: usize> Default for LazyArray<T, N> {
307
308
309
310
311
    fn default() -> Self {
        Self::new()
    }
}

312
impl<T, const N: usize> LazyArray<T, N> {
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
    /// Creates a new empty lazy array.
    ///
    /// # Note
    ///
    /// A lazy array created this way cannot be used to load from the contract storage.
    /// All operations that directly or indirectly load from storage will panic.
    pub fn new() -> Self {
        Self {
            key: None,
            cached_entries: Default::default(),
        }
    }

    /// Creates a new empty lazy array positioned at the given key.
    ///
    /// # Note
    ///
    /// This constructor is private and should never need to be called from
    /// outside this module. It is used to construct a lazy array from a
    /// key that is only useful upon a contract call.
    /// Use [`LazyArray::new`] for construction during contract initialization.
    fn lazy(key: Key) -> Self {
        Self {
            key: Some(key),
            cached_entries: Default::default(),
        }
    }

    /// Returns the constant capacity of the lazy array.
    #[inline]
    pub fn capacity(&self) -> u32 {
        array_capacity::<T, N>()
    }

    /// Returns the offset key of the lazy array if any.
    pub fn key(&self) -> Option<&Key> {
        self.key.as_ref()
    }

    /// Returns a shared reference to the underlying cached entries.
    ///
    /// # Safety
    ///
    /// This operation is safe since it returns a shared reference from
    /// a `&self` which is viable in safe Rust.
    fn cached_entries(&self) -> &EntryArray<T, N> {
        &self.cached_entries
    }

    /// Puts a new value into the given indexed slot.
    ///
    /// # Note
    ///
    /// Use [`LazyArray::put_get`]`(None)` to remove an element.
    pub fn put(&mut self, at: Index, new_value: Option<T>) {
        self.cached_entries().put(at, new_value);
    }
}

372
impl<T, const N: usize> SpreadLayout for LazyArray<T, N>
373
374
375
where
    T: PackedLayout,
{
376
    const FOOTPRINT: u64 = N as u64;
377
378

    fn pull_spread(ptr: &mut KeyPtr) -> Self {
379
        Self::lazy(*ExtKeyPtr::next_for::<Self>(ptr))
380
381
382
    }

    fn push_spread(&self, ptr: &mut KeyPtr) {
383
        let offset_key = ExtKeyPtr::next_for::<Self>(ptr);
384
385
        for (index, entry) in self.cached_entries().iter().enumerate() {
            if let Some(entry) = entry {
386
387
                let key = offset_key + (index as u64);
                entry.push_packed_root(&key);
388
389
390
391
392
393
394
395
396
397
398
399
400
            }
        }
    }

    #[inline]
    fn clear_spread(&self, _ptr: &mut KeyPtr) {
        // Low-level lazy abstractions won't perform automated clean-up since
        // they generally are not aware of their entire set of associated
        // elements. The high-level abstractions that build upon them are
        // responsible for cleaning up.
    }
}

401
impl<T, const N: usize> LazyArray<T, N> {
402
403
404
405
406
    /// Returns the offset key for the given index if not out of bounds.
    pub fn key_at(&self, at: Index) -> Option<Key> {
        if at >= self.capacity() {
            return None
        }
407
        self.key.as_ref().map(|key| key + at as u64)
408
409
410
    }
}

411
impl<T, const N: usize> LazyArray<T, N>
412
413
414
415
416
417
418
where
    T: PackedLayout,
{
    /// Loads the entry at the given index.
    ///
    /// Tries to load the entry from cache and falls back to lazily load the
    /// entry from the contract storage.
419
    fn load_through_cache(&self, at: Index) -> NonNull<StorageEntry<T>> {
420
421
422
423
424
425
426
427
428
429
430
431
432
        assert!(at < self.capacity(), "index is out of bounds");
        match unsafe { self.cached_entries.get_entry_mut(at) } {
            Some(entry) => {
                // Load value from cache.
                NonNull::from(entry)
            }
            None => {
                // Load value from storage and put into cache.
                // Then load value from cache.
                let value = self
                    .key_at(at)
                    .map(|key| pull_packed_root_opt::<T>(&key))
                    .unwrap_or(None);
433
                let entry = StorageEntry::new(value, EntryState::Preserved);
434
435
436
437
438
439
440
441
442
443
444
445
446
447
                unsafe { self.cached_entries.insert_entry(at, entry) }
            }
        }
    }

    /// Loads the entry at the given index.
    ///
    /// Tries to load the entry from cache and falls back to lazily load the
    /// entry from the contract storage.
    ///
    /// # Panics
    ///
    /// - If the lazy array is in a state that forbids lazy loading.
    /// - If the given index is out of bounds.
448
    fn load_through_cache_mut(&mut self, index: Index) -> &mut StorageEntry<T> {
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
        // SAFETY:
        // Returning a `&mut Entry<T>` from within a `&mut self` function
        // won't allow creating aliasing between exclusive references.
        unsafe { &mut *self.load_through_cache(index).as_ptr() }
    }

    /// Returns a shared reference to the element at the given index if any.
    ///
    /// # Note
    ///
    /// This operation eventually loads from contract storage.
    ///
    /// # Panics
    ///
    /// If the given index is out of bounds.
    pub fn get(&self, at: Index) -> Option<&T> {
        unsafe { &*self.load_through_cache(at).as_ptr() }
            .value()
            .into()
    }

    /// Returns an exclusive reference to the element at the given index if any.
    ///
    /// # Note
    ///
    /// This operation eventually loads from contract storage.
    ///
    /// # Panics
    ///
    /// If the given index is out of bounds.
    pub fn get_mut(&mut self, at: Index) -> Option<&mut T> {
        self.load_through_cache_mut(at).value_mut().into()
    }

    /// Puts the new value into the indexed slot and returns the old value if any.
    ///
    /// # Note
    ///
    /// - This operation eventually loads from contract storage.
    /// - Prefer [`LazyArray::put`] if you are not interested in the old value.
    /// - Use [`LazyArray::put_get`]`(None)` to remove an element.
    ///
    /// # Panics
    ///
    /// If the given index is out of bounds.
    pub fn put_get(&mut self, at: Index, new_value: Option<T>) -> Option<T> {
        self.load_through_cache_mut(at).put(new_value)
    }

    /// Swaps the values at indices x and y.
    ///
    /// # Note
    ///
    /// This operation eventually loads from contract storage.
    ///
    /// # Panics
    ///
    /// If any of the given indices is out of bounds.
    pub fn swap(&mut self, a: Index, b: Index) {
        assert!(a < self.capacity(), "a is out of bounds");
        assert!(b < self.capacity(), "b is out of bounds");
        if a == b {
            // Bail out early if both indices are the same.
            return
        }
        let (loaded_a, loaded_b) =
            // SAFETY: The loaded `x` and `y` entries are distinct from each
            //         other guaranteed by the previous checks so they cannot
            //         alias.
            unsafe { (
                &mut *self.load_through_cache(a).as_ptr(),
                &mut *self.load_through_cache(b).as_ptr(),
            ) };
        if loaded_a.value().is_none() && loaded_b.value().is_none() {
            // Bail out since nothing has to be swapped if both values are `None`.
            return
        }
        // At this point at least one of the values is `Some` so we have to
        // perform the swap and set both entry states to mutated.
        loaded_a.replace_state(EntryState::Mutated);
        loaded_b.replace_state(EntryState::Mutated);
        core::mem::swap(loaded_a.value_mut(), loaded_b.value_mut());
    }
}

#[cfg(test)]
mod tests {
    use super::{
        super::{
            EntryState,
539
            StorageEntry,
540
541
542
543
        },
        Index,
        LazyArray,
    };
544
545
546
    use crate::traits::{
        KeyPtr,
        SpreadLayout,
547
548
549
550
    };
    use ink_primitives::Key;

    /// Asserts that the cached entries of the given `imap` is equal to the `expected` slice.
551
    fn assert_cached_entries<const N: usize>(
552
        larray: &LazyArray<u8, N>,
553
        expected: &[(Index, StorageEntry<u8>)],
554
    ) {
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
        let mut len = 0;
        for (given, expected) in larray
            .cached_entries()
            .iter()
            .enumerate()
            .filter_map(|(index, entry)| {
                match entry {
                    Some(entry) => Some((index as u32, entry)),
                    None => None,
                }
            })
            .zip(expected.iter().map(|(index, entry)| (*index, entry)))
        {
            assert_eq!(given, expected);
            len += 1;
        }
        assert_eq!(len, expected.len());
    }

    #[test]
    fn new_works() {
576
        let larray = <LazyArray<u8, 4>>::new();
577
578
579
580
581
582
583
        // Key must be none.
        assert_eq!(larray.key(), None);
        assert_eq!(larray.key_at(0), None);
        assert_eq!(larray.capacity(), 4);
        // Cached elements must be empty.
        assert_cached_entries(&larray, &[]);
        // Same as default:
584
        let default_larray = <LazyArray<u8, 4>>::default();
585
586
587
588
589
590
591
592
        assert_eq!(default_larray.key(), larray.key());
        assert_eq!(default_larray.key_at(0), larray.key_at(0));
        assert_eq!(larray.capacity(), 4);
        assert_cached_entries(&default_larray, &[]);
    }

    #[test]
    fn lazy_works() {
593
        let key = Key::from([0x42; 32]);
594
        let larray = <LazyArray<u8, 4>>::lazy(key);
595
596
597
598
599
600
601
602
603
604
605
        // Key must be Some.
        assert_eq!(larray.key(), Some(&key));
        assert_eq!(larray.key_at(0), Some(key));
        assert_eq!(larray.key_at(1), Some(key + 1u64));
        assert_eq!(larray.capacity(), 4);
        // Cached elements must be empty.
        assert_cached_entries(&larray, &[]);
    }

    #[test]
    fn get_works() {
606
        let mut larray = <LazyArray<u8, 4>>::new();
607
        let nothing_changed = &[
608
609
610
611
            (0, StorageEntry::new(None, EntryState::Preserved)),
            (1, StorageEntry::new(Some(b'B'), EntryState::Mutated)),
            (2, StorageEntry::new(None, EntryState::Preserved)),
            (3, StorageEntry::new(Some(b'D'), EntryState::Mutated)),
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
        ];
        // Put some values.
        assert_eq!(larray.put_get(0, None), None);
        assert_eq!(larray.put_get(1, Some(b'B')), None);
        assert_eq!(larray.put_get(2, None), None);
        assert_eq!(larray.put_get(3, Some(b'D')), None);
        assert_cached_entries(&larray, nothing_changed);
        // `get` works:
        assert_eq!(larray.get(0), None);
        assert_eq!(larray.get(1), Some(&b'B'));
        assert_eq!(larray.get(2), None);
        assert_eq!(larray.get(3), Some(&b'D'));
        assert_cached_entries(&larray, nothing_changed);
        // `get_mut` works:
        assert_eq!(larray.get_mut(0), None);
        assert_eq!(larray.get_mut(1), Some(&mut b'B'));
        assert_eq!(larray.get_mut(2), None);
        assert_eq!(larray.get_mut(3), Some(&mut b'D'));
        assert_cached_entries(&larray, nothing_changed);
    }

    #[test]
    #[should_panic(expected = "index is out of bounds")]
    fn get_out_of_bounds_works() {
636
        let larray = <LazyArray<u8, 4>>::new();
637
638
639
640
641
        let _ = larray.get(4);
    }

    #[test]
    fn put_get_works() {
642
        let mut larray = <LazyArray<u8, 4>>::new();
643
644
645
646
647
648
649
650
651
        // Assert that the array cache is empty at first.
        assert_cached_entries(&larray, &[]);
        // Put none values.
        assert_eq!(larray.put_get(0, None), None);
        assert_eq!(larray.put_get(1, None), None);
        assert_eq!(larray.put_get(3, None), None);
        assert_cached_entries(
            &larray,
            &[
652
653
654
                (0, StorageEntry::new(None, EntryState::Preserved)),
                (1, StorageEntry::new(None, EntryState::Preserved)),
                (3, StorageEntry::new(None, EntryState::Preserved)),
655
656
657
658
659
660
661
662
663
            ],
        );
        // Override with some values.
        assert_eq!(larray.put_get(0, Some(b'A')), None);
        assert_eq!(larray.put_get(1, Some(b'B')), None);
        assert_eq!(larray.put_get(3, None), None);
        assert_cached_entries(
            &larray,
            &[
664
665
666
                (0, StorageEntry::new(Some(b'A'), EntryState::Mutated)),
                (1, StorageEntry::new(Some(b'B'), EntryState::Mutated)),
                (3, StorageEntry::new(None, EntryState::Preserved)),
667
668
669
670
671
672
673
674
            ],
        );
        // Override some values with none.
        assert_eq!(larray.put_get(1, None), Some(b'B'));
        assert_eq!(larray.put_get(3, None), None);
        assert_cached_entries(
            &larray,
            &[
675
676
677
                (0, StorageEntry::new(Some(b'A'), EntryState::Mutated)),
                (1, StorageEntry::new(None, EntryState::Mutated)),
                (3, StorageEntry::new(None, EntryState::Preserved)),
678
679
680
681
682
683
684
            ],
        );
    }

    #[test]
    #[should_panic(expected = "index is out of bounds")]
    fn put_get_out_of_bounds_works() {
685
        let mut larray = <LazyArray<u8, 4>>::new();
686
687
688
689
690
        let _ = larray.put_get(4, Some(b'A'));
    }

    #[test]
    fn put_works() {
691
        let mut larray = <LazyArray<u8, 4>>::new();
692
693
694
695
696
697
698
699
700
701
702
        // Put some values.
        larray.put(0, None);
        larray.put(1, Some(b'B'));
        larray.put(3, None);
        // The main difference between `put` and `put_get` is that `put` never
        // loads from storage which also has one drawback: Putting a `None`
        // value always ends-up in `Mutated` state for the entry even if the
        // entry is already `None`.
        assert_cached_entries(
            &larray,
            &[
703
704
705
                (0, StorageEntry::new(None, EntryState::Mutated)),
                (1, StorageEntry::new(Some(b'B'), EntryState::Mutated)),
                (3, StorageEntry::new(None, EntryState::Mutated)),
706
707
708
709
710
711
712
713
714
715
            ],
        );
        // Overwrite entries:
        larray.put(0, Some(b'A'));
        larray.put(1, None);
        larray.put(2, Some(b'C'));
        larray.put(3, None);
        assert_cached_entries(
            &larray,
            &[
716
717
718
719
                (0, StorageEntry::new(Some(b'A'), EntryState::Mutated)),
                (1, StorageEntry::new(None, EntryState::Mutated)),
                (2, StorageEntry::new(Some(b'C'), EntryState::Mutated)),
                (3, StorageEntry::new(None, EntryState::Mutated)),
720
721
722
723
724
725
726
            ],
        );
    }

    #[test]
    #[should_panic(expected = "index out of bounds: the len is 4 but the index is 4")]
    fn put_out_of_bounds_works() {
727
        let mut larray = <LazyArray<u8, 4>>::new();
728
729
730
731
732
        larray.put(4, Some(b'A'));
    }

    #[test]
    fn swap_works() {
733
        let mut larray = <LazyArray<u8, 4>>::new();
734
        let nothing_changed = &[
735
736
737
738
            (0, StorageEntry::new(Some(b'A'), EntryState::Mutated)),
            (1, StorageEntry::new(Some(b'B'), EntryState::Mutated)),
            (2, StorageEntry::new(None, EntryState::Preserved)),
            (3, StorageEntry::new(None, EntryState::Preserved)),
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
        ];
        // Put some values.
        assert_eq!(larray.put_get(0, Some(b'A')), None);
        assert_eq!(larray.put_get(1, Some(b'B')), None);
        assert_eq!(larray.put_get(2, None), None);
        assert_eq!(larray.put_get(3, None), None);
        assert_cached_entries(&larray, nothing_changed);
        // Swap same indices: Check that nothing has changed.
        for i in 0..4 {
            larray.swap(i, i);
        }
        assert_cached_entries(&larray, nothing_changed);
        // Swap `None` values: Check that nothing has changed.
        larray.swap(2, 3);
        larray.swap(3, 2);
        assert_cached_entries(&larray, nothing_changed);
        // Swap `Some` and `None`:
        larray.swap(0, 2);
        assert_cached_entries(
            &larray,
            &[
760
761
762
763
                (0, StorageEntry::new(None, EntryState::Mutated)),
                (1, StorageEntry::new(Some(b'B'), EntryState::Mutated)),
                (2, StorageEntry::new(Some(b'A'), EntryState::Mutated)),
                (3, StorageEntry::new(None, EntryState::Preserved)),
764
765
766
767
768
769
770
            ],
        );
        // Swap `Some` and `Some`:
        larray.swap(1, 2);
        assert_cached_entries(
            &larray,
            &[
771
772
773
774
                (0, StorageEntry::new(None, EntryState::Mutated)),
                (1, StorageEntry::new(Some(b'A'), EntryState::Mutated)),
                (2, StorageEntry::new(Some(b'B'), EntryState::Mutated)),
                (3, StorageEntry::new(None, EntryState::Preserved)),
775
776
777
778
779
780
781
            ],
        );
    }

    #[test]
    #[should_panic(expected = "b is out of bounds")]
    fn swap_rhs_out_of_bounds() {
782
        let mut larray = <LazyArray<u8, 4>>::new();
783
784
785
786
787
788
        larray.swap(0, 4);
    }

    #[test]
    #[should_panic(expected = "a is out of bounds")]
    fn swap_both_out_of_bounds() {
789
        let mut larray = <LazyArray<u8, 4>>::new();
790
791
792
793
        larray.swap(4, 4);
    }

    #[test]
794
    fn spread_layout_works() -> ink_env::Result<()> {
795
        ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| {
796
            let mut larray = <LazyArray<u8, 4>>::new();
797
            let nothing_changed = &[
798
799
800
801
                (0, StorageEntry::new(Some(b'A'), EntryState::Mutated)),
                (1, StorageEntry::new(Some(b'B'), EntryState::Mutated)),
                (2, StorageEntry::new(None, EntryState::Preserved)),
                (3, StorageEntry::new(None, EntryState::Preserved)),
802
803
804
805
806
807
808
809
810
811
            ];
            // Put some values.
            assert_eq!(larray.put_get(0, Some(b'A')), None);
            assert_eq!(larray.put_get(1, Some(b'B')), None);
            assert_eq!(larray.put_get(2, None), None);
            assert_eq!(larray.put_get(3, None), None);
            assert_cached_entries(&larray, nothing_changed);
            // Push the lazy index map onto the contract storage and then load
            // another instance of it from the contract stoarge.
            // Then: Compare both instances to be equal.
812
            let root_key = Key::from([0x42; 32]);
813
            SpreadLayout::push_spread(&larray, &mut KeyPtr::from(root_key));
814
            let larray2 = <LazyArray<u8, 4> as SpreadLayout>::pull_spread(
815
816
817
818
819
820
821
822
823
824
                &mut KeyPtr::from(root_key),
            );
            assert_cached_entries(&larray2, &[]);
            assert_eq!(larray2.get(0), Some(&b'A'));
            assert_eq!(larray2.get(1), Some(&b'B'));
            assert_eq!(larray2.get(2), None);
            assert_eq!(larray2.get(3), None);
            assert_cached_entries(
                &larray2,
                &[
825
826
827
828
                    (0, StorageEntry::new(Some(b'A'), EntryState::Preserved)),
                    (1, StorageEntry::new(Some(b'B'), EntryState::Preserved)),
                    (2, StorageEntry::new(None, EntryState::Preserved)),
                    (3, StorageEntry::new(None, EntryState::Preserved)),
829
830
831
832
833
834
835
836
837
838
839
840
841
842
                ],
            );
            // Clear the first lazy index map instance and reload another instance
            // to check whether the associated storage has actually been freed
            // again:
            SpreadLayout::clear_spread(&larray2, &mut KeyPtr::from(root_key));
            // The above `clear_spread` call is a no-op since lazy index map is
            // generally not aware of its associated elements. So we have to
            // manually clear them from the contract storage which is what the
            // high-level data structures like `storage::Vec` would command:
            larray2.clear_packed_at(0);
            larray2.clear_packed_at(1);
            larray2.clear_packed_at(2); // Not really needed here.
            larray2.clear_packed_at(3); // Not really needed here.
843
            let larray3 = <LazyArray<u8, 4> as SpreadLayout>::pull_spread(
844
845
846
847
848
849
850
851
852
853
                &mut KeyPtr::from(root_key),
            );
            assert_cached_entries(&larray3, &[]);
            assert_eq!(larray3.get(0), None);
            assert_eq!(larray3.get(1), None);
            assert_eq!(larray3.get(2), None);
            assert_eq!(larray3.get(3), None);
            assert_cached_entries(
                &larray3,
                &[
854
855
856
857
                    (0, StorageEntry::new(None, EntryState::Preserved)),
                    (1, StorageEntry::new(None, EntryState::Preserved)),
                    (2, StorageEntry::new(None, EntryState::Preserved)),
                    (3, StorageEntry::new(None, EntryState::Preserved)),
858
859
860
861
862
863
                ],
            );
            Ok(())
        })
    }
}