pub struct SerializableAnyMap { /* private fields */ }Expand description
A serializable heterogeneous-map keyed by a stable value derived from the type.
SerializableAnyMap behaves like anymap3 for most basic use-cases but
stores values in serialized form so the entire map can be serialized and
sent across process boundaries. The map implements Serialize and
Deserialize where only the serialized form is persisted; the cached
deserialized values are not persisted.
Inserted types must implement Serialize + Deserialize<'de> + 'static.
See method docs for usage patterns (insert, get, get_mut, entry, …).
Safety notes:
- Some escape hatches (
as_raw_mut,from_raw) areunsafe— the caller must ensure the key string matches the type stored under it.
A stored entry containing the serialized representation and an optional cached runtime value.
Implementations§
Source§impl SerializableAnyMap
impl SerializableAnyMap
Sourcepub fn new() -> Self
pub fn new() -> Self
Create a new empty SerializableAnyMap.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::new();
map.insert(42u32);
assert_eq!(map.get::<u32>().unwrap().unwrap(), &42u32);Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Creates a new empty map with preallocated space for capacity elements.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::with_capacity(8);
assert!(map.capacity() >= 8);
map.insert(42u32);
map.insert(42u16);
map.insert(42u8);
assert_eq!(map.len(), 3);
assert!(map.capacity() >= 8);Sourcepub fn capacity(&self) -> usize
pub fn capacity(&self) -> usize
Returns the number of elements the map can hold without reallocating.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::new();
map.insert(42u32);
map.insert(42u16);
map.insert(42u8);
assert_eq!(map.len(), 3);
assert!(map.capacity() >= 3);Sourcepub fn reserve(&mut self, additional: usize)
pub fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional more elements to be inserted.
The collection may reserve more space to avoid frequent reallocations.
§Panics
Panics if the new capacity overflows usize.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::new();
map.insert(42u32);
map.insert(42u16);
map.insert(42u8);
map.reserve(5);
assert!(map.capacity() >= 8);
Sourcepub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>
Tries to reserve capacity for at least additional more elements to be inserted in the HashMap. The collection may reserve more space to speculatively avoid frequent reallocations. After calling try_reserve, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). Does nothing if capacity is already sufficient.
§Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::new();
map.insert(42u32);
map.insert(42u16);
map.insert(42u8);
map.try_reserve(5).expect("not to fail");
assert!(map.capacity() >= 8);
Sourcepub fn shrink_to_fit(&mut self)
pub fn shrink_to_fit(&mut self)
Shrinks the capacity of the collection as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::with_capacity(128);
map.insert(42u32);
map.insert(42u16);
map.insert(42u8);
map.shrink_to_fit();
assert_eq!(map.len(), 3);
assert!(map.capacity() < 128);
Sourcepub fn shrink_to(&mut self, min_capcity: usize)
pub fn shrink_to(&mut self, min_capcity: usize)
Shrinks the capacity of the map with a lower limit. It will drop down no lower than the supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy. If the current capacity is less than the lower limit, this is a no-op.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::with_capacity(128);
map.insert(42u32);
map.insert(42u16);
map.insert(42u8);
map.shrink_to(64);
assert_eq!(map.len(), 3);
assert!(map.capacity() < 128 );
assert!(map.capacity() >= 64 );
Sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Returns the number of elements in the map. Note that this may not be the exact number of retrievable items, if deserialization of some items fail.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::with_capacity(128);
map.insert(42u32);
map.insert(42u16);
map.insert(42u8);
assert_eq!(map.len(), 3);
Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true if there are no items in the collection. Returns the number of elements in the map. Note that this may not be the exact number of retrievable items, if deserialization of some items fail.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::with_capacity(128);
assert_eq!(map.is_empty(), true);
map.insert(42u16);
assert_eq!(map.is_empty(), false);
Sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Removes all items from the collection. Keeps the allocated memory for reuse.
§Example
use anymap_serde::SerializableAnyMap;
let mut map = SerializableAnyMap::with_capacity(128);
map.insert(42u32);
map.clear();
assert_eq!(map.is_empty(), true)
Sourcepub fn try_get<T>(&self) -> Option<&T>where
T: for<'de> Deserialize<'de> + Any + 'static,
pub fn try_get<T>(&self) -> Option<&T>where
T: for<'de> Deserialize<'de> + Any + 'static,
Get an immutable reference to a cached value of type T if it exists AND was deserialized.
§Notes
This does NOT lazily deserialize, use Self::get if you want lazy deserialization.
This may return None even if the type is present in the map, but not deserialized yet, which
may happen if the map was deserialized from a serialized form and the type has not yet been accessed.
§Example
use anymap_serde::SerializableAnyMap;
use serde_json::json;
let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": 42 })).unwrap();
map.insert(42u16);
assert_eq!(map.try_get::<u32>(), None); // not deserialized yet
assert_eq!(map.try_get::<u16>(), Some(&42u16));
assert_eq!(map.get::<u32>().unwrap().unwrap(), &42u32); // deserialization happens now
assert_eq!(map.try_get::<u32>(), Some(&42u32)); // can now be access via try_get as well.Sourcepub fn get<T>(&mut self) -> Option<Result<&T, DeserializerError>>where
T: Serialize + for<'de> Deserialize<'de> + 'static,
pub fn get<T>(&mut self) -> Option<Result<&T, DeserializerError>>where
T: Serialize + for<'de> Deserialize<'de> + 'static,
Get an immutable reference to a value of type T, lazily deserializing if necessary.
§Notes
This requires a &mut self since it may need to deserialize and modify the entry.
If the item comes from deserializing the map, this may fail if the deserialization of the item fails.
In such case the item is removed from subsequent accesses.
§Example
use anymap_serde::SerializableAnyMap;
use serde_json::json;
let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom" })).unwrap();
map.insert(42u16);
assert_eq!(map.len(), 2);
assert!(matches!(map.get::<u32>(), Some(Err(_)))); // deserialization failed, removed from the map.
assert_eq!(map.len(), 1);
assert!(matches!(map.get::<u32>(), None)); // not present in the map anymore
assert_eq!(map.get::<u16>().unwrap().ok(), Some(&42u16)); // deserialization successfulSourcepub fn get_deserialized_copy<T>(&self) -> Option<T>where
T: for<'de> Deserialize<'de> + Any + 'static,
pub fn get_deserialized_copy<T>(&self) -> Option<T>where
T: for<'de> Deserialize<'de> + Any + 'static,
Gets a copy value of type T, by deserializing the value in the map. Note that this will
always return a copy of the item contained in the map, and may lose infomration that is #[serde(skip)].
§Example
use serde::{Deserialize, Serialize};
use anymap_serde::SerializableAnyMap;
use serde_json::from_value;
let mut map: SerializableAnyMap = SerializableAnyMap::new();
map.insert(42u32);
assert_eq!(map.get_deserialized_copy::<u32>(), Some(42u32));
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Foo { bar: u32, #[serde(skip)] baz: u32 }
map.insert(Foo { bar: 42, baz: 43 });
assert_eq!(map.get_deserialized_copy::<Foo>().unwrap(), Foo { bar: 42, baz: 0}); // deserialization looses `baz` valueSourcepub fn get_mut<T>(
&mut self,
) -> Option<Result<WriteGuard<'_, T>, DeserializerError>>
pub fn get_mut<T>( &mut self, ) -> Option<Result<WriteGuard<'_, T>, DeserializerError>>
Get a mutable reference to a value of type T, lazily deserializing into the cache if necessary.
§Example
use anymap_serde::SerializableAnyMap;
use serde_json::json;
let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom" })).unwrap();
map.insert(42u16);
assert_eq!(map.len(), 2);
assert!(matches!(map.get_mut::<u32>(), Some(Err(_)))); // deserialization failed, removed from the map.
assert_eq!(map.len(), 1);
assert!(matches!(map.get_mut::<u32>(), None)); // not present in the map anymore
assert_eq!(*map.get_mut::<u16>().unwrap().unwrap(), 42u16); // deserialization successful.Sourcepub fn get_serialized_value<T>(&self) -> Option<&Value>where
T: 'static,
pub fn get_serialized_value<T>(&self) -> Option<&Value>where
T: 'static,
Get the serialized serde_value::Value representation for type T
§Example
use anymap_serde::SerializableAnyMap;
let mut map: SerializableAnyMap = SerializableAnyMap::new();
map.insert(42u16);
assert_eq!(map.get_serialized_value::<u16>().unwrap(), &serde_value::Value::U16(42));Sourcepub fn insert_only_serialized<T>(&mut self, value: Value) -> Option<Item<T>>
pub fn insert_only_serialized<T>(&mut self, value: Value) -> Option<Item<T>>
Insert by type name key.
This is lower-level and useful if you already have a Value, but do not want to defer deserialization to first access.
§Notes
The provided Value needs to match the given match the type name, otherwise the insert will appear to succeed, but will not return the expected value on access.
§Example
use anymap_serde::SerializableAnyMap;
use serde_json::json;
let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom", "u16": 42 })).unwrap();
map.insert_only_serialized::<u32>(serde_value::to_value(json!("boom")).unwrap());
map.insert_only_serialized::<u16>(serde_value::to_value(json!(42)).unwrap());
assert_eq!(map.len(), 2);
assert!(matches!(map.get_mut::<u32>(), Some(Err(_)))); // deserialization failed, removed from the map.
assert_eq!(map.len(), 1);
assert!(matches!(map.get_mut::<u32>(), None)); // not present in the map anymore
assert_eq!(map.get_mut::<u16>().unwrap().unwrap().into_ref(), &42u16); // deserialization successful.Sourcepub fn insert<T>(&mut self, value: T) -> Option<Item<T>>
pub fn insert<T>(&mut self, value: T) -> Option<Item<T>>
Insert a value of type T. Returns the previous value of that type if present.
§Example
use anymap_serde::SerializableAnyMap;
let mut map: SerializableAnyMap = SerializableAnyMap::new();
assert!(map.insert::<u32>(1u32).is_none());
assert_eq!(map.insert::<u32>(2u32).unwrap().get().ok(), Some(&1u32));Sourcepub fn try_insert<'a, T>(
&'a mut self,
value: T,
) -> Result<WriteGuard<'a, T>, OccupiedError<'a, T>>
pub fn try_insert<'a, T>( &'a mut self, value: T, ) -> Result<WriteGuard<'a, T>, OccupiedError<'a, T>>
Tries to insert a value into the map, and returns a mutable reference to the value if successful.
If the map already had this type of value present, nothing is updated, and an error containing the occupied entry and the value is returned.
§Example
use anymap_serde::SerializableAnyMap;
let mut map: SerializableAnyMap = SerializableAnyMap::new();
assert_eq!(map.try_insert::<u32>(1u32).map(|e| e.into_ref()).ok(), Some(&1u32));
assert_eq!(map.try_insert::<u32>(1u32).is_err(), true);Sourcepub fn remove<T>(&mut self) -> Option<T>
pub fn remove<T>(&mut self) -> Option<T>
Remove the stored value of type T, returning it if was present, or None if it was not.
§Example
use anymap_serde::SerializableAnyMap;
use serde_json::json;
let mut map: SerializableAnyMap = SerializableAnyMap::new();
map.insert::<u32>(1u32);
assert_eq!(map.remove::<u32>(), Some(1u32));
assert_eq!(map.remove::<u32>(), None);
let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom" })).unwrap();
assert_eq!(map.remove::<u32>(), None); // Deserialization fails, so it is treated as if it is not present.
Sourcepub fn contains<T>(&self) -> boolwhere
T: 'static,
pub fn contains<T>(&self) -> boolwhere
T: 'static,
Returns true if a value of type T exists in the map (regardless whether already deserialized or not).
§Example
use anymap_serde::SerializableAnyMap;
use serde_json::json;
let mut map: SerializableAnyMap = SerializableAnyMap::new();
assert!(!map.contains::<u32>());
map.insert(1u32);
assert!(map.contains::<u32>());
let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom", "u16": 42 })).unwrap();
assert!(map.contains::<u32>());
assert!(map.contains::<u16>());
Sourcepub fn contains_deserialized<T>(&self) -> boolwhere
T: 'static,
pub fn contains_deserialized<T>(&self) -> boolwhere
T: 'static,
Returns true if a value of type T exists in the map and has already been deserialized
§Example
use anymap_serde::SerializableAnyMap;
use serde_json::json;
let mut map: SerializableAnyMap = SerializableAnyMap::new();
assert!(!map.contains_deserialized::<u32>());
map.insert(1u32);
assert!(map.contains_deserialized::<u32>());
let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom", "u16": 42 })).unwrap();
assert!(!map.contains_deserialized::<u32>());
assert!(!map.contains_deserialized::<u16>());
map.get_mut::<u16>(); // deserialization happens here
assert!(map.contains_deserialized::<u16>());
Sourcepub fn entry<'a, T>(&'a mut self) -> (Entry<'a, T>, Option<DeserializerError>)
pub fn entry<'a, T>(&'a mut self) -> (Entry<'a, T>, Option<DeserializerError>)
Entry API similar to HashMap::entry / anymap3::entry::<T>().
§Example
use anymap_serde::SerializableAnyMap;
let mut map: SerializableAnyMap = SerializableAnyMap::new();
map.insert(1u32);
map.entry::<u32>().0.and_modify(|mut v| *v += 1);
map.entry::<u16>().0.or_insert(42u16);
*map.entry::<u8>().0.or_default().unwrap() += 1;
assert_eq!(map.get::<u32>().unwrap().unwrap(), &2u32);
assert_eq!(map.get::<u16>().unwrap().unwrap(), &42u16);
assert_eq!(map.get::<u8>().unwrap().unwrap(), &1u8);Sourcepub fn keys(&self) -> impl Iterator<Item = &StableTypeId>
pub fn keys(&self) -> impl Iterator<Item = &StableTypeId>
Return an iterator over type-name keys.
Probably not very useful since the keys are opaque StableTypeIds, but here it is anyway.
If anyone has a valid use-case for this, please open an issue.
§Example
use anymap_serde::SerializableAnyMap;
use anymap_serde::StableTypeId;
let mut map: SerializableAnyMap = SerializableAnyMap::new();
map.insert(1u32);
assert_eq!(map.keys().next().unwrap(), &StableTypeId::for_type::<u32>());Sourcepub fn as_raw(&self) -> &HashMap<StableTypeId, RawItem>
pub fn as_raw(&self) -> &HashMap<StableTypeId, RawItem>
Get access to the raw hash map that backs this.
This will seldom be useful, but it’s conceivable that you could wish to iterate over all the items in the collection, and this lets you do that.
Provided to be on parity with anymap3
Sourcepub unsafe fn as_raw_mut(&mut self) -> &mut HashMap<StableTypeId, RawItem>
pub unsafe fn as_raw_mut(&mut self) -> &mut HashMap<StableTypeId, RawItem>
Get mutable access to the raw hash map that backs this.
This will seldom be useful, but it’s conceivable that you could wish to iterate over all the items in the collection mutably, or drain or something, or possibly even batch insert, and this lets you do that.
Provided to be on parity with anymap3
§Safety
If you insert any deserialized values to the raw map, the key must match the
value’s type name as returned by StableTypeId::for_type::<T>(), or undefined behaviour will occur when you access those values.
(Removing entries is perfectly safe.) (Inserting only serialiazed values is perfectly safe - but may disappear if they cannot be deserialized later on access)
Sourcepub fn into_raw(self) -> HashMap<StableTypeId, RawItem>
pub fn into_raw(self) -> HashMap<StableTypeId, RawItem>
Convert this into the raw hash map that backs this.
This will seldom be useful, but it’s conceivable that you could wish to consume all
the items in the collection and do something with some or all of them, and this
lets you do that, without the unsafe that .as_raw_mut().drain() would require.
Provided to be on parity with anymap3
Sourcepub unsafe fn from_raw(
raw: HashMap<StableTypeId, RawItem>,
) -> SerializableAnyMap
pub unsafe fn from_raw( raw: HashMap<StableTypeId, RawItem>, ) -> SerializableAnyMap
Construct a map from a collection of raw values.
You know what? I can’t immediately think of any legitimate use for this.
Perhaps this will be most practical as unsafe { SerializableAnyMap::from_raw(iter.collect()) },
iter being an iterator over (String, Box<dyn Any + Serialize + Deserialize + 'static>) pairs.
Eh, this method provides symmetry with into_raw, so I don’t care if literally no one ever uses it. I’m not
even going to write a test for it, it’s so trivial.
Provided to be on parity with anymap3
§Safety
For all entries in the raw map, the key (a String) must match the value’s type as returned by any::type_name(),
or undefined behaviour will occur when you access that entry.
Trait Implementations§
Source§impl Clone for SerializableAnyMap
impl Clone for SerializableAnyMap
Source§fn clone(&self) -> SerializableAnyMap
fn clone(&self) -> SerializableAnyMap
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for SerializableAnyMap
impl Debug for SerializableAnyMap
Source§impl Default for SerializableAnyMap
impl Default for SerializableAnyMap
Source§fn default() -> SerializableAnyMap
fn default() -> SerializableAnyMap
Source§impl<'de> Deserialize<'de> for SerializableAnyMap
impl<'de> Deserialize<'de> for SerializableAnyMap
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl<A: Any + Serialize + for<'de> Deserialize<'de>> Extend<Box<A>> for SerializableAnyMap
impl<A: Any + Serialize + for<'de> Deserialize<'de>> Extend<Box<A>> for SerializableAnyMap
Source§fn extend<T: IntoIterator<Item = Box<A>>>(&mut self, iter: T)
fn extend<T: IntoIterator<Item = Box<A>>>(&mut self, iter: T)
Source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)