|
| 1 | +// Copyright 2018-2021 Parity Technologies (UK) Ltd. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +//! A simple mapping to contract storage. |
| 16 | +//! |
| 17 | +//! # Note |
| 18 | +//! |
| 19 | +//! This mapping doesn't actually "own" any data. |
| 20 | +//! Instead it is just a simple wrapper around the contract storage facilities. |
| 21 | +
|
| 22 | +use crate::traits::{ |
| 23 | + pull_packed_root_opt, |
| 24 | + push_packed_root, |
| 25 | + ExtKeyPtr, |
| 26 | + KeyPtr, |
| 27 | + PackedLayout, |
| 28 | + SpreadAllocate, |
| 29 | + SpreadLayout, |
| 30 | +}; |
| 31 | +use core::marker::PhantomData; |
| 32 | + |
| 33 | +use ink_env::hash::{ |
| 34 | + Blake2x256, |
| 35 | + HashOutput, |
| 36 | +}; |
| 37 | +use ink_primitives::Key; |
| 38 | + |
| 39 | +/// A mapping of key-value pairs directly into contract storage. |
| 40 | +#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] |
| 41 | +#[derive(Default)] |
| 42 | +pub struct Mapping<K, V> { |
| 43 | + offset_key: Key, |
| 44 | + _marker: PhantomData<fn() -> (K, V)>, |
| 45 | +} |
| 46 | + |
| 47 | +impl<K, V> core::fmt::Debug for Mapping<K, V> { |
| 48 | + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { |
| 49 | + f.debug_struct("Mapping") |
| 50 | + .field("offset_key", &self.offset_key) |
| 51 | + .finish() |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +impl<K, V> Mapping<K, V> { |
| 56 | + /// Creates a new empty `Mapping`. |
| 57 | + fn new(offset_key: Key) -> Self { |
| 58 | + Self { |
| 59 | + offset_key, |
| 60 | + _marker: Default::default(), |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl<K, V> Mapping<K, V> |
| 66 | +where |
| 67 | + K: PackedLayout, |
| 68 | + V: PackedLayout, |
| 69 | +{ |
| 70 | + /// Insert the given `value` to the contract storage. |
| 71 | + #[inline] |
| 72 | + pub fn insert<Q, R>(&mut self, key: Q, value: &R) |
| 73 | + where |
| 74 | + Q: scale::EncodeLike<K>, |
| 75 | + R: scale::EncodeLike<V> + PackedLayout, |
| 76 | + { |
| 77 | + push_packed_root(value, &self.storage_key(key)); |
| 78 | + } |
| 79 | + |
| 80 | + /// Get the `value` at `key` from the contract storage. |
| 81 | + /// |
| 82 | + /// Returns `None` if no `value` exists at the given `key`. |
| 83 | + #[inline] |
| 84 | + pub fn get<Q>(&self, key: Q) -> Option<V> |
| 85 | + where |
| 86 | + Q: scale::EncodeLike<K>, |
| 87 | + { |
| 88 | + pull_packed_root_opt(&self.storage_key(key)) |
| 89 | + } |
| 90 | + |
| 91 | + /// Returns a `Key` pointer used internally by the storage API. |
| 92 | + /// |
| 93 | + /// This key is a combination of the `Mapping`'s internal `offset_key` |
| 94 | + /// and the user provided `key`. |
| 95 | + fn storage_key<Q>(&self, key: Q) -> Key |
| 96 | + where |
| 97 | + Q: scale::EncodeLike<K>, |
| 98 | + { |
| 99 | + let encodedable_key = (&self.offset_key, key); |
| 100 | + let mut output = <Blake2x256 as HashOutput>::Type::default(); |
| 101 | + ink_env::hash_encoded::<Blake2x256, _>(&encodedable_key, &mut output); |
| 102 | + output.into() |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | +impl<K, V> SpreadLayout for Mapping<K, V> { |
| 107 | + const FOOTPRINT: u64 = 1; |
| 108 | + const REQUIRES_DEEP_CLEAN_UP: bool = false; |
| 109 | + |
| 110 | + #[inline] |
| 111 | + fn pull_spread(ptr: &mut KeyPtr) -> Self { |
| 112 | + // Note: There is no need to pull anything from the storage for the |
| 113 | + // mapping type since it initializes itself entirely by the |
| 114 | + // given key pointer. |
| 115 | + Self::new(*ExtKeyPtr::next_for::<Self>(ptr)) |
| 116 | + } |
| 117 | + |
| 118 | + #[inline] |
| 119 | + fn push_spread(&self, ptr: &mut KeyPtr) { |
| 120 | + // Note: The mapping type does not store any state in its associated |
| 121 | + // storage region, therefore only the pointer has to be incremented. |
| 122 | + ptr.advance_by(Self::FOOTPRINT); |
| 123 | + } |
| 124 | + |
| 125 | + #[inline] |
| 126 | + fn clear_spread(&self, ptr: &mut KeyPtr) { |
| 127 | + // Note: The mapping type is not aware of its elements, therefore |
| 128 | + // it is not possible to clean up after itself. |
| 129 | + ptr.advance_by(Self::FOOTPRINT); |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +impl<K, V> SpreadAllocate for Mapping<K, V> { |
| 134 | + #[inline] |
| 135 | + fn allocate_spread(ptr: &mut KeyPtr) -> Self { |
| 136 | + // Note: The mapping type initializes itself entirely by the key pointer. |
| 137 | + Self::new(*ExtKeyPtr::next_for::<Self>(ptr)) |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +#[cfg(feature = "std")] |
| 142 | +const _: () = { |
| 143 | + use crate::traits::StorageLayout; |
| 144 | + use ink_metadata::layout::{ |
| 145 | + CellLayout, |
| 146 | + Layout, |
| 147 | + LayoutKey, |
| 148 | + }; |
| 149 | + |
| 150 | + impl<K, V> StorageLayout for Mapping<K, V> |
| 151 | + where |
| 152 | + K: scale_info::TypeInfo + 'static, |
| 153 | + V: scale_info::TypeInfo + 'static, |
| 154 | + { |
| 155 | + fn layout(key_ptr: &mut KeyPtr) -> Layout { |
| 156 | + Layout::Cell(CellLayout::new::<Self>(LayoutKey::from( |
| 157 | + key_ptr.advance_by(1), |
| 158 | + ))) |
| 159 | + } |
| 160 | + } |
| 161 | +}; |
| 162 | + |
| 163 | +#[cfg(test)] |
| 164 | +mod tests { |
| 165 | + use super::*; |
| 166 | + |
| 167 | + #[test] |
| 168 | + fn insert_and_get_work() { |
| 169 | + ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| { |
| 170 | + let mut mapping: Mapping<u8, _> = Mapping::new([0u8; 32].into()); |
| 171 | + mapping.insert(&1, &2); |
| 172 | + assert_eq!(mapping.get(&1), Some(2)); |
| 173 | + |
| 174 | + Ok(()) |
| 175 | + }) |
| 176 | + .unwrap() |
| 177 | + } |
| 178 | + |
| 179 | + #[test] |
| 180 | + fn gets_default_if_no_key_set() { |
| 181 | + ink_env::test::run_test::<ink_env::DefaultEnvironment, _>(|_| { |
| 182 | + let mapping: Mapping<u8, u8> = Mapping::new([0u8; 32].into()); |
| 183 | + assert_eq!(mapping.get(&1), None); |
| 184 | + |
| 185 | + Ok(()) |
| 186 | + }) |
| 187 | + .unwrap() |
| 188 | + } |
| 189 | +} |
0 commit comments