1 use core::fmt::{self, Debug};
2 use core::marker::PhantomData;
5 use crate::alloc::{Allocator, Global};
7 use super::super::borrow::DormantMutRef;
8 use super::super::node::{marker, Handle, NodeRef};
13 /// A view into a single entry in a map, which may either be vacant or occupied.
15 /// This `enum` is constructed from the [`entry`] method on [`BTreeMap`].
17 /// [`entry`]: BTreeMap::entry
18 #[stable(feature = "rust1", since = "1.0.0")]
19 #[cfg_attr(not(test), rustc_diagnostic_item = "BTreeEntry")]
24 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
27 #[stable(feature = "rust1", since = "1.0.0")]
28 Vacant(#[stable(feature = "rust1", since = "1.0.0")] VacantEntry<'a, K, V, A>),
30 /// An occupied entry.
31 #[stable(feature = "rust1", since = "1.0.0")]
32 Occupied(#[stable(feature = "rust1", since = "1.0.0")] OccupiedEntry<'a, K, V, A>),
35 #[stable(feature = "debug_btree_map", since = "1.12.0")]
36 impl<K: Debug + Ord, V: Debug, A: Allocator> Debug for Entry<'_, K, V, A> {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 Vacant(ref v) => f.debug_tuple("Entry").field(v).finish(),
40 Occupied(ref o) => f.debug_tuple("Entry").field(o).finish(),
45 /// A view into a vacant entry in a `BTreeMap`.
46 /// It is part of the [`Entry`] enum.
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub struct VacantEntry<
52 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
55 /// `None` for a (empty) map without root
56 pub(super) handle: Option<Handle<NodeRef<marker::Mut<'a>, K, V, marker::Leaf>, marker::Edge>>,
57 pub(super) dormant_map: DormantMutRef<'a, BTreeMap<K, V, A>>,
59 pub(super) alloc: &'a A,
61 // Be invariant in `K` and `V`
62 pub(super) _marker: PhantomData<&'a mut (K, V)>,
65 #[stable(feature = "debug_btree_map", since = "1.12.0")]
66 impl<K: Debug + Ord, V, A: Allocator> 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()
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")]
75 pub struct OccupiedEntry<
79 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
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>>,
84 pub(super) alloc: &'a A,
86 // Be invariant in `K` and `V`
87 pub(super) _marker: PhantomData<&'a mut (K, V)>,
90 #[stable(feature = "debug_btree_map", since = "1.12.0")]
91 impl<K: Debug + Ord, V: Debug, A: Allocator> Debug for OccupiedEntry<'_, K, V, A> {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.debug_struct("OccupiedEntry").field("key", self.key()).field("value", self.get()).finish()
97 /// The error returned by [`try_insert`](BTreeMap::try_insert) when the key already exists.
99 /// Contains the occupied entry, and the value that was not inserted.
100 #[unstable(feature = "map_try_insert", issue = "82766")]
101 pub struct OccupiedError<'a, K: 'a, V: 'a, A: Allocator = Global> {
102 /// The entry in the map that was already occupied.
103 pub entry: OccupiedEntry<'a, K, V, A>,
104 /// The value which was not inserted, because the entry was already occupied.
108 #[unstable(feature = "map_try_insert", issue = "82766")]
109 impl<K: Debug + Ord, V: Debug, A: Allocator> Debug for OccupiedError<'_, K, V, A> {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 f.debug_struct("OccupiedError")
112 .field("key", self.entry.key())
113 .field("old_value", self.entry.get())
114 .field("new_value", &self.value)
119 #[unstable(feature = "map_try_insert", issue = "82766")]
120 impl<'a, K: Debug + Ord, V: Debug, A: Allocator> fmt::Display for OccupiedError<'a, K, V, A> {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 "failed to insert {:?}, key {:?} already exists with value {:?}",
132 impl<'a, K: Ord, V, A: Allocator> Entry<'a, K, V, A> {
133 /// Ensures a value is in the entry by inserting the default if empty, and returns
134 /// a mutable reference to the value in the entry.
139 /// use std::collections::BTreeMap;
141 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
142 /// map.entry("poneyland").or_insert(12);
144 /// assert_eq!(map["poneyland"], 12);
146 #[stable(feature = "rust1", since = "1.0.0")]
147 pub fn or_insert(self, default: V) -> &'a mut V {
149 Occupied(entry) => entry.into_mut(),
150 Vacant(entry) => entry.insert(default),
154 /// Ensures a value is in the entry by inserting the result of the default function if empty,
155 /// and returns a mutable reference to the value in the entry.
160 /// use std::collections::BTreeMap;
162 /// let mut map: BTreeMap<&str, String> = BTreeMap::new();
163 /// let s = "hoho".to_string();
165 /// map.entry("poneyland").or_insert_with(|| s);
167 /// assert_eq!(map["poneyland"], "hoho".to_string());
169 #[stable(feature = "rust1", since = "1.0.0")]
170 pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V {
172 Occupied(entry) => entry.into_mut(),
173 Vacant(entry) => entry.insert(default()),
177 /// Ensures a value is in the entry by inserting, if empty, the result of the default function.
178 /// This method allows for generating key-derived values for insertion by providing the default
179 /// function a reference to the key that was moved during the `.entry(key)` method call.
181 /// The reference to the moved key is provided so that cloning or copying the key is
182 /// unnecessary, unlike with `.or_insert_with(|| ... )`.
187 /// use std::collections::BTreeMap;
189 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
191 /// map.entry("poneyland").or_insert_with_key(|key| key.chars().count());
193 /// assert_eq!(map["poneyland"], 9);
196 #[stable(feature = "or_insert_with_key", since = "1.50.0")]
197 pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V {
199 Occupied(entry) => entry.into_mut(),
201 let value = default(entry.key());
207 /// Returns a reference to this entry's key.
212 /// use std::collections::BTreeMap;
214 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
215 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
217 #[stable(feature = "map_entry_keys", since = "1.10.0")]
218 pub fn key(&self) -> &K {
220 Occupied(ref entry) => entry.key(),
221 Vacant(ref entry) => entry.key(),
225 /// Provides in-place mutable access to an occupied entry before any
226 /// potential inserts into the map.
231 /// use std::collections::BTreeMap;
233 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
235 /// map.entry("poneyland")
236 /// .and_modify(|e| { *e += 1 })
238 /// assert_eq!(map["poneyland"], 42);
240 /// map.entry("poneyland")
241 /// .and_modify(|e| { *e += 1 })
243 /// assert_eq!(map["poneyland"], 43);
245 #[stable(feature = "entry_and_modify", since = "1.26.0")]
246 pub fn and_modify<F>(self, f: F) -> Self
251 Occupied(mut entry) => {
255 Vacant(entry) => Vacant(entry),
260 impl<'a, K: Ord, V: Default, A: Allocator> Entry<'a, K, V, A> {
261 #[stable(feature = "entry_or_default", since = "1.28.0")]
262 /// Ensures a value is in the entry by inserting the default value if empty,
263 /// and returns a mutable reference to the value in the entry.
268 /// use std::collections::BTreeMap;
270 /// let mut map: BTreeMap<&str, Option<usize>> = BTreeMap::new();
271 /// map.entry("poneyland").or_default();
273 /// assert_eq!(map["poneyland"], None);
275 pub fn or_default(self) -> &'a mut V {
277 Occupied(entry) => entry.into_mut(),
278 Vacant(entry) => entry.insert(Default::default()),
283 impl<'a, K: Ord, V, A: Allocator> VacantEntry<'a, K, V, A> {
284 /// Gets a reference to the key that would be used when inserting a value
285 /// through the VacantEntry.
290 /// use std::collections::BTreeMap;
292 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
293 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
295 #[stable(feature = "map_entry_keys", since = "1.10.0")]
296 pub fn key(&self) -> &K {
300 /// Take ownership of the key.
305 /// use std::collections::BTreeMap;
306 /// use std::collections::btree_map::Entry;
308 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
310 /// if let Entry::Vacant(v) = map.entry("poneyland") {
314 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
315 pub fn into_key(self) -> K {
319 /// Sets the value of the entry with the `VacantEntry`'s key,
320 /// and returns a mutable reference to it.
325 /// use std::collections::BTreeMap;
326 /// use std::collections::btree_map::Entry;
328 /// let mut map: BTreeMap<&str, u32> = BTreeMap::new();
330 /// if let Entry::Vacant(o) = map.entry("poneyland") {
333 /// assert_eq!(map["poneyland"], 37);
335 #[stable(feature = "rust1", since = "1.0.0")]
336 pub fn insert(self, value: V) -> &'a mut V {
337 let out_ptr = match self.handle {
339 // SAFETY: There is no tree yet so no reference to it exists.
340 let map = unsafe { self.dormant_map.awaken() };
341 let mut root = NodeRef::new_leaf(self.alloc);
342 let val_ptr = root.borrow_mut().push(self.key, value) as *mut V;
343 map.root = Some(root.forget_type());
347 Some(handle) => match handle.insert_recursing(self.key, value, self.alloc) {
349 // SAFETY: We have consumed self.handle.
350 let map = unsafe { self.dormant_map.awaken() };
354 (Some(ins), val_ptr) => {
356 // SAFETY: We have consumed self.handle and dropped the
357 // remaining reference to the tree, ins.left.
358 let map = unsafe { self.dormant_map.awaken() };
359 let root = map.root.as_mut().unwrap(); // same as ins.left
360 root.push_internal_level(self.alloc).push(ins.kv.0, ins.kv.1, ins.right);
366 // Now that we have finished growing the tree using borrowed references,
367 // dereference the pointer to a part of it, that we picked up along the way.
368 unsafe { &mut *out_ptr }
372 impl<'a, K: Ord, V, A: Allocator> OccupiedEntry<'a, K, V, A> {
373 /// Gets a reference to the key in the entry.
378 /// use std::collections::BTreeMap;
380 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
381 /// map.entry("poneyland").or_insert(12);
382 /// assert_eq!(map.entry("poneyland").key(), &"poneyland");
385 #[stable(feature = "map_entry_keys", since = "1.10.0")]
386 pub fn key(&self) -> &K {
387 self.handle.reborrow().into_kv().0
390 /// Take ownership of the key and value from the map.
395 /// use std::collections::BTreeMap;
396 /// use std::collections::btree_map::Entry;
398 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
399 /// map.entry("poneyland").or_insert(12);
401 /// if let Entry::Occupied(o) = map.entry("poneyland") {
402 /// // We delete the entry from the map.
403 /// o.remove_entry();
406 /// // If now try to get the value, it will panic:
407 /// // println!("{}", map["poneyland"]);
409 #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")]
410 pub fn remove_entry(self) -> (K, V) {
414 /// Gets a reference to the value in the entry.
419 /// use std::collections::BTreeMap;
420 /// use std::collections::btree_map::Entry;
422 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
423 /// map.entry("poneyland").or_insert(12);
425 /// if let Entry::Occupied(o) = map.entry("poneyland") {
426 /// assert_eq!(o.get(), &12);
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn get(&self) -> &V {
432 self.handle.reborrow().into_kv().1
435 /// Gets a mutable reference to the value in the entry.
437 /// If you need a reference to the `OccupiedEntry` that may outlive the
438 /// destruction of the `Entry` value, see [`into_mut`].
440 /// [`into_mut`]: OccupiedEntry::into_mut
445 /// use std::collections::BTreeMap;
446 /// use std::collections::btree_map::Entry;
448 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
449 /// map.entry("poneyland").or_insert(12);
451 /// assert_eq!(map["poneyland"], 12);
452 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
453 /// *o.get_mut() += 10;
454 /// assert_eq!(*o.get(), 22);
456 /// // We can use the same Entry multiple times.
457 /// *o.get_mut() += 2;
459 /// assert_eq!(map["poneyland"], 24);
461 #[stable(feature = "rust1", since = "1.0.0")]
462 pub fn get_mut(&mut self) -> &mut V {
463 self.handle.kv_mut().1
466 /// Converts the entry into a mutable reference to its value.
468 /// If you need multiple references to the `OccupiedEntry`, see [`get_mut`].
470 /// [`get_mut`]: OccupiedEntry::get_mut
475 /// use std::collections::BTreeMap;
476 /// use std::collections::btree_map::Entry;
478 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
479 /// map.entry("poneyland").or_insert(12);
481 /// assert_eq!(map["poneyland"], 12);
482 /// if let Entry::Occupied(o) = map.entry("poneyland") {
483 /// *o.into_mut() += 10;
485 /// assert_eq!(map["poneyland"], 22);
487 #[must_use = "`self` will be dropped if the result is not used"]
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn into_mut(self) -> &'a mut V {
490 self.handle.into_val_mut()
493 /// Sets the value of the entry with the `OccupiedEntry`'s key,
494 /// and returns the entry's old value.
499 /// use std::collections::BTreeMap;
500 /// use std::collections::btree_map::Entry;
502 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
503 /// map.entry("poneyland").or_insert(12);
505 /// if let Entry::Occupied(mut o) = map.entry("poneyland") {
506 /// assert_eq!(o.insert(15), 12);
508 /// assert_eq!(map["poneyland"], 15);
510 #[stable(feature = "rust1", since = "1.0.0")]
511 pub fn insert(&mut self, value: V) -> V {
512 mem::replace(self.get_mut(), value)
515 /// Takes the value of the entry out of the map, and returns it.
520 /// use std::collections::BTreeMap;
521 /// use std::collections::btree_map::Entry;
523 /// let mut map: BTreeMap<&str, usize> = BTreeMap::new();
524 /// map.entry("poneyland").or_insert(12);
526 /// if let Entry::Occupied(o) = map.entry("poneyland") {
527 /// assert_eq!(o.remove(), 12);
529 /// // If we try to get "poneyland"'s value, it'll panic:
530 /// // println!("{}", map["poneyland"]);
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn remove(self) -> V {
537 // Body of `remove_entry`, probably separate because the name reflects the returned pair.
538 pub(super) fn remove_kv(self) -> (K, V) {
539 let mut emptied_internal_root = false;
541 self.handle.remove_kv_tracking(|| emptied_internal_root = true, self.alloc);
542 // SAFETY: we consumed the intermediate root borrow, `self.handle`.
543 let map = unsafe { self.dormant_map.awaken() };
545 if emptied_internal_root {
546 let root = map.root.as_mut().unwrap();
547 root.pop_internal_level(&*self.alloc);