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
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
//
// 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.

//! Low-level collections and data structures to manage storage entities in the
//! persisted contract storage.
//!
//! Users should generally avoid using these collections directly in their
//! contracts and should instead adhere to the high-level collections found
//! in [`collections`][`crate::collections`].
//! The low-level collections are mainly used as building blocks for internals
//! of other higher-level storage collections.
//!
//! These low-level collections are not aware of the elements they manage thus
//! extra care has to be taken when operating directly on them.

pub mod lazy_hmap;
pub mod mapping;

mod cache_cell;
mod entry;
mod lazy_array;
mod lazy_cell;
mod lazy_imap;

#[doc(inline)]
pub use self::lazy_array::LazyArray;
use self::{
    cache_cell::CacheCell,
    entry::{
        EntryState,
        StorageEntry,
    },
};
#[doc(inline)]
pub use self::{
    lazy_cell::LazyCell,
    lazy_hmap::LazyHashMap,
    lazy_imap::LazyIndexMap,
    mapping::Mapping,
};
use crate::traits::{
    KeyPtr,
    SpreadAllocate,
    SpreadLayout,
};
use ink_primitives::Key;

/// A lazy storage entity.
///
/// This loads its value from storage upon first use.
///
/// # Note
///
/// Use this if the storage field does not need to be loaded in some or most cases.
#[derive(Debug)]
pub struct Lazy<T>
where
    T: SpreadLayout,
{
    cell: LazyCell<T>,
}

#[cfg(feature = "std")]
const _: () = {
    use crate::traits::StorageLayout;
    use ink_metadata::layout::Layout;

    impl<T> StorageLayout for Lazy<T>
    where
        T: StorageLayout + SpreadLayout,
    {
        fn layout(key_ptr: &mut KeyPtr) -> Layout {
            <T as StorageLayout>::layout(key_ptr)
        }
    }
};

impl<T> SpreadLayout for Lazy<T>
where
    T: SpreadLayout,
{
    const FOOTPRINT: u64 = <T as SpreadLayout>::FOOTPRINT;

    fn pull_spread(ptr: &mut KeyPtr) -> Self {
        Self {
            cell: <LazyCell<T> as SpreadLayout>::pull_spread(ptr),
        }
    }

    fn push_spread(&self, ptr: &mut KeyPtr) {
        SpreadLayout::push_spread(&self.cell, ptr)
    }

    fn clear_spread(&self, ptr: &mut KeyPtr) {
        SpreadLayout::clear_spread(&self.cell, ptr)
    }
}

impl<T> SpreadAllocate for Lazy<T>
where
    T: SpreadLayout,
{
    fn allocate_spread(ptr: &mut KeyPtr) -> Self {
        Self {
            cell: <LazyCell<T> as SpreadAllocate>::allocate_spread(ptr),
        }
    }
}

impl<T> Lazy<T>
where
    T: SpreadLayout,
{
    /// Creates an eagerly populated lazy storage value.
    #[must_use]
    pub fn new(value: T) -> Self {
        Self {
            cell: LazyCell::new(Some(value)),
        }
    }

    /// Creates a true lazy storage value for the given key.
    #[must_use]
    pub(crate) fn from_key(key: Key) -> Self {
        Self {
            cell: LazyCell::lazy(key),
        }
    }
}

impl<T> Lazy<T>
where
    T: SpreadLayout,
{
    /// Returns a shared reference to the lazily loaded value.
    ///
    /// # Note
    ///
    /// This loads the value from the contract storage if this did not happen before.
    ///
    /// # Panics
    ///
    /// If loading from contract storage failed.
    #[must_use]
    pub fn get(lazy: &Self) -> &T {
        lazy.cell.get().expect("encountered empty storage cell")
    }

    /// Returns an exclusive reference to the lazily loaded value.
    ///
    /// # Note
    ///
    /// This loads the value from the contract storage if this did not happen before.
    ///
    /// # Panics
    ///
    /// If loading from contract storage failed.
    #[must_use]
    pub fn get_mut(lazy: &mut Self) -> &mut T {
        lazy.cell.get_mut().expect("encountered empty storage cell")
    }

    /// Sets the value to `value`, without executing any reads.
    ///
    /// # Note
    ///
    /// No reads from contract storage will be executed.
    ///
    /// This method should be preferred over dereferencing or `get_mut`
    /// in case the returned value is of no interest to the caller.
    ///
    /// # Panics
    ///
    /// If accessing the inner value fails.
    #[inline]
    pub fn set(lazy: &mut Self, new_value: T) {
        lazy.cell.set(new_value);
    }
}

impl<T> From<T> for Lazy<T>
where
    T: SpreadLayout,
{
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl<T> Default for Lazy<T>
where
    T: Default + SpreadLayout,
{
    fn default() -> Self {
        Self::new(Default::default())
    }
}

impl<T> core::cmp::PartialEq for Lazy<T>
where
    T: PartialEq + SpreadLayout,
{
    fn eq(&self, other: &Self) -> bool {
        PartialEq::eq(Lazy::get(self), Lazy::get(other))
    }
}

impl<T> core::cmp::Eq for Lazy<T> where T: Eq + SpreadLayout {}

impl<T> core::cmp::PartialOrd for Lazy<T>
where
    T: PartialOrd + SpreadLayout,
{
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        PartialOrd::partial_cmp(Lazy::get(self), Lazy::get(other))
    }
    fn lt(&self, other: &Self) -> bool {
        PartialOrd::lt(Lazy::get(self), Lazy::get(other))
    }
    fn le(&self, other: &Self) -> bool {
        PartialOrd::le(Lazy::get(self), Lazy::get(other))
    }
    fn ge(&self, other: &Self) -> bool {
        PartialOrd::ge(Lazy::get(self), Lazy::get(other))
    }
    fn gt(&self, other: &Self) -> bool {
        PartialOrd::gt(Lazy::get(self), Lazy::get(other))
    }
}

impl<T> core::cmp::Ord for Lazy<T>
where
    T: core::cmp::Ord + SpreadLayout,
{
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        Ord::cmp(Lazy::get(self), Lazy::get(other))
    }
}

impl<T> core::fmt::Display for Lazy<T>
where
    T: core::fmt::Display + SpreadLayout,
{
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        core::fmt::Display::fmt(Lazy::get(self), f)
    }
}

impl<T> core::hash::Hash for Lazy<T>
where
    T: core::hash::Hash + SpreadLayout,
{
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        Lazy::get(self).hash(state);
    }
}

impl<T> core::convert::AsRef<T> for Lazy<T>
where
    T: SpreadLayout,
{
    fn as_ref(&self) -> &T {
        Lazy::get(self)
    }
}

impl<T> core::convert::AsMut<T> for Lazy<T>
where
    T: SpreadLayout,
{
    fn as_mut(&mut self) -> &mut T {
        Lazy::get_mut(self)
    }
}

impl<T> ink_prelude::borrow::Borrow<T> for Lazy<T>
where
    T: SpreadLayout,
{
    fn borrow(&self) -> &T {
        Lazy::get(self)
    }
}

impl<T> ink_prelude::borrow::BorrowMut<T> for Lazy<T>
where
    T: SpreadLayout,
{
    fn borrow_mut(&mut self) -> &mut T {
        Lazy::get_mut(self)
    }
}

impl<T> core::ops::Deref for Lazy<T>
where
    T: SpreadLayout,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        Lazy::get(self)
    }
}

impl<T> core::ops::DerefMut for Lazy<T>
where
    T: SpreadLayout,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        Lazy::get_mut(self)
    }
}