difftreelog
Add properties key chars check
in: master
4 files changed
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -18,7 +18,7 @@
use core::ops::{Deref, DerefMut};
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use sp_std::{vec::Vec, collections::btree_map::BTreeMap};
+use sp_std::vec::Vec;
use pallet_evm::account::CrossAccountId;
use frame_support::{
dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},
@@ -36,7 +36,7 @@
CUSTOM_DATA_LIMIT, CollectionLimits, CustomDataLimit, CreateCollectionData, SponsorshipState,
CreateItemExData, SponsoringRateLimit, budget::Budget, COLLECTION_FIELD_LIMIT, CollectionField,
PhantomType, Property, Properties, PropertiesPermissionMap, PropertyKey, PropertyPermission,
- PropertiesError, PropertyKeyPermission, TokenData, CollectionPropertiesPermissionsVec,
+ PropertiesError, PropertyKeyPermission, TokenData, TrySet,
};
pub use pallet::*;
use sp_core::H160;
@@ -374,6 +374,9 @@
/// Unable to read array of unbounded keys
UnableToReadUnboundedKeys,
+
+ /// Only ASCII letters, digits, and '_', '-' are allowed
+ InvalidCharacterInPropertyKey,
}
#[pallet::storage]
@@ -676,19 +679,20 @@
meta_update_permission: data.meta_update_permission.unwrap_or_default(),
};
- CollectionProperties::<T>::insert(
- id,
- Properties::from_collection_props_vec(data.properties)
- .map_err(|e| -> Error<T> { e.into() })?,
- );
+ let mut collection_properties = up_data_structs::CollectionProperties::get();
+ collection_properties.try_set_from_iter(
+ data.properties.into_iter()
+ .map(|p| (p.key, p.value))
+ ).map_err(|e| -> Error<T> { e.into() })?;
+
+ CollectionProperties::<T>::insert(id, collection_properties);
- let token_props_permissions: PropertiesPermissionMap = data
- .token_property_permissions
+ let mut token_props_permissions = PropertiesPermissionMap::new();
+ token_props_permissions.try_set_from_iter(
+ data.token_property_permissions
.into_iter()
.map(|property| (property.key, property.permission))
- .collect::<BTreeMap<_, _>>()
- .try_into()
- .map_err(|_| -> Error<T> { PropertiesError::PropertyLimitReached.into() })?;
+ ).map_err(|e| -> Error<T> { e.into() })?;
CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
@@ -771,7 +775,8 @@
collection.check_is_owner_or_admin(sender)?;
CollectionProperties::<T>::try_mutate(collection.id, |properties| {
- properties.try_set_property(property.clone())
+ let property = property.clone();
+ properties.try_set(property.key, property.value)
})
.map_err(|e| -> Error<T> { e.into() })?;
@@ -799,9 +804,9 @@
) -> DispatchResult {
collection.check_is_owner_or_admin(sender)?;
- CollectionProperties::<T>::mutate(collection.id, |properties| {
- properties.remove_property(&property_key);
- });
+ CollectionProperties::<T>::try_mutate(collection.id, |properties| {
+ properties.remove(&property_key)
+ }).map_err(|e| -> Error<T> { e.into() })?;
Self::deposit_event(Event::CollectionPropertyDeleted(
collection.id,
@@ -841,7 +846,7 @@
CollectionPropertyPermissions::<T>::try_mutate(collection.id, |permissions| {
let property_permission = property_permission.clone();
- permissions.try_insert(property_permission.key, property_permission.permission)
+ permissions.try_set(property_permission.key, property_permission.permission)
})
.map_err(|_| -> Error<T> { PropertiesError::PropertyLimitReached.into() })?;
@@ -876,6 +881,19 @@
.collect::<Result<Vec<PropertyKey>, DispatchError>>()
}
+ pub fn check_property_key(key: &PropertyKey) -> Result<(), DispatchError> {
+ let key_str = sp_std::str::from_utf8(key.as_slice())
+ .map_err(|_| <Error<T>>::InvalidCharacterInPropertyKey)?;
+
+ for ch in key_str.chars() {
+ if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {
+ return Err(<Error<T>>::InvalidCharacterInPropertyKey.into());
+ }
+ }
+
+ Ok(())
+ }
+
pub fn filter_collection_properties(
collection_id: CollectionId,
keys: Vec<PropertyKey>,
@@ -885,10 +903,11 @@
let properties = keys
.into_iter()
.filter_map(|key| {
- properties.get_property(&key).map(|value| Property {
- key,
- value: value.clone(),
- })
+ properties.get(&key)
+ .map(|value| Property {
+ key,
+ value: value.clone(),
+ })
})
.collect();
@@ -1222,6 +1241,7 @@
match error {
PropertiesError::NoSpaceForProperty => Self::NoSpaceForProperty,
PropertiesError::PropertyLimitReached => Self::PropertyLimitReached,
+ PropertiesError::InvalidCharacterInPropertyKey => Self::InvalidCharacterInPropertyKey,
}
}
}
pallets/nonfungible/src/common.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use core::marker::PhantomData;1819use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};20use up_data_structs::{21 TokenId, CustomDataLimit, CreateItemExData, CollectionId, budget::Budget, Property,22 PropertyKey, PropertyKeyPermission,23};24use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};25use sp_runtime::DispatchError;26use sp_std::vec::Vec;2728use crate::{29 AccountBalance, Allowance, Config, CreateItemData, Error, NonfungibleHandle, Owned, Pallet,30 SelfWeightOf, TokenData, weights::WeightInfo, TokensMinted,31};3233pub struct CommonWeights<T: Config>(PhantomData<T>);34impl<T: Config> CommonWeightInfo<T::CrossAccountId> for CommonWeights<T> {35 fn create_item() -> Weight {36 <SelfWeightOf<T>>::create_item()37 }3839 fn create_multiple_items_ex(data: &CreateItemExData<T::CrossAccountId>) -> Weight {40 match data {41 CreateItemExData::NFT(t) => <SelfWeightOf<T>>::create_multiple_items_ex(t.len() as u32),42 _ => 0,43 }44 }4546 fn create_multiple_items(amount: u32) -> Weight {47 <SelfWeightOf<T>>::create_multiple_items(amount)48 }4950 fn burn_item() -> Weight {51 <SelfWeightOf<T>>::burn_item()52 }5354 fn set_collection_properties(amount: u32) -> Weight {55 <SelfWeightOf<T>>::set_collection_properties(amount)56 }5758 fn delete_collection_properties(amount: u32) -> Weight {59 <SelfWeightOf<T>>::delete_collection_properties(amount)60 }6162 fn set_token_properties(amount: u32) -> Weight {63 <SelfWeightOf<T>>::set_token_properties(amount)64 }6566 fn delete_token_properties(amount: u32) -> Weight {67 <SelfWeightOf<T>>::delete_token_properties(amount)68 }6970 fn set_property_permissions(amount: u32) -> Weight {71 <SelfWeightOf<T>>::set_property_permissions(amount)72 }7374 fn transfer() -> Weight {75 <SelfWeightOf<T>>::transfer()76 }7778 fn approve() -> Weight {79 <SelfWeightOf<T>>::approve()80 }8182 fn transfer_from() -> Weight {83 <SelfWeightOf<T>>::transfer_from()84 }8586 fn burn_from() -> Weight {87 <SelfWeightOf<T>>::burn_from()88 }8990 fn set_variable_metadata(bytes: u32) -> Weight {91 <SelfWeightOf<T>>::set_variable_metadata(bytes)92 }93}9495fn map_create_data<T: Config>(96 data: up_data_structs::CreateItemData,97 to: &T::CrossAccountId,98) -> Result<CreateItemData<T>, DispatchError> {99 match data {100 up_data_structs::CreateItemData::NFT(data) => Ok(CreateItemData::<T> {101 const_data: data.const_data,102 variable_data: data.variable_data,103 properties: data.properties,104 owner: to.clone(),105 }),106 _ => fail!(<Error<T>>::NotNonfungibleDataUsedToMintFungibleCollectionToken),107 }108}109110impl<T: Config> CommonCollectionOperations<T> for NonfungibleHandle<T> {111 fn create_item(112 &self,113 sender: T::CrossAccountId,114 to: T::CrossAccountId,115 data: up_data_structs::CreateItemData,116 nesting_budget: &dyn Budget,117 ) -> DispatchResultWithPostInfo {118 with_weight(119 <Pallet<T>>::create_item(120 self,121 &sender,122 map_create_data::<T>(data, &to)?,123 nesting_budget,124 ),125 <CommonWeights<T>>::create_item(),126 )127 }128129 fn create_multiple_items(130 &self,131 sender: T::CrossAccountId,132 to: T::CrossAccountId,133 data: Vec<up_data_structs::CreateItemData>,134 nesting_budget: &dyn Budget,135 ) -> DispatchResultWithPostInfo {136 let data = data137 .into_iter()138 .map(|d| map_create_data::<T>(d, &to))139 .collect::<Result<Vec<_>, DispatchError>>()?;140141 let amount = data.len();142 with_weight(143 <Pallet<T>>::create_multiple_items(self, &sender, data, nesting_budget),144 <CommonWeights<T>>::create_multiple_items(amount as u32),145 )146 }147148 fn create_multiple_items_ex(149 &self,150 sender: <T>::CrossAccountId,151 data: up_data_structs::CreateItemExData<<T>::CrossAccountId>,152 nesting_budget: &dyn Budget,153 ) -> DispatchResultWithPostInfo {154 let weight = <CommonWeights<T>>::create_multiple_items_ex(&data);155 let data = match data {156 up_data_structs::CreateItemExData::NFT(nft) => nft,157 _ => fail!(Error::<T>::NotNonfungibleDataUsedToMintFungibleCollectionToken),158 };159160 with_weight(161 <Pallet<T>>::create_multiple_items(self, &sender, data.into_inner(), nesting_budget),162 weight,163 )164 }165166 fn set_collection_properties(167 &self,168 sender: T::CrossAccountId,169 properties: Vec<Property>,170 ) -> DispatchResultWithPostInfo {171 let weight = <CommonWeights<T>>::set_collection_properties(properties.len() as u32);172173 with_weight(174 <Pallet<T>>::set_collection_properties(self, &sender, properties),175 weight,176 )177 }178179 fn delete_collection_properties(180 &self,181 sender: &T::CrossAccountId,182 property_keys: Vec<PropertyKey>,183 ) -> DispatchResultWithPostInfo {184 let weight = <CommonWeights<T>>::delete_collection_properties(property_keys.len() as u32);185186 with_weight(187 <Pallet<T>>::delete_collection_properties(self, &sender, property_keys),188 weight,189 )190 }191192 fn set_token_properties(193 &self,194 sender: T::CrossAccountId,195 token_id: TokenId,196 properties: Vec<Property>,197 ) -> DispatchResultWithPostInfo {198 let weight = <CommonWeights<T>>::set_token_properties(properties.len() as u32);199200 with_weight(201 <Pallet<T>>::set_token_properties(self, &sender, token_id, properties),202 weight,203 )204 }205206 fn delete_token_properties(207 &self,208 sender: T::CrossAccountId,209 token_id: TokenId,210 property_keys: Vec<PropertyKey>,211 ) -> DispatchResultWithPostInfo {212 let weight = <CommonWeights<T>>::delete_token_properties(property_keys.len() as u32);213214 with_weight(215 <Pallet<T>>::delete_token_properties(self, &sender, token_id, property_keys),216 weight,217 )218 }219220 fn set_property_permissions(221 &self,222 sender: &T::CrossAccountId,223 property_permissions: Vec<PropertyKeyPermission>,224 ) -> DispatchResultWithPostInfo {225 let weight =226 <CommonWeights<T>>::set_property_permissions(property_permissions.len() as u32);227228 with_weight(229 <Pallet<T>>::set_property_permissions(self, sender, property_permissions),230 weight,231 )232 }233234 fn burn_item(235 &self,236 sender: T::CrossAccountId,237 token: TokenId,238 amount: u128,239 ) -> DispatchResultWithPostInfo {240 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);241 if amount == 1 {242 with_weight(243 <Pallet<T>>::burn(self, &sender, token),244 <CommonWeights<T>>::burn_item(),245 )246 } else {247 Ok(().into())248 }249 }250251 fn transfer(252 &self,253 from: T::CrossAccountId,254 to: T::CrossAccountId,255 token: TokenId,256 amount: u128,257 nesting_budget: &dyn Budget,258 ) -> DispatchResultWithPostInfo {259 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);260 if amount == 1 {261 with_weight(262 <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),263 <CommonWeights<T>>::transfer(),264 )265 } else {266 Ok(().into())267 }268 }269270 fn approve(271 &self,272 sender: T::CrossAccountId,273 spender: T::CrossAccountId,274 token: TokenId,275 amount: u128,276 ) -> DispatchResultWithPostInfo {277 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);278279 with_weight(280 if amount == 1 {281 <Pallet<T>>::set_allowance(self, &sender, token, Some(&spender))282 } else {283 <Pallet<T>>::set_allowance(self, &sender, token, None)284 },285 <CommonWeights<T>>::approve(),286 )287 }288289 fn transfer_from(290 &self,291 sender: T::CrossAccountId,292 from: T::CrossAccountId,293 to: T::CrossAccountId,294 token: TokenId,295 amount: u128,296 nesting_budget: &dyn Budget,297 ) -> DispatchResultWithPostInfo {298 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);299300 if amount == 1 {301 with_weight(302 <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),303 <CommonWeights<T>>::transfer_from(),304 )305 } else {306 Ok(().into())307 }308 }309310 fn burn_from(311 &self,312 sender: T::CrossAccountId,313 from: T::CrossAccountId,314 token: TokenId,315 amount: u128,316 nesting_budget: &dyn Budget,317 ) -> DispatchResultWithPostInfo {318 ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);319320 if amount == 1 {321 with_weight(322 <Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),323 <CommonWeights<T>>::burn_from(),324 )325 } else {326 Ok(().into())327 }328 }329330 fn set_variable_metadata(331 &self,332 sender: T::CrossAccountId,333 token: TokenId,334 data: BoundedVec<u8, CustomDataLimit>,335 ) -> DispatchResultWithPostInfo {336 let len = data.len();337 with_weight(338 <Pallet<T>>::set_variable_metadata(self, &sender, token, data),339 <CommonWeights<T>>::set_variable_metadata(len as u32),340 )341 }342343 fn check_nesting(344 &self,345 sender: T::CrossAccountId,346 from: (CollectionId, TokenId),347 under: TokenId,348 budget: &dyn Budget,349 ) -> sp_runtime::DispatchResult {350 <Pallet<T>>::check_nesting(self, sender, from, under, budget)351 }352353 fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId> {354 <Owned<T>>::iter_prefix((self.id, account))355 .map(|(id, _)| id)356 .collect()357 }358359 fn collection_tokens(&self) -> Vec<TokenId> {360 <TokenData<T>>::iter_prefix((self.id,))361 .map(|(id, _)| id)362 .collect()363 }364365 fn token_exists(&self, token: TokenId) -> bool {366 <Pallet<T>>::token_exists(self, token)367 }368369 fn last_token_id(&self) -> TokenId {370 TokenId(<TokensMinted<T>>::get(self.id))371 }372373 fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId> {374 <TokenData<T>>::get((self.id, token)).map(|t| t.owner)375 }376 fn const_metadata(&self, token: TokenId) -> Vec<u8> {377 <TokenData<T>>::get((self.id, token))378 .map(|t| t.const_data)379 .unwrap_or_default()380 .into_inner()381 }382 fn variable_metadata(&self, token: TokenId) -> Vec<u8> {383 <TokenData<T>>::get((self.id, token))384 .map(|t| t.variable_data)385 .unwrap_or_default()386 .into_inner()387 }388389 fn token_properties(&self, token_id: TokenId, keys: Vec<PropertyKey>) -> Vec<Property> {390 let properties = <Pallet<T>>::token_properties((self.id, token_id));391392 keys.into_iter()393 .filter_map(|key| {394 properties.get_property(&key).map(|value| Property {395 key,396 value: value.clone(),397 })398 })399 .collect()400 }401402 fn total_supply(&self) -> u32 {403 <Pallet<T>>::total_supply(self)404 }405406 fn account_balance(&self, account: T::CrossAccountId) -> u32 {407 <AccountBalance<T>>::get((self.id, account))408 }409410 fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128 {411 if <TokenData<T>>::get((self.id, token))412 .map(|a| a.owner == account)413 .unwrap_or(false)414 {415 1416 } else {417 0418 }419 }420421 fn allowance(422 &self,423 sender: T::CrossAccountId,424 spender: T::CrossAccountId,425 token: TokenId,426 ) -> u128 {427 if <TokenData<T>>::get((self.id, token))428 .map(|a| a.owner != sender)429 .unwrap_or(true)430 {431 0432 } else if <Allowance<T>>::get((self.id, token)) == Some(spender) {433 1434 } else {435 0436 }437 }438}pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -21,7 +21,7 @@
use up_data_structs::{
AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,
- PropertyKey, PropertyKeyPermission, Properties,
+ PropertyKey, PropertyKeyPermission, Properties, TrySet,
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
@@ -265,7 +265,8 @@
Self::check_token_change_permission(collection, sender, token_id, &property.key)?;
<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
- properties.try_set_property(property.clone())
+ let property = property.clone();
+ properties.try_set(property.key, property.value)
})
.map_err(|e| -> CommonError<T> { e.into() })?;
@@ -299,9 +300,9 @@
) -> DispatchResult {
Self::check_token_change_permission(collection, sender, token_id, &property_key)?;
- <TokenProperties<T>>::mutate((collection.id, token_id), |properties| {
- properties.remove_property(&property_key);
- });
+ <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
+ properties.remove(&property_key)
+ }).map_err(|e| -> CommonError<T> { e.into() })?;
<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(
collection.id,
@@ -332,7 +333,7 @@
};
let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))
- .get_property(property_key)
+ .get(property_key)
.is_some();
match permission {
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -689,16 +689,82 @@
pub enum PropertiesError {
NoSpaceForProperty,
PropertyLimitReached,
+ InvalidCharacterInPropertyKey,
+}
+
+pub trait TrySet: Sized {
+ type Value;
+
+ fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError>;
+
+ fn try_set_from_iter<I>(&mut self, iter: I) -> Result<(), PropertiesError>
+ where
+ I: Iterator<Item=(PropertyKey, Self::Value)>
+ {
+ for (key, value) in iter {
+ self.try_set(key, value)?;
+ }
+
+ Ok(())
+ }
+}
+
+#[derive(Encode, Decode, TypeInfo, Derivative, Clone, PartialEq, MaxEncodedLen)]
+#[derivative(Default(bound = ""))]
+pub struct PropertiesMap<Value>(BoundedBTreeMap<PropertyKey, Value, ConstU32<MAX_PROPERTIES_PER_ITEM>>);
+
+impl<Value> PropertiesMap<Value> {
+ pub fn new() -> Self {
+ Self(BoundedBTreeMap::new())
+ }
+
+ pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<Value>, PropertiesError> {
+ Self::check_property_key(key)?;
+
+ Ok(self.0.remove(key))
+ }
+
+ pub fn get(&self, key: &PropertyKey) -> Option<&Value> {
+ self.0.get(key)
+ }
+
+ pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &Value)> {
+ self.0.iter()
+ }
+
+ fn check_property_key(key: &PropertyKey) -> Result<(), PropertiesError> {
+ let key_str = sp_std::str::from_utf8(key.as_slice())
+ .map_err(|_| PropertiesError::InvalidCharacterInPropertyKey)?;
+
+ for ch in key_str.chars() {
+ if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {
+ return Err(PropertiesError::InvalidCharacterInPropertyKey);
+ }
+ }
+
+ Ok(())
+ }
+}
+
+impl<Value> TrySet for PropertiesMap<Value> {
+ type Value = Value;
+
+ fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
+ Self::check_property_key(&key)?;
+
+ self.0
+ .try_insert(key, value)
+ .map_err(|_| PropertiesError::PropertyLimitReached)?;
+
+ Ok(())
+ }
}
-pub type PropertiesMap =
- BoundedBTreeMap<PropertyKey, PropertyValue, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
-pub type PropertiesPermissionMap =
- BoundedBTreeMap<PropertyKey, PropertyPermission, ConstU32<MAX_PROPERTIES_PER_ITEM>>;
+pub type PropertiesPermissionMap = PropertiesMap<PropertyPermission>;
#[derive(Encode, Decode, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
pub struct Properties {
- map: PropertiesMap,
+ map: PropertiesMap<PropertyValue>,
consumed_space: u32,
space_limit: u32,
}
@@ -706,57 +772,47 @@
impl Properties {
pub fn new(space_limit: u32) -> Self {
Self {
- map: BoundedBTreeMap::new(),
+ map: PropertiesMap::new(),
consumed_space: 0,
space_limit,
}
}
- pub fn from_collection_props_vec(
- data: CollectionPropertiesVec,
- ) -> Result<Self, PropertiesError> {
- let mut props = Self::new(MAX_COLLECTION_PROPERTIES_SIZE);
+ pub fn remove(&mut self, key: &PropertyKey) -> Result<Option<PropertyValue>, PropertiesError> {
+ let value = self.map.remove(key)?;
- for property in data.into_iter() {
- props.try_set_property(property)?;
+ if let Some(ref value) = value {
+ let value_len = value.len() as u32;
+ self.consumed_space -= value_len;
}
- Ok(props)
+ Ok(value)
}
- pub fn try_set_property(&mut self, property: Property) -> Result<(), PropertiesError> {
- let value_len = property.value.len();
+ pub fn get(&self, key: &PropertyKey) -> Option<&PropertyValue> {
+ self.map.get(key)
+ }
+ pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {
+ self.map.iter()
+ }
+}
+
+impl TrySet for Properties {
+ type Value = PropertyValue;
+
+ fn try_set(&mut self, key: PropertyKey, value: Self::Value) -> Result<(), PropertiesError> {
+ let value_len = value.len();
+
if self.consumed_space as usize + value_len > self.space_limit as usize {
return Err(PropertiesError::NoSpaceForProperty);
}
- self.map
- .try_insert(property.key, property.value)
- .map_err(|_| PropertiesError::PropertyLimitReached)?;
+ self.map.try_set(key, value)?;
self.consumed_space += value_len as u32;
Ok(())
- }
-
- pub fn remove_property(&mut self, key: &PropertyKey) {
- let property = self.map.get(key);
-
- if let Some(value) = property {
- let value_len = value.len() as u32;
-
- self.map.remove(key);
- self.consumed_space -= value_len;
- }
- }
-
- pub fn get_property(&self, key: &PropertyKey) -> Option<&PropertyValue> {
- self.map.get(key)
- }
-
- pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {
- self.map.iter()
}
}