pack.rs 14.5 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
//
// 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.

15
use crate::traits::{
16
    clear_spread_root,
17
18
19
20
21
22
23
    forward_clear_packed,
    forward_pull_packed,
    forward_push_packed,
    KeyPtr,
    PackedLayout,
    SpreadLayout,
};
24
use ink_prelude::vec::Vec;
25
26
27
28
29
30
31
use ink_primitives::Key;

/// Packs the inner `T` so that it only occupies a single contract storage cell.
///
/// # Note
///
/// This is an important modular building stone in order to manage contract
32
/// storage occupation. By default, types try to distribute themselves onto
33
34
35
36
37
38
39
/// their respective contract storage area. However, upon packing them into
/// `Pack<T>` they will be compressed to only ever make use of a single
/// contract storage cell. Sometimes this can be advantageous for performance
/// reasons.
///
/// # Usage
///
40
41
42
/// - A `Pack<i32>` instance is equivalent to `i32` in its storage occupation.
/// - A `Pack<(i32, i32)>` instance will occupy a single cell compared to
///   `(i32, i32)` which occupies a cell per `i32`.
43
/// - A `Lazy<Pack<[u8; 8]>>` lazily loads a `Pack<[u8; 8]>` which occupies
44
45
///   a single cell whereas a `[u8; 8]` array would occupy 8 cells in total,
///   one for each `u8`.
46
47
48
49
50
51
52
53
54
55
56
57
/// - Rust collections will never use more than a single cell. So
///   `Pack<LinkedList<T>>` and `LinkedList<T>` will occupy the same amount of
///   cells, namely 1.
/// - Packs can be packed. So for example a
///   `Pack<(Pack<(i32, i32)>, Pack<[u8; 8]>)` uses just one cell instead of
///   two cells which is the case for `(Pack<(i32, i32)>, Pack<[u8; 8]>)`.
/// - Not all `storage` types can be packed. Only those that are implementing
///   the `PackedLayout` trait. For example `storage::Vec<T>` does not implement
///   this trait and thus cannot be packed.
///
/// As a general advice pack values together that are frequently used together.
/// Also pack many very small elements (e.g. `u8`, `bool`, `u16`) together.
58
59
60
61
62
#[derive(Debug, Clone)]
pub struct Pack<T>
where
    T: PackedLayout,
{
63
64
    /// The packed `T` value.
    inner: T,
65
66
67
68
69
70
71
    /// The key to load the packed value from.
    ///
    /// # Note
    ///
    /// This can be `None` on contract initialization, but will be
    /// initialized with a concrete value on `pull_spread`.
    key: Option<Key>,
72
73
}

74
75
76
77
78
79
80
impl<T> scale::Encode for Pack<T>
where
    T: scale::Encode + PackedLayout,
{
    #[inline]
    fn size_hint(&self) -> usize {
        <T as scale::Encode>::size_hint(&self.inner)
81
82
    }

83
    #[inline]
84
    fn encode_to<O: scale::Output + ?Sized>(&self, dest: &mut O) {
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
        <T as scale::Encode>::encode_to(&self.inner, dest)
    }

    #[inline]
    fn encode(&self) -> Vec<u8> {
        <T as scale::Encode>::encode(&self.inner)
    }

    #[inline]
    fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
        <T as scale::Encode>::using_encoded(&self.inner, f)
    }
}

impl<T> scale::Decode for Pack<T>
where
    T: scale::Decode + PackedLayout,
{
    fn decode<I: scale::Input>(input: &mut I) -> Result<Self, scale::Error> {
        Ok(Self::new(<T as scale::Decode>::decode(input)?))
    }
}

impl<T> Pack<T>
where
    T: PackedLayout,
{
    /// Creates a new packed value.
    pub fn new(value: T) -> Self {
        Self {
            inner: value,
            key: None,
        }
118
119
120
121
122
123
124
125
126
127
128
129
130
    }

    /// Returns a shared reference to the packed value.
    pub fn as_inner(pack: &Pack<T>) -> &T {
        &pack.inner
    }

    /// Returns an exclusive reference to the packed value.
    pub fn as_inner_mut(pack: &mut Pack<T>) -> &mut T {
        &mut pack.inner
    }
}

131
132
133
134
135
136
137
138
139
140
141
impl<T> Drop for Pack<T>
where
    T: PackedLayout,
{
    fn drop(&mut self) {
        if let Some(key) = self.key {
            clear_spread_root::<T>(&self.inner, &key)
        }
    }
}

