/
storage_vec.sw
886 lines (824 loc) 路 25.7 KB
/
storage_vec.sw
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
library;
use ::alloc::{alloc_bytes, realloc_bytes};
use ::assert::assert;
use ::hash::*;
use ::option::Option::{self, *};
use ::storage::storage_api::*;
use ::storage::storage_key::*;
use ::vec::Vec;
/// A persistent vector struct.
pub struct StorageVec<V> {}
impl<V> StorageKey<StorageVec<V>> {
/// Appends the value to the end of the vector.
///
/// # Arguments
///
/// * `value`: [V] - The item being added to the end of the vector.
///
/// # Number of Storage Accesses
///
/// * Reads: `3`
/// * Writes: `2`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// let five = 5_u64;
/// storage.vec.push(five);
/// assert(five == storage.vec.get(0).unwrap());
/// }
/// ```
#[storage(read, write)]
pub fn push(self, value: V) {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
// Storing the value at the current length index (if this is the first item, starts off at 0)
let key = sha256(self.field_id());
let offset = offset_calculator::<V>(len);
write::<V>(key, offset, value);
// Incrementing the length
write(self.field_id(), 0, len + 1);
}
/// Removes the last element of the vector and returns it, `None` if empty.
///
/// # Returns
///
/// * [Option<V>] - The last element `V` or `None`.
///
/// # Number of Storage Accesses
///
/// * Reads: `3`
/// * Writes: `1`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// let five = 5_u64;
/// storage.vec.push(five);
/// let popped_value = storage.vec.pop().unwrap();
/// assert(five == popped_value);
/// let none_value = storage.vec.pop();
/// assert(none_value.is_none())
/// }
/// ```
#[storage(read, write)]
pub fn pop(self) -> Option<V> {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
// if the length is 0, there is no item to pop from the vec
if len == 0 {
return None;
}
// reduces len by 1, effectively removing the last item in the vec
write(self.field_id(), 0, len - 1);
let key = sha256(self.field_id());
let offset = offset_calculator::<V>(len - 1);
read::<V>(key, offset)
}
/// Gets the value in the given index, `None` if index is out of bounds.
///
/// # Arguments
///
/// * `index`: [u64] - The index of the vec to retrieve the item from.
///
/// # Returns
///
/// * [Option<StorageKey<V>>] - Describes the raw location in storage of the value stored at
/// `key` or `None` if out of bounds.
///
/// # Number of Storage Accesses
///
/// * Reads: `1`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// let five = 5_u64;
/// storage.vec.push(five);
/// assert(five == storage.vec.get(0).unwrap());
/// assert(storage.vec.get(1).is_none())
/// }
/// ```
#[storage(read)]
pub fn get(self, index: u64) -> Option<StorageKey<V>> {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
// if the index is larger or equal to len, there is no item to return
if len <= index {
return None;
}
let key = sha256(self.field_id());
let offset = offset_calculator::<V>(index);
// This StorageKey can be read by the standard storage api.
// Field Id must be unique such that nested storage vecs work as they have a
// __size_of() zero and will therefore always have an offset of zero.
Some(StorageKey::<V>::new(key, offset, sha256((index, key))))
}
/// Removes the element in the given index and moves all the elements in the following indexes
/// down one index. Also returns the element.
///
/// # Additional Information
///
/// **_WARNING:_** Expensive for larger vecs.
///
/// # Arguments
///
/// * `index`: [u64] - The index of the vec to remove the item from.
///
/// # Returns
///
/// * [V] - The element that has been removed at the index.
///
/// # Reverts
///
/// * Reverts if index is larger or equal to length of the vec.
///
/// # Number of Storage Accesses
///
/// * Reads: `3 + (2 * (self.len() - index))`
/// * Writes: `self.len() - index`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// storage.vec.push(5);
/// storage.vec.push(10);
/// storage.vec.push(15);
/// let removed_value = storage.vec.remove(1);
/// assert(10 == removed_value);
/// assert(storage.vec.len() == 2);
/// }
/// ```
#[storage(read, write)]
pub fn remove(self, index: u64) -> V {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
// if the index is larger or equal to len, there is no item to remove
assert(index < len);
// gets the element before removing it, so it can be returned
let key = sha256(self.field_id());
let removed_offset = offset_calculator::<V>(index);
let removed_element = read::<V>(key, removed_offset).unwrap();
// for every element in the vec with an index greater than the input index,
// shifts the index for that element down one
let mut count = index + 1;
while count < len {
// gets the storage location for the previous index and
// moves the element of the current index into the previous index
let write_offset = offset_calculator::<V>(count - 1);
let read_offset = offset_calculator::<V>(count);
write::<V>(key, write_offset, read::<V>(key, read_offset).unwrap());
count += 1;
}
// decrements len by 1
write(self.field_id(), 0, len - 1);
removed_element
}
/// Removes the element at the specified index and fills it with the last element.
/// This does not preserve ordering and returns the element.
///
/// # Arguments
///
/// * `index`: [u64] - The index of the vec to remove the item from.
///
/// # Returns
///
/// * [V] - The element that has been removed at the index.
///
/// # Reverts
///
/// * Reverts if index is larger or equal to length of the vec.
///
/// # Number of Storage Accesses
///
/// * Reads: `5`
/// * Writes: `2`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// storage.vec.push(5);
/// storage.vec.push(10);
/// storage.vec.push(15);
/// let removed_value = storage.vec.swap_remove(0);
/// assert(5 == removed_value);
/// let swapped_value = storage.vec.get(0).unwrap();
/// assert(15 == swapped_value);
/// }
/// ```
#[storage(read, write)]
pub fn swap_remove(self, index: u64) -> V {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
// if the index is larger or equal to len, there is no item to remove
assert(index < len);
let key = sha256(self.field_id());
// gets the element before removing it, so it can be returned
let element_offset = offset_calculator::<V>(index);
let element_to_be_removed = read::<V>(key, element_offset).unwrap();
let last_offset = offset_calculator::<V>(len - 1);
let last_element = read::<V>(key, last_offset).unwrap();
write::<V>(key, element_offset, last_element);
// decrements len by 1
write(self.field_id(), 0, len - 1);
element_to_be_removed
}
/// Sets or mutates the value at the given index.
///
/// # Arguments
///
/// * `index`: [u64] - The index of the vec to set the value at
/// * `value`: [V] - The value to be set
///
/// # Reverts
///
/// * Reverts if index is larger than or equal to the length of the vec.
///
/// # Number of Storage Accesses
///
/// * Reads: `2`
/// * Writes: `1`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// storage.vec.push(5);
/// storage.vec.push(10);
/// storage.vec.push(15);
///
/// storage.vec.set(0, 20);
/// let set_value = storage.vec.get(0).unwrap();
/// assert(20 == set_value);
/// }
/// ```
#[storage(read, write)]
pub fn set(self, index: u64, value: V) {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
// if the index is higher than or equal len, there is no element to set
assert(index < len);
let key = sha256(self.field_id());
let offset = offset_calculator::<V>(index);
write::<V>(key, offset, value);
}
/// Inserts the value at the given index, moving the current index's value
/// as well as the following index's value up by one index.
///
/// # Additional Information
///
/// > **_WARNING:_** Expensive for larger vecs.
///
/// # Arguments
///
/// * `index`: [u64] - The index of the vec to insert the item into.
/// * `value`: [V] - The value to insert into the vec.
///
/// # Reverts
///
/// * Reverts if index is larger than the length of the vec.
///
/// # Number of Storage Accesses
///
/// * Reads: `if self.len() == index { 3 } else { 5 + (2 * (self.len() - index)) }`
/// * Writes: `if self.len() == index { 2 } else { 2 + self.len() - index }`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// storage.vec.push(5);
/// storage.vec.push(15);
///
/// storage.vec.insert(1, 10);
///
/// assert(5 == storage.vec.get(0).unwrap());
/// assert(10 == storage.vec.get(1).unwrap());
/// assert(15 == storage.vec.get(2).unwrap());
/// }
/// ```
#[storage(read, write)]
pub fn insert(self, index: u64, value: V) {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
// if the index is larger than len, there is no space to insert
assert(index <= len);
// if len is 0, index must also be 0 due to above check
let key = sha256(self.field_id());
if len == index {
let offset = offset_calculator::<V>(index);
write::<V>(key, offset, value);
// increments len by 1
write(self.field_id(), 0, len + 1);
return;
}
// for every element in the vec with an index larger than the input index,
// move the element up one index.
// performed in reverse to prevent data overwriting
let mut count = len - 1;
while count >= index {
// shifts all the values up one index
let write_offset = offset_calculator::<V>(count + 1);
let read_offset = offset_calculator::<V>(count);
write::<V>(key, write_offset, read::<V>(key, read_offset).unwrap());
if count == 0 {
break;
}
count -= 1;
}
// inserts the value into the now unused index
let offset = offset_calculator::<V>(index);
write::<V>(key, offset, value);
// increments len by 1
write(self.field_id(), 0, len + 1);
}
/// Returns the length of the vector.
///
/// # Returns
///
/// * [u64] - The stored length of the vector.
///
/// # Number of Storage Accesses
///
/// * Reads: `1`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// assert(0 == storage.vec.len());
/// storage.vec.push(5);
/// assert(1 == storage.vec.len());
/// storage.vec.push(10);
/// assert(2 == storage.vec.len());
/// }
/// ```
#[storage(read)]
pub fn len(self) -> u64 {
read::<u64>(self.field_id(), 0).unwrap_or(0)
}
/// Checks whether the len is zero or not.
///
/// # Returns
///
/// * [bool] - Indicates whether the vector is or is not empty.
///
/// # Number of Storage Accesses
///
/// * Reads: `1`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// assert(true == storage.vec.is_empty());
///
/// storage.vec.push(5);
///
/// assert(false == storage.vec.is_empty());
///
/// storage.vec.clear();
///
/// assert(true == storage.vec.is_empty());
/// }
/// ```
#[storage(read)]
pub fn is_empty(self) -> bool {
read::<u64>(self.field_id(), 0).unwrap_or(0) == 0
}
/// Swaps two elements.
///
/// # Arguments
///
/// * `element1_index`: [u64] - The index of the first element.
/// * `element2_index`: [u64] - The index of the second element.
///
/// # Reverts
///
/// * If `element1_index` or `element2_index` is greater than the length of the vector.
///
/// # Number of Storage Accesses
///
/// * Reads: `5`
/// * Writes: `2`
///
/// # Examples
///
/// ```sway
/// use std::storage::storage_vec::*;
///
/// storage {
/// vec: StorageVec<u64> = StorageVec {}
/// }
///
/// fn foo() {
/// storage.vec.push(5);
/// storage.vec.push(10);
/// storage.vec.push(15);
///
/// storage.vec.swap(0, 2);
/// assert(15 == storage.vec.get(0).unwrap());
/// assert(10 == storage.vec.get(1).unwrap());
/// assert(5 == storage.vec.get(2).unwrap());
/// ```
#[storage(read, write)]
pub fn swap(self, element1_index: u64, element2_index: u64) {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
assert(element1_index < len);
assert(element2_index < len);
if element1_index == element2_index {
return;
}
let key = sha256(self.field_id());
let element1_offset = offset_calculator::<V>(element1_index);
let element2_offset = offset_calculator::<V>(element2_index);
let element1_value = read::<V>(key, element1_offset).unwrap();
write::<V>(
key,
element1_offset,
read::<V>(key, element2_offset)
.unwrap(),
);
write::<V>(key, element2_offset, element1_value);
}
/// Returns the first element of the vector, or `None` if it is empty.
///
/// # Returns
///
/// * [Option<StorageKey<V>>] - Describes the raw location in storage of the value stored at
/// the start of the vector or zero if the vector is empty.
///
/// # Number of Storage Accesses
///
/// * Reads: `1`
///
/// # Examples
///
/// ```sway
/// storage {
/// vec: StorageVec<u64> = StorageVec {},
/// }
///
/// fn foo() {
/// assert(storage.vec.first().is_none());
///
/// storage.vec.push(5);
///
/// assert(5 == storage.vec.first().unwrap());
/// }
/// ```
#[storage(read)]
pub fn first(self) -> Option<StorageKey<V>> {
let key = sha256(self.field_id());
match read::<u64>(self.field_id(), 0).unwrap_or(0) {
0 => None,
_ => Some(StorageKey::<V>::new(key, 0, sha256((0, key)))),
}
}
/// Returns the last element of the vector, or `None` if it is empty.
///
/// # Returns
///
/// * [Option<StorageKey<V>>] - Describes the raw location in storage of the value stored at
/// the end of the vector or zero if the vector is empty.
///
/// # Number of Storage Accesses
///
/// * Reads: `1`
///
/// # Examples
///
/// ```sway
/// storage {
/// vec: StorageVec<u64> = StorageVec {},
/// }
///
/// fn foo() {
/// assert(storage.vec.last().is_none());
///
/// storage.vec.push(5);
/// storage.vec.push(10);
///
/// assert(10 == storage.vec.last().unwrap());
/// }
/// ```
#[storage(read)]
pub fn last(self) -> Option<StorageKey<V>> {
let key = sha256(self.field_id());
match read::<u64>(self.field_id(), 0).unwrap_or(0) {
0 => None,
len => {
let offset = offset_calculator::<V>(len - 1);
Some(StorageKey::<V>::new(key, offset, sha256((len - 1, key))))
},
}
}
/// Reverses the order of elements in the vector, in place.
///
/// # Number of Storage Accesses
///
/// * Reads: `1 + (3 * (self.len() / 2))`
/// * Writes: `2 * (self.len() / 2)`
///
/// # Examples
///
/// ```sway
/// storage {
/// vec: StorageVec<u64> = StorageVec {},
/// }
///
/// fn foo() {
/// storage.vec.push(5);
/// storage.vec.push(10);
/// storage.vec.push(15);
/// storage.vec.reverse();
///
/// assert(15 == storage.vec.get(0).unwrap());
/// assert(10 == storage.vec.get(1).unwrap());
/// assert(5 == storage.vec.get(2).unwrap());
/// }
/// ```
#[storage(read, write)]
pub fn reverse(self) {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
if len < 2 {
return;
}
let key = sha256(self.field_id());
let mid = len / 2;
let mut i = 0;
while i < mid {
let i_offset = offset_calculator::<V>(i);
let other_offset = offset_calculator::<V>(len - i - 1);
let element1_value = read::<V>(key, i_offset).unwrap();
write::<V>(key, i_offset, read::<V>(key, other_offset).unwrap());
write::<V>(key, other_offset, element1_value);
i += 1;
}
}
/// Fills `self` with elements by cloning `value`.
///
/// # Arguments
///
/// * `value`: [V] - Value to copy to each element of the vector.
///
/// # Number of Storage Accesses
///
/// * Reads: `1 + self.len()`
/// * Writes: `self.len()`
///
/// # Examples
///
/// ```sway
/// storage {
/// vec: StorageVec<u64> = StorageVec {},
/// }
///
/// fn foo() {
/// storage.vec.push(5);
/// storage.vec.push(10);
/// storage.vec.push(15);
/// storage.vec.fill(20);
///
/// assert(20 == storage.vec.get(0).unwrap());
/// assert(20 == storage.vec.get(1).unwrap());
/// assert(20 == storage.vec.get(2).unwrap());
/// }
/// ```
#[storage(read, write)]
pub fn fill(self, value: V) {
let len = read::<u64>(self.field_id(), 0).unwrap_or(0);
let key = sha256(self.field_id());
let mut i = 0;
while i < len {
let offset = offset_calculator::<V>(i);
write::<V>(key, offset, value);
i += 1;
}
}
/// Resizes `self` in place so that `len` is equal to `new_len`.
///
/// # Additional Information
///
/// If `new_len` is greater than `len`, `self` is extended by the difference, with each
/// additional slot being filled with `value`. If the `new_len` is less than `len`, `self` is
/// simply truncated.
///
/// # Arguments
///
/// * `new_len`: [u64] - The new length to expand or truncate to
/// * `value`: [V] - The value to fill into new slots if the `new_len` is greater than the current length
///
/// # Number of Storage Accesses
///
/// * Reads - `if new_len > self.len() { new_len - len + 2 } else { 2 }`
/// * Writes - `if new_len > self.len() { new_len - len + 1 } else { 1 }`
///
/// # Examples
///
/// ```sway
/// storage {
/// vec: StorageVec<u64> = StorageVec {},
/// }
///
/// fn foo() {
/// storage.vec.push(5);
/// storage.vec.push(10);
/// storage.vec.resize(4, 20);
///
/// assert(5 == storage.vec.get(0).unwrap());
/// assert(10 == storage.vec.get(1).unwrap());
/// assert(20 == storage.vec.get(2).unwrap());
/// assert(20 == storage.vec.get(3).unwrap());
///
/// storage.vec.resize(2, 0);
///
/// assert(5 == storage.vec.get(0).unwrap());
/// assert(10 == storage.vec.get(1).unwrap());
/// assert(None == storage.vec.get(2));
/// assert(None == storage.vec.get(3));
/// }
/// ```
#[storage(read, write)]
pub fn resize(self, new_len: u64, value: V) {
let mut len = read::<u64>(self.field_id(), 0).unwrap_or(0);
let key = sha256(self.field_id());
while len < new_len {
let offset = offset_calculator::<V>(len);
write::<V>(key, offset, value);
len += 1;
}
write::<u64>(self.field_id(), 0, new_len);
}
// TODO: This should be moved into the vec.sw file and `From<StorageKey<StorageVec>> for Vec`
// implemented instead of this when https://github.com/FuelLabs/sway/issues/409 is resolved.
// Implementation will change from this:
// ```sway
// let my_vec = Vec::new();
// storage.storage_vec.store_vec(my_vec);
// let other_vec = storage.storage_vec.load_vec();
// ```
// To this:
// ```sway
// let my_vec = Vec::new();
// storage.storage_vec = my_vec.into();
// let other_vec = Vec::from(storage.storage_vec);
// ```
/// Stores a `Vec` as a `StorageVec`.
///
/// # Additional Information
///
/// This will overwrite any existing values in the `StorageVec`.
///
/// # Arguments
///
/// * `vec`: [Vec<V>] - The vector to store in storage.
///
/// # Number of Storage Accesses
///
/// * Writes - `2`
///
/// # Examples
///
/// ```sway
/// storage {
/// vec: StorageVec<u64> = StorageVec {},
/// }
///
/// fn foo() {
/// let mut vec = Vec::<u64>::new();
/// vec.push(5);
/// vec.push(10);
/// vec.push(15);
///
/// storage.vec.store_vec(vec);
///
/// assert(5 == storage.vec.get(0).unwrap());
/// assert(10 == storage.vec.get(1).unwrap());
/// assert(15 == storage.vec.get(2).unwrap());
/// }
/// ```
#[storage(write)]
pub fn store_vec(self, vec: Vec<V>) {
let slice = vec.as_raw_slice();
// Get the number of storage slots needed based on the size of bytes.
let number_of_bytes = slice.number_of_bytes();
let number_of_slots = (number_of_bytes + 31) >> 5;
let mut ptr = slice.ptr();
// The capacity needs to be a multiple of 32 bytes so we can
// make the 'quad' storage instruction store without accessing unallocated heap memory.
ptr = realloc_bytes(ptr, number_of_bytes, number_of_slots * 32);
// Store `number_of_slots * 32` bytes starting at storage slot `key`.
let _ = __state_store_quad(sha256(self.field_id()), ptr, number_of_slots);
// Store the length, NOT the bytes.
// This differs from the existing `write_slice()` function to be compatible with `StorageVec`.
write::<u64>(self.field_id(), 0, number_of_bytes / __size_of::<V>());
}
/// Load a `Vec` from the `StorageVec`.
///
/// # Returns
///
/// * [Option<Vec<V>>] - The vector constructed from storage or `None`.
///
/// # Number of Storage Accesses
///
/// * Reads - `2`
///
/// # Examples
///
/// ```sway
/// storage {
/// vec: StorageVec<u64> = StorageVec {},
/// }
///
/// fn foo() {
/// let mut vec = Vec::<u64>::new();
/// vec.push(5);
/// vec.push(10);
/// vec.push(15);
///
/// storage.vec.store_vec(vec);
/// let returned_vec = storage.vec.load_vec();
///
/// assert(5 == returned_vec.get(0).unwrap());
/// assert(10 == returned_vec.get(1).unwrap());
/// assert(15 == returned_vec.get(2).unwrap());
/// }
/// ```
#[storage(read)]
pub fn load_vec(self) -> Vec<V> {
// Get the length of the slice that is stored.
match read::<u64>(self.field_id(), 0).unwrap_or(0) {
0 => Vec::new(),
len => {
// Get the number of storage slots needed based on the size.
let bytes = len * __size_of::<V>();
let number_of_slots = (bytes + 31) >> 5;
let ptr = alloc_bytes(number_of_slots * 32);
// Load the stored slice into the pointer.
let _ = __state_load_quad(sha256(self.field_id()), ptr, number_of_slots);
Vec::from(asm(ptr: (ptr, bytes)) {
ptr: raw_slice
})
}
}
}
}
// Add padding to type so it can correctly use the storage api
fn offset_calculator<T>(offset: u64) -> u64 {
let size_in_bytes = __size_of::<T>();
let size_in_bytes = (size_in_bytes + (8 - 1)) - ((size_in_bytes + (8 - 1)) % 8);
(offset * size_in_bytes) / 8
}