unc_sdk/collections/mod.rs
1//! Collections that offer an alternative to standard containers from `std::collections::*` by
2//! utilizing the underlying blockchain trie storage more efficiently.
3//!
4//! The updated version of this module lives in [`unc_sdk::store`](crate::store),
5//! where the data structures are more optimized and have a closer API to [`std::collections`].
6//!
7//! For example, the following smart contract does not work with state efficiently, because it will
8//! load the entire `HashMap` at the beginning of the contract call, and will save it entirely at
9//! the end, in cases when there is state modification. This is fine for small number of elements,
10//! but very inefficient for large numbers.
11//!
12//! ```
13//! # use std::collections::HashMap;
14//! # use unc_sdk_macros::unc;
15//!
16//! #[unc(contract_state)]
17//! pub struct StatusMessage {
18//! records: HashMap<String, String>,
19//! }
20//! ```
21//!
22//! The following is an efficient alternative. It will load each element individually only when it is
23//! read and will save it only when it is written/removed.
24//! ```
25//! # use unc_sdk_macros::unc;
26//! # use unc_sdk::collections::LookupMap;
27//!
28//! #[unc(contract_state)]
29//! pub struct StatusMessage {
30//! records: LookupMap<String, String>,
31//! }
32//! ```
33//!
34//! The efficiency of `LookupMap` comes at the cost, since it has fewer methods than `HashMap` and is not
35//! that seamlessly integrated with the rest of the Rust standard library.
36
37mod legacy_tree_map;
38#[allow(deprecated)]
39pub use legacy_tree_map::LegacyTreeMap;
40
41mod lookup_map;
42pub use lookup_map::LookupMap;
43
44mod lookup_set;
45pub use lookup_set::LookupSet;
46
47pub mod vector;
48pub use vector::Vector;
49
50pub mod unordered_map;
51pub use unordered_map::UnorderedMap;
52
53mod unordered_set;
54pub use unordered_set::UnorderedSet;
55
56mod lazy_option;
57pub use lazy_option::LazyOption;
58
59mod tree_map;
60pub use tree_map::TreeMap;
61
62pub const ERR_INCONSISTENT_STATE: &str = "The collection is in an inconsistent state. Have any collections been updated without committing changes to contract state?";
63pub const ERR_ELEMENT_SERIALIZATION: &str = "Cannot serialize element with Borsh.";
64pub const ERR_ELEMENT_DESERIALIZATION: &str = "Cannot deserialize element with Borsh.";
65
66pub(crate) fn append(id: &[u8], chr: u8) -> Vec<u8> {
67 append_slice(id, &[chr])
68}
69
70pub(crate) fn append_slice(id: &[u8], extra: &[u8]) -> Vec<u8> {
71 [id, extra].concat()
72}