142
143
#[cfg(feature = "std")]
const _: () = {
144
    use crate::traits::StorageLayout;
145
    use ink_metadata::layout::{
146
147
148
149
        CellLayout,
        Layout,
        LayoutKey,
    };
150
    use scale_info::TypeInfo;
151
152
153

    impl<T> StorageLayout for Pack<T>
    where
154
        T: PackedLayout + TypeInfo + 'static,
155
156
157
158
159
160
161
    {
        fn layout(key_ptr: &mut KeyPtr) -> Layout {
            Layout::Cell(CellLayout::new::<T>(LayoutKey::from(key_ptr.advance_by(1))))
        }
    }
};

162
163
164
165
166
167
168
impl<T> SpreadLayout for Pack<T>
where
    T: PackedLayout,
{
    const FOOTPRINT: u64 = 1;

    fn pull_spread(ptr: &mut KeyPtr) -> Self {
169
170
171
172
173
        let inner = forward_pull_packed::<T>(ptr);
        Self {
            inner,
            key: Some(*ptr.key()),
        }
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
    }

    fn push_spread(&self, ptr: &mut KeyPtr) {
        forward_push_packed::<T>(Self::as_inner(self), ptr)
    }

    fn clear_spread(&self, ptr: &mut KeyPtr) {
        forward_clear_packed::<T>(Self::as_inner(self), ptr)
    }
}

impl<T> PackedLayout for Pack<T>
where
    T: PackedLayout,
{
    fn pull_packed(&mut self, at: &Key) {
        <T as PackedLayout>::pull_packed(Self::as_inner_mut(self), at)
    }
    fn push_packed(&self, at: &Key) {
        <T as PackedLayout>::push_packed(Self::as_inner(self), at)
    }
    fn clear_packed(&self, at: &Key) {
        <T as PackedLayout>::clear_packed(Self::as_inner(self), at)
    }
}

200
201
202
203
impl<T> From<T> for Pack<T>
where
    T: PackedLayout,
{
204
205
206
207
208
209
210
    fn from(value: T) -> Self {
        Self::new(value)
    }
}

impl<T> Default for Pack<T>
where
211
    T: Default + PackedLayout,
212
213
214
215
216
217
{
    fn default() -> Self {
        Self::new(Default::default())
    }
}

218
219
220
221
impl<T> core::ops::Deref for Pack<T>
where
    T: PackedLayout,
{
222
223
224
225
226
227
228
    type Target = T;

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

229
230
231
232
impl<T> core::ops::DerefMut for Pack<T>
where
    T: PackedLayout,
{
233
234
235
236
237
238
239
    fn deref_mut(&mut self) -> &mut Self::Target {
        Self::as_inner_mut(self)
    }
}

impl<T> core::cmp::PartialEq for Pack<T>
where
240
    T: PartialEq + PackedLayout,
241
242
243
244
245
246
{
    fn eq(&self, other: &Self) -> bool {
        PartialEq::eq(Self::as_inner(self), Self::as_inner(other))
    }
}

247
impl<T> core::cmp::Eq for Pack<T> where T: Eq + PackedLayout {}
248
249
250

impl<T> core::cmp::PartialOrd for Pack<T>
where
251
    T: PartialOrd + PackedLayout,
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
{
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        PartialOrd::partial_cmp(Self::as_inner(self), Self::as_inner(other))
    }
    fn lt(&self, other: &Self) -> bool {
        PartialOrd::lt(Self::as_inner(self), Self::as_inner(other))
    }
    fn le(&self, other: &Self) -> bool {
        PartialOrd::le(Self::as_inner(self), Self::as_inner(other))
    }
    fn ge(&self, other: &Self) -> bool {
        PartialOrd::ge(Self::as_inner(self), Self::as_inner(other))
    }
    fn gt(&self, other: &Self) -> bool {
        PartialOrd::gt(Self::as_inner(self), Self::as_inner(other))
    }
}

impl<T> core::cmp::Ord for Pack<T>
where
272
    T: core::cmp::Ord + PackedLayout,
273
274
275
276
277
278
279
280
{
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        Ord::cmp(Self::as_inner(self), Self::as_inner(other))
    }
}

impl<T> core::fmt::Display for Pack<T>
where
281
    T: core::fmt::Display + PackedLayout,
282
283
284
285
286
287
288
289
{
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        core::fmt::Display::fmt(Self::as_inner(self), f)
    }
}

impl<T> core::hash::Hash for Pack<T>
where
290
    T: core::hash::Hash + PackedLayout,
