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: cosmwasm_std::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: cosmwasm_std::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: cosmwasm_std::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: cosmwasm_std::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: cosmwasm_std::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: cosmwasm_std::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), Ok(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), Ok(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), Ok(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), Ok(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    use serde::{Deserialize, Serialize};
350    use std::ops::Deref;
351
352    use cosmwasm_std::testing::MockStorage;
353    use cosmwasm_std::to_json_binary;
354    use cosmwasm_std::StdError::InvalidUtf8;
355    #[cfg(feature = "iterator")]
356    use cosmwasm_std::{Order, StdResult};
357
358    #[cfg(feature = "iterator")]
359    use crate::bound::Bounder;
360
361    use crate::int_key::IntKey;
362
363    #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
364    struct Data {
365        pub name: String,
366        pub age: i32,
367    }
368
369    const PEOPLE: Map<&[u8], Data> = Map::new("people");
370    #[cfg(feature = "iterator")]
371    const PEOPLE_STR_KEY: &str = "people2";
372    #[cfg(feature = "iterator")]
373    const PEOPLE_STR: Map<&str, Data> = Map::new(PEOPLE_STR_KEY);
374    #[cfg(feature = "iterator")]
375    const PEOPLE_ID: Map<u32, Data> = Map::new("people_id");
376    #[cfg(feature = "iterator")]
377    const SIGNED_ID: Map<i32, Data> = Map::new("signed_id");
378
379    const ALLOWANCE: Map<(&[u8], &[u8]), u64> = Map::new("allow");
380
381    const TRIPLE: Map<(&[u8], u8, &str), u64> = Map::new("triple");
382
383    #[test]
384    fn create_path() {
385        let path = PEOPLE.key(b"john");
386        let key = path.deref();
387        // this should be prefixed(people) || john
388        assert_eq!("people".len() + "john".len() + 2, key.len());
389        assert_eq!(b"people".to_vec().as_slice(), &key[2..8]);
390        assert_eq!(b"john".to_vec().as_slice(), &key[8..]);
391
392        let path = ALLOWANCE.key((b"john", b"maria"));
393        let key = path.deref();
394        // this should be prefixed(allow) || prefixed(john) || maria
395        assert_eq!(
396            "allow".len() + "john".len() + "maria".len() + 2 * 2,
397            key.len()
398        );
399        assert_eq!(b"allow".to_vec().as_slice(), &key[2..7]);
400        assert_eq!(b"john".to_vec().as_slice(), &key[9..13]);
401        assert_eq!(b"maria".to_vec().as_slice(), &key[13..]);
402
403        let path = TRIPLE.key((b"john", 8u8, "pedro"));
404        let key = path.deref();
405        // this should be prefixed(allow) || prefixed(john) || maria
406        assert_eq!(
407            "triple".len() + "john".len() + 1 + "pedro".len() + 2 * 3,
408            key.len()
409        );
410        assert_eq!(b"triple".to_vec().as_slice(), &key[2..8]);
411        assert_eq!(b"john".to_vec().as_slice(), &key[10..14]);
412        assert_eq!(8u8.to_cw_bytes(), &key[16..17]);
413        assert_eq!(b"pedro".to_vec().as_slice(), &key[17..]);
414    }
415
416    #[test]
417    fn save_and_load() {
418        let mut store = MockStorage::new();
419
420        // save and load on one key
421        let john = PEOPLE.key(b"john");
422        let data = Data {
423            name: "John".to_string(),
424            age: 32,
425        };
426        assert_eq!(None, john.may_load(&store).unwrap());
427        john.save(&mut store, &data).unwrap();
428        assert_eq!(data, john.load(&store).unwrap());
429
430        // nothing on another key
431        assert_eq!(None, PEOPLE.may_load(&store, b"jack").unwrap());
432
433        // same named path gets the data
434        assert_eq!(data, PEOPLE.load(&store, b"john").unwrap());
435
436        // removing leaves us empty
437        john.remove(&mut store);
438        assert_eq!(None, john.may_load(&store).unwrap());
439    }
440
441    #[test]
442    fn existence() {
443        let mut store = MockStorage::new();
444
445        // set data in proper format
446        let data = Data {
447            name: "John".to_string(),
448            age: 32,
449        };
450        PEOPLE.save(&mut store, b"john", &data).unwrap();
451
452        // set and remove it
453        PEOPLE.save(&mut store, b"removed", &data).unwrap();
454        PEOPLE.remove(&mut store, b"removed");
455
456        // invalid, but non-empty data
457        store.set(&PEOPLE.key(b"random"), b"random-data");
458
459        // any data, including invalid or empty is returned as "has"
460        assert!(PEOPLE.has(&store, b"john"));
461        assert!(PEOPLE.has(&store, b"random"));
462
463        // if nothing was written, it is false
464        assert!(!PEOPLE.has(&store, b"never-writen"));
465        assert!(!PEOPLE.has(&store, b"removed"));
466    }
467
468    #[test]
469    fn composite_keys() {
470        let mut store = MockStorage::new();
471
472        // save and load on a composite key
473        let allow = ALLOWANCE.key((b"owner", b"spender"));
474        assert_eq!(None, allow.may_load(&store).unwrap());
475        allow.save(&mut store, &1234).unwrap();
476        assert_eq!(1234, allow.load(&store).unwrap());
477
478        // not under other key
479        let different = ALLOWANCE.may_load(&store, (b"owners", b"pender")).unwrap();
480        assert_eq!(None, different);
481
482        // matches under a proper copy
483        let same = ALLOWANCE.load(&store, (b"owner", b"spender")).unwrap();
484        assert_eq!(1234, same);
485    }
486
487    #[test]
488    fn triple_keys() {
489        let mut store = MockStorage::new();
490
491        // save and load on a triple composite key
492        let triple = TRIPLE.key((b"owner", 10u8, "recipient"));
493        assert_eq!(None, triple.may_load(&store).unwrap());
494        triple.save(&mut store, &1234).unwrap();
495        assert_eq!(1234, triple.load(&store).unwrap());
496
497        // not under other key
498        let different = TRIPLE
499            .may_load(&store, (b"owners", 10u8, "ecipient"))
500            .unwrap();
501        assert_eq!(None, different);
502
503        // matches under a proper copy
504        let same = TRIPLE.load(&store, (b"owner", 10u8, "recipient")).unwrap();
505        assert_eq!(1234, same);
506    }
507
508    #[test]
509    #[cfg(feature = "iterator")]
510    fn range_raw_simple_key() {
511        let mut store = MockStorage::new();
512
513        // save and load on two keys
514        let data = Data {
515            name: "John".to_string(),
516            age: 32,
517        };
518        PEOPLE.save(&mut store, b"john", &data).unwrap();
519
520        let data2 = Data {
521            name: "Jim".to_string(),
522            age: 44,
523        };
524        PEOPLE.save(&mut store, b"jim", &data2).unwrap();
525
526        // let's try to iterate!
527        let all: StdResult<Vec<_>> = PEOPLE
528            .range_raw(&store, None, None, Order::Ascending)
529            .collect();
530        let all = all.unwrap();
531        assert_eq!(2, all.len());
532        assert_eq!(
533            all,
534            vec![
535                (b"jim".to_vec(), data2.clone()),
536                (b"john".to_vec(), data.clone())
537            ]
538        );
539
540        // let's try to iterate over a range
541        let all: StdResult<Vec<_>> = PEOPLE
542            .range_raw(
543                &store,
544                Some(Bound::inclusive(b"j" as &[u8])),
545                None,
546                Order::Ascending,
547            )
548            .collect();
549        let all = all.unwrap();
550        assert_eq!(2, all.len());
551        assert_eq!(
552            all,
553            vec![(b"jim".to_vec(), data2), (b"john".to_vec(), data.clone())]
554        );
555
556        // let's try to iterate over a more restrictive range
557        let all: StdResult<Vec<_>> = PEOPLE
558            .range_raw(
559                &store,
560                Some(Bound::inclusive(b"jo" as &[u8])),
561                None,
562                Order::Ascending,
563            )
564            .collect();
565        let all = all.unwrap();
566        assert_eq!(1, all.len());
567        assert_eq!(all, vec![(b"john".to_vec(), data)]);
568    }
569
570    #[test]
571    #[cfg(feature = "iterator")]
572    fn range_simple_string_key() {
573        let mut store = MockStorage::new();
574
575        // save and load on three keys
576        let data = Data {
577            name: "John".to_string(),
578            age: 32,
579        };
580        PEOPLE.save(&mut store, b"john", &data).unwrap();
581
582        let data2 = Data {
583            name: "Jim".to_string(),
584            age: 44,
585        };
586        PEOPLE.save(&mut store, b"jim", &data2).unwrap();
587
588        let data3 = Data {
589            name: "Ada".to_string(),
590            age: 23,
591        };
592        PEOPLE.save(&mut store, b"ada", &data3).unwrap();
593
594        // let's try to iterate!
595        let all: StdResult<Vec<_>> = PEOPLE.range(&store, None, None, Order::Ascending).collect();
596        let all = all.unwrap();
597        assert_eq!(3, all.len());
598        assert_eq!(
599            all,
600            vec![
601                (b"ada".to_vec(), data3),
602                (b"jim".to_vec(), data2.clone()),
603                (b"john".to_vec(), data.clone())
604            ]
605        );
606
607        // let's try to iterate over a range
608        let all: StdResult<Vec<_>> = PEOPLE
609            .range(&store, b"j".inclusive_bound(), None, Order::Ascending)
610            .collect();
611        let all = all.unwrap();
612        assert_eq!(2, all.len());
613        assert_eq!(
614            all,
615            vec![(b"jim".to_vec(), data2), (b"john".to_vec(), data.clone())]
616        );
617
618        // let's try to iterate over a more restrictive range
619        let all: StdResult<Vec<_>> = PEOPLE
620            .range(&store, b"jo".inclusive_bound(), None, Order::Ascending)
621            .collect();
622        let all = all.unwrap();
623        assert_eq!(1, all.len());
624        assert_eq!(all, vec![(b"john".to_vec(), data)]);
625    }
626
627    #[test]
628    #[cfg(feature = "iterator")]
629    fn range_key_broken_deserialization_errors() {
630        let mut store = MockStorage::new();
631
632        // save and load on three keys
633        let data = Data {
634            name: "John".to_string(),
635            age: 32,
636        };
637        PEOPLE_STR.save(&mut store, "john", &data).unwrap();
638
639        let data2 = Data {
640            name: "Jim".to_string(),
641            age: 44,
642        };
643        PEOPLE_STR.save(&mut store, "jim", &data2).unwrap();
644
645        let data3 = Data {
646            name: "Ada".to_string(),
647            age: 23,
648        };
649        PEOPLE_STR.save(&mut store, "ada", &data3).unwrap();
650
651        // let's iterate!
652        let all: StdResult<Vec<_>> = PEOPLE_STR
653            .range(&store, None, None, Order::Ascending)
654            .collect();
655        let all = all.unwrap();
656        assert_eq!(3, all.len());
657        assert_eq!(
658            all,
659            vec![
660                ("ada".to_string(), data3.clone()),
661                ("jim".to_string(), data2.clone()),
662                ("john".to_string(), data.clone())
663            ]
664        );
665
666        // Manually add a broken key (invalid utf-8)
667        store.set(
668            &[
669                [0u8, PEOPLE_STR_KEY.len() as u8].as_slice(),
670                PEOPLE_STR_KEY.as_bytes(),
671                b"\xddim",
672            ]
673            .concat(),
674            &to_json_binary(&data2).unwrap(),
675        );
676
677        // Let's try to iterate again!
678        let all: StdResult<Vec<_>> = PEOPLE_STR
679            .range(&store, None, None, Order::Ascending)
680            .collect();
681        assert!(all.is_err());
682        assert!(matches!(all.unwrap_err(), InvalidUtf8 { .. }));
683
684        // And the same with keys()
685        let all: StdResult<Vec<_>> = PEOPLE_STR
686            .keys(&store, None, None, Order::Ascending)
687            .collect();
688        assert!(all.is_err());
689        assert!(matches!(all.unwrap_err(), InvalidUtf8 { .. }));
690
691        // But range_raw still works
692        let all: StdResult<Vec<_>> = PEOPLE_STR
693            .range_raw(&store, None, None, Order::Ascending)
694            .collect();
695
696        let all = all.unwrap();
697        assert_eq!(4, all.len());
698        assert_eq!(
699            all,
700            vec![
701                (b"ada".to_vec(), data3.clone()),
702                (b"jim".to_vec(), data2.clone()),
703                (b"john".to_vec(), data.clone()),
704                (b"\xddim".to_vec(), data2.clone()),
705            ]
706        );
707
708        // And the same with keys_raw
709        let all: Vec<_> = PEOPLE_STR
710            .keys_raw(&store, None, None, Order::Ascending)
711            .collect();
712
713        assert_eq!(4, all.len());
714        assert_eq!(
715            all,
716            vec![
717                b"ada".to_vec(),
718                b"jim".to_vec(),
719                b"john".to_vec(),
720                b"\xddim".to_vec(),
721            ]
722        );
723    }
724
725    #[test]
726    #[cfg(feature = "iterator")]
727    fn range_simple_integer_key() {
728        let mut store = MockStorage::new();
729
730        // save and load on two keys
731        let data = Data {
732            name: "John".to_string(),
733            age: 32,
734        };
735        PEOPLE_ID.save(&mut store, 1234, &data).unwrap();
736
737        let data2 = Data {
738            name: "Jim".to_string(),
739            age: 44,
740        };
741        PEOPLE_ID.save(&mut store, 56, &data2).unwrap();
742
743        // let's try to iterate!
744        let all: StdResult<Vec<_>> = PEOPLE_ID
745            .range(&store, None, None, Order::Ascending)
746            .collect();
747        let all = all.unwrap();
748        assert_eq!(2, all.len());
749        assert_eq!(all, vec![(56, data2.clone()), (1234, data.clone())]);
750
751        // let's try to iterate over a range
752        let all: StdResult<Vec<_>> = PEOPLE_ID
753            .range(
754                &store,
755                Some(Bound::inclusive(56u32)),
756                None,
757                Order::Ascending,
758            )
759            .collect();
760        let all = all.unwrap();
761        assert_eq!(2, all.len());
762        assert_eq!(all, vec![(56, data2), (1234, data.clone())]);
763
764        // let's try to iterate over a more restrictive range
765        let all: StdResult<Vec<_>> = PEOPLE_ID
766            .range(
767                &store,
768                Some(Bound::inclusive(57u32)),
769                None,
770                Order::Ascending,
771            )
772            .collect();
773        let all = all.unwrap();
774        assert_eq!(1, all.len());
775        assert_eq!(all, vec![(1234, data)]);
776    }
777
778    #[test]
779    #[cfg(feature = "iterator")]
780    fn range_simple_integer_key_with_bounder_trait() {
781        let mut store = MockStorage::new();
782
783        // save and load on two keys
784        let data = Data {
785            name: "John".to_string(),
786            age: 32,
787        };
788        PEOPLE_ID.save(&mut store, 1234, &data).unwrap();
789
790        let data2 = Data {
791            name: "Jim".to_string(),
792            age: 44,
793        };
794        PEOPLE_ID.save(&mut store, 56, &data2).unwrap();
795
796        // let's try to iterate!
797        let all: StdResult<Vec<_>> = PEOPLE_ID
798            .range(&store, None, None, Order::Ascending)
799            .collect();
800        let all = all.unwrap();
801        assert_eq!(2, all.len());
802        assert_eq!(all, vec![(56, data2.clone()), (1234, data.clone())]);
803
804        // let's try to iterate over a range
805        let all: StdResult<Vec<_>> = PEOPLE_ID
806            .range(&store, 56u32.inclusive_bound(), None, Order::Ascending)
807            .collect();
808        let all = all.unwrap();
809        assert_eq!(2, all.len());
810        assert_eq!(all, vec![(56, data2), (1234, data.clone())]);
811
812        // let's try to iterate over a more restrictive range
813        let all: StdResult<Vec<_>> = PEOPLE_ID
814            .range(&store, 57u32.inclusive_bound(), None, Order::Ascending)
815            .collect();
816        let all = all.unwrap();
817        assert_eq!(1, all.len());
818        assert_eq!(all, vec![(1234, data)]);
819    }
820
821    #[test]
822    #[cfg(feature = "iterator")]
823    fn range_simple_signed_integer_key() {
824        let mut store = MockStorage::new();
825
826        // save and load on three keys
827        let data = Data {
828            name: "John".to_string(),
829            age: 32,
830        };
831        SIGNED_ID.save(&mut store, -1234, &data).unwrap();
832
833        let data2 = Data {
834            name: "Jim".to_string(),
835            age: 44,
836        };
837        SIGNED_ID.save(&mut store, -56, &data2).unwrap();
838
839        let data3 = Data {
840            name: "Jules".to_string(),
841            age: 55,
842        };
843        SIGNED_ID.save(&mut store, 50, &data3).unwrap();
844
845        // let's try to iterate!
846        let all: StdResult<Vec<_>> = SIGNED_ID
847            .range(&store, None, None, Order::Ascending)
848            .collect();
849        let all = all.unwrap();
850        assert_eq!(3, all.len());
851        // order is correct
852        assert_eq!(
853            all,
854            vec![(-1234, data), (-56, data2.clone()), (50, data3.clone())]
855        );
856
857        // let's try to iterate over a range
858        let all: StdResult<Vec<_>> = SIGNED_ID
859            .range(
860                &store,
861                Some(Bound::inclusive(-56i32)),
862                None,
863                Order::Ascending,
864            )
865            .collect();
866        let all = all.unwrap();
867        assert_eq!(2, all.len());
868        assert_eq!(all, vec![(-56, data2), (50, data3.clone())]);
869
870        // let's try to iterate over a more restrictive range
871        let all: StdResult<Vec<_>> = SIGNED_ID
872            .range(
873                &store,
874                Some(Bound::inclusive(-55i32)),
875                Some(Bound::inclusive(50i32)),
876                Order::Descending,
877            )
878            .collect();
879        let all = all.unwrap();
880        assert_eq!(1, all.len());
881        assert_eq!(all, vec![(50, data3)]);
882    }
883
884    #[test]
885    #[cfg(feature = "iterator")]
886    fn range_simple_signed_integer_key_with_bounder_trait() {
887        let mut store = MockStorage::new();
888
889        // save and load on three keys
890        let data = Data {
891            name: "John".to_string(),
892            age: 32,
893        };
894        SIGNED_ID.save(&mut store, -1234, &data).unwrap();
895
896        let data2 = Data {
897            name: "Jim".to_string(),
898            age: 44,
899        };
900        SIGNED_ID.save(&mut store, -56, &data2).unwrap();
901
902        let data3 = Data {
903            name: "Jules".to_string(),
904            age: 55,
905        };
906        SIGNED_ID.save(&mut store, 50, &data3).unwrap();
907
908        // let's try to iterate!
909        let all: StdResult<Vec<_>> = SIGNED_ID
910            .range(&store, None, None, Order::Ascending)
911            .collect();
912        let all = all.unwrap();
913        assert_eq!(3, all.len());
914        // order is correct
915        assert_eq!(
916            all,
917            vec![(-1234, data), (-56, data2.clone()), (50, data3.clone())]
918        );
919
920        // let's try to iterate over a range
921        let all: StdResult<Vec<_>> = SIGNED_ID
922            .range(&store, (-56i32).inclusive_bound(), None, Order::Ascending)
923            .collect();
924        let all = all.unwrap();
925        assert_eq!(2, all.len());
926        assert_eq!(all, vec![(-56, data2), (50, data3.clone())]);
927
928        // let's try to iterate over a more restrictive range
929        let all: StdResult<Vec<_>> = SIGNED_ID
930            .range(
931                &store,
932                (-55i32).inclusive_bound(),
933                50i32.inclusive_bound(),
934                Order::Descending,
935            )
936            .collect();
937        let all = all.unwrap();
938        assert_eq!(1, all.len());
939        assert_eq!(all, vec![(50, data3)]);
940    }
941
942    #[test]
943    #[cfg(feature = "iterator")]
944    fn range_raw_composite_key() {
945        let mut store = MockStorage::new();
946
947        // save and load on three keys, one under different owner
948        ALLOWANCE
949            .save(&mut store, (b"owner", b"spender"), &1000)
950            .unwrap();
951        ALLOWANCE
952            .save(&mut store, (b"owner", b"spender2"), &3000)
953            .unwrap();
954        ALLOWANCE
955            .save(&mut store, (b"owner2", b"spender"), &5000)
956            .unwrap();
957
958        // let's try to iterate!
959        let all: StdResult<Vec<_>> = ALLOWANCE
960            .range_raw(&store, None, None, Order::Ascending)
961            .collect();
962        let all = all.unwrap();
963        assert_eq!(3, all.len());
964        assert_eq!(
965            all,
966            vec![
967                ((b"owner".to_vec(), b"spender".to_vec()).joined_key(), 1000),
968                ((b"owner".to_vec(), b"spender2".to_vec()).joined_key(), 3000),
969                ((b"owner2".to_vec(), b"spender".to_vec()).joined_key(), 5000),
970            ]
971        );
972
973        // let's try to iterate over a prefix
974        let all: StdResult<Vec<_>> = ALLOWANCE
975            .prefix(b"owner")
976            .range_raw(&store, None, None, Order::Ascending)
977            .collect();
978        let all = all.unwrap();
979        assert_eq!(2, all.len());
980        assert_eq!(
981            all,
982            vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000)]
983        );
984    }
985
986    #[test]
987    #[cfg(feature = "iterator")]
988    fn range_composite_key() {
989        let mut store = MockStorage::new();
990
991        // save and load on three keys, one under different owner
992        ALLOWANCE
993            .save(&mut store, (b"owner", b"spender"), &1000)
994            .unwrap();
995        ALLOWANCE
996            .save(&mut store, (b"owner", b"spender2"), &3000)
997            .unwrap();
998        ALLOWANCE
999            .save(&mut store, (b"owner2", b"spender"), &5000)
1000            .unwrap();
1001
1002        // let's try to iterate!
1003        let all: StdResult<Vec<_>> = ALLOWANCE
1004            .range(&store, None, None, Order::Ascending)
1005            .collect();
1006        let all = all.unwrap();
1007        assert_eq!(3, all.len());
1008        assert_eq!(
1009            all,
1010            vec![
1011                ((b"owner".to_vec(), b"spender".to_vec()), 1000),
1012                ((b"owner".to_vec(), b"spender2".to_vec()), 3000),
1013                ((b"owner2".to_vec(), b"spender".to_vec()), 5000)
1014            ]
1015        );
1016
1017        // let's try to iterate over a prefix
1018        let all: StdResult<Vec<_>> = ALLOWANCE
1019            .prefix(b"owner")
1020            .range(&store, None, None, Order::Ascending)
1021            .collect();
1022        let all = all.unwrap();
1023        assert_eq!(2, all.len());
1024        assert_eq!(
1025            all,
1026            vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000),]
1027        );
1028
1029        // let's try to iterate over a prefixed restricted inclusive range
1030        let all: StdResult<Vec<_>> = ALLOWANCE
1031            .prefix(b"owner")
1032            .range(&store, b"spender".inclusive_bound(), None, Order::Ascending)
1033            .collect();
1034        let all = all.unwrap();
1035        assert_eq!(2, all.len());
1036        assert_eq!(
1037            all,
1038            vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000),]
1039        );
1040
1041        // let's try to iterate over a prefixed restricted exclusive range
1042        let all: StdResult<Vec<_>> = ALLOWANCE
1043            .prefix(b"owner")
1044            .range(&store, b"spender".exclusive_bound(), None, Order::Ascending)
1045            .collect();
1046        let all = all.unwrap();
1047        assert_eq!(1, all.len());
1048        assert_eq!(all, vec![(b"spender2".to_vec(), 3000),]);
1049    }
1050
1051    #[test]
1052    #[cfg(feature = "iterator")]
1053    fn range_raw_triple_key() {
1054        let mut store = MockStorage::new();
1055
1056        // save and load on three keys, one under different owner
1057        TRIPLE
1058            .save(&mut store, (b"owner", 9, "recipient"), &1000)
1059            .unwrap();
1060        TRIPLE
1061            .save(&mut store, (b"owner", 9, "recipient2"), &3000)
1062            .unwrap();
1063        TRIPLE
1064            .save(&mut store, (b"owner", 10, "recipient3"), &3000)
1065            .unwrap();
1066        TRIPLE
1067            .save(&mut store, (b"owner2", 9, "recipient"), &5000)
1068            .unwrap();
1069
1070        // let's try to iterate!
1071        let all: StdResult<Vec<_>> = TRIPLE
1072            .range_raw(&store, None, None, Order::Ascending)
1073            .collect();
1074        let all = all.unwrap();
1075        assert_eq!(4, all.len());
1076        assert_eq!(
1077            all,
1078            vec![
1079                (
1080                    (b"owner".to_vec(), 9u8, b"recipient".to_vec()).joined_key(),
1081                    1000
1082                ),
1083                (
1084                    (b"owner".to_vec(), 9u8, b"recipient2".to_vec()).joined_key(),
1085                    3000
1086                ),
1087                (
1088                    (b"owner".to_vec(), 10u8, b"recipient3".to_vec()).joined_key(),
1089                    3000
1090                ),
1091                (
1092                    (b"owner2".to_vec(), 9u8, b"recipient".to_vec()).joined_key(),
1093                    5000
1094                )
1095            ]
1096        );
1097
1098        // let's iterate over a prefix
1099        let all: StdResult<Vec<_>> = TRIPLE
1100            .prefix((b"owner", 9))
1101            .range_raw(&store, None, None, Order::Ascending)
1102            .collect();
1103        let all = all.unwrap();
1104        assert_eq!(2, all.len());
1105        assert_eq!(
1106            all,
1107            vec![
1108                (b"recipient".to_vec(), 1000),
1109                (b"recipient2".to_vec(), 3000)
1110            ]
1111        );
1112
1113        // let's iterate over a sub prefix
1114        let all: StdResult<Vec<_>> = TRIPLE
1115            .sub_prefix(b"owner")
1116            .range_raw(&store, None, None, Order::Ascending)
1117            .collect();
1118        let all = all.unwrap();
1119        assert_eq!(3, all.len());
1120        // Use range() if you want key deserialization
1121        assert_eq!(
1122            all,
1123            vec![
1124                ((9u8, b"recipient".to_vec()).joined_key(), 1000),
1125                ((9u8, b"recipient2".to_vec()).joined_key(), 3000),
1126                ((10u8, b"recipient3".to_vec()).joined_key(), 3000)
1127            ]
1128        );
1129    }
1130
1131    #[test]
1132    #[cfg(feature = "iterator")]
1133    fn range_triple_key() {
1134        let mut store = MockStorage::new();
1135
1136        // save and load on three keys, one under different owner
1137        TRIPLE
1138            .save(&mut store, (b"owner", 9u8, "recipient"), &1000)
1139            .unwrap();
1140        TRIPLE
1141            .save(&mut store, (b"owner", 9u8, "recipient2"), &3000)
1142            .unwrap();
1143        TRIPLE
1144            .save(&mut store, (b"owner", 10u8, "recipient3"), &3000)
1145            .unwrap();
1146        TRIPLE
1147            .save(&mut store, (b"owner2", 9u8, "recipient"), &5000)
1148            .unwrap();
1149
1150        // let's try to iterate!
1151        let all: StdResult<Vec<_>> = TRIPLE.range(&store, None, None, Order::Ascending).collect();
1152        let all = all.unwrap();
1153        assert_eq!(4, all.len());
1154        assert_eq!(
1155            all,
1156            vec![
1157                ((b"owner".to_vec(), 9, "recipient".to_string()), 1000),
1158                ((b"owner".to_vec(), 9, "recipient2".to_string()), 3000),
1159                ((b"owner".to_vec(), 10, "recipient3".to_string()), 3000),
1160                ((b"owner2".to_vec(), 9, "recipient".to_string()), 5000)
1161            ]
1162        );
1163
1164        // let's iterate over a sub_prefix
1165        let all: StdResult<Vec<_>> = TRIPLE
1166            .sub_prefix(b"owner")
1167            .range(&store, None, None, Order::Ascending)
1168            .collect();
1169        let all = all.unwrap();
1170        assert_eq!(3, all.len());
1171        assert_eq!(
1172            all,
1173            vec![
1174                ((9, "recipient".to_string()), 1000),
1175                ((9, "recipient2".to_string()), 3000),
1176                ((10, "recipient3".to_string()), 3000),
1177            ]
1178        );
1179
1180        // let's iterate over a prefix
1181        let all: StdResult<Vec<_>> = TRIPLE
1182            .prefix((b"owner", 9))
1183            .range(&store, None, None, Order::Ascending)
1184            .collect();
1185        let all = all.unwrap();
1186        assert_eq!(2, all.len());
1187        assert_eq!(
1188            all,
1189            vec![
1190                ("recipient".to_string(), 1000),
1191                ("recipient2".to_string(), 3000),
1192            ]
1193        );
1194
1195        // let's try to iterate over a prefixed restricted inclusive range
1196        let all: StdResult<Vec<_>> = TRIPLE
1197            .prefix((b"owner", 9))
1198            .range(
1199                &store,
1200                "recipient".inclusive_bound(),
1201                None,
1202                Order::Ascending,
1203            )
1204            .collect();
1205        let all = all.unwrap();
1206        assert_eq!(2, all.len());
1207        assert_eq!(
1208            all,
1209            vec![
1210                ("recipient".to_string(), 1000),
1211                ("recipient2".to_string(), 3000),
1212            ]
1213        );
1214
1215        // let's try to iterate over a prefixed restricted exclusive range
1216        let all: StdResult<Vec<_>> = TRIPLE
1217            .prefix((b"owner", 9))
1218            .range(
1219                &store,
1220                "recipient".exclusive_bound(),
1221                None,
1222                Order::Ascending,
1223            )
1224            .collect();
1225        let all = all.unwrap();
1226        assert_eq!(1, all.len());
1227        assert_eq!(all, vec![("recipient2".to_string(), 3000),]);
1228    }
1229
1230    #[test]
1231    fn basic_update() {
1232        let mut store = MockStorage::new();
1233
1234        let add_ten = |a: Option<u64>| -> StdResult<_> { Ok(a.unwrap_or_default() + 10) };
1235
1236        // save and load on three keys, one under different owner
1237        let key: (&[u8], &[u8]) = (b"owner", b"spender");
1238        ALLOWANCE.update(&mut store, key, add_ten).unwrap();
1239        let twenty = ALLOWANCE.update(&mut store, key, add_ten).unwrap();
1240        assert_eq!(20, twenty);
1241        let loaded = ALLOWANCE.load(&store, key).unwrap();
1242        assert_eq!(20, loaded);
1243    }
1244
1245    #[test]
1246    fn readme_works() -> StdResult<()> {
1247        let mut store = MockStorage::new();
1248        let data = Data {
1249            name: "John".to_string(),
1250            age: 32,
1251        };
1252
1253        // load and save with extra key argument
1254        let empty = PEOPLE.may_load(&store, b"john")?;
1255        assert_eq!(None, empty);
1256        PEOPLE.save(&mut store, b"john", &data)?;
1257        let loaded = PEOPLE.load(&store, b"john")?;
1258        assert_eq!(data, loaded);
1259
1260        // nothing on another key
1261        let missing = PEOPLE.may_load(&store, b"jack")?;
1262        assert_eq!(None, missing);
1263
1264        // update function for new or existing keys
1265        let birthday = |d: Option<Data>| -> StdResult<Data> {
1266            match d {
1267                Some(one) => Ok(Data {
1268                    name: one.name,
1269                    age: one.age + 1,
1270                }),
1271                None => Ok(Data {
1272                    name: "Newborn".to_string(),
1273                    age: 0,
1274                }),
1275            }
1276        };
1277
1278        let old_john = PEOPLE.update(&mut store, b"john", birthday)?;
1279        assert_eq!(33, old_john.age);
1280        assert_eq!("John", old_john.name.as_str());
1281
1282        let new_jack = PEOPLE.update(&mut store, b"jack", birthday)?;
1283        assert_eq!(0, new_jack.age);
1284        assert_eq!("Newborn", new_jack.name.as_str());
1285
1286        // update also changes the store
1287        assert_eq!(old_john, PEOPLE.load(&store, b"john")?);
1288        assert_eq!(new_jack, PEOPLE.load(&store, b"jack")?);
1289
1290        // removing leaves us empty
1291        PEOPLE.remove(&mut store, b"john");
1292        let empty = PEOPLE.may_load(&store, b"john")?;
1293        assert_eq!(None, empty);
1294
1295        Ok(())
1296    }
1297
1298    #[test]
1299    fn readme_works_composite_keys() -> StdResult<()> {
1300        let mut store = MockStorage::new();
1301
1302        // save and load on a composite key
1303        let empty = ALLOWANCE.may_load(&store, (b"owner", b"spender"))?;
1304        assert_eq!(None, empty);
1305        ALLOWANCE.save(&mut store, (b"owner", b"spender"), &777)?;
1306        let loaded = ALLOWANCE.load(&store, (b"owner", b"spender"))?;
1307        assert_eq!(777, loaded);
1308
1309        // doesn't appear under other key (even if a concat would be the same)
1310        let different = ALLOWANCE.may_load(&store, (b"owners", b"pender")).unwrap();
1311        assert_eq!(None, different);
1312
1313        // simple update
1314        ALLOWANCE.update(&mut store, (b"owner", b"spender"), |v| -> StdResult<u64> {
1315            Ok(v.unwrap_or_default() + 222)
1316        })?;
1317        let loaded = ALLOWANCE.load(&store, (b"owner", b"spender"))?;
1318        assert_eq!(999, loaded);
1319
1320        Ok(())
1321    }
1322
1323    #[test]
1324    fn readme_works_with_path() -> StdResult<()> {
1325        let mut store = MockStorage::new();
1326        let data = Data {
1327            name: "John".to_string(),
1328            age: 32,
1329        };
1330
1331        // create a Path one time to use below
1332        let john = PEOPLE.key(b"john");
1333
1334        // Use this just like an Item above
1335        let empty = john.may_load(&store)?;
1336        assert_eq!(None, empty);
1337        john.save(&mut store, &data)?;
1338        let loaded = john.load(&store)?;
1339        assert_eq!(data, loaded);
1340        john.remove(&mut store);
1341        let empty = john.may_load(&store)?;
1342        assert_eq!(None, empty);
1343
1344        // same for composite keys, just use both parts in key()
1345        let allow = ALLOWANCE.key((b"owner", b"spender"));
1346        allow.save(&mut store, &1234)?;
1347        let loaded = allow.load(&store)?;
1348        assert_eq!(1234, loaded);
1349        allow.update(&mut store, |x| -> StdResult<u64> {
1350            Ok(x.unwrap_or_default() * 2)
1351        })?;
1352        let loaded = allow.load(&store)?;
1353        assert_eq!(2468, loaded);
1354
1355        Ok(())
1356    }
1357
1358    #[test]
1359    #[cfg(feature = "iterator")]
1360    fn readme_with_range_raw() -> StdResult<()> {
1361        let mut store = MockStorage::new();
1362
1363        // save and load on two keys
1364        let data = Data {
1365            name: "John".to_string(),
1366            age: 32,
1367        };
1368        PEOPLE.save(&mut store, b"john", &data)?;
1369        let data2 = Data {
1370            name: "Jim".to_string(),
1371            age: 44,
1372        };
1373        PEOPLE.save(&mut store, b"jim", &data2)?;
1374
1375        // iterate over them all
1376        let all: StdResult<Vec<_>> = PEOPLE
1377            .range_raw(&store, None, None, Order::Ascending)
1378            .collect();
1379        assert_eq!(
1380            all?,
1381            vec![(b"jim".to_vec(), data2), (b"john".to_vec(), data.clone())]
1382        );
1383
1384        // or just show what is after jim
1385        let all: StdResult<Vec<_>> = PEOPLE
1386            .range_raw(
1387                &store,
1388                Some(Bound::exclusive(b"jim" as &[u8])),
1389                None,
1390                Order::Ascending,
1391            )
1392            .collect();
1393        assert_eq!(all?, vec![(b"john".to_vec(), data)]);
1394
1395        // save and load on three keys, one under different owner
1396        ALLOWANCE.save(&mut store, (b"owner", b"spender"), &1000)?;
1397        ALLOWANCE.save(&mut store, (b"owner", b"spender2"), &3000)?;
1398        ALLOWANCE.save(&mut store, (b"owner2", b"spender"), &5000)?;
1399
1400        // get all under one key
1401        let all: StdResult<Vec<_>> = ALLOWANCE
1402            .prefix(b"owner")
1403            .range_raw(&store, None, None, Order::Ascending)
1404            .collect();
1405        assert_eq!(
1406            all?,
1407            vec![(b"spender".to_vec(), 1000), (b"spender2".to_vec(), 3000)]
1408        );
1409
1410        // Or ranges between two items (even reverse)
1411        let all: StdResult<Vec<_>> = ALLOWANCE
1412            .prefix(b"owner")
1413            .range_raw(
1414                &store,
1415                Some(Bound::exclusive(b"spender1" as &[u8])),
1416                Some(Bound::inclusive(b"spender2" as &[u8])),
1417                Order::Descending,
1418            )
1419            .collect();
1420        assert_eq!(all?, vec![(b"spender2".to_vec(), 3000)]);
1421
1422        Ok(())
1423    }
1424
1425    #[test]
1426    #[cfg(feature = "iterator")]
1427    fn prefixed_range_raw_works() {
1428        // this is designed to look as much like a secondary index as possible
1429        // we want to query over a range of u32 for the first key and all subkeys
1430        const AGES: Map<(u32, Vec<u8>), u64> = Map::new("ages");
1431
1432        let mut store = MockStorage::new();
1433        AGES.save(&mut store, (2, vec![1, 2, 3]), &123).unwrap();
1434        AGES.save(&mut store, (3, vec![4, 5, 6]), &456).unwrap();
1435        AGES.save(&mut store, (5, vec![7, 8, 9]), &789).unwrap();
1436        AGES.save(&mut store, (5, vec![9, 8, 7]), &987).unwrap();
1437        AGES.save(&mut store, (7, vec![20, 21, 22]), &2002).unwrap();
1438        AGES.save(&mut store, (8, vec![23, 24, 25]), &2332).unwrap();
1439
1440        // typical range under one prefix as a control
1441        let fives = AGES
1442            .prefix(5)
1443            .range_raw(&store, None, None, Order::Ascending)
1444            .collect::<StdResult<Vec<_>>>()
1445            .unwrap();
1446        assert_eq!(fives.len(), 2);
1447        assert_eq!(fives, vec![(vec![7, 8, 9], 789), (vec![9, 8, 7], 987)]);
1448
1449        let keys: Vec<_> = AGES
1450            .keys_raw(&store, None, None, Order::Ascending)
1451            .collect();
1452        println!("keys: {:?}", keys);
1453
1454        // using inclusive bounds both sides
1455        let include = AGES
1456            .prefix_range_raw(
1457                &store,
1458                Some(PrefixBound::inclusive(3u32)),
1459                Some(PrefixBound::inclusive(7u32)),
1460                Order::Ascending,
1461            )
1462            .map(|r| r.map(|(_, v)| v))
1463            .collect::<StdResult<Vec<_>>>()
1464            .unwrap();
1465        assert_eq!(include.len(), 4);
1466        assert_eq!(include, vec![456, 789, 987, 2002]);
1467
1468        // using exclusive bounds both sides
1469        let exclude = AGES
1470            .prefix_range_raw(
1471                &store,
1472                Some(PrefixBound::exclusive(3u32)),
1473                Some(PrefixBound::exclusive(7u32)),
1474                Order::Ascending,
1475            )
1476            .map(|r| r.map(|(_, v)| v))
1477            .collect::<StdResult<Vec<_>>>()
1478            .unwrap();
1479        assert_eq!(exclude.len(), 2);
1480        assert_eq!(exclude, vec![789, 987]);
1481
1482        // using inclusive in descending
1483        let include = AGES
1484            .prefix_range_raw(
1485                &store,
1486                Some(PrefixBound::inclusive(3u32)),
1487                Some(PrefixBound::inclusive(5u32)),
1488                Order::Descending,
1489            )
1490            .map(|r| r.map(|(_, v)| v))
1491            .collect::<StdResult<Vec<_>>>()
1492            .unwrap();
1493        assert_eq!(include.len(), 3);
1494        assert_eq!(include, vec![987, 789, 456]);
1495
1496        // using exclusive in descending
1497        let include = AGES
1498            .prefix_range_raw(
1499                &store,
1500                Some(PrefixBound::exclusive(2u32)),
1501                Some(PrefixBound::exclusive(5u32)),
1502                Order::Descending,
1503            )
1504            .map(|r| r.map(|(_, v)| v))
1505            .collect::<StdResult<Vec<_>>>()
1506            .unwrap();
1507        assert_eq!(include.len(), 1);
1508        assert_eq!(include, vec![456]);
1509    }
1510
1511    #[test]
1512    #[cfg(feature = "iterator")]
1513    fn prefixed_range_works() {
1514        // this is designed to look as much like a secondary index as possible
1515        // we want to query over a range of u32 for the first key and all subkeys
1516        const AGES: Map<(u32, &str), u64> = Map::new("ages");
1517
1518        let mut store = MockStorage::new();
1519        AGES.save(&mut store, (2, "123"), &123).unwrap();
1520        AGES.save(&mut store, (3, "456"), &456).unwrap();
1521        AGES.save(&mut store, (5, "789"), &789).unwrap();
1522        AGES.save(&mut store, (5, "987"), &987).unwrap();
1523        AGES.save(&mut store, (7, "202122"), &2002).unwrap();
1524        AGES.save(&mut store, (8, "232425"), &2332).unwrap();
1525
1526        // typical range under one prefix as a control
1527        let fives = AGES
1528            .prefix(5)
1529            .range(&store, None, None, Order::Ascending)
1530            .collect::<StdResult<Vec<_>>>()
1531            .unwrap();
1532        assert_eq!(fives.len(), 2);
1533        assert_eq!(
1534            fives,
1535            vec![("789".to_string(), 789), ("987".to_string(), 987)]
1536        );
1537
1538        let keys: Vec<_> = AGES.keys(&store, None, None, Order::Ascending).collect();
1539        println!("keys: {:?}", keys);
1540
1541        // using inclusive bounds both sides
1542        let include = AGES
1543            .prefix_range(
1544                &store,
1545                Some(PrefixBound::inclusive(3u32)),
1546                Some(PrefixBound::inclusive(7u32)),
1547                Order::Ascending,
1548            )
1549            .map(|r| r.map(|(_, v)| v))
1550            .collect::<StdResult<Vec<_>>>()
1551            .unwrap();
1552        assert_eq!(include.len(), 4);
1553        assert_eq!(include, vec![456, 789, 987, 2002]);
1554
1555        // using exclusive bounds both sides
1556        let exclude = AGES
1557            .prefix_range(
1558                &store,
1559                Some(PrefixBound::exclusive(3u32)),
1560                Some(PrefixBound::exclusive(7u32)),
1561                Order::Ascending,
1562            )
1563            .map(|r| r.map(|(_, v)| v))
1564            .collect::<StdResult<Vec<_>>>()
1565            .unwrap();
1566        assert_eq!(exclude.len(), 2);
1567        assert_eq!(exclude, vec![789, 987]);
1568
1569        // using inclusive in descending
1570        let include = AGES
1571            .prefix_range(
1572                &store,
1573                Some(PrefixBound::inclusive(3u32)),
1574                Some(PrefixBound::inclusive(5u32)),
1575                Order::Descending,
1576            )
1577            .map(|r| r.map(|(_, v)| v))
1578            .collect::<StdResult<Vec<_>>>()
1579            .unwrap();
1580        assert_eq!(include.len(), 3);
1581        assert_eq!(include, vec![987, 789, 456]);
1582
1583        // using exclusive in descending
1584        let include = AGES
1585            .prefix_range(
1586                &store,
1587                Some(PrefixBound::exclusive(2u32)),
1588                Some(PrefixBound::exclusive(5u32)),
1589                Order::Descending,
1590            )
1591            .map(|r| r.map(|(_, v)| v))
1592            .collect::<StdResult<Vec<_>>>()
1593            .unwrap();
1594        assert_eq!(include.len(), 1);
1595        assert_eq!(include, vec![456]);
1596    }
1597
1598    #[test]
1599    #[cfg(feature = "iterator")]
1600    fn clear_works() {
1601        const TEST_MAP: Map<&str, u32> = Map::new("test_map");
1602
1603        let mut storage = MockStorage::new();
1604        TEST_MAP.save(&mut storage, "key0", &0u32).unwrap();
1605        TEST_MAP.save(&mut storage, "key1", &1u32).unwrap();
1606        TEST_MAP.save(&mut storage, "key2", &2u32).unwrap();
1607        TEST_MAP.save(&mut storage, "key3", &3u32).unwrap();
1608        TEST_MAP.save(&mut storage, "key4", &4u32).unwrap();
1609
1610        TEST_MAP.clear(&mut storage);
1611
1612        assert!(!TEST_MAP.has(&storage, "key0"));
1613        assert!(!TEST_MAP.has(&storage, "key1"));
1614        assert!(!TEST_MAP.has(&storage, "key2"));
1615        assert!(!TEST_MAP.has(&storage, "key3"));
1616        assert!(!TEST_MAP.has(&storage, "key4"));
1617    }
1618
1619    #[test]
1620    #[cfg(feature = "iterator")]
1621    fn is_empty_works() {
1622        const TEST_MAP: Map<&str, u32> = Map::new("test_map");
1623
1624        let mut storage = MockStorage::new();
1625
1626        assert!(TEST_MAP.is_empty(&storage));
1627
1628        TEST_MAP.save(&mut storage, "key1", &1u32).unwrap();
1629        TEST_MAP.save(&mut storage, "key2", &2u32).unwrap();
1630
1631        assert!(!TEST_MAP.is_empty(&storage));
1632    }
1633
1634    #[test]
1635    #[cfg(feature = "iterator")]
1636    fn first_last_work() {
1637        let mut storage = cosmwasm_std::testing::MockStorage::new();
1638        const MAP: Map<&str, u32> = Map::new("map");
1639
1640        // empty map
1641        assert_eq!(MAP.first(&storage), Ok(None));
1642        assert_eq!(MAP.last(&storage), Ok(None));
1643
1644        // insert entries
1645        MAP.save(&mut storage, "ghi", &1).unwrap();
1646        MAP.save(&mut storage, "abc", &2).unwrap();
1647        MAP.save(&mut storage, "def", &3).unwrap();
1648
1649        assert_eq!(MAP.first(&storage), Ok(Some(("abc".to_string(), 2))));
1650        assert_eq!(MAP.last(&storage), Ok(Some(("ghi".to_string(), 1))));
1651    }
1652}