forked from CosmWasm/cw-storage-plus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
map.rs
1580 lines (1395 loc) · 49.7 KB
/
map.rs
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
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::marker::PhantomData;
#[cfg(feature = "iterator")]
use crate::bound::{Bound, PrefixBound};
#[cfg(feature = "iterator")]
use crate::de::KeyDeserialize;
use crate::helpers::query_raw;
#[cfg(feature = "iterator")]
use crate::iter_helpers::{deserialize_kv, deserialize_v};
#[cfg(feature = "iterator")]
use crate::keys::Prefixer;
use crate::keys::{Key, PrimaryKey};
use crate::path::Path;
#[cfg(feature = "iterator")]
use crate::prefix::{namespaced_prefix_range, Prefix};
use cosmwasm_std::{from_slice, Addr, CustomQuery, QuerierWrapper, StdError, StdResult, Storage};
#[derive(Debug, Clone)]
pub struct Map<'a, K, T> {
namespace: &'a [u8],
// see https://doc.rust-lang.org/std/marker/struct.PhantomData.html#unused-type-parameters for why this is needed
key_type: PhantomData<K>,
data_type: PhantomData<T>,
}
impl<'a, K, T> Map<'a, K, T> {
pub const fn new(namespace: &'a str) -> Self {
Map {
namespace: namespace.as_bytes(),
data_type: PhantomData,
key_type: PhantomData,
}
}
pub fn namespace(&self) -> &'a [u8] {
self.namespace
}
}
impl<'a, K, T> Map<'a, K, T>
where
T: Serialize + DeserializeOwned,
K: PrimaryKey<'a>,
{
pub fn key(&self, k: K) -> Path<T> {
Path::new(
self.namespace,
&k.key().iter().map(Key::as_ref).collect::<Vec<_>>(),
)
}
#[cfg(feature = "iterator")]
pub(crate) fn no_prefix_raw(&self) -> Prefix<Vec<u8>, T, K> {
Prefix::new(self.namespace, &[])
}
pub fn save(&self, store: &mut dyn Storage, k: K, data: &T) -> StdResult<()> {
self.key(k).save(store, data)
}
pub fn remove(&self, store: &mut dyn Storage, k: K) {
self.key(k).remove(store)
}
/// load will return an error if no data is set at the given key, or on parse error
pub fn load(&self, store: &dyn Storage, k: K) -> StdResult<T> {
self.key(k).load(store)
}
/// may_load will parse the data stored at the key if present, returns Ok(None) if no data there.
/// returns an error on issues parsing
pub fn may_load(&self, store: &dyn Storage, k: K) -> StdResult<Option<T>> {
self.key(k).may_load(store)
}
/// has returns true or false if any data is at this key, without parsing or interpreting the
/// contents.
pub fn has(&self, store: &dyn Storage, k: K) -> bool {
self.key(k).has(store)
}
/// Loads the data, perform the specified action, and store the result
/// in the database. This is shorthand for some common sequences, which may be useful.
///
/// If the data exists, `action(Some(value))` is called. Otherwise `action(None)` is called.
pub fn update<A, E>(&self, store: &mut dyn Storage, k: K, action: A) -> Result<T, E>
where
A: FnOnce(Option<T>) -> Result<T, E>,
E: From<StdError>,
{
self.key(k).update(store, action)
}
/// If you import the proper Map from the remote contract, this will let you read the data
/// from a remote contract in a type-safe way using WasmQuery::RawQuery
pub fn query<Q: CustomQuery>(
&self,
querier: &QuerierWrapper<Q>,
remote_contract: Addr,
k: K,
) -> StdResult<Option<T>> {
let key = self.key(k).storage_key.into();
let result = query_raw(querier, remote_contract, key)?;
if result.is_empty() {
Ok(None)
} else {
from_slice(&result).map(Some)
}
}
/// Clears the map, removing all elements.
#[cfg(feature = "iterator")]
pub fn clear(&self, store: &mut dyn Storage) {
const TAKE: usize = 10;
let mut cleared = false;
while !cleared {
let paths = self
.no_prefix_raw()
.keys_raw(store, None, None, cosmwasm_std::Order::Ascending)
.map(|raw_key| Path::<T>::new(self.namespace, &[raw_key.as_slice()]))
// Take just TAKE elements to prevent possible heap overflow if the Map is big.
.take(TAKE)
.collect::<Vec<_>>();
paths.iter().for_each(|path| store.remove(path));
cleared = paths.len() < TAKE;
}
}
/// Returns `true` if the map is empty.
#[cfg(feature = "iterator")]
pub fn is_empty(&self, store: &dyn Storage) -> bool {
self.no_prefix_raw()
.keys_raw(store, None, None, cosmwasm_std::Order::Ascending)
.next()
.is_none()
}
}
#[cfg(feature = "iterator")]
impl<'a, K, T> Map<'a, K, T>
where
T: Serialize + DeserializeOwned,
K: PrimaryKey<'a>,
{
pub fn sub_prefix(&self, p: K::SubPrefix) -> Prefix<K::SuperSuffix, T, K::SuperSuffix> {
Prefix::new(self.namespace, &p.prefix())
}
pub fn prefix(&self, p: K::Prefix) -> Prefix<K::Suffix, T, K::Suffix> {
Prefix::new(self.namespace, &p.prefix())
}
}
// short-cut for simple keys, rather than .prefix(()).range_raw(...)
#[cfg(feature = "iterator")]
impl<'a, K, T> Map<'a, K, T>
where
T: Serialize + DeserializeOwned,
// TODO: this should only be when K::Prefix == ()
// Other cases need to call prefix() first
K: PrimaryKey<'a>,
{
/// While `range_raw` over a `prefix` fixes the prefix to one element and iterates over the
/// remaining, `prefix_range_raw` accepts bounds for the lowest and highest elements of the `Prefix`
/// itself, and iterates over those (inclusively or exclusively, depending on `PrefixBound`).
/// There are some issues that distinguish these two, and blindly casting to `Vec<u8>` doesn't
/// solve them.
pub fn prefix_range_raw<'c>(
&self,
store: &'c dyn Storage,
min: Option<PrefixBound<'a, K::Prefix>>,
max: Option<PrefixBound<'a, K::Prefix>>,
order: cosmwasm_std::Order,
) -> Box<dyn Iterator<Item = StdResult<cosmwasm_std::Record<T>>> + 'c>
where
T: 'c,
'a: 'c,
{
let mapped =
namespaced_prefix_range(store, self.namespace, min, max, order).map(deserialize_v);
Box::new(mapped)
}
}
#[cfg(feature = "iterator")]
impl<'a, K, T> Map<'a, K, T>
where
T: Serialize + DeserializeOwned,
K: PrimaryKey<'a> + KeyDeserialize,
{
/// While `range` over a `prefix` fixes the prefix to one element and iterates over the
/// remaining, `prefix_range` accepts bounds for the lowest and highest elements of the
/// `Prefix` itself, and iterates over those (inclusively or exclusively, depending on
/// `PrefixBound`).
/// There are some issues that distinguish these two, and blindly casting to `Vec<u8>` doesn't
/// solve them.
pub fn prefix_range<'c>(
&self,
store: &'c dyn Storage,
min: Option<PrefixBound<'a, K::Prefix>>,
max: Option<PrefixBound<'a, K::Prefix>>,
order: cosmwasm_std::Order,
) -> Box<dyn Iterator<Item = StdResult<(K::Output, T)>> + 'c>
where
T: 'c,
'a: 'c,
K: 'c,
K::Output: 'static,
{
let mapped = namespaced_prefix_range(store, self.namespace, min, max, order)
.map(deserialize_kv::<K, T>);
Box::new(mapped)
}
fn no_prefix(&self) -> Prefix<K, T, K> {
Prefix::new(self.namespace, &[])
}
}
#[cfg(feature = "iterator")]
impl<'a, K, T> Map<'a, K, T>
where
T: Serialize + DeserializeOwned,
K: PrimaryKey<'a>,
{
pub fn range_raw<'c>(
&self,
store: &'c dyn Storage,
min: Option<Bound<'a, K>>,
max: Option<Bound<'a, K>>,
order: cosmwasm_std::Order,
) -> Box<dyn Iterator<Item = StdResult<cosmwasm_std::Record<T>>> + 'c>
where
T: 'c,
{
self.no_prefix_raw().range_raw(store, min, max, order)
}
pub fn keys_raw<'c>(
&self,
store: &'c dyn Storage,
min: Option<Bound<'a, K>>,
max: Option<Bound<'a, K>>,
order: cosmwasm_std::Order,
) -> Box<dyn Iterator<Item = Vec<u8>> + 'c>
where
T: 'c,
{
self.no_prefix_raw().keys_raw(store, min, max, order)
}
}
#[cfg(feature = "iterator")]
impl<'a, K, T> Map<'a, K, T>
where
T: Serialize + DeserializeOwned,
K: PrimaryKey<'a> + KeyDeserialize,
{
pub fn range<'c>(
&self,
store: &'c dyn Storage,
min: Option<Bound<'a, K>>,
max: Option<Bound<'a, K>>,
order: cosmwasm_std::Order,
) -> Box<dyn Iterator<Item = StdResult<(K::Output, T)>> + 'c>
where
T: 'c,
K::Output: 'static,
{
self.no_prefix().range(store, min, max, order)
}
pub fn keys<'c>(
&self,
store: &'c dyn Storage,
min: Option<Bound<'a, K>>,
max: Option<Bound<'a, K>>,
order: cosmwasm_std::Order,
) -> Box<dyn Iterator<Item = StdResult<K::Output>> + 'c>
where
T: 'c,
K::Output: 'static,
{
self.no_prefix().keys(store, min, max, order)
}
}
#[cfg(test)]
mod test {
use super::*;
use serde::{Deserialize, Serialize};
use std::ops::Deref;
use cosmwasm_std::testing::MockStorage;
use cosmwasm_std::to_binary;
use cosmwasm_std::StdError::InvalidUtf8;
#[cfg(feature = "iterator")]
use cosmwasm_std::{Order, StdResult};
#[cfg(feature = "iterator")]
use crate::bound::Bounder;
use crate::int_key::IntKey;
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
struct Data {
pub name: String,
pub age: i32,
}
const PEOPLE: Map<&[u8], Data> = Map::new("people");
#[cfg(feature = "iterator")]
const PEOPLE_STR_KEY: &str = "people2";
#[cfg(feature = "iterator")]
const PEOPLE_STR: Map<&str, Data> = Map::new(PEOPLE_STR_KEY);
#[cfg(feature = "iterator")]
const PEOPLE_ID: Map<u32, Data> = Map::new("people_id");
#[cfg(feature = "iterator")]
const SIGNED_ID: Map<i32, Data> = Map::new("signed_id");
const ALLOWANCE: Map<(&[u8], &[u8]), u64> = Map::new("allow");
const TRIPLE: Map<(&[u8], u8, &str), u64> = Map::new("triple");
#[test]
fn create_path() {
let path = PEOPLE.key(b"john");
let key = path.deref();
// this should be prefixed(people) || john
assert_eq!("people".len() + "john".len() + 2, key.len());
assert_eq!(b"people".to_vec().as_slice(), &key[2..8]);
assert_eq!(b"john".to_vec().as_slice(), &key[8..]);
let path = ALLOWANCE.key((b"john", b"maria"));
let key = path.deref();
// this should be prefixed(allow) || prefixed(john) || maria
assert_eq!(
"allow".len() + "john".len() + "maria".len() + 2 * 2,
key.len()
);
assert_eq!(b"allow".to_vec().as_slice(), &key[2..7]);
assert_eq!(b"john".to_vec().as_slice(), &key[9..13]);
assert_eq!(b"maria".to_vec().as_slice(), &key[13..]);
let path = TRIPLE.key((b"john", 8u8, "pedro"));
let key = path.deref();
// this should be prefixed(allow) || prefixed(john) || maria
assert_eq!(
"triple".len() + "john".len() + 1 + "pedro".len() + 2 * 3,
key.len()
);
assert_eq!(b"triple".to_vec().as_slice(), &key[2..8]);
assert_eq!(b"john".to_vec().as_slice(), &key[10..14]);
assert_eq!(8u8.to_cw_bytes(), &key[16..17]);
assert_eq!(b"pedro".to_vec().as_slice(), &key[17..]);
}
#[test]
fn save_and_load() {
let mut store = MockStorage::new();
// save and load on one key
let john = PEOPLE.key(b"john");
let data = Data {
name: "John".to_string(),
age: 32,
};
assert_eq!(None, john.may_load(&store).unwrap());
john.save(&mut store, &data).unwrap();
assert_eq!(data, john.load(&store).unwrap());
// nothing on another key
assert_eq!(None, PEOPLE.may_load(&store, b"jack").unwrap());
// same named path gets the data
assert_eq!(data, PEOPLE.load(&store, b"john").unwrap());
// removing leaves us empty
john.remove(&mut store);
assert_eq!(None, john.may_load(&store).unwrap());
}
#[test]
fn existence() {
let mut store = MockStorage::new();
// set data in proper format
let data = Data {
name: "John".to_string(),
age: 32,
};
PEOPLE.save(&mut store, b"john", &data).unwrap();
// set and remove it
PEOPLE.save(&mut store, b"removed", &data).unwrap();
PEOPLE.remove(&mut store, b"removed");
// invalid, but non-empty data
store.set(&PEOPLE.key(b"random"), b"random-data");
// any data, including invalid or empty is returned as "has"
assert!(PEOPLE.has(&store, b"john"));
assert!(PEOPLE.has(&store, b"random"));
// if nothing was written, it is false
assert!(!PEOPLE.has(&store, b"never-writen"));
assert!(!PEOPLE.has(&store, b"removed"));
}
#[test]
fn composite_keys() {
let mut store = MockStorage::new();
// save and load on a composite key
let allow = ALLOWANCE.key((b"owner", b"spender"));
assert_eq!(None, allow.may_load(&store).unwrap());
allow.save(&mut store, &1234).unwrap();
assert_eq!(1234, allow.load(&store).unwrap());
// not under other key
let different = ALLOWANCE.may_load(&store, (b"owners", b"pender")).unwrap();
assert_eq!(None, different);
// matches under a proper copy
let same = ALLOWANCE.load(&store, (b"owner", b"spender")).unwrap();
assert_eq!(1234, same);
}
#[test]
fn triple_keys() {
let mut store = MockStorage::new();
// save and load on a triple composite key
let triple = TRIPLE.key((b"owner", 10u8, "recipient"));
assert_eq!(None, triple.may_load(&store).unwrap());
triple.save(&mut store, &1234).unwrap();
assert_eq!(1234, triple.load(&store).unwrap());
// not under other key
let different = TRIPLE
.may_load(&store, (b"owners", 10u8, "ecipient"))
.unwrap();
assert_eq!(None, different);
// matches under a proper copy
let same = TRIPLE.load(&store, (b"owner", 10u8, "recipient")).unwrap();
assert_eq!(1234, same);
}
#[test]
#[cfg(feature = "iterator")]
fn range_raw_simple_key() {
let mut store = MockStorage::new();
// save and load on two keys
let data = Data {
name: "John".to_string(),
age: 32,
};
PEOPLE.save(&mut store, b"john", &data).unwrap();
let data2 = Data {
name: "Jim".to_string(),
age: 44,
};
PEOPLE.save(&mut store, b"jim", &data2).unwrap();
// let's try to iterate!
let all: StdResult<Vec<_>> = PEOPLE
.range_raw(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(
all,
vec![
(b"jim".to_vec(), data2.clone()),
(b"john".to_vec(), data.clone())
]
);
// let's try to iterate over a range
let all: StdResult<Vec<_>> = PEOPLE
.range_raw(
&store,
Some(Bound::inclusive(b"j" as &[u8])),
None,
Order::Ascending,
)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(
all,
vec![(b"jim".to_vec(), data2), (b"john".to_vec(), data.clone())]
);
// let's try to iterate over a more restrictive range
let all: StdResult<Vec<_>> = PEOPLE
.range_raw(
&store,
Some(Bound::inclusive(b"jo" as &[u8])),
None,
Order::Ascending,
)
.collect();
let all = all.unwrap();
assert_eq!(1, all.len());
assert_eq!(all, vec![(b"john".to_vec(), data)]);
}
#[test]
#[cfg(feature = "iterator")]
fn range_simple_string_key() {
let mut store = MockStorage::new();
// save and load on three keys
let data = Data {
name: "John".to_string(),
age: 32,
};
PEOPLE.save(&mut store, b"john", &data).unwrap();
let data2 = Data {
name: "Jim".to_string(),
age: 44,
};
PEOPLE.save(&mut store, b"jim", &data2).unwrap();
let data3 = Data {
name: "Ada".to_string(),
age: 23,
};
PEOPLE.save(&mut store, b"ada", &data3).unwrap();
// let's try to iterate!
let all: StdResult<Vec<_>> = PEOPLE.range(&store, None, None, Order::Ascending).collect();
let all = all.unwrap();
assert_eq!(3, all.len());
assert_eq!(
all,
vec![
(b"ada".to_vec(), data3),
(b"jim".to_vec(), data2.clone()),
(b"john".to_vec(), data.clone())
]
);
// let's try to iterate over a range
let all: StdResult<Vec<_>> = PEOPLE
.range(&store, b"j".inclusive_bound(), None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(
all,
vec![(b"jim".to_vec(), data2), (b"john".to_vec(), data.clone())]
);
// let's try to iterate over a more restrictive range
let all: StdResult<Vec<_>> = PEOPLE
.range(&store, b"jo".inclusive_bound(), None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(1, all.len());
assert_eq!(all, vec![(b"john".to_vec(), data)]);
}
#[test]
#[cfg(feature = "iterator")]
fn range_key_broken_deserialization_errors() {
let mut store = MockStorage::new();
// save and load on three keys
let data = Data {
name: "John".to_string(),
age: 32,
};
PEOPLE_STR.save(&mut store, "john", &data).unwrap();
let data2 = Data {
name: "Jim".to_string(),
age: 44,
};
PEOPLE_STR.save(&mut store, "jim", &data2).unwrap();
let data3 = Data {
name: "Ada".to_string(),
age: 23,
};
PEOPLE_STR.save(&mut store, "ada", &data3).unwrap();
// let's iterate!
let all: StdResult<Vec<_>> = PEOPLE_STR
.range(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(3, all.len());
assert_eq!(
all,
vec![
("ada".to_string(), data3.clone()),
("jim".to_string(), data2.clone()),
("john".to_string(), data.clone())
]
);
// Manually add a broken key (invalid utf-8)
store.set(
&[
[0u8, PEOPLE_STR_KEY.len() as u8].as_slice(),
PEOPLE_STR_KEY.as_bytes(),
b"\xddim",
]
.concat(),
&to_binary(&data2).unwrap(),
);
// Let's try to iterate again!
let all: StdResult<Vec<_>> = PEOPLE_STR
.range(&store, None, None, Order::Ascending)
.collect();
assert!(all.is_err());
assert!(matches!(all.unwrap_err(), InvalidUtf8 { .. }));
// And the same with keys()
let all: StdResult<Vec<_>> = PEOPLE_STR
.keys(&store, None, None, Order::Ascending)
.collect();
assert!(all.is_err());
assert!(matches!(all.unwrap_err(), InvalidUtf8 { .. }));
// But range_raw still works
let all: StdResult<Vec<_>> = PEOPLE_STR
.range_raw(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(4, all.len());
assert_eq!(
all,
vec![
(b"ada".to_vec(), data3.clone()),
(b"jim".to_vec(), data2.clone()),
(b"john".to_vec(), data.clone()),
(b"\xddim".to_vec(), data2.clone()),
]
);
// And the same with keys_raw
let all: Vec<_> = PEOPLE_STR
.keys_raw(&store, None, None, Order::Ascending)
.collect();
assert_eq!(4, all.len());
assert_eq!(
all,
vec![
b"ada".to_vec(),
b"jim".to_vec(),
b"john".to_vec(),
b"\xddim".to_vec(),
]
);
}
#[test]
#[cfg(feature = "iterator")]
fn range_simple_integer_key() {
let mut store = MockStorage::new();
// save and load on two keys
let data = Data {
name: "John".to_string(),
age: 32,
};
PEOPLE_ID.save(&mut store, 1234, &data).unwrap();
let data2 = Data {
name: "Jim".to_string(),
age: 44,
};
PEOPLE_ID.save(&mut store, 56, &data2).unwrap();
// let's try to iterate!
let all: StdResult<Vec<_>> = PEOPLE_ID
.range(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(all, vec![(56, data2.clone()), (1234, data.clone())]);
// let's try to iterate over a range
let all: StdResult<Vec<_>> = PEOPLE_ID
.range(
&store,
Some(Bound::inclusive(56u32)),
None,
Order::Ascending,
)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(all, vec![(56, data2), (1234, data.clone())]);
// let's try to iterate over a more restrictive range
let all: StdResult<Vec<_>> = PEOPLE_ID
.range(
&store,
Some(Bound::inclusive(57u32)),
None,
Order::Ascending,
)
.collect();
let all = all.unwrap();
assert_eq!(1, all.len());
assert_eq!(all, vec![(1234, data)]);
}
#[test]
#[cfg(feature = "iterator")]
fn range_simple_integer_key_with_bounder_trait() {
let mut store = MockStorage::new();
// save and load on two keys
let data = Data {
name: "John".to_string(),
age: 32,
};
PEOPLE_ID.save(&mut store, 1234, &data).unwrap();
let data2 = Data {
name: "Jim".to_string(),
age: 44,
};
PEOPLE_ID.save(&mut store, 56, &data2).unwrap();
// let's try to iterate!
let all: StdResult<Vec<_>> = PEOPLE_ID
.range(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(all, vec![(56, data2.clone()), (1234, data.clone())]);
// let's try to iterate over a range
let all: StdResult<Vec<_>> = PEOPLE_ID
.range(&store, 56u32.inclusive_bound(), None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(all, vec![(56, data2), (1234, data.clone())]);
// let's try to iterate over a more restrictive range
let all: StdResult<Vec<_>> = PEOPLE_ID
.range(&store, 57u32.inclusive_bound(), None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(1, all.len());
assert_eq!(all, vec![(1234, data)]);
}
#[test]
#[cfg(feature = "iterator")]
fn range_simple_signed_integer_key() {
let mut store = MockStorage::new();
// save and load on three keys
let data = Data {
name: "John".to_string(),
age: 32,
};
SIGNED_ID.save(&mut store, -1234, &data).unwrap();
let data2 = Data {
name: "Jim".to_string(),
age: 44,
};
SIGNED_ID.save(&mut store, -56, &data2).unwrap();
let data3 = Data {
name: "Jules".to_string(),
age: 55,
};
SIGNED_ID.save(&mut store, 50, &data3).unwrap();
// let's try to iterate!
let all: StdResult<Vec<_>> = SIGNED_ID
.range(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(3, all.len());
// order is correct
assert_eq!(
all,
vec![(-1234, data), (-56, data2.clone()), (50, data3.clone())]
);
// let's try to iterate over a range
let all: StdResult<Vec<_>> = SIGNED_ID
.range(
&store,
Some(Bound::inclusive(-56i32)),
None,
Order::Ascending,
)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(all, vec![(-56, data2), (50, data3.clone())]);
// let's try to iterate over a more restrictive range
let all: StdResult<Vec<_>> = SIGNED_ID
.range(
&store,
Some(Bound::inclusive(-55i32)),
Some(Bound::inclusive(50i32)),
Order::Descending,
)
.collect();
let all = all.unwrap();
assert_eq!(1, all.len());
assert_eq!(all, vec![(50, data3)]);
}
#[test]
#[cfg(feature = "iterator")]
fn range_simple_signed_integer_key_with_bounder_trait() {
let mut store = MockStorage::new();
// save and load on three keys
let data = Data {
name: "John".to_string(),
age: 32,
};
SIGNED_ID.save(&mut store, -1234, &data).unwrap();
let data2 = Data {
name: "Jim".to_string(),
age: 44,
};
SIGNED_ID.save(&mut store, -56, &data2).unwrap();
let data3 = Data {
name: "Jules".to_string(),
age: 55,
};
SIGNED_ID.save(&mut store, 50, &data3).unwrap();
// let's try to iterate!
let all: StdResult<Vec<_>> = SIGNED_ID
.range(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(3, all.len());
// order is correct
assert_eq!(
all,
vec![(-1234, data), (-56, data2.clone()), (50, data3.clone())]
);
// let's try to iterate over a range
let all: StdResult<Vec<_>> = SIGNED_ID
.range(&store, (-56i32).inclusive_bound(), None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(all, vec![(-56, data2), (50, data3.clone())]);
// let's try to iterate over a more restrictive range
let all: StdResult<Vec<_>> = SIGNED_ID
.range(
&store,
(-55i32).inclusive_bound(),
50i32.inclusive_bound(),
Order::Descending,
)
.collect();
let all = all.unwrap();
assert_eq!(1, all.len());
assert_eq!(all, vec![(50, data3)]);
}
#[test]
#[cfg(feature = "iterator")]
fn range_raw_composite_key() {
let mut store = MockStorage::new();
// save and load on three keys, one under different owner
ALLOWANCE
.save(&mut store, (b"owner", b"spender"), &1000)
.unwrap();
ALLOWANCE
.save(&mut store, (b"owner", b"spender2"), &3000)
.unwrap();
ALLOWANCE
.save(&mut store, (b"owner2", b"spender"), &5000)
.unwrap();
// let's try to iterate!
let all: StdResult<Vec<_>> = ALLOWANCE
.range_raw(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(3, all.len());
assert_eq!(
all,
vec![
((b"owner".to_vec(), b"spender".to_vec()).joined_key(), 1000),
((b"owner".to_vec(), b"spender2".to_vec()).joined_key(), 3000),
((b"owner2".to_vec(), b"spender".to_vec()).joined_key(), 5000),
]
);
// let's try to iterate over a prefix
let all: StdResult<Vec<_>> = ALLOWANCE
.prefix(b"owner")
.range_raw(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(
all,
vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000)]
);
}
#[test]
#[cfg(feature = "iterator")]
fn range_composite_key() {
let mut store = MockStorage::new();
// save and load on three keys, one under different owner
ALLOWANCE
.save(&mut store, (b"owner", b"spender"), &1000)
.unwrap();
ALLOWANCE
.save(&mut store, (b"owner", b"spender2"), &3000)
.unwrap();
ALLOWANCE
.save(&mut store, (b"owner2", b"spender"), &5000)
.unwrap();
// let's try to iterate!
let all: StdResult<Vec<_>> = ALLOWANCE
.range(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(3, all.len());
assert_eq!(
all,
vec![
((b"owner".to_vec(), b"spender".to_vec()), 1000),
((b"owner".to_vec(), b"spender2".to_vec()), 3000),
((b"owner2".to_vec(), b"spender".to_vec()), 5000)
]
);
// let's try to iterate over a prefix
let all: StdResult<Vec<_>> = ALLOWANCE
.prefix(b"owner")
.range(&store, None, None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(
all,
vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000),]
);
// let's try to iterate over a prefixed restricted inclusive range
let all: StdResult<Vec<_>> = ALLOWANCE
.prefix(b"owner")
.range(&store, b"spender".inclusive_bound(), None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(2, all.len());
assert_eq!(
all,
vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000),]
);
// let's try to iterate over a prefixed restricted exclusive range
let all: StdResult<Vec<_>> = ALLOWANCE
.prefix(b"owner")
.range(&store, b"spender".exclusive_bound(), None, Order::Ascending)
.collect();
let all = all.unwrap();
assert_eq!(1, all.len());
assert_eq!(all, vec![(b"spender2".to_vec(), 3000),]);
}
#[test]
#[cfg(feature = "iterator")]
fn range_raw_triple_key() {