stable_map/occupied_error.rs
1use {
2 crate::entry::OccupiedEntry,
3 core::fmt::{Debug, Display, Formatter},
4};
5
6/// The error returned by [`try_insert`](crate::StableMap::try_insert) when the key already exists.
7///
8/// Contains the occupied entry, and the value that was not inserted.
9///
10/// # Examples
11///
12/// ```
13/// use stable_map::{OccupiedError, StableMap};
14///
15/// let mut map: StableMap<_, _> = [("a", 10), ("b", 20)].into();
16///
17/// // try_insert method returns mutable reference to the value if keys are vacant,
18/// // but if the map did have key present, nothing is updated, and the provided
19/// // value is returned inside `Err(_)` variant
20/// match map.try_insert("a", 100) {
21/// Err(OccupiedError { mut entry, value }) => {
22/// assert_eq!(entry.key(), &"a");
23/// assert_eq!(value, 100);
24/// assert_eq!(entry.insert(100), 10)
25/// }
26/// _ => unreachable!(),
27/// }
28/// assert_eq!(map[&"a"], 100);
29/// ```
30pub struct OccupiedError<'a, K, V, S> {
31 /// The entry in the map that was already occupied.
32 pub entry: OccupiedEntry<'a, K, V, S>,
33 /// The value which was not inserted, because the entry was already occupied.
34 pub value: V,
35}
36
37impl<K, V, S> Debug for OccupiedError<'_, K, V, S>
38where
39 K: Debug,
40 V: Debug,
41{
42 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
43 f.debug_struct("OccupiedError")
44 .field("key", self.entry.key())
45 .field("old_value", self.entry.get())
46 .field("new_value", &self.value)
47 .finish()
48 }
49}
50
51impl<K, V, S> Display for OccupiedError<'_, K, V, S>
52where
53 K: Debug,
54 V: Debug,
55{
56 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
57 write!(
58 f,
59 "failed to insert {:?}, key {:?} already exists with value {:?}",
60 self.value,
61 self.entry.key(),
62 self.entry.get(),
63 )
64 }
65}