alloc/collections/btree/map/
entry.rs

1use core::fmt::{self, Debug};
2use core::marker::PhantomData;
3use core::mem;
4
5use Entry::*;
6
7use super::super::borrow::DormantMutRef;
8use super::super::node::{Handle, NodeRef, marker};
9use super::BTreeMap;
10use crate::alloc::{Allocator, Global};
11
12/// A view into a single entry in a map, which may either be vacant or occupied.
13///
14/// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
15///
16/// [`entry`]: BTreeMap::entry
17#[stable(feature = "rust1", since = "1.0.0")]
18#[cfg_attr(not(test), rustc_diagnostic_item = "BTreeEntry")]
19pub enum Entry<
20    'a,
21    K: 'a,
22    V: 'a,
23    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
24> {
25    /// A vacant entry.
26    #[stable(feature = "rust1", since = "1.0.0")]
27    Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V, A>),
28
29    /// An occupied entry.
30    #[stable(feature = "rust1", since = "1.0.0")]
31    Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V, A>),
32}
33
34#[stable(feature = "debug_btree_map", since = "1.12.0")]
35impl<K: Debug + Ord, V: Debug, A: Allocator + Clone> Debug for Entry<'_, K, V, A> {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match *self {
38            Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
39            Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
40        }
41    }
42}
43
44/// A view into a vacant entry in a `BTreeMap`.
45/// It is part of the [`Entry`] enum.
46#[stable(feature = "rust1", since = "1.0.0")]
47pub struct VacantEntry<
48    'a,
49    K,
50    V,
51    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
52> {
53    pub(super) key: K,
54    /// `None` for a (empty) map without root
55    pub(super) handle: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
56    pub(super) dormant_map: DormantMutRef<'a, BTreeMap<K, V, A>>,
57
58    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
59    pub(super) alloc: A,
60
61    // Be invariant in `K` and `V`
62    pub(super) _marker: PhantomData<&'a mut (K, V)>,
63}
64
65#[stable(feature = "debug_btree_map", since = "1.12.0")]
66impl<K: Debug + Ord, V, A: Allocator + Clone> Debug for VacantEntry<'_, K, V, A> {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.debug_tuple("VacantEntry").field(self.key()).finish()
69    }
70}
71
72/// A view into an occupied entry in a `BTreeMap`.
73/// It is part of the [`Entry`] enum.
74#[stable(feature = "rust1", since = "1.0.0")]
75pub struct OccupiedEntry<
76    'a,
77    K,
78    V,
79    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + Clone = Global,
80> {
81    pub(super) handle: Handle<NodeRef<marker::Mut<'a>, K, V, marker::LeafOrInternal>, marker::KV>,
82    pub(super) dormant_map: DormantMutRef<'a, BTreeMap<K, V, A>>,
83
84    /// The BTreeMap will outlive this IntoIter so we don't care about drop order for `alloc`.
85    pub(super) alloc: A,
86
87    // Be invariant in `K` and `V`
88    pub(super) _marker: PhantomData<&'a mut (K, V)>,
89}
90
91#[stable(feature = "debug_btree_map", since = "1.12.0")]
92impl<K: Debug + Ord, V: Debug, A: Allocator + Clone> Debug for OccupiedEntry<'_, K, V, A> {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
95    }
96}
97
98/// The error returned by [`try_insert`](BTreeMap::try_insert) when the key already exists.
99///
100/// Contains the occupied entry, and the value that was not inserted.
101#[unstable(feature = "map_try_insert", issue = "82766")]
102pub struct OccupiedError<'a, K: 'a, V: 'a, A: Allocator + Clone = Global> {
103    /// The entry in the map that was already occupied.
104    pub entry: OccupiedEntry<'a, K, V, A>,
105    /// The value which was not inserted, because the entry was already occupied.
106    pub value: V,
107}
108
109#[unstable(feature = "map_try_insert", issue = "82766")]
110impl<K: Debug + Ord, V: Debug, A: Allocator + Clone> Debug for OccupiedError<'_, K, V, A> {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        f.debug_struct("OccupiedError")
113            .field("key", self.entry.key())
114            .field("old_value", self.entry.get())
115            .field("new_value", &self.value)
116            .finish()
117    }
118}
119
120#[unstable(feature = "map_try_insert", issue = "82766")]
121impl<'a, K: Debug + Ord, V: Debug, A: Allocator + Clone> fmt::Display
122    for OccupiedError<'a, K, V, A>
123{
124    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125        write!(
126            f,
127            "failed to insert {:?}, key {:?} already exists with value {:?}",
128            self.value,
129            self.entry.key(),
130            self.entry.get(),
131        )
132    }
133}
134
135#[unstable(feature = "map_try_insert", issue = "82766")]
136impl<'a, K: core::fmt::Debug + Ord, V: core::fmt::Debug> core::error::Error
137    for crate::collections::btree_map::OccupiedError<'a, K, V>
138{
139}
140
141impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> {
142    /// Ensures a value is in the entry by inserting the default if empty, and returns
143    /// a mutable reference to the value in the entry.
144    ///
145    /// # Examples
146    ///
147    /// ```
148    /// use std::collections::BTreeMap;
149    ///
150    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
151    /// map.entry("poneyland").or_insert(12);
152    ///
153    /// assert_eq!(map["poneyland"], 12);
154    /// ```
155    #[stable(feature = "rust1", since = "1.0.0")]
156    pub fn or_insert(self, default: V) -> &'a mut V {
157        match self {
158            Occupied(entry) => entry.into_mut(),
159            Vacant(entry) => entry.insert(default),
160        }
161    }
162
163    /// Ensures a value is in the entry by inserting the result of the default function if empty,
164    /// and returns a mutable reference to the value in the entry.
165    ///
166    /// # Examples
167    ///
168    /// ```
169    /// use std::collections::BTreeMap;
170    ///
171    /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
172    /// let s = "hoho".to_string();
173    ///
174    /// map.entry("poneyland").or_insert_with(|| s);
175    ///
176    /// assert_eq!(map["poneyland"], "hoho".to_string());
177    /// ```
178    #[stable(feature = "rust1", since = "1.0.0")]
179    pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
180        match self {
181            Occupied(entry) => entry.into_mut(),
182            Vacant(entry) => entry.insert(default()),
183        }
184    }
185
186    /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
187    ///
188    /// This method allows for generating key-derived values for insertion by providing the default
189    /// function a reference to the key that was moved during the `.entry(key)` method call.
190    ///
191    /// The reference to the moved key is provided so that cloning or copying the key is
192    /// unnecessary, unlike with `.or_insert_with(|| ... )`.
193    ///
194    /// # Examples
195    ///
196    /// ```
197    /// use std::collections::BTreeMap;
198    ///
199    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
200    ///
201    /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
202    ///
203    /// assert_eq!(map["poneyland"], 9);
204    /// ```
205    #[inline]
206    #[stable(feature = "or_insert_with_key", since = "1.50.0")]
207    pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
208        match self {
209            Occupied(entry) => entry.into_mut(),
210            Vacant(entry) => {
211                let value = default(entry.key());
212                entry.insert(value)
213            }
214        }
215    }
216
217    /// Returns a reference to this entry's key.
218    ///
219    /// # Examples
220    ///
221    /// ```
222    /// use std::collections::BTreeMap;
223    ///
224    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
225    /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
226    /// ```
227    #[stable(feature = "map_entry_keys", since = "1.10.0")]
228    pub fn key(&self) -> &K {
229        match *self {
230            Occupied(ref entry) => entry.key(),
231            Vacant(ref entry) => entry.key(),
232        }
233    }
234
235    /// Provides in-place mutable access to an occupied entry before any
236    /// potential inserts into the map.
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// use std::collections::BTreeMap;
242    ///
243    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
244    ///
245    /// map.entry("poneyland")
246    ///    .and_modify(|e| { *e += 1 })
247    ///    .or_insert(42);
248    /// assert_eq!(map["poneyland"], 42);
249    ///
250    /// map.entry("poneyland")
251    ///    .and_modify(|e| { *e += 1 })
252    ///    .or_insert(42);
253    /// assert_eq!(map["poneyland"], 43);
254    /// ```
255    #[stable(feature = "entry_and_modify", since = "1.26.0")]
256    pub fn and_modify<F>(self, f: F) -> Self
257    where
258        F: FnOnce(&mut V),
259    {
260        match self {
261            Occupied(mut entry) => {
262                f(entry.get_mut());
263                Occupied(entry)
264            }
265            Vacant(entry) => Vacant(entry),
266        }
267    }
268
269    /// Sets the value of the entry, and returns an `OccupiedEntry`.
270    ///
271    /// # Examples
272    ///
273    /// ```
274    /// use std::collections::BTreeMap;
275    ///
276    /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
277    /// let entry = map.entry("poneyland").insert_entry("hoho".to_string());
278    ///
279    /// assert_eq!(entry.key(), &"poneyland");
280    /// ```
281    #[inline]
282    #[stable(feature = "btree_entry_insert", since = "CURRENT_RUSTC_VERSION")]
283    pub fn insert_entry(self, value: V) -> OccupiedEntry<'a, K, V, A> {
284        match self {
285            Occupied(mut entry) => {
286                entry.insert(value);
287                entry
288            }
289            Vacant(entry) => entry.insert_entry(value),
290        }
291    }
292}
293
294impl<'a, K: Ord, V: Default, A: Allocator + Clone> Entry<'a, K, V, A> {
295    #[stable(feature = "entry_or_default", since = "1.28.0")]
296    /// Ensures a value is in the entry by inserting the default value if empty,
297    /// and returns a mutable reference to the value in the entry.
298    ///
299    /// # Examples
300    ///
301    /// ```
302    /// use std::collections::BTreeMap;
303    ///
304    /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
305    /// map.entry("poneyland").or_default();
306    ///
307    /// assert_eq!(map["poneyland"], None);
308    /// ```
309    pub fn or_default(self) -> &'a mut V {
310        match self {
311            Occupied(entry) => entry.into_mut(),
312            Vacant(entry) => entry.insert(Default::default()),
313        }
314    }
315}
316
317impl<'a, K: Ord, V, A: Allocator + Clone> VacantEntry<'a, K, V, A> {
318    /// Gets a reference to the key that would be used when inserting a value
319    /// through the VacantEntry.
320    ///
321    /// # Examples
322    ///
323    /// ```
324    /// use std::collections::BTreeMap;
325    ///
326    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
327    /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
328    /// ```
329    #[stable(feature = "map_entry_keys", since = "1.10.0")]
330    pub fn key(&self) -> &K {
331        &self.key
332    }
333
334    /// Take ownership of the key.
335    ///
336    /// # Examples
337    ///
338    /// ```
339    /// use std::collections::BTreeMap;
340    /// use std::collections::btree_map::Entry;
341    ///
342    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
343    ///
344    /// if let Entry::Vacant(v) = map.entry("poneyland") {
345    ///     v.into_key();
346    /// }
347    /// ```
348    #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
349    pub fn into_key(self) -> K {
350        self.key
351    }
352
353    /// Sets the value of the entry with the `VacantEntry`'s key,
354    /// and returns a mutable reference to it.
355    ///
356    /// # Examples
357    ///
358    /// ```
359    /// use std::collections::BTreeMap;
360    /// use std::collections::btree_map::Entry;
361    ///
362    /// let mut map: BTreeMap<&str, u32> = BTreeMap::new();
363    ///
364    /// if let Entry::Vacant(o) = map.entry("poneyland") {
365    ///     o.insert(37);
366    /// }
367    /// assert_eq!(map["poneyland"], 37);
368    /// ```
369    #[stable(feature = "rust1", since = "1.0.0")]
370    #[rustc_confusables("push", "put")]
371    pub fn insert(self, value: V) -> &'a mut V {
372        self.insert_entry(value).into_mut()
373    }
374
375    /// Sets the value of the entry with the `VacantEntry`'s key,
376    /// and returns an `OccupiedEntry`.
377    ///
378    /// # Examples
379    ///
380    /// ```
381    /// use std::collections::BTreeMap;
382    /// use std::collections::btree_map::Entry;
383    ///
384    /// let mut map: BTreeMap<&str, u32> = BTreeMap::new();
385    ///
386    /// if let Entry::Vacant(o) = map.entry("poneyland") {
387    ///     let entry = o.insert_entry(37);
388    ///     assert_eq!(entry.get(), &37);
389    /// }
390    /// assert_eq!(map["poneyland"], 37);
391    /// ```
392    #[stable(feature = "btree_entry_insert", since = "CURRENT_RUSTC_VERSION")]
393    pub fn insert_entry(mut self, value: V) -> OccupiedEntry<'a, K, V, A> {
394        let handle = match self.handle {
395            None => {
396                // SAFETY: There is no tree yet so no reference to it exists.
397                let map = unsafe { self.dormant_map.reborrow() };
398                let root = map.root.insert(NodeRef::new_leaf(self.alloc.clone()).forget_type());
399                // SAFETY: We *just* created the root as a leaf, and we're
400                // stacking the new handle on the original borrow lifetime.
401                unsafe {
402                    let mut leaf = root.borrow_mut().cast_to_leaf_unchecked();
403                    leaf.push_with_handle(self.key, value)
404                }
405            }
406            Some(handle) => handle.insert_recursing(self.key, value, self.alloc.clone(), |ins| {
407                drop(ins.left);
408                // SAFETY: Pushing a new root node doesn't invalidate
409                // handles to existing nodes.
410                let map = unsafe { self.dormant_map.reborrow() };
411                let root = map.root.as_mut().unwrap(); // same as ins.left
412                root.push_internal_level(self.alloc.clone()).push(ins.kv.0, ins.kv.1, ins.right)
413            }),
414        };
415
416        // SAFETY: modifying the length doesn't invalidate handles to existing nodes.
417        unsafe { self.dormant_map.reborrow().length += 1 };
418
419        OccupiedEntry {
420            handle: handle.forget_node_type(),
421            dormant_map: self.dormant_map,
422            alloc: self.alloc,
423            _marker: PhantomData,
424        }
425    }
426}
427
428impl<'a, K: Ord, V, A: Allocator + Clone> OccupiedEntry<'a, K, V, A> {
429    /// Gets a reference to the key in the entry.
430    ///
431    /// # Examples
432    ///
433    /// ```
434    /// use std::collections::BTreeMap;
435    ///
436    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
437    /// map.entry("poneyland").or_insert(12);
438    /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
439    /// ```
440    #[must_use]
441    #[stable(feature = "map_entry_keys", since = "1.10.0")]
442    pub fn key(&self) -> &K {
443        self.handle.reborrow().into_kv().0
444    }
445
446    /// Converts the entry into a reference to its key.
447    pub(crate) fn into_key(self) -> &'a K {
448        self.handle.into_kv_mut().0
449    }
450
451    /// Take ownership of the key and value from the map.
452    ///
453    /// # Examples
454    ///
455    /// ```
456    /// use std::collections::BTreeMap;
457    /// use std::collections::btree_map::Entry;
458    ///
459    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
460    /// map.entry("poneyland").or_insert(12);
461    ///
462    /// if let Entry::Occupied(o) = map.entry("poneyland") {
463    ///     // We delete the entry from the map.
464    ///     o.remove_entry();
465    /// }
466    ///
467    /// // If now try to get the value, it will panic:
468    /// // println!("{}", map["poneyland"]);
469    /// ```
470    #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
471    pub fn remove_entry(self) -> (K, V) {
472        self.remove_kv()
473    }
474
475    /// Gets a reference to the value in the entry.
476    ///
477    /// # Examples
478    ///
479    /// ```
480    /// use std::collections::BTreeMap;
481    /// use std::collections::btree_map::Entry;
482    ///
483    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
484    /// map.entry("poneyland").or_insert(12);
485    ///
486    /// if let Entry::Occupied(o) = map.entry("poneyland") {
487    ///     assert_eq!(o.get(), &12);
488    /// }
489    /// ```
490    #[must_use]
491    #[stable(feature = "rust1", since = "1.0.0")]
492    pub fn get(&self) -> &V {
493        self.handle.reborrow().into_kv().1
494    }
495
496    /// Gets a mutable reference to the value in the entry.
497    ///
498    /// If you need a reference to the `OccupiedEntry` that may outlive the
499    /// destruction of the `Entry` value, see [`into_mut`].
500    ///
501    /// [`into_mut`]: OccupiedEntry::into_mut
502    ///
503    /// # Examples
504    ///
505    /// ```
506    /// use std::collections::BTreeMap;
507    /// use std::collections::btree_map::Entry;
508    ///
509    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
510    /// map.entry("poneyland").or_insert(12);
511    ///
512    /// assert_eq!(map["poneyland"], 12);
513    /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
514    ///     *o.get_mut() += 10;
515    ///     assert_eq!(*o.get(), 22);
516    ///
517    ///     // We can use the same Entry multiple times.
518    ///     *o.get_mut() += 2;
519    /// }
520    /// assert_eq!(map["poneyland"], 24);
521    /// ```
522    #[stable(feature = "rust1", since = "1.0.0")]
523    pub fn get_mut(&mut self) -> &mut V {
524        self.handle.kv_mut().1
525    }
526
527    /// Converts the entry into a mutable reference to its value.
528    ///
529    /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
530    ///
531    /// [`get_mut`]: OccupiedEntry::get_mut
532    ///
533    /// # Examples
534    ///
535    /// ```
536    /// use std::collections::BTreeMap;
537    /// use std::collections::btree_map::Entry;
538    ///
539    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
540    /// map.entry("poneyland").or_insert(12);
541    ///
542    /// assert_eq!(map["poneyland"], 12);
543    /// if let Entry::Occupied(o) = map.entry("poneyland") {
544    ///     *o.into_mut() += 10;
545    /// }
546    /// assert_eq!(map["poneyland"], 22);
547    /// ```
548    #[must_use = "`self` will be dropped if the result is not used"]
549    #[stable(feature = "rust1", since = "1.0.0")]
550    pub fn into_mut(self) -> &'a mut V {
551        self.handle.into_val_mut()
552    }
553
554    /// Sets the value of the entry with the `OccupiedEntry`'s key,
555    /// and returns the entry's old value.
556    ///
557    /// # Examples
558    ///
559    /// ```
560    /// use std::collections::BTreeMap;
561    /// use std::collections::btree_map::Entry;
562    ///
563    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
564    /// map.entry("poneyland").or_insert(12);
565    ///
566    /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
567    ///     assert_eq!(o.insert(15), 12);
568    /// }
569    /// assert_eq!(map["poneyland"], 15);
570    /// ```
571    #[stable(feature = "rust1", since = "1.0.0")]
572    #[rustc_confusables("push", "put")]
573    pub fn insert(&mut self, value: V) -> V {
574        mem::replace(self.get_mut(), value)
575    }
576
577    /// Takes the value of the entry out of the map, and returns it.
578    ///
579    /// # Examples
580    ///
581    /// ```
582    /// use std::collections::BTreeMap;
583    /// use std::collections::btree_map::Entry;
584    ///
585    /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
586    /// map.entry("poneyland").or_insert(12);
587    ///
588    /// if let Entry::Occupied(o) = map.entry("poneyland") {
589    ///     assert_eq!(o.remove(), 12);
590    /// }
591    /// // If we try to get "poneyland"'s value, it'll panic:
592    /// // println!("{}", map["poneyland"]);
593    /// ```
594    #[stable(feature = "rust1", since = "1.0.0")]
595    #[rustc_confusables("delete", "take")]
596    pub fn remove(self) -> V {
597        self.remove_kv().1
598    }
599
600    // Body of `remove_entry`, probably separate because the name reflects the returned pair.
601    pub(super) fn remove_kv(self) -> (K, V) {
602        let mut emptied_internal_root = false;
603        let (old_kv, _) =
604            self.handle.remove_kv_tracking(|| emptied_internal_root = true, self.alloc.clone());
605        // SAFETY: we consumed the intermediate root borrow, `self.handle`.
606        let map = unsafe { self.dormant_map.awaken() };
607        map.length -= 1;
608        if emptied_internal_root {
609            let root = map.root.as_mut().unwrap();
610            root.pop_internal_level(self.alloc);
611        }
612        old_kv
613    }
614}