cw_storage_plus/
map.rs

1use serde::de::DeserializeOwned;
2use serde::Serialize;
3use std::marker::PhantomData;
4
5#[cfg(feature = "iterator")]
6use crate::bound::{Bound, PrefixBound};
7#[cfg(feature = "iterator")]
8use crate::de::KeyDeserialize;
9use crate::helpers::query_raw;
10#[cfg(feature = "iterator")]
11use crate::iter_helpers::{deserialize_kv, deserialize_v};
12#[cfg(feature = "iterator")]
13use crate::keys::Prefixer;
14use crate::keys::{Key, PrimaryKey};
15use crate::namespace::Namespace;
16use crate::path::Path;
17#[cfg(feature = "iterator")]
18use crate::prefix::{namespaced_prefix_range, Prefix};
19#[cfg(feature = "iterator")]
20use cosmwasm_std::Order;
21use cosmwasm_std::{from_json, Addr, CustomQuery, QuerierWrapper, StdError, StdResult, Storage};
22
23#[derive(Debug, Clone)]
24pub struct Map<K, T> {
25    namespace: Namespace,
26    // see https://doc.rust-lang.org/std/marker/struct.PhantomData.html#unused-type-parameters for why this is needed
27    key_type: PhantomData<K>,
28    data_type: PhantomData<T>,
29}
30
31impl<K, T> Map<K, T> {
32    /// Creates a new [`Map`] with the given storage key. This is a const fn only suitable
33    /// when you have the storage key in the form of a static string slice.
34    pub const fn new(namespace: &'static str) -> Self {
35        Map {
36            namespace: Namespace::from_static_str(namespace),
37            data_type: PhantomData,
38            key_type: PhantomData,
39        }
40    }
41
42    /// Creates a new [`Map`] with the given storage key. Use this if you might need to handle
43    /// a dynamic string. Otherwise, you might prefer [`Map::new`].
44    pub fn new_dyn(namespace: impl Into<Namespace>) -> Self {
45        Map {
46            namespace: namespace.into(),
47            data_type: PhantomData,
48            key_type: PhantomData,
49        }
50    }
51
52    pub fn namespace_bytes(&self) -> &[u8] {
53        self.namespace.as_slice()
54    }
55}
56
57impl<'a, K, T> Map<K, T>
58where
59    T: Serialize + DeserializeOwned,
60    K: PrimaryKey<'a>,
61{
62    pub fn key(&self, k: K) -> Path<T> {
63        Path::new(
64            self.namespace.as_slice(),
65            &k.key().iter().map(Key::as_ref).collect::<Vec<_>>(),
66        )
67    }
68
69    #[cfg(feature = "iterator")]
70    pub(crate) fn no_prefix_raw(&self) -> Prefix<Vec<u8>, T, K> {
71        Prefix::new(self.namespace.as_slice(), &[])
72    }
73
74    pub fn save(&self, store: &mut dyn Storage, k: K, data: &T) -> StdResult<()> {
75        self.key(k).save(store, data)
76    }
77
78    pub fn remove(&self, store: &mut dyn Storage, k: K) {
79        self.key(k).remove(store)
80    }
81
82    /// load will return an error if no data is set at the given key, or on parse error
83    pub fn load(&self, store: &dyn Storage, k: K) -> StdResult<T> {
84        self.key(k).load(store)
85    }
86
87    /// may_load will parse the data stored at the key if present, returns Ok(None) if no data there.
88    /// returns an error on issues parsing
89    pub fn may_load(&self, store: &dyn Storage, k: K) -> StdResult<Option<T>> {
90        self.key(k).may_load(store)
91    }
92
93    /// has returns true or false if any data is at this key, without parsing or interpreting the
94    /// contents.
95    pub fn has(&self, store: &dyn Storage, k: K) -> bool {
96        self.key(k).has(store)
97    }
98
99    /// Loads the data, perform the specified action, and store the result
100    /// in the database. This is shorthand for some common sequences, which may be useful.
101    ///
102    /// If the data exists, `action(Some(value))` is called. Otherwise, `action(None)` is called.
103    pub fn update<A, E>(&self, store: &mut dyn Storage, k: K, action: A) -> Result<T, E>
104    where
105        A: FnOnce(Option<T>) -> Result<T, E>,
106        E: From<StdError>,
107    {
108        self.key(k).update(store, action)
109    }
110
111    /// If you import the proper Map from the remote contract, this will let you read the data
112    /// from a remote contract in a type-safe way using WasmQuery::RawQuery
113    pub fn query<Q: CustomQuery>(
114        &self,
115        querier: &QuerierWrapper<Q>,
116        remote_contract: Addr,
117        k: K,
118    ) -> StdResult<Option<T>> {
119        let key = self.key(k).storage_key.into();
120        let result = query_raw(querier, remote_contract, key)?;
121        if result.is_empty() {
122            Ok(None)
123        } else {
124            from_json(&result).map(Some)
125        }
126    }
127
128    /// Clears the map, removing all elements.
129    #[cfg(feature = "iterator")]
130    pub fn clear(&self, store: &mut dyn Storage) {
131        self.no_prefix_raw().clear(store, None);
132    }
133
134    /// Returns `true` if the map is empty.
135    #[cfg(feature = "iterator")]
136    pub fn is_empty(&self, store: &dyn Storage) -> bool {
137        self.no_prefix_raw().is_empty(store)
138    }
139}
140
141#[cfg(feature = "iterator")]
142impl<'a, K, T> Map<K, T>
143where
144    T: Serialize + DeserializeOwned,
145    K: PrimaryKey<'a>,
146{
147    pub fn sub_prefix(&self, p: K::SubPrefix) -> Prefix<K::SuperSuffix, T, K::SuperSuffix> {
148        Prefix::new(self.namespace.as_slice(), &p.prefix())
149    }
150
151    pub fn prefix(&self, p: K::Prefix) -> Prefix<K::Suffix, T, K::Suffix> {
152        Prefix::new(self.namespace.as_slice(), &p.prefix())
153    }
154}
155
156// short-cut for simple keys, rather than .prefix(()).range_raw(...)
157#[cfg(feature = "iterator")]
158impl<'a, K, T> Map<K, T>
159where
160    T: Serialize + DeserializeOwned,
161    // TODO: this should only be when K::Prefix == ()
162    // Other cases need to call prefix() first
163    K: PrimaryKey<'a>,
164{
165    /// While `range_raw` over a `prefix` fixes the prefix to one element and iterates over the
166    /// remaining, `prefix_range_raw` accepts bounds for the lowest and highest elements of the `Prefix`
167    /// itself, and iterates over those (inclusively or exclusively, depending on `PrefixBound`).
168    /// There are some issues that distinguish these two, and blindly casting to `Vec<u8>` doesn't
169    /// solve them.
170    pub fn prefix_range_raw<'c>(
171        &self,
172        store: &'c dyn Storage,
173        min: Option<PrefixBound<'a, K::Prefix>>,
174        max: Option<PrefixBound<'a, K::Prefix>>,
175        order: Order,
176    ) -> Box<dyn Iterator<Item = StdResult<cosmwasm_std::Record<T>>> + 'c>
177    where
178        T: 'c,
179        'a: 'c,
180    {
181        let mapped = namespaced_prefix_range(store, self.namespace.as_slice(), min, max, order)
182            .map(deserialize_v);
183        Box::new(mapped)
184    }
185}
186
187#[cfg(feature = "iterator")]
188impl<'a, K, T> Map<K, T>
189where
190    T: Serialize + DeserializeOwned,
191    K: PrimaryKey<'a> + KeyDeserialize,
192{
193    /// While `range` over a `prefix` fixes the prefix to one element and iterates over the
194    /// remaining, `prefix_range` accepts bounds for the lowest and highest elements of the
195    /// `Prefix` itself, and iterates over those (inclusively or exclusively, depending on
196    /// `PrefixBound`).
197    /// There are some issues that distinguish these two, and blindly casting to `Vec<u8>` doesn't
198    /// solve them.
199    pub fn prefix_range<'c>(
200        &self,
201        store: &'c dyn Storage,
202        min: Option<PrefixBound<'a, K::Prefix>>,
203        max: Option<PrefixBound<'a, K::Prefix>>,
204        order: Order,
205    ) -> Box<dyn Iterator<Item = StdResult<(K::Output, T)>> + 'c>
206    where
207        T: 'c,
208        'a: 'c,
209        K: 'c,
210        K::Output: 'static,
211    {
212        let mapped = namespaced_prefix_range(store, self.namespace.as_slice(), min, max, order)
213            .map(deserialize_kv::<K, T>);
214        Box::new(mapped)
215    }
216
217    fn no_prefix(&self) -> Prefix<K, T, K> {
218        Prefix::new(self.namespace.as_slice(), &[])
219    }
220}
221
222#[cfg(feature = "iterator")]
223impl<'a, K, T> Map<K, T>
224where
225    T: Serialize + DeserializeOwned,
226    K: PrimaryKey<'a>,
227{
228    pub fn range_raw<'c>(
229        &self,
230        store: &'c dyn Storage,
231        min: Option<Bound<'a, K>>,
232        max: Option<Bound<'a, K>>,
233        order: Order,
234    ) -> Box<dyn Iterator<Item = StdResult<cosmwasm_std::Record<T>>> + 'c>
235    where
236        T: 'c,
237    {
238        self.no_prefix_raw().range_raw(store, min, max, order)
239    }
240
241    pub fn keys_raw<'c>(
242        &self,
243        store: &'c dyn Storage,
244        min: Option<Bound<'a, K>>,
245        max: Option<Bound<'a, K>>,
246        order: Order,
247    ) -> Box<dyn Iterator<Item = Vec<u8>> + 'c>
248    where
249        T: 'c,
250    {
251        self.no_prefix_raw().keys_raw(store, min, max, order)
252    }
253}
254
255#[cfg(feature = "iterator")]
256impl<'a, K, T> Map<K, T>
257where
258    T: Serialize + DeserializeOwned,
259    K: PrimaryKey<'a> + KeyDeserialize,
260{
261    pub fn range<'c>(
262        &self,
263        store: &'c dyn Storage,
264        min: Option<Bound<'a, K>>,
265        max: Option<Bound<'a, K>>,
266        order: Order,
267    ) -> Box<dyn Iterator<Item = StdResult<(K::Output, T)>> + 'c>
268    where
269        T: 'c,
270        K::Output: 'static,
271    {
272        self.no_prefix().range(store, min, max, order)
273    }
274
275    pub fn keys<'c>(
276        &self,
277        store: &'c dyn Storage,
278        min: Option<Bound<'a, K>>,
279        max: Option<Bound<'a, K>>,
280        order: Order,
281    ) -> Box<dyn Iterator<Item = StdResult<K::Output>> + 'c>
282    where
283        T: 'c,
284        K::Output: 'static,
285    {
286        self.no_prefix().keys(store, min, max, order)
287    }
288
289    /// Returns the first key-value pair in the map.
290    /// This is *not* according to insertion-order, but according to the key ordering.
291    ///
292    /// # Examples
293    ///
294    /// ```rust
295    /// # use cw_storage_plus::{Map};
296    /// # let mut storage = cosmwasm_std::testing::MockStorage::new();
297    /// const MAP: Map<i32, u32> = Map::new("map");
298    ///
299    /// // empty map
300    /// assert_eq!(MAP.first(&storage).unwrap(), None);
301    ///
302    /// // insert entries
303    /// MAP.save(&mut storage, 1, &10).unwrap();
304    /// MAP.save(&mut storage, -2, &20).unwrap();
305    ///
306    /// assert_eq!(MAP.first(&storage).unwrap(), Some((-2, 20)));
307    /// ```
308    pub fn first(&self, storage: &dyn Storage) -> StdResult<Option<(K::Output, T)>>
309    where
310        K::Output: 'static,
311    {
312        self.range(storage, None, None, Order::Ascending)
313            .next()
314            .transpose()
315    }
316
317    /// Returns the last key-value pair in the map.
318    /// This is *not* according to insertion-order, but according to the key ordering.
319    ///
320    /// # Examples
321    ///
322    /// ```rust
323    /// # use cw_storage_plus::{Map};
324    /// # let mut storage = cosmwasm_std::testing::MockStorage::new();
325    /// const MAP: Map<i32, u32> = Map::new("map");
326    ///
327    /// // empty map
328    /// assert_eq!(MAP.last(&storage).unwrap(), None);
329    ///
330    /// // insert entries
331    /// MAP.save(&mut storage, 1, &10).unwrap();
332    /// MAP.save(&mut storage, -2, &20).unwrap();
333    ///
334    /// assert_eq!(MAP.last(&storage).unwrap(), Some((1, 10)));
335    /// ```
336    pub fn last(&self, storage: &dyn Storage) -> StdResult<Option<(K::Output, T)>>
337    where
338        K::Output: 'static,
339    {
340        self.range(storage, None, None, Order::Descending)
341            .next()
342            .transpose()
343    }
344}
345
346#[cfg(test)]
347mod test {
348    use super::*;
349    #[cfg(feature = "iterator")]
350    use crate::bound::Bounder;
351    use crate::int_key::IntKey;
352    use cosmwasm_std::testing::MockStorage;
353    #[cfg(feature = "iterator")]
354    use cosmwasm_std::to_json_binary;
355    #[cfg(feature = "iterator")]
356    use cosmwasm_std::{Order, StdResult};
357    use serde::{Deserialize, Serialize};
358    use std::ops::Deref;
359
360    #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
361    struct Data {
362        pub name: String,
363        pub age: i32,
364    }
365
366    const PEOPLE: Map<&[u8], Data> = Map::new("people");
367    #[cfg(feature = "iterator")]
368    const PEOPLE_STR_KEY: &str = "people2";
369    #[cfg(feature = "iterator")]
370    const PEOPLE_STR: Map<&str, Data> = Map::new(PEOPLE_STR_KEY);
371    #[cfg(feature = "iterator")]
372    const PEOPLE_ID: Map<u32, Data> = Map::new("people_id");
373    #[cfg(feature = "iterator")]
374    const SIGNED_ID: Map<i32, Data> = Map::new("signed_id");
375
376    const ALLOWANCE: Map<(&[u8], &[u8]), u64> = Map::new("allow");
377
378    const TRIPLE: Map<(&[u8], u8, &str), u64> = Map::new("triple");
379
380    #[test]
381    fn create_path() {
382        let path = PEOPLE.key(b"john");
383        let key = path.deref();
384        // this should be prefixed(people) || john
385        assert_eq!("people".len() + "john".len() + 2, key.len());
386        assert_eq!(b"people".to_vec().as_slice(), &key[2..8]);
387        assert_eq!(b"john".to_vec().as_slice(), &key[8..]);
388
389        let path = ALLOWANCE.key((b"john", b"maria"));
390        let key = path.deref();
391        // this should be prefixed(allow) || prefixed(john) || maria
392        assert_eq!(
393            "allow".len() + "john".len() + "maria".len() + 2 * 2,
394            key.len()
395        );
396        assert_eq!(b"allow".to_vec().as_slice(), &key[2..7]);
397        assert_eq!(b"john".to_vec().as_slice(), &key[9..13]);
398        assert_eq!(b"maria".to_vec().as_slice(), &key[13..]);
399
400        let path = TRIPLE.key((b"john", 8u8, "pedro"));
401        let key = path.deref();
402        // this should be prefixed(triple) || prefixed(john) || prefixed(8u8) || pedro
403        assert_eq!(
404            "triple".len() + "john".len() + 1 + "pedro".len() + 2 * 3,
405            key.len()
406        );
407        assert_eq!(b"triple".to_vec().as_slice(), &key[2..8]);
408        assert_eq!(b"john".to_vec().as_slice(), &key[10..14]);
409        assert_eq!(8u8.to_cw_bytes(), &key[16..17]);
410        assert_eq!(b"pedro".to_vec().as_slice(), &key[17..]);
411    }
412
413    #[test]
414    fn save_and_load() {
415        let mut store = MockStorage::new();
416
417        // save and load on one key
418        let john = PEOPLE.key(b"john");
419        let data = Data {
420            name: "John".to_string(),
421            age: 32,
422        };
423        assert_eq!(None, john.may_load(&store).unwrap());
424        john.save(&mut store, &data).unwrap();
425        assert_eq!(data, john.load(&store).unwrap());
426
427        // nothing on another key
428        assert_eq!(None, PEOPLE.may_load(&store, b"jack").unwrap());
429
430        // same named path gets the data
431        assert_eq!(data, PEOPLE.load(&store, b"john").unwrap());
432
433        // removing leaves us empty
434        john.remove(&mut store);
435        assert_eq!(None, john.may_load(&store).unwrap());
436    }
437
438    #[test]
439    fn existence() {
440        let mut store = MockStorage::new();
441
442        // set data in proper format
443        let data = Data {
444            name: "John".to_string(),
445            age: 32,
446        };
447        PEOPLE.save(&mut store, b"john", &data).unwrap();
448
449        // set and remove it
450        PEOPLE.save(&mut store, b"removed", &data).unwrap();
451        PEOPLE.remove(&mut store, b"removed");
452
453        // invalid, but non-empty data
454        store.set(&PEOPLE.key(b"random"), b"random-data");
455
456        // any data, including invalid or empty is returned as "has"
457        assert!(PEOPLE.has(&store, b"john"));
458        assert!(PEOPLE.has(&store, b"random"));
459
460        // if nothing was written, it is false
461        assert!(!PEOPLE.has(&store, b"never-writen"));
462        assert!(!PEOPLE.has(&store, b"removed"));
463    }
464
465    #[test]
466    fn composite_keys() {
467        let mut store = MockStorage::new();
468
469        // save and load on a composite key
470        let allow = ALLOWANCE.key((b"owner", b"spender"));
471        assert_eq!(None, allow.may_load(&store).unwrap());
472        allow.save(&mut store, &1234).unwrap();
473        assert_eq!(1234, allow.load(&store).unwrap());
474
475        // not under other key
476        let different = ALLOWANCE.may_load(&store, (b"owners", b"pender")).unwrap();
477        assert_eq!(None, different);
478
479        // matches under a proper copy
480        let same = ALLOWANCE.load(&store, (b"owner", b"spender")).unwrap();
481        assert_eq!(1234, same);
482    }
483
484    #[test]
485    fn triple_keys() {
486        let mut store = MockStorage::new();
487
488        // save and load on a triple composite key
489        let triple = TRIPLE.key((b"owner", 10u8, "recipient"));
490        assert_eq!(None, triple.may_load(&store).unwrap());
491        triple.save(&mut store, &1234).unwrap();
492        assert_eq!(1234, triple.load(&store).unwrap());
493
494        // not under other key
495        let different = TRIPLE
496            .may_load(&store, (b"owners", 10u8, "receiver"))
497            .unwrap();
498        assert_eq!(None, different);
499
500        // matches under a proper copy
501        let same = TRIPLE.load(&store, (b"owner", 10u8, "recipient")).unwrap();
502        assert_eq!(1234, same);
503    }
504
505    #[test]
506    #[cfg(feature = "iterator")]
507    fn range_raw_simple_key() {
508        let mut store = MockStorage::new();
509
510        // save and load on two keys
511        let data = Data {
512            name: "John".to_string(),
513            age: 32,
514        };
515        PEOPLE.save(&mut store, b"john", &data).unwrap();
516
517        let data2 = Data {
518            name: "Jim".to_string(),
519            age: 44,
520        };
521        PEOPLE.save(&mut store, b"jim", &data2).unwrap();
522
523        // let's try to iterate!
524        let all: StdResult<Vec<_>> = PEOPLE
525            .range_raw(&store, None, None, Order::Ascending)
526            .collect();
527        let all = all.unwrap();
528        assert_eq!(2, all.len());
529        assert_eq!(
530            all,
531            vec![
532                (b"jim".to_vec(), data2.clone()),
533                (b"john".to_vec(), data.clone())
534            ]
535        );
536
537        // let's try to iterate over a range
538        let all: StdResult<Vec<_>> = PEOPLE
539            .range_raw(
540                &store,
541                Some(Bound::inclusive(b"j" as &[u8])),
542                None,
543                Order::Ascending,
544            )
545            .collect();
546        let all = all.unwrap();
547        assert_eq!(2, all.len());
548        assert_eq!(
549            all,
550            vec![(b"jim".to_vec(), data2), (b"john".to_vec(), data.clone())]
551        );
552
553        // let's try to iterate over a more restrictive range
554        let all: StdResult<Vec<_>> = PEOPLE
555            .range_raw(
556                &store,
557                Some(Bound::inclusive(b"jo" as &[u8])),
558                None,
559                Order::Ascending,
560            )
561            .collect();
562        let all = all.unwrap();
563        assert_eq!(1, all.len());
564        assert_eq!(all, vec![(b"john".to_vec(), data)]);
565    }
566
567    #[test]
568    #[cfg(feature = "iterator")]
569    fn range_simple_string_key() {
570        let mut store = MockStorage::new();
571
572        // save and load on three keys
573        let data = Data {
574            name: "John".to_string(),
575            age: 32,
576        };
577        PEOPLE.save(&mut store, b"john", &data).unwrap();
578
579        let data2 = Data {
580            name: "Jim".to_string(),
581            age: 44,
582        };
583        PEOPLE.save(&mut store, b"jim", &data2).unwrap();
584
585        let data3 = Data {
586            name: "Ada".to_string(),
587            age: 23,
588        };
589        PEOPLE.save(&mut store, b"ada", &data3).unwrap();
590
591        // let's try to iterate!
592        let all: StdResult<Vec<_>> = PEOPLE.range(&store, None, None, Order::Ascending).collect();
593        let all = all.unwrap();
594        assert_eq!(3, all.len());
595        assert_eq!(
596            all,
597            vec![
598                (b"ada".to_vec(), data3),
599                (b"jim".to_vec(), data2.clone()),
600                (b"john".to_vec(), data.clone())
601            ]
602        );
603
604        // let's try to iterate over a range
605        let all: StdResult<Vec<_>> = PEOPLE
606            .range(&store, b"j".inclusive_bound(), None, Order::Ascending)
607            .collect();
608        let all = all.unwrap();
609        assert_eq!(2, all.len());
610        assert_eq!(
611            all,
612            vec![(b"jim".to_vec(), data2), (b"john".to_vec(), data.clone())]
613        );
614
615        // let's try to iterate over a more restrictive range
616        let all: StdResult<Vec<_>> = PEOPLE
617            .range(&store, b"jo".inclusive_bound(), None, Order::Ascending)
618            .collect();
619        let all = all.unwrap();
620        assert_eq!(1, all.len());
621        assert_eq!(all, vec![(b"john".to_vec(), data)]);
622    }
623
624    #[test]
625    #[cfg(feature = "iterator")]
626    fn range_key_broken_deserialization_errors() {
627        let mut store = MockStorage::new();
628
629        // save and load on three keys
630        let data = Data {
631            name: "John".to_string(),
632            age: 32,
633        };
634        PEOPLE_STR.save(&mut store, "john", &data).unwrap();
635
636        let data2 = Data {
637            name: "Jim".to_string(),
638            age: 44,
639        };
640        PEOPLE_STR.save(&mut store, "jim", &data2).unwrap();
641
642        let data3 = Data {
643            name: "Ada".to_string(),
644            age: 23,
645        };
646        PEOPLE_STR.save(&mut store, "ada", &data3).unwrap();
647
648        // let's iterate!
649        let all: StdResult<Vec<_>> = PEOPLE_STR
650            .range(&store, None, None, Order::Ascending)
651            .collect();
652        let all = all.unwrap();
653        assert_eq!(3, all.len());
654        assert_eq!(
655            all,
656            vec![
657                ("ada".to_string(), data3.clone()),
658                ("jim".to_string(), data2.clone()),
659                ("john".to_string(), data.clone())
660            ]
661        );
662
663        // Manually add a broken key (invalid utf-8)
664        store.set(
665            &[
666                [0u8, PEOPLE_STR_KEY.len() as u8].as_slice(),
667                PEOPLE_STR_KEY.as_bytes(),
668                b"\xddim",
669            ]
670            .concat(),
671            &to_json_binary(&data2).unwrap(),
672        );
673
674        // Let's try to iterate again!
675        let all: StdResult<Vec<_>> = PEOPLE_STR
676            .range(&store, None, None, Order::Ascending)
677            .collect();
678        assert!(all.is_err());
679        //assert!(matches!(all.unwrap_err(), InvalidUtf8 { .. }));
680
681        // And the same with keys()
682        let all: StdResult<Vec<_>> = PEOPLE_STR
683            .keys(&store, None, None, Order::Ascending)
684            .collect();
685        assert!(all.is_err());
686        //assert!(matches!(all.unwrap_err(), InvalidUtf8 { .. }));
687
688        // But range_raw still works
689        let all: StdResult<Vec<_>> = PEOPLE_STR
690            .range_raw(&store, None, None, Order::Ascending)
691            .collect();
692
693        let all = all.unwrap();
694        assert_eq!(4, all.len());
695        assert_eq!(
696            all,
697            vec![
698                (b"ada".to_vec(), data3.clone()),
699                (b"jim".to_vec(), data2.clone()),
700                (b"john".to_vec(), data.clone()),
701                (b"\xddim".to_vec(), data2.clone()),
702            ]
703        );
704
705        // And the same with keys_raw
706        let all: Vec<_> = PEOPLE_STR
707            .keys_raw(&store, None, None, Order::Ascending)
708            .collect();
709
710        assert_eq!(4, all.len());
711        assert_eq!(
712            all,
713            vec![
714                b"ada".to_vec(),
715                b"jim".to_vec(),
716                b"john".to_vec(),
717                b"\xddim".to_vec(),
718            ]
719        );
720    }
721
722    #[test]
723    #[cfg(feature = "iterator")]
724    fn range_simple_integer_key() {
725        let mut store = MockStorage::new();
726
727        // save and load on two keys
728        let data = Data {
729            name: "John".to_string(),
730            age: 32,
731        };
732        PEOPLE_ID.save(&mut store, 1234, &data).unwrap();
733
734        let data2 = Data {
735            name: "Jim".to_string(),
736            age: 44,
737        };
738        PEOPLE_ID.save(&mut store, 56, &data2).unwrap();
739
740        // let's try to iterate!
741        let all: StdResult<Vec<_>> = PEOPLE_ID
742            .range(&store, None, None, Order::Ascending)
743            .collect();
744        let all = all.unwrap();
745        assert_eq!(2, all.len());
746        assert_eq!(all, vec![(56, data2.clone()), (1234, data.clone())]);
747
748        // let's try to iterate over a range
749        let all: StdResult<Vec<_>> = PEOPLE_ID
750            .range(
751                &store,
752                Some(Bound::inclusive(56u32)),
753                None,
754                Order::Ascending,
755            )
756            .collect();
757        let all = all.unwrap();
758        assert_eq!(2, all.len());
759        assert_eq!(all, vec![(56, data2), (1234, data.clone())]);
760
761        // let's try to iterate over a more restrictive range
762        let all: StdResult<Vec<_>> = PEOPLE_ID
763            .range(
764                &store,
765                Some(Bound::inclusive(57u32)),
766                None,
767                Order::Ascending,
768            )
769            .collect();
770        let all = all.unwrap();
771        assert_eq!(1, all.len());
772        assert_eq!(all, vec![(1234, data)]);
773    }
774
775    #[test]
776    #[cfg(feature = "iterator")]
777    fn range_simple_integer_key_with_bounder_trait() {
778        let mut store = MockStorage::new();
779
780        // save and load on two keys
781        let data = Data {
782            name: "John".to_string(),
783            age: 32,
784        };
785        PEOPLE_ID.save(&mut store, 1234, &data).unwrap();
786
787        let data2 = Data {
788            name: "Jim".to_string(),
789            age: 44,
790        };
791        PEOPLE_ID.save(&mut store, 56, &data2).unwrap();
792
793        // let's try to iterate!
794        let all: StdResult<Vec<_>> = PEOPLE_ID
795            .range(&store, None, None, Order::Ascending)
796            .collect();
797        let all = all.unwrap();
798        assert_eq!(2, all.len());
799        assert_eq!(all, vec![(56, data2.clone()), (1234, data.clone())]);
800
801        // let's try to iterate over a range
802        let all: StdResult<Vec<_>> = PEOPLE_ID
803            .range(&store, 56u32.inclusive_bound(), None, Order::Ascending)
804            .collect();
805        let all = all.unwrap();
806        assert_eq!(2, all.len());
807        assert_eq!(all, vec![(56, data2), (1234, data.clone())]);
808
809        // let's try to iterate over a more restrictive range
810        let all: StdResult<Vec<_>> = PEOPLE_ID
811            .range(&store, 57u32.inclusive_bound(), None, Order::Ascending)
812            .collect();
813        let all = all.unwrap();
814        assert_eq!(1, all.len());
815        assert_eq!(all, vec![(1234, data)]);
816    }
817
818    #[test]
819    #[cfg(feature = "iterator")]
820    fn range_simple_signed_integer_key() {
821        let mut store = MockStorage::new();
822
823        // save and load on three keys
824        let data = Data {
825            name: "John".to_string(),
826            age: 32,
827        };
828        SIGNED_ID.save(&mut store, -1234, &data).unwrap();
829
830        let data2 = Data {
831            name: "Jim".to_string(),
832            age: 44,
833        };
834        SIGNED_ID.save(&mut store, -56, &data2).unwrap();
835
836        let data3 = Data {
837            name: "Jules".to_string(),
838            age: 55,
839        };
840        SIGNED_ID.save(&mut store, 50, &data3).unwrap();
841
842        // let's try to iterate!
843        let all: StdResult<Vec<_>> = SIGNED_ID
844            .range(&store, None, None, Order::Ascending)
845            .collect();
846        let all = all.unwrap();
847        assert_eq!(3, all.len());
848        // order is correct
849        assert_eq!(
850            all,
851            vec![(-1234, data), (-56, data2.clone()), (50, data3.clone())]
852        );
853
854        // let's try to iterate over a range
855        let all: StdResult<Vec<_>> = SIGNED_ID
856            .range(
857                &store,
858                Some(Bound::inclusive(-56i32)),
859                None,
860                Order::Ascending,
861            )
862            .collect();
863        let all = all.unwrap();
864        assert_eq!(2, all.len());
865        assert_eq!(all, vec![(-56, data2), (50, data3.clone())]);
866
867        // let's try to iterate over a more restrictive range
868        let all: StdResult<Vec<_>> = SIGNED_ID
869            .range(
870                &store,
871                Some(Bound::inclusive(-55i32)),
872                Some(Bound::inclusive(50i32)),
873                Order::Descending,
874            )
875            .collect();
876        let all = all.unwrap();
877        assert_eq!(1, all.len());
878        assert_eq!(all, vec![(50, data3)]);
879    }
880
881    #[test]
882    #[cfg(feature = "iterator")]
883    fn range_simple_signed_integer_key_with_bounder_trait() {
884        let mut store = MockStorage::new();
885
886        // save and load on three keys
887        let data = Data {
888            name: "John".to_string(),
889            age: 32,
890        };
891        SIGNED_ID.save(&mut store, -1234, &data).unwrap();
892
893        let data2 = Data {
894            name: "Jim".to_string(),
895            age: 44,
896        };
897        SIGNED_ID.save(&mut store, -56, &data2).unwrap();
898
899        let data3 = Data {
900            name: "Jules".to_string(),
901            age: 55,
902        };
903        SIGNED_ID.save(&mut store, 50, &data3).unwrap();
904
905        // let's try to iterate!
906        let all: StdResult<Vec<_>> = SIGNED_ID
907            .range(&store, None, None, Order::Ascending)
908            .collect();
909        let all = all.unwrap();
910        assert_eq!(3, all.len());
911        // order is correct
912        assert_eq!(
913            all,
914            vec![(-1234, data), (-56, data2.clone()), (50, data3.clone())]
915        );
916
917        // let's try to iterate over a range
918        let all: StdResult<Vec<_>> = SIGNED_ID
919            .range(&store, (-56i32).inclusive_bound(), None, Order::Ascending)
920            .collect();
921        let all = all.unwrap();
922        assert_eq!(2, all.len());
923        assert_eq!(all, vec![(-56, data2), (50, data3.clone())]);
924
925        // let's try to iterate over a more restrictive range
926        let all: StdResult<Vec<_>> = SIGNED_ID
927            .range(
928                &store,
929                (-55i32).inclusive_bound(),
930                50i32.inclusive_bound(),
931                Order::Descending,
932            )
933            .collect();
934        let all = all.unwrap();
935        assert_eq!(1, all.len());
936        assert_eq!(all, vec![(50, data3)]);
937    }
938
939    #[test]
940    #[cfg(feature = "iterator")]
941    fn range_raw_composite_key() {
942        let mut store = MockStorage::new();
943
944        // save and load on three keys, one under different owner
945        ALLOWANCE
946            .save(&mut store, (b"owner", b"spender"), &1000)
947            .unwrap();
948        ALLOWANCE
949            .save(&mut store, (b"owner", b"spender2"), &3000)
950            .unwrap();
951        ALLOWANCE
952            .save(&mut store, (b"owner2", b"spender"), &5000)
953            .unwrap();
954
955        // let's try to iterate!
956        let all: StdResult<Vec<_>> = ALLOWANCE
957            .range_raw(&store, None, None, Order::Ascending)
958            .collect();
959        let all = all.unwrap();
960        assert_eq!(3, all.len());
961        assert_eq!(
962            all,
963            vec![
964                ((b"owner".to_vec(), b"spender".to_vec()).joined_key(), 1000),
965                ((b"owner".to_vec(), b"spender2".to_vec()).joined_key(), 3000),
966                ((b"owner2".to_vec(), b"spender".to_vec()).joined_key(), 5000),
967            ]
968        );
969
970        // let's try to iterate over a prefix
971        let all: StdResult<Vec<_>> = ALLOWANCE
972            .prefix(b"owner")
973            .range_raw(&store, None, None, Order::Ascending)
974            .collect();
975        let all = all.unwrap();
976        assert_eq!(2, all.len());
977        assert_eq!(
978            all,
979            vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000)]
980        );
981    }
982
983    #[test]
984    #[cfg(feature = "iterator")]
985    fn range_composite_key() {
986        let mut store = MockStorage::new();
987
988        // save and load on three keys, one under different owner
989        ALLOWANCE
990            .save(&mut store, (b"owner", b"spender"), &1000)
991            .unwrap();
992        ALLOWANCE
993            .save(&mut store, (b"owner", b"spender2"), &3000)
994            .unwrap();
995        ALLOWANCE
996            .save(&mut store, (b"owner2", b"spender"), &5000)
997            .unwrap();
998
999        // let's try to iterate!
1000        let all: StdResult<Vec<_>> = ALLOWANCE
1001            .range(&store, None, None, Order::Ascending)
1002            .collect();
1003        let all = all.unwrap();
1004        assert_eq!(3, all.len());
1005        assert_eq!(
1006            all,
1007            vec![
1008                ((b"owner".to_vec(), b"spender".to_vec()), 1000),
1009                ((b"owner".to_vec(), b"spender2".to_vec()), 3000),
1010                ((b"owner2".to_vec(), b"spender".to_vec()), 5000)
1011            ]
1012        );
1013
1014        // let's try to iterate over a prefix
1015        let all: StdResult<Vec<_>> = ALLOWANCE
1016            .prefix(b"owner")
1017            .range(&store, None, None, Order::Ascending)
1018            .collect();
1019        let all = all.unwrap();
1020        assert_eq!(2, all.len());
1021        assert_eq!(
1022            all,
1023            vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000),]
1024        );
1025
1026        // let's try to iterate over a prefixed restricted inclusive range
1027        let all: StdResult<Vec<_>> = ALLOWANCE
1028            .prefix(b"owner")
1029            .range(&store, b"spender".inclusive_bound(), None, Order::Ascending)
1030            .collect();
1031        let all = all.unwrap();
1032        assert_eq!(2, all.len());
1033        assert_eq!(
1034            all,
1035            vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000),]
1036        );
1037
1038        // let's try to iterate over a prefixed restricted exclusive range
1039        let all: StdResult<Vec<_>> = ALLOWANCE
1040            .prefix(b"owner")
1041            .range(&store, b"spender".exclusive_bound(), None, Order::Ascending)
1042            .collect();
1043        let all = all.unwrap();
1044        assert_eq!(1, all.len());
1045        assert_eq!(all, vec![(b"spender2".to_vec(), 3000),]);
1046    }
1047
1048    #[test]
1049    #[cfg(feature = "iterator")]
1050    fn range_raw_triple_key() {
1051        let mut store = MockStorage::new();
1052
1053        // save and load on three keys, one under different owner
1054        TRIPLE
1055            .save(&mut store, (b"owner", 9, "recipient"), &1000)
1056            .unwrap();
1057        TRIPLE
1058            .save(&mut store, (b"owner", 9, "recipient2"), &3000)
1059            .unwrap();
1060        TRIPLE
1061            .save(&mut store, (b"owner", 10, "recipient3"), &3000)
1062            .unwrap();
1063        TRIPLE
1064            .save(&mut store, (b"owner2", 9, "recipient"), &5000)
1065            .unwrap();
1066
1067        // let's try to iterate!
1068        let all: StdResult<Vec<_>> = TRIPLE
1069            .range_raw(&store, None, None, Order::Ascending)
1070            .collect();
1071        let all = all.unwrap();
1072        assert_eq!(4, all.len());
1073        assert_eq!(
1074            all,
1075            vec![
1076                (
1077                    (b"owner".to_vec(), 9u8, b"recipient".to_vec()).joined_key(),
1078                    1000
1079                ),
1080                (
1081                    (b"owner".to_vec(), 9u8, b"recipient2".to_vec()).joined_key(),
1082                    3000
1083                ),
1084                (
1085                    (b"owner".to_vec(), 10u8, b"recipient3".to_vec()).joined_key(),
1086                    3000
1087                ),
1088                (
1089                    (b"owner2".to_vec(), 9u8, b"recipient".to_vec()).joined_key(),
1090                    5000
1091                )
1092            ]
1093        );
1094
1095        // let's iterate over a prefix
1096        let all: StdResult<Vec<_>> = TRIPLE
1097            .prefix((b"owner", 9))
1098            .range_raw(&store, None, None, Order::Ascending)
1099            .collect();
1100        let all = all.unwrap();
1101        assert_eq!(2, all.len());
1102        assert_eq!(
1103            all,
1104            vec![
1105                (b"recipient".to_vec(), 1000),
1106                (b"recipient2".to_vec(), 3000)
1107            ]
1108        );
1109
1110        // let's iterate over a sub prefix
1111        let all: StdResult<Vec<_>> = TRIPLE
1112            .sub_prefix(b"owner")
1113            .range_raw(&store, None, None, Order::Ascending)
1114            .collect();
1115        let all = all.unwrap();
1116        assert_eq!(3, all.len());
1117        // Use range() if you want key deserialization
1118        assert_eq!(
1119            all,
1120            vec![
1121                ((9u8, b"recipient".to_vec()).joined_key(), 1000),
1122                ((9u8, b"recipient2".to_vec()).joined_key(), 3000),
1123                ((10u8, b"recipient3".to_vec()).joined_key(), 3000)
1124            ]
1125        );
1126    }
1127
1128    #[test]
1129    #[cfg(feature = "iterator")]
1130    fn range_triple_key() {
1131        let mut store = MockStorage::new();
1132
1133        // save and load on three keys, one under different owner
1134        TRIPLE
1135            .save(&mut store, (b"owner", 9u8, "recipient"), &1000)
1136            .unwrap();
1137        TRIPLE
1138            .save(&mut store, (b"owner", 9u8, "recipient2"), &3000)
1139            .unwrap();
1140        TRIPLE
1141            .save(&mut store, (b"owner", 10u8, "recipient3"), &3000)
1142            .unwrap();
1143        TRIPLE
1144            .save(&mut store, (b"owner2", 9u8, "recipient"), &5000)
1145            .unwrap();
1146
1147        // let's try to iterate!
1148        let all: StdResult<Vec<_>> = TRIPLE.range(&store, None, None, Order::Ascending).collect();
1149        let all = all.unwrap();
1150        assert_eq!(4, all.len());
1151        assert_eq!(
1152            all,
1153            vec![
1154                ((b"owner".to_vec(), 9, "recipient".to_string()), 1000),
1155                ((b"owner".to_vec(), 9, "recipient2".to_string()), 3000),
1156                ((b"owner".to_vec(), 10, "recipient3".to_string()), 3000),
1157                ((b"owner2".to_vec(), 9, "recipient".to_string()), 5000)
1158            ]
1159        );
1160
1161        // let's iterate over a sub_prefix
1162        let all: StdResult<Vec<_>> = TRIPLE
1163            .sub_prefix(b"owner")
1164            .range(&store, None, None, Order::Ascending)
1165            .collect();
1166        let all = all.unwrap();
1167        assert_eq!(3, all.len());
1168        assert_eq!(
1169            all,
1170            vec![
1171                ((9, "recipient".to_string()), 1000),
1172                ((9, "recipient2".to_string()), 3000),
1173                ((10, "recipient3".to_string()), 3000),
1174            ]
1175        );
1176
1177        // let's iterate over a prefix
1178        let all: StdResult<Vec<_>> = TRIPLE
1179            .prefix((b"owner", 9))
1180            .range(&store, None, None, Order::Ascending)
1181            .collect();
1182        let all = all.unwrap();
1183        assert_eq!(2, all.len());
1184        assert_eq!(
1185            all,
1186            vec![
1187                ("recipient".to_string(), 1000),
1188                ("recipient2".to_string(), 3000),
1189            ]
1190        );
1191
1192        // let's try to iterate over a prefixed restricted inclusive range
1193        let all: StdResult<Vec<_>> = TRIPLE
1194            .prefix((b"owner", 9))
1195            .range(
1196                &store,
1197                "recipient".inclusive_bound(),
1198                None,
1199                Order::Ascending,
1200            )
1201            .collect();
1202        let all = all.unwrap();
1203        assert_eq!(2, all.len());
1204        assert_eq!(
1205            all,
1206            vec![
1207                ("recipient".to_string(), 1000),
1208                ("recipient2".to_string(), 3000),
1209            ]
1210        );
1211
1212        // let's try to iterate over a prefixed restricted exclusive range
1213        let all: StdResult<Vec<_>> = TRIPLE
1214            .prefix((b"owner", 9))
1215            .range(
1216                &store,
1217                "recipient".exclusive_bound(),
1218                None,
1219                Order::Ascending,
1220            )
1221            .collect();
1222        let all = all.unwrap();
1223        assert_eq!(1, all.len());
1224        assert_eq!(all, vec![("recipient2".to_string(), 3000),]);
1225    }
1226
1227    #[test]
1228    fn basic_update() {
1229        let mut store = MockStorage::new();
1230
1231        let add_ten = |a: Option<u64>| -> StdResult<_> { Ok(a.unwrap_or_default() + 10) };
1232
1233        // save and load on three keys, one under different owner
1234        let key: (&[u8], &[u8]) = (b"owner", b"spender");
1235        ALLOWANCE.update(&mut store, key, add_ten).unwrap();
1236        let twenty = ALLOWANCE.update(&mut store, key, add_ten).unwrap();
1237        assert_eq!(20, twenty);
1238        let loaded = ALLOWANCE.load(&store, key).unwrap();
1239        assert_eq!(20, loaded);
1240    }
1241
1242    #[test]
1243    fn readme_works() -> StdResult<()> {
1244        let mut store = MockStorage::new();
1245        let data = Data {
1246            name: "John".to_string(),
1247            age: 32,
1248        };
1249
1250        // load and save with extra key argument
1251        let empty = PEOPLE.may_load(&store, b"john")?;
1252        assert_eq!(None, empty);
1253        PEOPLE.save(&mut store, b"john", &data)?;
1254        let loaded = PEOPLE.load(&store, b"john")?;
1255        assert_eq!(data, loaded);
1256
1257        // nothing on another key
1258        let missing = PEOPLE.may_load(&store, b"jack")?;
1259        assert_eq!(None, missing);
1260
1261        // update function for new or existing keys
1262        let birthday = |d: Option<Data>| -> StdResult<Data> {
1263            match d {
1264                Some(one) => Ok(Data {
1265                    name: one.name,
1266                    age: one.age + 1,
1267                }),
1268                None => Ok(Data {
1269                    name: "Newborn".to_string(),
1270                    age: 0,
1271                }),
1272            }
1273        };
1274
1275        let old_john = PEOPLE.update(&mut store, b"john", birthday)?;
1276        assert_eq!(33, old_john.age);
1277        assert_eq!("John", old_john.name.as_str());
1278
1279        let new_jack = PEOPLE.update(&mut store, b"jack", birthday)?;
1280        assert_eq!(0, new_jack.age);
1281        assert_eq!("Newborn", new_jack.name.as_str());
1282
1283        // update also changes the store
1284        assert_eq!(old_john, PEOPLE.load(&store, b"john")?);
1285        assert_eq!(new_jack, PEOPLE.load(&store, b"jack")?);
1286
1287        // removing leaves us empty
1288        PEOPLE.remove(&mut store, b"john");
1289        let empty = PEOPLE.may_load(&store, b"john")?;
1290        assert_eq!(None, empty);
1291
1292        Ok(())
1293    }
1294
1295    #[test]
1296    fn readme_works_composite_keys() -> StdResult<()> {
1297        let mut store = MockStorage::new();
1298
1299        // save and load on a composite key
1300        let empty = ALLOWANCE.may_load(&store, (b"owner", b"spender"))?;
1301        assert_eq!(None, empty);
1302        ALLOWANCE.save(&mut store, (b"owner", b"spender"), &777)?;
1303        let loaded = ALLOWANCE.load(&store, (b"owner", b"spender"))?;
1304        assert_eq!(777, loaded);
1305
1306        // doesn't appear under other key (even if a concat would be the same)
1307        let different = ALLOWANCE.may_load(&store, (b"owners", b"pender"))?;
1308        assert_eq!(None, different);
1309
1310        // simple update
1311        ALLOWANCE.update(&mut store, (b"owner", b"spender"), |v| -> StdResult<u64> {
1312            Ok(v.unwrap_or_default() + 222)
1313        })?;
1314        let loaded = ALLOWANCE.load(&store, (b"owner", b"spender"))?;
1315        assert_eq!(999, loaded);
1316
1317        Ok(())
1318    }
1319
1320    #[test]
1321    fn readme_works_with_path() -> StdResult<()> {
1322        let mut store = MockStorage::new();
1323        let data = Data {
1324            name: "John".to_string(),
1325            age: 32,
1326        };
1327
1328        // create a Path one time to use below
1329        let john = PEOPLE.key(b"john");
1330
1331        // Use this just like an Item above
1332        let empty = john.may_load(&store)?;
1333        assert_eq!(None, empty);
1334        john.save(&mut store, &data)?;
1335        let loaded = john.load(&store)?;
1336        assert_eq!(data, loaded);
1337        john.remove(&mut store);
1338        let empty = john.may_load(&store)?;
1339        assert_eq!(None, empty);
1340
1341        // same for composite keys, just use both parts in key()
1342        let allow = ALLOWANCE.key((b"owner", b"spender"));
1343        allow.save(&mut store, &1234)?;
1344        let loaded = allow.load(&store)?;
1345        assert_eq!(1234, loaded);
1346        allow.update(&mut store, |x| -> StdResult<u64> {
1347            Ok(x.unwrap_or_default() * 2)
1348        })?;
1349        let loaded = allow.load(&store)?;
1350        assert_eq!(2468, loaded);
1351
1352        Ok(())
1353    }
1354
1355    #[test]
1356    #[cfg(feature = "iterator")]
1357    fn readme_with_range_raw() -> StdResult<()> {
1358        let mut store = MockStorage::new();
1359
1360        // save and load on two keys
1361        let data = Data {
1362            name: "John".to_string(),
1363            age: 32,
1364        };
1365        PEOPLE.save(&mut store, b"john", &data)?;
1366        let data2 = Data {
1367            name: "Jim".to_string(),
1368            age: 44,
1369        };
1370        PEOPLE.save(&mut store, b"jim", &data2)?;
1371
1372        // iterate over them all
1373        let all: StdResult<Vec<_>> = PEOPLE
1374            .range_raw(&store, None, None, Order::Ascending)
1375            .collect();
1376        assert_eq!(
1377            all?,
1378            vec![(b"jim".to_vec(), data2), (b"john".to_vec(), data.clone())]
1379        );
1380
1381        // or just show what is after jim
1382        let all: StdResult<Vec<_>> = PEOPLE
1383            .range_raw(
1384                &store,
1385                Some(Bound::exclusive(b"jim" as &[u8])),
1386                None,
1387                Order::Ascending,
1388            )
1389            .collect();
1390        assert_eq!(all?, vec![(b"john".to_vec(), data)]);
1391
1392        // save and load on three keys, one under different owner
1393        ALLOWANCE.save(&mut store, (b"owner", b"spender"), &1000)?;
1394        ALLOWANCE.save(&mut store, (b"owner", b"spender2"), &3000)?;
1395        ALLOWANCE.save(&mut store, (b"owner2", b"spender"), &5000)?;
1396
1397        // get all under one key
1398        let all: StdResult<Vec<_>> = ALLOWANCE
1399            .prefix(b"owner")
1400            .range_raw(&store, None, None, Order::Ascending)
1401            .collect();
1402        assert_eq!(
1403            all?,
1404            vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000)]
1405        );
1406
1407        // Or ranges between two items (even reverse)
1408        let all: StdResult<Vec<_>> = ALLOWANCE
1409            .prefix(b"owner")
1410            .range_raw(
1411                &store,
1412                Some(Bound::exclusive(b"spender1" as &[u8])),
1413                Some(Bound::inclusive(b"spender2" as &[u8])),
1414                Order::Descending,
1415            )
1416            .collect();
1417        assert_eq!(all?, vec![(b"spender2".to_vec(), 3000)]);
1418
1419        Ok(())
1420    }
1421
1422    #[test]
1423    #[cfg(feature = "iterator")]
1424    fn prefixed_range_raw_works() {
1425        // this is designed to look as much like a secondary index as possible
1426        // we want to query over a range of u32 for the first key and all subkeys
1427        const AGES: Map<(u32, Vec<u8>), u64> = Map::new("ages");
1428
1429        let mut store = MockStorage::new();
1430        AGES.save(&mut store, (2, vec![1, 2, 3]), &123).unwrap();
1431        AGES.save(&mut store, (3, vec![4, 5, 6]), &456).unwrap();
1432        AGES.save(&mut store, (5, vec![7, 8, 9]), &789).unwrap();
1433        AGES.save(&mut store, (5, vec![9, 8, 7]), &987).unwrap();
1434        AGES.save(&mut store, (7, vec![20, 21, 22]), &2002).unwrap();
1435        AGES.save(&mut store, (8, vec![23, 24, 25]), &2332).unwrap();
1436
1437        // typical range under one prefix as a control
1438        let fives = AGES
1439            .prefix(5)
1440            .range_raw(&store, None, None, Order::Ascending)
1441            .collect::<StdResult<Vec<_>>>()
1442            .unwrap();
1443        assert_eq!(fives.len(), 2);
1444        assert_eq!(fives, vec![(vec![7, 8, 9], 789), (vec![9, 8, 7], 987)]);
1445
1446        let keys: Vec<_> = AGES
1447            .keys_raw(&store, None, None, Order::Ascending)
1448            .collect();
1449        println!("keys: {keys:?}");
1450
1451        // using inclusive bounds both sides
1452        let include = AGES
1453            .prefix_range_raw(
1454                &store,
1455                Some(PrefixBound::inclusive(3u32)),
1456                Some(PrefixBound::inclusive(7u32)),
1457                Order::Ascending,
1458            )
1459            .map(|r| r.map(|(_, v)| v))
1460            .collect::<StdResult<Vec<_>>>()
1461            .unwrap();
1462        assert_eq!(include.len(), 4);
1463        assert_eq!(include, vec![456, 789, 987, 2002]);
1464
1465        // using exclusive bounds both sides
1466        let exclude = AGES
1467            .prefix_range_raw(
1468                &store,
1469                Some(PrefixBound::exclusive(3u32)),
1470                Some(PrefixBound::exclusive(7u32)),
1471                Order::Ascending,
1472            )
1473            .map(|r| r.map(|(_, v)| v))
1474            .collect::<StdResult<Vec<_>>>()
1475            .unwrap();
1476        assert_eq!(exclude.len(), 2);
1477        assert_eq!(exclude, vec![789, 987]);
1478
1479        // using inclusive in descending
1480        let include = AGES
1481            .prefix_range_raw(
1482                &store,
1483                Some(PrefixBound::inclusive(3u32)),
1484                Some(PrefixBound::inclusive(5u32)),
1485                Order::Descending,
1486            )
1487            .map(|r| r.map(|(_, v)| v))
1488            .collect::<StdResult<Vec<_>>>()
1489            .unwrap();
1490        assert_eq!(include.len(), 3);
1491        assert_eq!(include, vec![987, 789, 456]);
1492
1493        // using exclusive in descending
1494        let include = AGES
1495            .prefix_range_raw(
1496                &store,
1497                Some(PrefixBound::exclusive(2u32)),
1498                Some(PrefixBound::exclusive(5u32)),
1499                Order::Descending,
1500            )
1501            .map(|r| r.map(|(_, v)| v))
1502            .collect::<StdResult<Vec<_>>>()
1503            .unwrap();
1504        assert_eq!(include.len(), 1);
1505        assert_eq!(include, vec![456]);
1506    }
1507
1508    #[test]
1509    #[cfg(feature = "iterator")]
1510    fn prefixed_range_works() {
1511        // this is designed to look as much like a secondary index as possible
1512        // we want to query over a range of u32 for the first key and all subkeys
1513        const AGES: Map<(u32, &str), u64> = Map::new("ages");
1514
1515        let mut store = MockStorage::new();
1516        AGES.save(&mut store, (2, "123"), &123).unwrap();
1517        AGES.save(&mut store, (3, "456"), &456).unwrap();
1518        AGES.save(&mut store, (5, "789"), &789).unwrap();
1519        AGES.save(&mut store, (5, "987"), &987).unwrap();
1520        AGES.save(&mut store, (7, "202122"), &2002).unwrap();
1521        AGES.save(&mut store, (8, "232425"), &2332).unwrap();
1522
1523        // typical range under one prefix as a control
1524        let fives = AGES
1525            .prefix(5)
1526            .range(&store, None, None, Order::Ascending)
1527            .collect::<StdResult<Vec<_>>>()
1528            .unwrap();
1529        assert_eq!(fives.len(), 2);
1530        assert_eq!(
1531            fives,
1532            vec![("789".to_string(), 789), ("987".to_string(), 987)]
1533        );
1534
1535        let keys: Vec<_> = AGES.keys(&store, None, None, Order::Ascending).collect();
1536        println!("keys: {keys:?}");
1537
1538        // using inclusive bounds both sides
1539        let include = AGES
1540            .prefix_range(
1541                &store,
1542                Some(PrefixBound::inclusive(3u32)),
1543                Some(PrefixBound::inclusive(7u32)),
1544                Order::Ascending,
1545            )
1546            .map(|r| r.map(|(_, v)| v))
1547            .collect::<StdResult<Vec<_>>>()
1548            .unwrap();
1549        assert_eq!(include.len(), 4);
1550        assert_eq!(include, vec![456, 789, 987, 2002]);
1551
1552        // using exclusive bounds both sides
1553        let exclude = AGES
1554            .prefix_range(
1555                &store,
1556                Some(PrefixBound::exclusive(3u32)),
1557                Some(PrefixBound::exclusive(7u32)),
1558                Order::Ascending,
1559            )
1560            .map(|r| r.map(|(_, v)| v))
1561            .collect::<StdResult<Vec<_>>>()
1562            .unwrap();
1563        assert_eq!(exclude.len(), 2);
1564        assert_eq!(exclude, vec![789, 987]);
1565
1566        // using inclusive in descending
1567        let include = AGES
1568            .prefix_range(
1569                &store,
1570                Some(PrefixBound::inclusive(3u32)),
1571                Some(PrefixBound::inclusive(5u32)),
1572                Order::Descending,
1573            )
1574            .map(|r| r.map(|(_, v)| v))
1575            .collect::<StdResult<Vec<_>>>()
1576            .unwrap();
1577        assert_eq!(include.len(), 3);
1578        assert_eq!(include, vec![987, 789, 456]);
1579
1580        // using exclusive in descending
1581        let include = AGES
1582            .prefix_range(
1583                &store,
1584                Some(PrefixBound::exclusive(2u32)),
1585                Some(PrefixBound::exclusive(5u32)),
1586                Order::Descending,
1587            )
1588            .map(|r| r.map(|(_, v)| v))
1589            .collect::<StdResult<Vec<_>>>()
1590            .unwrap();
1591        assert_eq!(include.len(), 1);
1592        assert_eq!(include, vec![456]);
1593    }
1594
1595    #[test]
1596    #[cfg(feature = "iterator")]
1597    fn clear_works() {
1598        const TEST_MAP: Map<&str, u32> = Map::new("test_map");
1599
1600        let mut storage = MockStorage::new();
1601        TEST_MAP.save(&mut storage, "key0", &0u32).unwrap();
1602        TEST_MAP.save(&mut storage, "key1", &1u32).unwrap();
1603        TEST_MAP.save(&mut storage, "key2", &2u32).unwrap();
1604        TEST_MAP.save(&mut storage, "key3", &3u32).unwrap();
1605        TEST_MAP.save(&mut storage, "key4", &4u32).unwrap();
1606
1607        TEST_MAP.clear(&mut storage);
1608
1609        assert!(!TEST_MAP.has(&storage, "key0"));
1610        assert!(!TEST_MAP.has(&storage, "key1"));
1611        assert!(!TEST_MAP.has(&storage, "key2"));
1612        assert!(!TEST_MAP.has(&storage, "key3"));
1613        assert!(!TEST_MAP.has(&storage, "key4"));
1614    }
1615
1616    #[test]
1617    #[cfg(feature = "iterator")]
1618    fn is_empty_works() {
1619        const TEST_MAP: Map<&str, u32> = Map::new("test_map");
1620
1621        let mut storage = MockStorage::new();
1622
1623        assert!(TEST_MAP.is_empty(&storage));
1624
1625        TEST_MAP.save(&mut storage, "key1", &1u32).unwrap();
1626        TEST_MAP.save(&mut storage, "key2", &2u32).unwrap();
1627
1628        assert!(!TEST_MAP.is_empty(&storage));
1629    }
1630
1631    #[test]
1632    #[cfg(feature = "iterator")]
1633    fn first_last_work() {
1634        let mut storage = MockStorage::new();
1635        const MAP: Map<&str, u32> = Map::new("map");
1636
1637        // empty map
1638        assert_eq!(MAP.first(&storage).unwrap(), None);
1639        assert_eq!(MAP.last(&storage).unwrap(), None);
1640
1641        // insert entries
1642        MAP.save(&mut storage, "ghi", &1).unwrap();
1643        MAP.save(&mut storage, "abc", &2).unwrap();
1644        MAP.save(&mut storage, "def", &3).unwrap();
1645
1646        assert_eq!(MAP.first(&storage).unwrap(), Some(("abc".to_string(), 2)));
1647        assert_eq!(MAP.last(&storage).unwrap(), Some(("ghi".to_string(), 1)));
1648    }
1649}