291
292
293
294
295
296
{
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        Self::as_inner(self).hash(state);
    }
}

297
298
299
300
impl<T> core::convert::AsRef<T> for Pack<T>
where
    T: PackedLayout,
{
301
302
303
304
305
    fn as_ref(&self) -> &T {
        Self::as_inner(self)
    }
}

306
307
308
309
impl<T> core::convert::AsMut<T> for Pack<T>
where
    T: PackedLayout,
{
310
311
312
313
314
    fn as_mut(&mut self) -> &mut T {
        Self::as_inner_mut(self)
    }
}

315
316
317
318
impl<T> ink_prelude::borrow::Borrow<T> for Pack<T>
where
    T: PackedLayout,
{
319
320
321
322
323
    fn borrow(&self) -> &T {
        Self::as_inner(self)
    }
}

324
325
326
327
impl<T> ink_prelude::borrow::BorrowMut<T> for Pack<T>
where
    T: PackedLayout,
{
328
329
330
331
332
333
334
335
    fn borrow_mut(&mut self) -> &mut T {
        Self::as_inner_mut(self)
    }
}

#[cfg(test)]
mod tests {
    use super::Pack;
336
337
338
339
    use crate::traits::{
        pull_packed_root,
        push_packed_root,
        KeyPtr,
340
        PackedLayout,
341
        SpreadLayout,
342
343
344
345
346
347
348
349
350
351
352
353
    };
    use core::{
        cmp::Ordering,
        convert::{
            AsMut,
            AsRef,
        },
        ops::{
            Deref,
            DerefMut,
        },
    };
354
    use ink_env::test::DefaultAccounts;
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
    use ink_prelude::borrow::{
        Borrow,
        BorrowMut,
    };
    use ink_primitives::Key;

    type ComplexTuple = (u8, [i32; 4], (bool, i32));

    fn complex_value() -> ComplexTuple {
        (b'A', [0x00; 4], (true, 42))
    }

    #[test]
    fn new_works() {
        let mut expected = complex_value();
        let mut pack = Pack::new(expected);
        assert_eq!(<Pack<_> as Deref>::deref(&pack), &expected);
        assert_eq!(<Pack<_> as DerefMut>::deref_mut(&mut pack), &mut expected);
        assert_eq!(<Pack<_> as AsRef<_>>::as_ref(&pack), &expected);
        assert_eq!(<Pack<_> as AsMut<_>>::as_mut(&mut pack), &mut expected);
        assert_eq!(Borrow::<ComplexTuple>::borrow(&pack), &expected);
        assert_eq!(
            BorrowMut::<ComplexTuple>::borrow_mut(&mut pack),
            &mut expected
        );
        assert_eq!(Pack::as_inner(&pack), &expected);
        assert_eq!(Pack::as_inner_mut(&mut pack), &mut expected);
382
        assert_eq!(pack.inner, expected);
383
384
385
386
387
388
389
390
391
    }

    #[test]
    fn from_works() {
        let mut expected = complex_value();
        let mut from = Pack::from(expected);
        assert_eq!(from, Pack::new(expected));
        assert_eq!(Pack::as_inner(&from), &expected);
        assert_eq!(Pack::as_inner_mut(&mut from), &mut expected);
392
        assert_eq!(from.inner, expected);
393
394
395
396
397
398
399
    }

    #[test]
    fn default_works() {
        use core::fmt::Debug;
        fn assert_default<T>()
        where
400
            T: Debug + Default + PartialEq + PackedLayout,
401
402
        {
            let pack_default = <Pack<T> as Default>::default();
403
            assert_eq!(pack_default.inner, <T as Default>::default());
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
        }
        assert_default::<bool>();
        assert_default::<u8>();
        assert_default::<Option<i32>>();
        assert_default::<Pack<[u8; 4]>>();
    }

    #[test]
    fn partial_eq_works() {
        let b1 = Pack::new(b'X');
        let b2 = Pack::new(b'Y');
        let b3 = Pack::new(b'X');
        assert!(<Pack<u8> as PartialEq>::ne(&b1, &b2));
        assert!(<Pack<u8> as PartialEq>::eq(&b1, &b3));
    }

