anymap_serde/
lib.rs

1//! A serializable AnyMap-like container keyed by `type_name::<T>()`.
2//! A serializable AnyMap-like container keyed by `type_name::<T>()`.
3//!
4//! This crate provides `SerializableAnyMap`, an AnyMap-compatible container that
5//! stores values in a serializable form (`serde_value::Value`) and optionally
6//! caches a deserialized `Box<dyn Any>` for fast access. Keys are the stable
7//! string returned by `StableTypeId::for_type::<T>()`, not `TypeId`, which makes
8//! the map suitable for sending over the network and reconstructing on another
9//! process / compilation unit.
10//!
11//! Key properties:
12//! - The on-disk / on-wire representation is a `HashMap<String, serde_value::Value>`.
13//! - Deserialized values are stored in-memory only and are not serialized.
14//! - Inserting a value serializes it immediately and stores the value in both forms.
15//! - Deserialization reconstructs only the serialized representation; the cache is empty
16//!   until a lazy access triggers deserialization, since we don't have access to type information
17//!   at collection deserialization time
18//!
19//! # Motivation
20//!
21//! This is useful for extension holders (for example request extensions) where
22//! heterogeneous typed data must be transported and reconstructed remotely.
23//!
24//! Example (illustrative):
25//! ```rust
26//! # use serde::{Serialize, Deserialize};
27//! # use serde_json;
28//! # use anymap_serde::SerializableAnyMap;
29//! #[derive(Serialize, Deserialize, Debug, PartialEq)]
30//! struct Ext { a: u32 }
31//!
32//! let mut map = SerializableAnyMap::new();
33//! map.insert(Ext { a: 10 });
34//!
35//! // Serialize to JSON
36//! let json = serde_json::to_string(&map).unwrap();
37//!
38//! // On the other side, deserialize and access the stored type by `type_name::<T>()`
39//! let mut map2: SerializableAnyMap = serde_json::from_str(&json).unwrap();
40//! let value: &Ext = map2.get::<Ext>().unwrap().unwrap();
41//! assert_eq!(value.a, 10);
42//! ```
43
44#![deny(missing_docs, unused, warnings)]
45
46mod entry;
47mod stable_type_id;
48mod write_guard;
49
50use crate::entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry};
51use crate::write_guard::WriteGuard;
52use serde::{Deserialize, Serialize};
53use serde_value::{Value, to_value};
54pub use stable_type_id::StableTypeId;
55use std::collections::{TryReserveError, hash_map};
56use std::marker::PhantomData;
57use std::{any::Any, collections::HashMap};
58
59/// A serializable heterogeneous-map keyed by a stable value derived from the type.
60///
61/// `SerializableAnyMap` behaves like `anymap3` for most basic use-cases but
62/// stores values in serialized form so the entire map can be serialized and
63/// sent across process boundaries. The map implements `Serialize` and
64/// `Deserialize` where only the serialized form is persisted; the cached
65/// deserialized values are not persisted.
66///
67/// Inserted types must implement `Serialize + Deserialize<'de> + 'static`.
68///
69/// See method docs for usage patterns (`insert`, `get`, `get_mut`, `entry`, …).
70///
71/// Safety notes:
72/// - Some escape hatches (`as_raw_mut`, `from_raw`) are `unsafe` — the caller
73///   must ensure the key string matches the type stored under it.
74///
75/// A stored entry containing the serialized representation and an optional
76/// cached runtime value.
77///
78#[derive(Default, Serialize, Deserialize, Debug, Clone)]
79#[serde(transparent)]
80pub struct SerializableAnyMap {
81    raw: HashMap<StableTypeId, RawItem>,
82}
83
84impl SerializableAnyMap {
85    /// Create a new empty `SerializableAnyMap`.
86    ///
87    /// # Example
88    ///
89    /// ```
90    /// use anymap_serde::SerializableAnyMap;
91    ///
92    /// let mut map = SerializableAnyMap::new();
93    /// map.insert(42u32);
94    /// assert_eq!(map.get::<u32>().unwrap().unwrap(), &42u32);
95    /// ```
96    #[inline]
97    pub fn new() -> Self {
98        Self {
99            raw: HashMap::new(),
100        }
101    }
102
103    /// Creates a new empty map with preallocated space for `capacity` elements.
104    ///
105    /// # Example
106    ///
107    /// ```
108    /// use anymap_serde::SerializableAnyMap;
109    ///
110    /// let mut map = SerializableAnyMap::with_capacity(8);
111    /// assert!(map.capacity() >= 8);
112    /// map.insert(42u32);
113    /// map.insert(42u16);
114    /// map.insert(42u8);
115    /// assert_eq!(map.len(), 3);
116    /// assert!(map.capacity() >= 8);
117    /// ```
118    #[inline]
119    pub fn with_capacity(capacity: usize) -> Self {
120        Self {
121            raw: HashMap::with_capacity(capacity),
122        }
123    }
124
125    /// Returns the number of elements the map can hold without reallocating.
126    ///
127    /// # Example
128    ///
129    /// ```
130    /// use anymap_serde::SerializableAnyMap;
131    ///
132    /// let mut map = SerializableAnyMap::new();
133    /// map.insert(42u32);
134    /// map.insert(42u16);
135    /// map.insert(42u8);
136    /// assert_eq!(map.len(), 3);
137    /// assert!(map.capacity() >= 3);
138    /// ```
139    #[inline]
140    pub fn capacity(&self) -> usize {
141        self.raw.capacity()
142    }
143
144    /// Reserves capacity for at least `additional` more elements to be inserted.
145    /// The collection may reserve more space to avoid frequent reallocations.
146    ///
147    /// # Panics
148    ///
149    /// Panics if the new capacity overflows `usize`.
150    ///
151    /// # Example
152    ///
153    /// ```
154    /// use anymap_serde::SerializableAnyMap;
155    ///
156    /// let mut map = SerializableAnyMap::new();
157    /// map.insert(42u32);
158    /// map.insert(42u16);
159    /// map.insert(42u8);
160    /// map.reserve(5);
161    /// assert!(map.capacity() >= 8);
162    ///
163    /// ```
164    #[inline]
165    pub fn reserve(&mut self, additional: usize) {
166        self.raw.reserve(additional);
167    }
168
169    /// Tries to reserve capacity for at least additional more elements to be inserted in the HashMap.
170    /// The collection may reserve more space to speculatively avoid frequent reallocations.
171    /// After calling try_reserve, capacity will be greater than or equal to self.len() + additional
172    /// if it returns Ok(()). Does nothing if capacity is already sufficient.
173    ///
174    /// # Errors
175    ///
176    /// If the capacity overflows, or the allocator reports a failure, then an error is returned.
177    ///
178    /// # Example
179    ///
180    /// ```
181    /// use anymap_serde::SerializableAnyMap;
182    ///
183    /// let mut map = SerializableAnyMap::new();
184    /// map.insert(42u32);
185    /// map.insert(42u16);
186    /// map.insert(42u8);
187    /// map.try_reserve(5).expect("not to fail");
188    /// assert!(map.capacity() >= 8);
189    ///
190    /// ```
191    #[inline]
192    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
193        self.raw.try_reserve(additional)
194    }
195
196    /// Shrinks the capacity of the collection as much as possible. It will drop
197    /// down as much as possible while maintaining the internal rules
198    /// and possibly leaving some space in accordance with the resize policy.
199    ///
200    /// # Example
201    ///
202    /// ```
203    /// use anymap_serde::SerializableAnyMap;
204    ///
205    /// let mut map = SerializableAnyMap::with_capacity(128);
206    /// map.insert(42u32);
207    /// map.insert(42u16);
208    /// map.insert(42u8);
209    /// map.shrink_to_fit();
210    /// assert_eq!(map.len(), 3);
211    /// assert!(map.capacity() < 128);
212    ///
213    /// ```
214    #[inline]
215    pub fn shrink_to_fit(&mut self) {
216        self.raw.shrink_to_fit()
217    }
218
219    /// Shrinks the capacity of the map with a lower limit. It will drop down no lower than the
220    /// supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
221    /// If the current capacity is less than the lower limit, this is a no-op.
222    ///
223    /// # Example
224    ///
225    /// ```
226    /// use anymap_serde::SerializableAnyMap;
227    ///
228    /// let mut map = SerializableAnyMap::with_capacity(128);
229    /// map.insert(42u32);
230    /// map.insert(42u16);
231    /// map.insert(42u8);
232    /// map.shrink_to(64);
233    /// assert_eq!(map.len(), 3);
234    /// assert!(map.capacity() < 128 );
235    /// assert!(map.capacity() >= 64 );
236    ///
237    /// ```
238    #[inline]
239    pub fn shrink_to(&mut self, min_capcity: usize) {
240        self.raw.shrink_to(min_capcity)
241    }
242
243    /// Returns the number of elements in the map. Note that this may not be the exact number of
244    /// retrievable items, if deserialization of some items fail.
245    ///
246    /// # Example
247    ///
248    /// ```
249    /// use anymap_serde::SerializableAnyMap;
250    ///
251    /// let mut map = SerializableAnyMap::with_capacity(128);
252    /// map.insert(42u32);
253    /// map.insert(42u16);
254    /// map.insert(42u8);
255    /// assert_eq!(map.len(), 3);
256    ///
257    /// ```
258    #[inline]
259    pub fn len(&self) -> usize {
260        self.raw.len()
261    }
262
263    /// Returns true if there are no items in the collection.
264    /// Returns the number of elements in the map. Note that this may not be the exact number of
265    /// retrievable items, if deserialization of some items fail.
266    ///
267    /// # Example
268    ///
269    /// ```
270    /// use anymap_serde::SerializableAnyMap;
271    ///
272    /// let mut map = SerializableAnyMap::with_capacity(128);
273    /// assert_eq!(map.is_empty(), true);
274    /// map.insert(42u16);
275    /// assert_eq!(map.is_empty(), false);
276    ///
277    /// ```
278    #[inline]
279    pub fn is_empty(&self) -> bool {
280        self.raw.is_empty()
281    }
282
283    /// Removes all items from the collection. Keeps the allocated memory for reuse.
284    ///
285    /// # Example
286    ///
287    /// ```
288    /// use anymap_serde::SerializableAnyMap;
289    ///
290    /// let mut map = SerializableAnyMap::with_capacity(128);
291    /// map.insert(42u32);
292    /// map.clear();
293    /// assert_eq!(map.is_empty(), true)
294    ///
295    /// ```
296    #[inline]
297    pub fn clear(&mut self) {
298        self.raw.clear()
299    }
300
301    /// Get an immutable reference to a cached value of type `T` if it exists AND was deserialized.
302    ///
303    /// # Notes
304    ///
305    /// This does NOT lazily deserialize, use [`Self::get`] if you want lazy deserialization.
306    /// This may return None even if the type is present in the map, but not deserialized yet, which
307    /// may happen if the map was deserialized from a serialized form and the type has not yet been accessed.
308    ///
309    /// # Example
310    ///
311    /// ```
312    /// use anymap_serde::SerializableAnyMap;
313    /// use serde_json::json;
314    ///
315    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": 42 })).unwrap();
316    /// map.insert(42u16);
317    /// assert_eq!(map.try_get::<u32>(), None); // not deserialized yet
318    /// assert_eq!(map.try_get::<u16>(), Some(&42u16));
319    /// assert_eq!(map.get::<u32>().unwrap().unwrap(), &42u32); // deserialization happens now
320    /// assert_eq!(map.try_get::<u32>(), Some(&42u32)); // can now be access via try_get as well.
321    /// ```
322    ///
323    #[inline]
324    pub fn try_get<T>(&self) -> Option<&T>
325    where
326        T: for<'de> Deserialize<'de> + Any + 'static,
327    {
328        let key = StableTypeId::for_type::<T>();
329        self.raw.get(&key)?.try_get()
330    }
331
332    /// Get an immutable reference to a value of type `T`, lazily deserializing if necessary.
333    ///
334    /// # Notes
335    ///
336    /// This requires a `&mut self` since it may need to deserialize and modify the entry.
337    /// If the item comes from deserializing the map, this may fail if the deserialization of the item fails.
338    /// In such case the item is removed from subsequent accesses.
339    ///
340    /// # Example
341    ///
342    /// ```
343    /// use anymap_serde::SerializableAnyMap;
344    /// use serde_json::json;
345    ///
346    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom" })).unwrap();
347    /// map.insert(42u16);
348    /// assert_eq!(map.len(), 2);
349    /// assert!(matches!(map.get::<u32>(), Some(Err(_)))); // deserialization failed, removed from the map.
350    /// assert_eq!(map.len(), 1);
351    /// assert!(matches!(map.get::<u32>(), None)); // not present in the map anymore
352    /// assert_eq!(map.get::<u16>().unwrap().ok(), Some(&42u16)); // deserialization successful
353    /// ```
354    #[inline]
355    pub fn get<T>(&mut self) -> Option<Result<&T, serde_value::DeserializerError>>
356    where
357        T: Serialize + for<'de> Deserialize<'de> + 'static,
358    {
359        match self.entry::<T>() {
360            (Entry::Occupied(inner), None) => Some(inner.into_mut().map(|g| g.into_ref())),
361            (Entry::Vacant(_), None) => None,
362            (_, Some(e)) => Some(Err(e)),
363        }
364    }
365
366    /// Gets a copy value of type `T`, by deserializing the value in the map. Note that this will
367    /// *always* return a copy of the item contained in the map, and may lose infomration that is `#[serde(skip)]`.
368    ///
369    /// # Example
370    ///
371    /// ```
372    /// use serde::{Deserialize, Serialize};
373    /// use anymap_serde::SerializableAnyMap;
374    /// use serde_json::from_value;
375    ///
376    /// let mut map: SerializableAnyMap = SerializableAnyMap::new();
377    /// map.insert(42u32);
378    /// assert_eq!(map.get_deserialized_copy::<u32>(), Some(42u32));
379    ///
380    /// #[derive(Debug, PartialEq, Serialize, Deserialize)]
381    /// struct Foo { bar: u32, #[serde(skip)] baz: u32 }
382    /// map.insert(Foo { bar: 42, baz: 43 });
383    /// assert_eq!(map.get_deserialized_copy::<Foo>().unwrap(), Foo { bar: 42, baz: 0}); // deserialization looses `baz` value
384    /// ```
385    #[inline]
386    pub fn get_deserialized_copy<T>(&self) -> Option<T>
387    where
388        T: for<'de> Deserialize<'de> + Any + 'static,
389    {
390        self.get_serialized_value::<T>()
391            .and_then(|v| T::deserialize(v.clone()).ok())
392    }
393
394    /// Get a mutable reference to a value of type `T`, lazily deserializing into the cache if necessary.
395    ///
396    /// # Example
397    ///
398    /// ```
399    /// use anymap_serde::SerializableAnyMap;
400    /// use serde_json::json;
401    ///
402    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom" })).unwrap();
403    /// map.insert(42u16);
404    /// assert_eq!(map.len(), 2);
405    /// assert!(matches!(map.get_mut::<u32>(), Some(Err(_)))); // deserialization failed, removed from the map.
406    /// assert_eq!(map.len(), 1);
407    /// assert!(matches!(map.get_mut::<u32>(), None)); // not present in the map anymore
408    /// assert_eq!(*map.get_mut::<u16>().unwrap().unwrap(), 42u16); // deserialization successful.
409    /// ```
410    pub fn get_mut<T>(
411        &mut self,
412    ) -> Option<Result<WriteGuard<'_, T>, serde_value::DeserializerError>>
413    where
414        T: Serialize + for<'de> Deserialize<'de> + Any + 'static,
415    {
416        match self.entry::<T>() {
417            (Entry::Occupied(inner), None) => Some(inner.into_mut()),
418            (Entry::Vacant(_), None) => None,
419            (_, Some(e)) => Some(Err(e)),
420        }
421    }
422
423    /// Get the serialized [`serde_value::Value`] representation for type `T`
424    ///
425    /// # Example
426    ///
427    /// ```
428    /// use anymap_serde::SerializableAnyMap;
429    ///
430    /// let mut map: SerializableAnyMap = SerializableAnyMap::new();
431    /// map.insert(42u16);
432    /// assert_eq!(map.get_serialized_value::<u16>().unwrap(), &serde_value::Value::U16(42));
433    /// ```
434    #[inline]
435    pub fn get_serialized_value<T>(&self) -> Option<&Value>
436    where
437        T: 'static,
438    {
439        let key = StableTypeId::for_type::<T>();
440        self.raw.get(&key).map(|e| &e.serialized)
441    }
442
443    /// Insert by type name key.
444    ///
445    /// This is lower-level and useful if you already have a Value, but do not want to defer
446    /// deserialization to first access.
447    ///
448    /// # Notes
449    /// The provided Value needs to match the given match the type name, otherwise the insert will
450    /// appear to succeed, but will not return the expected value on access.
451    ///
452    /// # Example
453    ///
454    /// ```
455    /// use anymap_serde::SerializableAnyMap;
456    /// use serde_json::json;
457    ///
458    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom", "u16": 42 })).unwrap();
459    /// map.insert_only_serialized::<u32>(serde_value::to_value(json!("boom")).unwrap());
460    /// map.insert_only_serialized::<u16>(serde_value::to_value(json!(42)).unwrap());
461    ///
462    /// assert_eq!(map.len(), 2);
463    /// assert!(matches!(map.get_mut::<u32>(), Some(Err(_)))); // deserialization failed, removed from the map.
464    /// assert_eq!(map.len(), 1);
465    /// assert!(matches!(map.get_mut::<u32>(), None)); // not present in the map anymore
466    /// assert_eq!(map.get_mut::<u16>().unwrap().unwrap().into_ref(), &42u16); // deserialization successful.
467    /// ```
468    #[inline]
469    pub fn insert_only_serialized<T>(&mut self, value: Value) -> Option<Item<T>> {
470        let key = StableTypeId::for_type::<T>();
471
472        let e = RawItem {
473            serialized: value,
474            value: None,
475        };
476        self.raw.insert(key, e).map(RawItem::wrap)
477    }
478
479    /// Insert a value of type `T`. Returns the previous value of that type if present.
480    ///
481    /// # Example
482    ///
483    /// ```
484    /// use anymap_serde::SerializableAnyMap;
485    ///
486    /// let mut map: SerializableAnyMap = SerializableAnyMap::new();
487    /// assert!(map.insert::<u32>(1u32).is_none());
488    /// assert_eq!(map.insert::<u32>(2u32).unwrap().get().ok(), Some(&1u32));
489    /// ```
490    #[inline]
491    pub fn insert<T>(&mut self, value: T) -> Option<Item<T>>
492    where
493        T: Serialize + for<'de> Deserialize<'de> + Any + 'static,
494    {
495        let key = StableTypeId::for_type::<T>();
496        let serialized = to_value(&value).expect("serialization failed");
497
498        let new_entry = RawItem {
499            serialized,
500            value: Some(Box::new(value)),
501        };
502        self.raw.insert(key, new_entry).map(RawItem::wrap)
503    }
504
505    /// Tries to insert a value into the map, and returns
506    /// a mutable reference to the value if successful.
507    ///
508    /// If the map already had this type of value present, nothing is updated, and
509    /// an error containing the occupied entry and the value is returned.
510    ///
511    /// # Example
512    ///
513    /// ```
514    /// use anymap_serde::SerializableAnyMap;
515    ///
516    /// let mut map: SerializableAnyMap = SerializableAnyMap::new();
517    /// assert_eq!(map.try_insert::<u32>(1u32).map(|e| e.into_ref()).ok(), Some(&1u32));
518    /// assert_eq!(map.try_insert::<u32>(1u32).is_err(), true);
519    /// ```
520    pub fn try_insert<'a, T>(
521        &'a mut self,
522        value: T,
523    ) -> Result<WriteGuard<'a, T>, OccupiedError<'a, T>>
524    where
525        T: Serialize + for<'de> Deserialize<'de> + Any + 'static,
526    {
527        match self.entry::<T>().0 {
528            Entry::Occupied(entry) => Err(OccupiedError { entry, value }),
529            Entry::Vacant(entry) => Ok(entry.insert(value)),
530        }
531    }
532
533    /// Remove the stored value of type `T`, returning it if was present, or None if it was not.
534    ///
535    /// # Example
536    ///
537    /// ```
538    /// use anymap_serde::SerializableAnyMap;
539    /// use serde_json::json;
540    ///
541    /// let mut map: SerializableAnyMap = SerializableAnyMap::new();
542    /// map.insert::<u32>(1u32);
543    /// assert_eq!(map.remove::<u32>(), Some(1u32));
544    /// assert_eq!(map.remove::<u32>(), None);
545    ///
546    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom" })).unwrap();
547    /// assert_eq!(map.remove::<u32>(), None); // Deserialization fails, so it is treated as if it is not present.
548    ///
549    /// ```
550    #[inline]
551    pub fn remove<T>(&mut self) -> Option<T>
552    where
553        T: Serialize + for<'de> Deserialize<'de> + Any + 'static,
554    {
555        let key = StableTypeId::for_type::<T>();
556        self.raw
557            .remove(&key)
558            .and_then(|item| item.into_inner().ok())
559    }
560
561    /// Returns true if a value of type `T` exists in the map (regardless whether already deserialized or not).
562    ///
563    /// # Example
564    ///
565    /// ```
566    /// use anymap_serde::SerializableAnyMap;
567    /// use serde_json::json;
568    ///
569    /// let mut map: SerializableAnyMap = SerializableAnyMap::new();
570    /// assert!(!map.contains::<u32>());
571    /// map.insert(1u32);
572    /// assert!(map.contains::<u32>());
573    ///
574    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom", "u16": 42 })).unwrap();
575    /// assert!(map.contains::<u32>());
576    /// assert!(map.contains::<u16>());
577    ///
578    /// ```
579    #[inline]
580    pub fn contains<T>(&self) -> bool
581    where
582        T: 'static,
583    {
584        let key = StableTypeId::for_type::<T>();
585        self.raw.contains_key(&key)
586    }
587
588    /// Returns true if a value of type `T` exists in the map and has already been deserialized
589    ///
590    /// # Example
591    ///
592    /// ```
593    /// use anymap_serde::SerializableAnyMap;
594    /// use serde_json::json;
595    ///
596    /// let mut map: SerializableAnyMap = SerializableAnyMap::new();
597    /// assert!(!map.contains_deserialized::<u32>());
598    /// map.insert(1u32);
599    /// assert!(map.contains_deserialized::<u32>());
600    ///
601    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom", "u16": 42 })).unwrap();
602    /// assert!(!map.contains_deserialized::<u32>());
603    /// assert!(!map.contains_deserialized::<u16>());
604    /// map.get_mut::<u16>(); // deserialization happens here
605    /// assert!(map.contains_deserialized::<u16>());
606    ///
607    /// ```
608    #[inline]
609    pub fn contains_deserialized<T>(&self) -> bool
610    where
611        T: 'static,
612    {
613        let key = StableTypeId::for_type::<T>();
614        self.raw
615            .get(&key)
616            .map(|e| e.value.is_some())
617            .unwrap_or(false)
618    }
619
620    /// Entry API similar to `HashMap::entry` / `anymap3::entry::<T>()`.
621    ///
622    /// # Example
623    ///
624    /// ```
625    /// use anymap_serde::SerializableAnyMap;
626    ///
627    /// let mut map: SerializableAnyMap = SerializableAnyMap::new();
628    /// map.insert(1u32);
629    /// map.entry::<u32>().0.and_modify(|mut v| *v += 1);
630    /// map.entry::<u16>().0.or_insert(42u16);
631    /// *map.entry::<u8>().0.or_default().unwrap() += 1;
632    ///
633    /// assert_eq!(map.get::<u32>().unwrap().unwrap(), &2u32);
634    /// assert_eq!(map.get::<u16>().unwrap().unwrap(), &42u16);
635    /// assert_eq!(map.get::<u8>().unwrap().unwrap(), &1u8);
636    /// ```
637    #[inline]
638    pub fn entry<'a, T>(&'a mut self) -> (Entry<'a, T>, Option<serde_value::DeserializerError>)
639    where
640        T: Serialize + for<'de> Deserialize<'de> + Any + 'static,
641    {
642        let key = StableTypeId::for_type::<T>();
643
644        let err = match self.raw.entry(key.clone()) {
645            hash_map::Entry::Occupied(mut inner) => inner.get_mut().get_mut::<T>().err(),
646            _ => None,
647        };
648
649        if err.is_some() {
650            self.raw.remove(&key);
651        }
652
653        match self.raw.entry(key) {
654            hash_map::Entry::Occupied(inner) => (Entry::Occupied(OccupiedEntry::new(inner)), err),
655            hash_map::Entry::Vacant(inner) => (Entry::Vacant(VacantEntry::new(inner)), err),
656        }
657    }
658
659    /// Return an iterator over type-name keys.
660    ///
661    /// Probably not very useful since the keys are opaque `StableTypeId`s, but here it is anyway.
662    /// If anyone has a valid use-case for this, please open an issue.
663    ///
664    /// # Example
665    ///
666    /// ```
667    /// use anymap_serde::SerializableAnyMap;
668    /// use anymap_serde::StableTypeId;
669    ///
670    /// let mut map: SerializableAnyMap = SerializableAnyMap::new();
671    /// map.insert(1u32);
672    ///
673    /// assert_eq!(map.keys().next().unwrap(), &StableTypeId::for_type::<u32>());
674    /// ```
675    pub fn keys(&self) -> impl Iterator<Item = &StableTypeId> {
676        self.raw.keys()
677    }
678
679    /// Get access to the raw hash map that backs this.
680    ///
681    /// This will seldom be useful, but it’s conceivable that you could wish to iterate
682    /// over all the items in the collection, and this lets you do that.
683    ///
684    /// Provided to be on parity with anymap3
685    #[inline]
686    pub fn as_raw(&self) -> &HashMap<StableTypeId, RawItem> {
687        &self.raw
688    }
689
690    /// Get mutable access to the raw hash map that backs this.
691    ///
692    /// This will seldom be useful, but it’s conceivable that you could wish to iterate
693    /// over all the items in the collection mutably, or drain or something, or *possibly*
694    /// even batch insert, and this lets you do that.
695    ///
696    /// Provided to be on parity with anymap3
697    ///
698    /// # Safety
699    ///
700    /// If you insert any deserialized values to the raw map, the key must match the
701    /// value’s type name as returned by [`StableTypeId::for_type::<T>()`], or *undefined behaviour* will occur when you access those values.
702    ///
703    /// (*Removing* entries is perfectly safe.)
704    /// (*Inserting only serialiazed values* is perfectly safe - but may disappear if they cannot be deserialized later on access)
705    ///
706    #[inline]
707    pub unsafe fn as_raw_mut(&mut self) -> &mut HashMap<StableTypeId, RawItem> {
708        &mut self.raw
709    }
710
711    /// Convert this into the raw hash map that backs this.
712    ///
713    /// This will seldom be useful, but it’s conceivable that you could wish to consume all
714    /// the items in the collection and do *something* with some or all of them, and this
715    /// lets you do that, without the `unsafe` that `.as_raw_mut().drain()` would require.
716    ///
717    /// Provided to be on parity with anymap3
718    #[inline]
719    pub fn into_raw(self) -> HashMap<StableTypeId, RawItem> {
720        self.raw
721    }
722
723    /// Construct a map from a collection of raw values.
724    ///
725    /// You know what? I can’t immediately think of any legitimate use for this.
726    ///
727    /// Perhaps this will be most practical as `unsafe { SerializableAnyMap::from_raw(iter.collect()) }`,
728    /// `iter` being an iterator over `(String, Box<dyn Any + Serialize + Deserialize + 'static>)` pairs.
729    /// Eh, this method provides symmetry with `into_raw`, so I don’t care if literally no one ever uses it. I’m not
730    /// even going to write a test for it, it’s so trivial.
731    ///
732    /// Provided to be on parity with anymap3
733    ///
734    /// # Safety
735    ///
736    /// For all entries in the raw map, the key (a `String`) must match the value’s type as returned by any::type_name(),
737    /// or *undefined behaviour* will occur when you access that entry.
738    #[inline]
739    pub unsafe fn from_raw(raw: HashMap<StableTypeId, RawItem>) -> SerializableAnyMap {
740        Self { raw }
741    }
742}
743
744impl<A: Any + Serialize + for<'de> Deserialize<'de>> Extend<Box<A>> for SerializableAnyMap {
745    #[inline]
746    fn extend<T: IntoIterator<Item = Box<A>>>(&mut self, iter: T) {
747        for item in iter {
748            let serialized = to_value(&*item).expect("serialization failed");
749            let _ = self.raw.insert(
750                StableTypeId::for_type::<T>(),
751                RawItem {
752                    serialized,
753                    value: Some(item),
754                },
755            );
756        }
757    }
758}
759
760/// A stored entry containing the serialized representation and an optional
761/// cached runtime value.
762///
763/// - `serialized`: the `serde_value::Value` used for Serialize/Deserialize of the map.
764/// - `value`: an optional `Box<dyn Any>` holding the deserialized value. This field is not
765///   serialized and is cleared on `Clone` and `Deserialize`.
766///
767/// Semantics:
768/// - On `insert`, both `serialized` and `value` are populated.
769/// - On access (`get`/`get_mut`), the entry will lazily deserialize `serialized` into
770///   `value` if the cache is empty.
771/// - `into_inner` attempts to extract the concrete type from the cache or by deserializing.
772///
773/// Notes:
774/// - The cloning, serialization and deserialization happens based on the serialized `serde_value::Value`, so
775///   any modifications to fields that are marked `#[serde(skip)]` will not be lost after a serialization
776///   round-trip, or after cloning the map.
777/// - Currently any modifications to the cached `value` are not reflected back into the `serialized` form, so
778///   serialization WILL reflect the original value only. This is a known limitation and is planned to be
779///   addressed in a future version by returning a Guard object that will update the serialized value on Drop.
780#[derive(Serialize, Deserialize, Debug)]
781#[serde(transparent)]
782pub struct RawItem {
783    serialized: Value,
784
785    /// value runtime representation; skipped during (de)serialization.
786    #[serde(skip)]
787    #[serde(default)]
788    value: Option<Box<dyn Any>>,
789}
790
791impl Clone for RawItem {
792    fn clone(&self) -> Self {
793        RawItem {
794            serialized: self.serialized.clone(),
795            value: None, // do not clone cached value
796        }
797    }
798}
799
800///TODO Docuemnt
801pub struct Item<T>(RawItem, PhantomData<T>);
802
803impl<T> Item<T> {
804    /// Attempt to get an immutable reference to the deserialized value of type `T`. Will return None
805    /// if the value has not yet been deserialized, as we need a mutable reference to mutate the
806    /// entry to save the deserialized value.
807    ///
808    /// # Example
809    ///
810    /// ```
811    /// use anymap_serde::SerializableAnyMap;
812    /// use serde_json::json;
813    ///
814    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u16": 42 })).unwrap();
815    /// let mut old = map.insert(43u16).unwrap();
816    ///
817    /// assert_eq!(old.try_get(), None); // not deserialized yet
818    /// old.get(); // Trigger deserialization
819    /// assert_eq!(old.try_get(), Some(&42));
820    /// ```
821    ///
822    pub fn try_get(&self) -> Option<&T>
823    where
824        T: for<'de> Deserialize<'de> + 'static,
825    {
826        self.0.value.as_ref()?.downcast_ref::<T>()
827    }
828
829    /// Attempt to get an immutable reference to the deserialized value of type `T`,
830    /// lazily deserializing if necessary. We need a mutable reference in order to save the
831    /// deserialized value to the entry
832    ///
833    /// # Example
834    ///
835    /// ```
836    /// use anymap_serde::SerializableAnyMap;
837    /// use serde_json::json;
838    ///
839    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": 42 })).unwrap();
840    /// let mut old = map.insert(43u32).unwrap();
841    ///
842    /// assert_eq!(old.get().ok(), Some(&42));
843    ///
844    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": "boom" })).unwrap();
845    /// let mut old = map.insert(43u32).unwrap();
846    ///
847    /// assert_eq!(old.get().is_err(), true);
848    /// assert_eq!(old.get().is_err(), true);
849    /// ```
850    pub fn get(&mut self) -> Result<&T, serde_value::DeserializerError>
851    where
852        T: Serialize + for<'de> Deserialize<'de> + 'static,
853    {
854        self.0.get_mut().map(|x: WriteGuard<T>| x.into_ref())
855    }
856
857    /// Attempt to an mutable reference to the deserialized value of type `T`,
858    /// lazily deserializing if necessary.
859    ///
860    /// # Example
861    ///
862    /// ```
863    /// use anymap_serde::SerializableAnyMap;
864    /// use serde_json::json;
865    /// use std::ops::DerefMut;
866    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u16": 42 })).unwrap();
867    ///
868    /// let mut old = map.insert(43u16).unwrap();
869    ///
870    /// *old.get_mut().unwrap() += 100;
871    ///
872    /// assert_eq!(old.get_mut().unwrap().deref_mut(), &mut 142u16);
873    /// ```
874    pub fn get_mut<'a>(&'a mut self) -> Result<WriteGuard<'a, T>, serde_value::DeserializerError>
875    where
876        T: for<'de> Deserialize<'de> + Serialize + 'static,
877    {
878        if self.0.value.is_none() {
879            let deserialized = T::deserialize(self.0.serialized.clone())?;
880            self.0.value = Some(Box::new(deserialized));
881        }
882
883        Ok(WriteGuard::new(&mut self.0))
884    }
885
886    /// Attempt to extract the inner value by deserializing if necessary.
887    ///
888    /// # Example
889    ///
890    /// ```
891    /// use anymap_serde::SerializableAnyMap;
892    /// use serde_json::json;
893    ///
894    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": 42 })).unwrap();
895    /// let item = map.insert(41u32).unwrap();
896    ///
897    /// assert_eq!(item.into_inner().unwrap(), 42u32);
898    /// ```
899    pub fn into_inner(mut self) -> Result<T, serde_value::DeserializerError>
900    where
901        T: for<'de> Deserialize<'de> + 'static,
902    {
903        self.0
904            .value
905            .take()
906            .map(|a| Ok(*a.downcast::<T>().unwrap()))
907            .unwrap_or_else(|| T::deserialize(self.0.serialized))
908    }
909}
910
911impl RawItem {
912    /// Attempt to get an immutable reference to the deserialized value of type `T`. Will return None
913    /// if the value has not yet been deserialized, as we need a mutable reference to mutate the
914    /// entry to save the deserialized value.
915    ///
916    /// # Example
917    ///
918    /// ```
919    /// use anymap_serde::SerializableAnyMap;
920    /// use serde_json::json;
921    ///
922    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": 42 })).unwrap();
923    ///
924    /// let mut item = map.insert(43u32).unwrap();
925    ///
926    /// assert_eq!(item.try_get(), None); // Not yet deserialized
927    /// item.get(); // Trigger deserialization
928    /// assert_eq!(item.try_get(), Some(&42u32));
929    /// ```
930    ///
931    fn try_get<T>(&self) -> Option<&T>
932    where
933        T: for<'de> Deserialize<'de> + 'static,
934    {
935        self.value.as_ref()?.downcast_ref::<T>()
936    }
937
938    /// Attempt to get an immutable reference to the deserialized value of type `T`,
939    /// lazily deserializing if necessary. We need a mutable reference in order to save the
940    /// deserialized value to the entry
941    ///
942    /// # Example
943    ///
944    /// ```
945    /// use anymap_serde::SerializableAnyMap;
946    /// use serde_json::json;
947    ///
948    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": 42 })).unwrap();
949    /// let mut item = map.insert(43u32).unwrap();
950    ///
951    /// assert_eq!(item.get().unwrap(), &42); // Deserializes value on demand
952    /// ```
953    fn get<T>(&mut self) -> Result<&T, serde_value::DeserializerError>
954    where
955        T: Serialize + for<'de> Deserialize<'de> + 'static,
956    {
957        self.get_mut().map(|x: WriteGuard<T>| x.into_ref())
958    }
959
960    /// Attempt to an mutable reference to the deserialized value of type `T`,
961    /// lazily deserializing if necessary.
962    ///
963    /// # Example
964    ///
965    /// ```
966    /// use anymap_serde::SerializableAnyMap;
967    /// use serde_json::json;
968    ///
969    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": 42 })).unwrap();
970    ///
971    /// let mut item = map.insert(43u32).unwrap();
972    ///
973    /// *item.get_mut().unwrap() += 100;
974    ///
975    /// assert_eq!(item.get().unwrap(), &mut 142); // Deserializes value on demand
976    /// ```
977    fn get_mut<'a, T>(&'a mut self) -> Result<WriteGuard<'a, T>, serde_value::DeserializerError>
978    where
979        T: for<'de> Deserialize<'de> + Serialize + 'static,
980    {
981        if self.value.is_none() {
982            let deserialized = T::deserialize(self.serialized.clone())?;
983            self.value = Some(Box::new(deserialized));
984        }
985
986        Ok(WriteGuard::new(self))
987    }
988
989    /// Attempt to extract the inner value by deserializing if necessary.
990    ///
991    /// # Example
992    ///
993    /// ```
994    /// use anymap_serde::SerializableAnyMap;
995    /// use serde_json::json;
996    ///
997    /// let mut map: SerializableAnyMap = serde_json::from_value(json!({ "u32": 42 })).unwrap();
998    /// let item = map.insert(42u32).unwrap();
999    ///
1000    /// assert_eq!(item.into_inner().unwrap(), 42);
1001    /// ```
1002    fn into_inner<T>(mut self) -> Result<T, serde_value::DeserializerError>
1003    where
1004        T: for<'de> Deserialize<'de> + 'static,
1005    {
1006        self.value
1007            .take()
1008            .map(|a| Ok(*a.downcast::<T>().unwrap()))
1009            .unwrap_or_else(|| T::deserialize(self.serialized))
1010    }
1011
1012    fn wrap<T>(self) -> Item<T> {
1013        Item(self, PhantomData)
1014    }
1015}