-
Notifications
You must be signed in to change notification settings - Fork 12
/
slot.rs
203 lines (180 loc) · 5.42 KB
/
slot.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
//! Managed storage slots
//!
//! Makes it easy to create and manage storage keys and avoid unnecessary
//! writes to contract storage. This reduces transaction IO and saves on gas.
use std::{marker::PhantomData, ops::Deref};
use near_sdk::{
borsh::{self, BorshDeserialize, BorshSerialize},
env, near, IntoStorageKey,
};
use crate::utils::prefix_key;
#[derive(Clone, Debug)]
#[near]
/// A storage slot, composed of a storage location (key) and a data type
pub struct Slot<T> {
/// The storage key this slot controls.
pub key: Vec<u8>,
#[borsh(skip)]
_marker: PhantomData<T>,
}
impl Slot<()> {
/// A placeholder slot. Useful for creating namespaced fields.
pub fn root<K: IntoStorageKey>(key: K) -> Self {
Self {
key: key.into_storage_key(),
_marker: PhantomData,
}
}
}
impl<T> Slot<T> {
/// Creates a new [`Slot`] that controls the given storage key
pub fn new(key: impl IntoStorageKey) -> Self {
Self {
key: key.into_storage_key(),
_marker: PhantomData,
}
}
/// Creates a new [`Slot`] that controls the given key namespaced (prefixed)
/// by the parent key, to be used as a namespace for another subfield.
pub fn ns(&self, key: impl IntoStorageKey) -> Slot<()> {
Slot {
key: prefix_key(&self.key, &key.into_storage_key()),
_marker: PhantomData,
}
}
/// Creates a new [`Slot`] that controls the given key namespaced (prefixed)
/// by the parent key.
pub fn field<U>(&self, key: impl IntoStorageKey) -> Slot<U> {
Slot {
key: prefix_key(&self.key, &key.into_storage_key()),
_marker: PhantomData,
}
}
/// Creates a [`Slot`] that tries to parse a different data type from the same
/// storage slot.
///
/// # Warning
///
/// If the data in the slot is not parsable into the new type, methods like
/// [`Slot::read`] and [`Slot::take`] will panic.
#[must_use]
pub fn transmute<U>(&self) -> Slot<U> {
Slot {
key: self.key.clone(),
_marker: PhantomData,
}
}
/// Write raw bytes into the storage slot. No type checking.
pub fn write_raw(&mut self, value: &[u8]) -> bool {
env::storage_write(&self.key, value)
}
/// Read raw bytes from the slot. No type checking or parsing.
#[must_use]
pub fn read_raw(&self) -> Option<Vec<u8>> {
env::storage_read(&self.key)
}
/// Returns `true` if this slot's key is currently present in the smart
/// contract storage, `false` otherwise.
#[must_use]
pub fn exists(&self) -> bool {
env::storage_has_key(&self.key)
}
/// Removes the managed key from storage.
pub fn remove(&mut self) -> bool {
env::storage_remove(&self.key)
}
}
impl<T: BorshSerialize> Slot<T> {
/// Writes a value to the managed storage slot.
///
/// # Panics
///
/// If Borsh serialization fails.
pub fn write(&mut self, value: &T) -> bool {
self.write_raw(&borsh::to_vec(value).unwrap())
}
/// Writes a value to the managed storage slot which is dereferenced from
/// the target type.
///
/// # Panics
///
/// If Borsh serialization fails.
pub fn write_deref<U: BorshSerialize + ?Sized>(&mut self, value: &U) -> bool
where
T: Deref<Target = U>,
{
self.write_raw(&borsh::to_vec(value).unwrap())
}
/// If the given value is `Some(T)`, writes `T` to storage. Otherwise,
/// removes the key from storage.
pub fn set(&mut self, value: Option<&T>) -> bool {
match value {
Some(value) => self.write(value),
_ => self.remove(),
}
}
}
impl<T: BorshDeserialize> Slot<T> {
/// Reads a value from storage, if present.
///
/// # Panics
///
/// If Borsh deserialization fails.
#[must_use]
pub fn read(&self) -> Option<T> {
self.read_raw().map(|v| T::try_from_slice(&v).unwrap())
}
/// Removes a value from storage and returns it if present.
///
/// # Panics
///
/// If Borsh deserialization fails.
#[must_use]
pub fn take(&mut self) -> Option<T> {
if self.remove() {
// unwrap should be safe if remove returns true
Some(T::try_from_slice(&env::storage_get_evicted().unwrap()).unwrap())
} else {
None
}
}
}
impl<T: BorshSerialize + BorshDeserialize> Slot<T> {
/// Writes a value to storage and returns the evicted value, if present.
///
/// # Panics
///
/// If Borsh serialization fails.
#[must_use]
pub fn swap(&mut self, value: &T) -> Option<T> {
let v = borsh::to_vec(&value).unwrap();
if self.write_raw(&v) {
// unwrap should be safe because write_raw returned true
Some(T::try_from_slice(&env::storage_get_evicted().unwrap()).unwrap())
} else {
None
}
}
}
impl<T> IntoStorageKey for Slot<T> {
fn into_storage_key(self) -> Vec<u8> {
self.key
}
}
impl<T, U> PartialEq<Slot<U>> for Slot<T> {
fn eq(&self, other: &Slot<U>) -> bool {
self.key == other.key
}
}
#[cfg(test)]
mod tests {
use super::Slot;
#[test]
fn partialeq() {
let a1 = Slot::<u32>::new(b"a");
let a2 = Slot::<i32>::new(b"a");
assert_eq!(a1, a2);
let b = Slot::<u32>::new(b"b");
assert_ne!(a1, b);
}
}