    #[test]
    fn partial_ord_works() {
        let b1 = Pack::new(1);
        let b2 = Pack::new(2);
        let b3 = Pack::new(1);
        assert_eq!(
            <Pack<u8> as PartialOrd>::partial_cmp(&b1, &b2),
            Some(Ordering::Less)
        );
        assert_eq!(
            <Pack<u8> as PartialOrd>::partial_cmp(&b2, &b1),
            Some(Ordering::Greater)
        );
        assert_eq!(
            <Pack<u8> as PartialOrd>::partial_cmp(&b1, &b3),
            Some(Ordering::Equal)
        );
        // Less-than
        assert!(<Pack<u8> as PartialOrd>::lt(&b1, &b2));
        // Less-than-or-equals
        assert!(<Pack<u8> as PartialOrd>::le(&b1, &b2));
        assert!(<Pack<u8> as PartialOrd>::le(&b1, &b3));
        // Greater-than
        assert!(<Pack<u8> as PartialOrd>::gt(&b2, &b1));
        // Greater-than-or-equals
        assert!(<Pack<u8> as PartialOrd>::ge(&b2, &b1));
        assert!(<Pack<u8> as PartialOrd>::ge(&b3, &b1));
    }

    fn run_test<F>(f: F)
    where
451
        F: FnOnce(DefaultAccounts<ink_env::DefaultEnvironment>),
452
    {
453
        ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|default_accounts| {
454
455
456
457
458
459
460
461
462
463
464
            f(default_accounts);
            Ok(())
        })
        .unwrap()
    }

    #[test]
    fn spread_layout_push_pull_works() {
        run_test(|_| {
            let p1 = Pack::new((b'A', [0x00; 4], (true, 42)));
            assert_eq!(*p1, (b'A', [0x00; 4], (true, 42)));
465
            let root_key = Key::from([0x42; 32]);
466
467
468
469
470
471
472
473
474
475
476
477
478
479
            SpreadLayout::push_spread(&p1, &mut KeyPtr::from(root_key));
            // Now load another instance of a pack from the same key and check
            // if both instances are equal:
            let p2 = SpreadLayout::pull_spread(&mut KeyPtr::from(root_key));
            assert_eq!(p1, p2);
        })
    }

    #[test]
    #[should_panic(expected = "storage entry was empty")]
    fn spread_layout_clear_works() {
        run_test(|_| {
            let p1 = Pack::new((b'A', [0x00; 4], (true, 42)));
            assert_eq!(*p1, (b'A', [0x00; 4], (true, 42)));
480
            let root_key = Key::from([0x42; 32]);
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
            SpreadLayout::push_spread(&p1, &mut KeyPtr::from(root_key));
            // Now load another instance of a pack from the same key and check
            // if both instances are equal:
            let p2 = SpreadLayout::pull_spread(&mut KeyPtr::from(root_key));
            assert_eq!(p1, p2);
            // Clearing the underlying storage of p2 immediately so that
            // loading another instance of pack again should panic.
            SpreadLayout::clear_spread(&p2, &mut KeyPtr::from(root_key));
            let p3 = SpreadLayout::pull_spread(&mut KeyPtr::from(root_key));
            assert_eq!(p1, p3);
        })
    }

    #[test]
    fn spread_and_packed_layout_are_equal() {
        run_test(|_| {
            // Push as spread, pull as packed:
            let p1 = Pack::new((b'A', [0x00; 4], (true, 42)));
            assert_eq!(*p1, (b'A', [0x00; 4], (true, 42)));
500
            let root_key = Key::from([0x42; 32]);
501
502
503
504
            SpreadLayout::push_spread(&p1, &mut KeyPtr::from(root_key));
            let p2 = pull_packed_root::<Pack<(u8, [i32; 4], (bool, i32))>>(&root_key);
            assert_eq!(p1, p2);
            // Push as packed, pull as spread:
505
            let root_key2 = Key::from([0x43; 32]);
506
507
508
509
510
511
            push_packed_root(&p2, &root_key2);
            let p3 = SpreadLayout::pull_spread(&mut KeyPtr::from(root_key2));
            assert_eq!(p2, p3);
        })
    }
}
512
513
514
515
516
517
518
519
520
521
522
523
524
525

#[cfg(all(test, feature = "std", feature = "ink-fuzz-tests"))]
use quickcheck::{
    Arbitrary,
    Gen,
};

#[cfg(all(test, feature = "std", feature = "ink-fuzz-tests"))]
impl<T: Arbitrary + PackedLayout + Send + Clone + 'static> Arbitrary for Pack<T> {
    fn arbitrary(g: &mut Gen) -> Pack<T> {
        let a = <T as Arbitrary>::arbitrary(g);
        Pack::new(a)
    }
}