SerializableAnyMap

Struct SerializableAnyMap 

Source
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) are unsafe — 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

Source

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);
Source

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);
Source

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);
Source

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);
Source

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);
Source

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);
Source

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 );
Source

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);
Source

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);
Source

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)
Source

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.
Source

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 successful
Source

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` value
Source

pub fn get_mut<T>( &mut self, ) -> Option<Result<WriteGuard<'_, T>, DeserializerError>>
where T: Serialize + for<'de> Deserialize<'de> + Any + 'static,

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.
Source

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));
Source

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.
Source

pub fn insert<T>(&mut self, value: T) -> Option<Item<T>>
where T: Serialize + for<'de> Deserialize<'de> + Any + 'static,

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));
Source

pub fn try_insert<'a, T>( &'a mut self, value: T, ) -> Result<WriteGuard<'a, T>, OccupiedError<'a, T>>
where T: Serialize + for<'de> Deserialize<'de> + Any + 'static,

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);
Source

pub fn remove<T>(&mut self) -> Option<T>
where T: Serialize + for<'de> Deserialize<'de> + Any + 'static,

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.
Source

pub fn contains<T>(&self) -> bool
where 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>());
Source

pub fn contains_deserialized<T>(&self) -> bool
where 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>());
Source

pub fn entry<'a, T>(&'a mut self) -> (Entry<'a, T>, Option<DeserializerError>)
where T: Serialize + for<'de> Deserialize<'de> + Any + 'static,

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);
Source

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>());
Source

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

Source

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)

Source

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

Source

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

Source§

fn clone(&self) -> SerializableAnyMap

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SerializableAnyMap

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for SerializableAnyMap

Source§

fn default() -> SerializableAnyMap

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for SerializableAnyMap

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

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)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl Serialize for SerializableAnyMap

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,