scapegoat/map.rs
1use core::borrow::Borrow;
2use core::fmt::{self, Debug};
3use core::iter::FromIterator;
4use core::ops::{Index, RangeBounds};
5
6use crate::map_types::{
7 Entry, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, OccupiedEntry, OccupiedError,
8 Range, RangeMut, VacantEntry, Values, ValuesMut,
9};
10use crate::tree::{node::NodeGetHelper, Idx, SgError, SgTree};
11
12/// Safe, fallible, embedded-friendly ordered map.
13///
14/// ### Fallible APIs
15///
16/// * [`try_insert`][crate::map::SgMap::try_insert]
17/// * [`try_append`][crate::map::SgMap::try_append]
18/// * [`try_extend`][crate::map::SgMap::try_extend]
19/// * [`try_from_iter`][crate::map::SgMap::try_from_iter]
20///
21/// [`TryFrom`](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html) isn't implemented because it would collide with the blanket implementation.
22/// See [this open GitHub issue](https://github.com/rust-lang/rust/issues/50133#issuecomment-64690839) from 2018,
23/// this is a known Rust limitation that should be fixed via specialization in the future.
24///
25/// ### Attribution Note
26///
27/// The majority of API examples and descriptions are adapted or directly copied from the standard library's [`BTreeMap`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html).
28/// The goal is to offer embedded developers familiar, ergonomic APIs on resource constrained systems that otherwise don't get the luxury of dynamic collections.
29#[derive(Default, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
30pub struct SgMap<K: Ord + Default, V: Default, const N: usize> {
31 pub(crate) bst: SgTree<K, V, N>,
32}
33
34impl<K: Ord + Default, V: Default, const N: usize> SgMap<K, V, N> {
35 /// Makes a new, empty `SgMap`.
36 ///
37 /// # Examples
38 ///
39 /// ```
40 /// use scapegoat::SgMap;
41 ///
42 /// let mut map = SgMap::<_, _, 10>::new();
43 ///
44 /// map.insert(1, "a");
45 /// ```
46 pub fn new() -> Self {
47 SgMap { bst: SgTree::new() }
48 }
49
50 /// The [original scapegoat tree paper's](https://people.csail.mit.edu/rivest/pubs/GR93.pdf) alpha, `a`, can be chosen in the range `0.5 <= a < 1.0`.
51 /// `a` tunes how "aggressively" the data structure self-balances.
52 /// It controls the trade-off between total rebuild time and maximum height guarantees.
53 ///
54 /// * As `a` approaches `0.5`, the tree will rebalance more often. Ths means slower insertions, but faster lookups and deletions.
55 /// * An `a` equal to `0.5` means a tree that always maintains a perfect balance (e.g."complete" binary tree, at all times).
56 ///
57 /// * As `a` approaches `1.0`, the tree will rebalance less often. This means quicker insertions, but slower lookups and deletions.
58 /// * If `a` reached `1.0`, it'd mean a tree that never rebalances.
59 ///
60 /// Returns `Err` if `0.5 <= alpha_num / alpha_denom < 1.0` isn't `true` (invalid `a`, out of range).
61 ///
62 /// # Examples
63 ///
64 /// ```
65 /// use scapegoat::SgMap;
66 ///
67 /// let mut map: SgMap<isize, isize, 10> = SgMap::new();
68 ///
69 /// // Set 2/3, e.g. `a = 0.666...` (it's default value).
70 /// assert!(map.set_rebal_param(2.0, 3.0).is_ok());
71 /// ```
72 #[doc(alias = "rebalance")]
73 #[doc(alias = "alpha")]
74 pub fn set_rebal_param(&mut self, alpha_num: f32, alpha_denom: f32) -> Result<(), SgError> {
75 self.bst.set_rebal_param(alpha_num, alpha_denom)
76 }
77
78 /// Get the current rebalance parameter, alpha, as a tuple of `(alpha_numerator, alpha_denominator)`.
79 /// See [the corresponding setter method][SgMap::set_rebal_param] for more details.
80 ///
81 /// # Examples
82 ///
83 /// ```
84 /// use scapegoat::SgMap;
85 ///
86 /// let mut map: SgMap<isize, isize, 10> = SgMap::new();
87 ///
88 /// // Set 2/3, e.g. `a = 0.666...` (it's default value).
89 /// assert!(map.set_rebal_param(2.0, 3.0).is_ok());
90 ///
91 /// // Get the currently set value
92 /// assert_eq!(map.rebal_param(), (2.0, 3.0));
93 /// ```
94 #[doc(alias = "rebalance")]
95 #[doc(alias = "alpha")]
96 pub fn rebal_param(&self) -> (f32, f32) {
97 self.bst.rebal_param()
98 }
99
100 /// Total capacity, e.g. maximum number of map pairs.
101 ///
102 /// # Examples
103 ///
104 /// ```
105 /// use scapegoat::SgMap;
106 ///
107 /// let mut map = SgMap::<usize, &str, 10>::new();
108 ///
109 /// assert!(map.capacity() == 10);
110 /// ```
111 pub fn capacity(&self) -> usize {
112 self.bst.capacity()
113 }
114
115 /// Gets an iterator over the keys of the map, in sorted order.
116 ///
117 /// # Examples
118 ///
119 /// ```
120 /// use scapegoat::SgMap;
121 ///
122 /// let mut a = SgMap::<_, _, 10>::new();
123 /// a.insert(2, "b");
124 /// a.insert(1, "a");
125 ///
126 /// let keys: Vec<_> = a.keys().cloned().collect();
127 /// assert_eq!(keys, [1, 2]);
128 /// ```
129 pub fn keys(&self) -> Keys<'_, K, V, N> {
130 Keys { inner: self.iter() }
131 }
132
133 /// Creates a consuming iterator visiting all the keys, in sorted order.
134 /// The map cannot be used after calling this.
135 /// The iterator element type is `K`.
136 ///
137 /// # Examples
138 ///
139 /// ```
140 /// use scapegoat::SgMap;
141 ///
142 /// let mut a = SgMap::<_, _, 10>::new();
143 /// a.insert(2, "b");
144 /// a.insert(1, "a");
145 ///
146 /// let keys: Vec<i32> = a.into_keys().collect();
147 /// assert_eq!(keys, [1, 2]);
148 /// ```
149 pub fn into_keys(self) -> IntoKeys<K, V, N> {
150 IntoKeys {
151 inner: self.into_iter(),
152 }
153 }
154
155 /// Gets an iterator over the values of the map, in order by key.
156 ///
157 /// # Examples
158 ///
159 /// ```
160 /// use scapegoat::SgMap;
161 ///
162 /// let mut a = SgMap::<_, _, 10>::new();
163 /// a.insert(1, "hello");
164 /// a.insert(2, "goodbye");
165 ///
166 /// let values: Vec<&str> = a.values().cloned().collect();
167 /// assert_eq!(values, ["hello", "goodbye"]);
168 /// ```
169 pub fn values(&self) -> Values<'_, K, V, N> {
170 Values { inner: self.iter() }
171 }
172
173 /// Creates a consuming iterator visiting all the values, in order by key.
174 /// The map cannot be used after calling this.
175 /// The iterator element type is `V`.
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// use scapegoat::SgMap;
181 ///
182 /// let mut a = SgMap::<_, _, 10>::new();
183 /// a.insert(1, "hello");
184 /// a.insert(2, "goodbye");
185 ///
186 /// let values: Vec<&str> = a.into_values().collect();
187 /// assert_eq!(values, ["hello", "goodbye"]);
188 /// ```
189 pub fn into_values(self) -> IntoValues<K, V, N> {
190 IntoValues {
191 inner: self.into_iter(),
192 }
193 }
194
195 /// Gets a mutable iterator over the values of the map, in order by key.
196 ///
197 /// # Examples
198 ///
199 /// ```
200 /// use scapegoat::SgMap;
201 ///
202 /// let mut a = SgMap::<_, _, 10>::new();
203 /// a.insert(1, String::from("hello"));
204 /// a.insert(2, String::from("goodbye"));
205 ///
206 /// for value in a.values_mut() {
207 /// value.push_str("!");
208 /// }
209 ///
210 /// let values: Vec<String> = a.values().cloned().collect();
211 /// assert_eq!(values, [String::from("hello!"),
212 /// String::from("goodbye!")]);
213 /// ```
214 pub fn values_mut(&mut self) -> ValuesMut<'_, K, V, N> {
215 ValuesMut {
216 inner: self.iter_mut(),
217 }
218 }
219
220 /// Moves all elements from `other` into `self`, leaving `other` empty.
221 ///
222 /// # Examples
223 ///
224 /// ```
225 /// use scapegoat::SgMap;
226 ///
227 /// let mut a = SgMap::<_, _, 10>::new();
228 /// a.insert(1, "a");
229 /// a.insert(2, "b");
230 /// a.insert(3, "c");
231 ///
232 /// let mut b = SgMap::<_, _, 10>::new();
233 /// b.insert(3, "d");
234 /// b.insert(4, "e");
235 /// b.insert(5, "f");
236 ///
237 /// a.append(&mut b);
238 ///
239 /// assert_eq!(a.len(), 5);
240 /// assert_eq!(b.len(), 0);
241 ///
242 /// assert_eq!(a[&1], "a");
243 /// assert_eq!(a[&2], "b");
244 /// assert_eq!(a[&3], "d");
245 /// assert_eq!(a[&4], "e");
246 /// assert_eq!(a[&5], "f");
247 /// ```
248 pub fn append(&mut self, other: &mut SgMap<K, V, N>) {
249 self.bst.append(&mut other.bst);
250 }
251
252 /// Attempts to move all elements from `other` into `self`, leaving `other` empty.
253 ///
254 /// # Examples
255 ///
256 /// ```
257 /// use core::iter::FromIterator;
258 /// use scapegoat::{SgMap, SgError};
259 ///
260 /// let mut a = SgMap::<_, _, 10>::new();
261 /// a.try_insert(1, "a").is_ok();
262 /// a.try_insert(2, "b").is_ok();
263 /// a.try_insert(3, "c").is_ok();
264 ///
265 /// let mut b = SgMap::<_, _, 10>::new();
266 /// b.try_insert(3, "d").is_ok(); // Overwrite previous
267 /// b.try_insert(4, "e").is_ok();
268 /// b.try_insert(5, "f").is_ok();
269 ///
270 /// // Successful append
271 /// assert!(a.try_append(&mut b).is_ok());
272 ///
273 /// // Elements moved
274 /// assert_eq!(a.len(), 5);
275 /// assert_eq!(b.len(), 0);
276 ///
277 /// assert_eq!(a[&1], "a");
278 /// assert_eq!(a[&2], "b");
279 /// assert_eq!(a[&3], "d");
280 /// assert_eq!(a[&4], "e");
281 /// assert_eq!(a[&5], "f");
282 ///
283 /// // Fill remaining capacity
284 /// let mut key = 6;
285 /// while a.len() < a.capacity() {
286 /// assert!(a.try_insert(key, "filler").is_ok());
287 /// key += 1;
288 /// }
289 ///
290 /// // Full
291 /// assert!(a.is_full());
292 ///
293 /// // More data
294 /// let mut c = SgMap::<_, _, 10>::from_iter([(11, "k"), (12, "l")]);
295 /// let mut d = SgMap::<_, _, 10>::from_iter([(1, "a2"), (2, "b2")]);
296 ///
297 /// // Cannot append new pairs
298 /// assert_eq!(a.try_append(&mut c), Err(SgError::StackCapacityExceeded));
299 ///
300 /// // Can still replace existing pairs
301 /// assert!(a.try_append(&mut d).is_ok());
302 /// ```
303 pub fn try_append(&mut self, other: &mut SgMap<K, V, N>) -> Result<(), SgError> {
304 self.bst.try_append(&mut other.bst)
305 }
306
307 /// Insert a key-value pair into the map.
308 /// If the map did not have this key present, `None` is returned.
309 /// If the map did have this key present, the value is updated, the old value is returned,
310 /// and the key is updated. This accommodates types that can be `==` without being identical.
311 ///
312 /// # Examples
313 ///
314 /// ```
315 /// use scapegoat::SgMap;
316 ///
317 /// let mut map = SgMap::<_, _, 10>::new();
318 /// assert_eq!(map.insert(37, "a"), None);
319 /// assert_eq!(map.is_empty(), false);
320 ///
321 /// map.insert(37, "b");
322 /// assert_eq!(map.insert(37, "c"), Some("b"));
323 /// assert_eq!(map[&37], "c");
324 /// ```
325 pub fn insert(&mut self, key: K, val: V) -> Option<V>
326 where
327 K: Ord,
328 {
329 self.bst.insert(key, val)
330 }
331
332 /// Insert a key-value pair into the map.
333 /// Returns `Err` if the operation can't be completed, else the `Ok` contains:
334 /// * `None` if the map did not have this key present.
335 /// * The old value if the map did have this key present (both the value and key are updated,
336 /// this accommodates types that can be `==` without being identical).
337 ///
338 /// ### Warning
339 ///
340 /// Unlike other APIs in this crate, the semantics and return type of this API are *NOT* the same as `BTreeMap`'s nightly [`try_insert`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.try_insert).
341 /// For an equivalent, use [`try_insert_std`][`SgMap::try_insert_std`].
342 ///
343 /// # Examples
344 ///
345 /// ```
346 /// use scapegoat::{SgMap, SgError};
347 ///
348 /// let mut map = SgMap::<_, _, 10>::new();
349 ///
350 /// // Add a new pair
351 /// assert_eq!(map.try_insert(37, "a"), Ok(None));
352 /// assert_eq!(map.is_empty(), false);
353 ///
354 /// // Replace existing pair
355 /// map.insert(37, "b");
356 /// assert_eq!(map.try_insert(37, "c"), Ok(Some("b")));
357 /// assert_eq!(map[&37], "c");
358 ///
359 /// // Fill remaining capacity
360 /// let mut key = 38;
361 /// while map.len() < map.capacity() {
362 /// assert!(map.try_insert(key, "filler").is_ok());
363 /// key += 1;
364 /// }
365 ///
366 /// // Full
367 /// assert!(map.is_full());
368 ///
369 /// // Cannot insert new pair
370 /// assert_eq!(map.try_insert(key, "out of bounds"), Err(SgError::StackCapacityExceeded));
371 ///
372 /// // Can still replace existing pair
373 /// assert_eq!(map.try_insert(key - 1, "overwrite filler"), Ok(Some("filler")));
374 /// ```
375 ///
376 pub fn try_insert(&mut self, key: K, val: V) -> Result<Option<V>, SgError>
377 where
378 K: Ord,
379 {
380 self.bst.try_insert(key, val)
381 }
382
383 /// Tries to insert a key-value pair into the map, and returns
384 /// a mutable reference to the value in the entry.
385 ///
386 /// If the map already had this key present, nothing is updated, and
387 /// an error containing the occupied entry and the value is returned.
388 ///
389 /// ### Warning
390 ///
391 /// The semantics and return type of this API match `BTreeMap`'s nightly [`try_insert`](https://doc.rust-lang.org/std/collections/struct.BTreeMap.html#method.try_insert), *NOT* the other `try_*` APIs in this crate.
392 /// For a fallible insert, use [`try_insert`][`SgMap::try_insert`].
393 ///
394 /// # Examples
395 ///
396 /// Basic usage:
397 ///
398 /// ```
399 /// use scapegoat::SgMap;
400 ///
401 /// let mut map = SgMap::<_, _, 10>::new();
402 /// assert_eq!(map.try_insert_std(37, "a").unwrap(), &"a");
403 ///
404 /// let err = map.try_insert_std(37, "b").unwrap_err();
405 /// assert_eq!(err.entry.key(), &37);
406 /// assert_eq!(err.entry.get(), &"a");
407 /// assert_eq!(err.value, "b");
408 /// ```
409 pub fn try_insert_std(&mut self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, N>>
410 where
411 K: Ord,
412 {
413 match self.entry(key) {
414 Entry::Occupied(entry) => Err(OccupiedError { entry, value }),
415 Entry::Vacant(entry) => Ok(entry.insert(value)),
416 }
417 }
418
419 /// Attempt to extend a collection with the contents of an iterator.
420 ///
421 /// # Examples
422 ///
423 /// ```
424 /// use core::iter::FromIterator;
425 /// use scapegoat::{SgMap, SgError};
426 ///
427 /// let mut a = SgMap::<_, _, 2>::new();
428 /// let mut b = SgMap::<_, _, 3>::from_iter([(1, "a"), (2, "b"), (3, "c")]);
429 /// let mut c = SgMap::<_, _, 2>::from_iter([(1, "a"), (2, "b")]);
430 ///
431 /// // Too big
432 /// assert_eq!(a.try_extend(b.into_iter()), Err(SgError::StackCapacityExceeded));
433 ///
434 /// // Fits
435 /// assert!(a.try_extend(c.into_iter()).is_ok());
436 /// ```
437 ///
438 /// ### Note
439 ///
440 /// There is no `TryExtend` trait in `core`/`std`.
441 pub fn try_extend<I: ExactSizeIterator + IntoIterator<Item = (K, V)>>(
442 &mut self,
443 iter: I,
444 ) -> Result<(), SgError> {
445 self.bst.try_extend(iter)
446 }
447
448 /// Attempt conversion from an iterator.
449 /// Will fail if iterator length exceeds `u16::MAX`.
450 ///
451 /// # Examples
452 ///
453 /// ```
454 /// use scapegoat::{SgMap, SgError};
455 ///
456 /// const CAPACITY_1: usize = 1_000;
457 /// let vec: Vec<(usize, usize)> = (0..CAPACITY_1).map(|n|(n, n)).collect();
458 /// assert!(SgMap::<usize, usize, CAPACITY_1>::try_from_iter(vec.into_iter()).is_ok());
459 ///
460 /// const CAPACITY_2: usize = (u16::MAX as usize) + 1;
461 /// let vec: Vec<(usize, usize)> = (0..CAPACITY_2).map(|n|(n, n)).collect();
462 /// assert_eq!(
463 /// SgMap::<usize, usize, CAPACITY_2>::try_from_iter(vec.into_iter()),
464 /// Err(SgError::MaximumCapacityExceeded)
465 /// );
466 /// ```
467 ///
468 /// ### Note
469 ///
470 /// There is no `TryFromIterator` trait in `core`/`std`.
471 pub fn try_from_iter<I: ExactSizeIterator + IntoIterator<Item = (K, V)>>(
472 iter: I,
473 ) -> Result<Self, SgError> {
474 match iter.len() <= SgTree::<K, V, N>::max_capacity() {
475 true => Ok(SgMap::from_iter(iter)),
476 false => Err(SgError::MaximumCapacityExceeded),
477 }
478 }
479
480 /// Gets an iterator over the entries of the map, sorted by key.
481 ///
482 /// # Examples
483 ///
484 /// ```
485 /// use scapegoat::SgMap;
486 ///
487 /// let mut map = SgMap::<_, _, 10>::new();
488 /// map.insert(3, "c");
489 /// map.insert(2, "b");
490 /// map.insert(1, "a");
491 ///
492 /// for (key, value) in map.iter() {
493 /// println!("{}: {}", key, value);
494 /// }
495 ///
496 /// let (first_key, first_value) = map.iter().next().unwrap();
497 /// assert_eq!((*first_key, *first_value), (1, "a"));
498 /// ```
499 pub fn iter(&self) -> Iter<'_, K, V, N> {
500 Iter::new(self)
501 }
502
503 /// Gets a mutable iterator over the entries of the map, sorted by key.
504 ///
505 /// # Examples
506 ///
507 /// ```
508 /// use scapegoat::SgMap;
509 ///
510 /// let mut map = SgMap::<_, _, 10>::new();
511 /// map.insert("a", 1);
512 /// map.insert("b", 2);
513 /// map.insert("c", 3);
514 ///
515 /// // Add 10 to the value if the key isn't "a"
516 /// for (key, value) in map.iter_mut() {
517 /// if key != &"a" {
518 /// *value += 10;
519 /// }
520 /// }
521 ///
522 /// let (second_key, second_value) = map.iter().skip(1).next().unwrap();
523 /// assert_eq!((*second_key, *second_value), ("b", 12));
524 /// ```
525 pub fn iter_mut(&mut self) -> IterMut<'_, K, V, N> {
526 IterMut::new(self)
527 }
528
529 /// Removes a key from the map, returning the stored key and value if the key
530 /// was previously in the map.
531 ///
532 /// The key may be any borrowed form of the map's key type, but the ordering
533 /// on the borrowed form *must* match the ordering on the key type.
534 ///
535 /// # Examples
536 ///
537 /// ```
538 /// use scapegoat::SgMap;
539 ///
540 /// let mut map = SgMap::<_, _, 10>::new();
541 /// map.insert(1, "a");
542 /// assert_eq!(map.remove_entry(&1), Some((1, "a")));
543 /// assert_eq!(map.remove_entry(&1), None);
544 /// ```
545 pub fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
546 where
547 K: Borrow<Q> + Ord,
548 Q: Ord + ?Sized,
549 {
550 self.bst.remove_entry(key)
551 }
552
553 /// Retains only the elements specified by the predicate.
554 ///
555 /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`.
556 /// The elements are visited in ascending key order.
557 ///
558 /// # Examples
559 ///
560 /// ```
561 /// use scapegoat::SgMap;
562 ///
563 /// let mut map: SgMap<i32, i32, 10> = (0..8).map(|x| (x, x*10)).collect();
564 /// // Keep only the elements with even-numbered keys.
565 /// map.retain(|&k, _| k % 2 == 0);
566 /// assert!(map.into_iter().eq(vec![(0, 0), (2, 20), (4, 40), (6, 60)]));
567 /// ```
568 pub fn retain<F>(&mut self, mut f: F)
569 where
570 K: Ord,
571 F: FnMut(&K, &mut V) -> bool,
572 {
573 self.bst.retain(|k, v| f(k, v));
574 }
575
576 /// Splits the collection into two at the given key. Returns everything after the given key,
577 /// including the key.
578 ///
579 /// # Examples
580 ///
581 /// ```
582 /// use scapegoat::SgMap;
583 ///
584 /// let mut a = SgMap::<_, _, 10>::new();
585 /// a.insert(1, "a");
586 /// a.insert(2, "b");
587 /// a.insert(3, "c");
588 /// a.insert(17, "d");
589 /// a.insert(41, "e");
590 ///
591 /// let b = a.split_off(&3);
592 ///
593 /// assert_eq!(a.len(), 2);
594 /// assert_eq!(b.len(), 3);
595 ///
596 /// assert_eq!(a[&1], "a");
597 /// assert_eq!(a[&2], "b");
598 ///
599 /// assert_eq!(b[&3], "c");
600 /// assert_eq!(b[&17], "d");
601 /// assert_eq!(b[&41], "e");
602 /// ```
603 pub fn split_off<Q>(&mut self, key: &Q) -> SgMap<K, V, N>
604 where
605 K: Borrow<Q> + Ord,
606 Q: Ord + ?Sized,
607 {
608 SgMap {
609 bst: self.bst.split_off(key),
610 }
611 }
612
613 /// Removes a key from the map, returning the value at the key if the key
614 /// was previously in the map.
615 ///
616 /// The key may be any borrowed form of the map's key type, but the ordering
617 /// on the borrowed form *must* match the ordering on the key type.
618 ///
619 /// # Examples
620 ///
621 /// ```
622 /// use scapegoat::SgMap;
623 ///
624 /// let mut map = SgMap::<_, _, 10>::new();
625 /// map.insert(1, "a");
626 /// assert_eq!(map.remove(&1), Some("a"));
627 /// assert_eq!(map.remove(&1), None);
628 /// ```
629 pub fn remove<Q>(&mut self, key: &Q) -> Option<V>
630 where
631 K: Borrow<Q> + Ord,
632 Q: Ord + ?Sized,
633 {
634 self.bst.remove(key)
635 }
636
637 /// Returns the key-value pair corresponding to the supplied key.
638 ///
639 /// The supplied key may be any borrowed form of the map's key type, but the ordering
640 /// on the borrowed form *must* match the ordering on the key type.
641 ///
642 /// # Examples
643 ///
644 /// ```
645 /// use scapegoat::SgMap;
646 ///
647 /// let mut map = SgMap::<_, _, 10>::new();
648 /// map.insert(1, "a");
649 /// assert_eq!(map.get_key_value(&1), Some((&1, &"a")));
650 /// assert_eq!(map.get_key_value(&2), None);
651 /// ```
652 pub fn get_key_value<Q>(&self, key: &Q) -> Option<(&K, &V)>
653 where
654 K: Borrow<Q> + Ord,
655 Q: Ord + ?Sized,
656 {
657 self.bst.get_key_value(key)
658 }
659
660 /// Returns a reference to the value corresponding to the key.
661 ///
662 /// The key may be any borrowed form of the map's key type, but the ordering
663 /// on the borrowed form *must* match the ordering on the key type.
664 ///
665 /// # Examples
666 ///
667 /// ```
668 /// use scapegoat::SgMap;
669 ///
670 /// let mut map = SgMap::<_, _, 10>::new();
671 /// map.insert(1, "a");
672 /// assert_eq!(map.get(&1), Some(&"a"));
673 /// assert_eq!(map.get(&2), None);
674 /// ```
675 pub fn get<Q>(&self, key: &Q) -> Option<&V>
676 where
677 K: Borrow<Q> + Ord,
678 Q: Ord + ?Sized,
679 {
680 self.bst.get(key)
681 }
682
683 // Returns a mutable reference to the value corresponding to the key.
684 ///
685 /// The key may be any borrowed form of the map's key type, but the ordering
686 /// on the borrowed form *must* match the ordering on the key type.
687 ///
688 /// # Examples
689 ///
690 /// ```
691 /// use scapegoat::SgMap;
692 ///
693 /// let mut map = SgMap::<_, _, 10>::new();
694 /// map.insert(1, "a");
695 /// if let Some(x) = map.get_mut(&1) {
696 /// *x = "b";
697 /// }
698 /// assert_eq!(map[&1], "b");
699 /// ```
700 pub fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
701 where
702 K: Borrow<Q> + Ord,
703 Q: Ord + ?Sized,
704 {
705 self.bst.get_mut(key)
706 }
707
708 /// Clears the map, removing all elements.
709 ///
710 /// # Examples
711 ///
712 /// ```
713 /// use scapegoat::SgMap;
714 ///
715 /// let mut a = SgMap::<_, _, 10>::new();
716 /// a.insert(1, "a");
717 /// a.clear();
718 /// assert!(a.is_empty());
719 /// ```
720 pub fn clear(&mut self) {
721 self.bst.clear()
722 }
723
724 /// Returns `true` if the map contains a value for the specified key.
725 ///
726 /// The key may be any borrowed form of the map's key type, but the ordering
727 /// on the borrowed form *must* match the ordering on the key type.
728 /// # Examples
729 ///
730 /// ```
731 /// use scapegoat::SgMap;
732 ///
733 /// let mut map = SgMap::<_, _, 10>::new();
734 /// map.insert(1, "a");
735 /// assert_eq!(map.contains_key(&1), true);
736 /// assert_eq!(map.contains_key(&2), false);
737 /// ```
738 pub fn contains_key<Q>(&self, key: &Q) -> bool
739 where
740 K: Borrow<Q> + Ord,
741 Q: Ord + ?Sized,
742 {
743 self.bst.contains_key(key)
744 }
745
746 /// Returns `true` if the map contains no elements.
747 ///
748 /// # Examples
749 ///
750 /// ```
751 /// use scapegoat::SgMap;
752 ///
753 /// let mut a = SgMap::<_, _, 10>::new();
754 /// assert!(a.is_empty());
755 /// a.insert(1, "a");
756 /// assert!(!a.is_empty());
757 /// ```
758 pub fn is_empty(&self) -> bool {
759 self.bst.is_empty()
760 }
761
762 /// Returns `true` if the map's capacity is filled.
763 ///
764 /// # Examples
765 ///
766 /// ```
767 /// use scapegoat::SgMap;
768 ///
769 /// let mut a = SgMap::<_, _, 2>::new();
770 /// a.insert(1, "a");
771 /// assert!(!a.is_full());
772 /// a.insert(2, "b");
773 /// assert!(a.is_full());
774 /// ```
775 pub fn is_full(&self) -> bool {
776 self.bst.is_full()
777 }
778
779 /// Returns a reference to the first key-value pair in the map.
780 /// The key in this pair is the minimum key in the map.
781 ///
782 /// # Examples
783 ///
784 /// ```
785 /// use scapegoat::SgMap;
786 ///
787 /// let mut map = SgMap::<_, _, 10>::new();
788 /// assert_eq!(map.first_key_value(), None);
789 /// map.insert(1, "b");
790 /// map.insert(2, "a");
791 /// assert_eq!(map.first_key_value(), Some((&1, &"b")));
792 /// ```
793 pub fn first_key_value(&self) -> Option<(&K, &V)>
794 where
795 K: Ord,
796 {
797 self.bst.first_key_value()
798 }
799
800 /// Returns a reference to the first/minium key in the map, if any.
801 ///
802 /// # Examples
803 ///
804 /// ```
805 /// use scapegoat::SgMap;
806 ///
807 /// let mut map = SgMap::<_, _, 10>::new();
808 /// assert_eq!(map.first_key_value(), None);
809 /// map.insert(1, "b");
810 /// map.insert(2, "a");
811 /// assert_eq!(map.first_key(), Some(&1));
812 /// ```
813 pub fn first_key(&self) -> Option<&K>
814 where
815 K: Ord,
816 {
817 self.bst.first_key()
818 }
819
820 /// Removes and returns the first element in the map.
821 /// The key of this element is the minimum key that was in the map.
822 ///
823 /// # Examples
824 ///
825 /// Draining elements in ascending order, while keeping a usable map each iteration.
826 ///
827 /// ```
828 /// use scapegoat::SgMap;
829 ///
830 /// let mut map = SgMap::<_, _, 10>::new();
831 /// map.insert(1, "a");
832 /// map.insert(2, "b");
833 /// while let Some((key, _val)) = map.pop_first() {
834 /// assert!((&map).into_iter().all(|(k, _v)| *k > key));
835 /// }
836 /// assert!(map.is_empty());
837 /// ```
838 pub fn pop_first(&mut self) -> Option<(K, V)>
839 where
840 K: Ord,
841 {
842 self.bst.pop_first()
843 }
844
845 /// Returns a reference to the last key-value pair in the map.
846 /// The key in this pair is the maximum key in the map.
847 ///
848 /// # Examples
849 ///
850 /// ```
851 /// use scapegoat::SgMap;
852 ///
853 /// let mut map = SgMap::<_, _, 10>::new();
854 /// map.insert(1, "b");
855 /// map.insert(2, "a");
856 /// assert_eq!(map.last_key_value(), Some((&2, &"a")));
857 /// ```
858 pub fn last_key_value(&self) -> Option<(&K, &V)>
859 where
860 K: Ord,
861 {
862 self.bst.last_key_value()
863 }
864
865 /// Returns a reference to the last/maximum key in the map, if any.
866 ///
867 /// # Examples
868 ///
869 /// ```
870 /// use scapegoat::SgMap;
871 ///
872 /// let mut map = SgMap::<_, _, 10>::new();
873 /// map.insert(1, "b");
874 /// map.insert(2, "a");
875 /// assert_eq!(map.last_key(), Some(&2));
876 /// ```
877 pub fn last_key(&self) -> Option<&K>
878 where
879 K: Ord,
880 {
881 self.bst.last_key()
882 }
883
884 /// Removes and returns the last element in the map.
885 /// The key of this element is the maximum key that was in the map.
886 ///
887 /// # Examples
888 ///
889 /// Draining elements in descending order, while keeping a usable map each iteration.
890 ///
891 /// ```
892 /// use scapegoat::SgMap;
893 ///
894 /// let mut map = SgMap::<_, _, 10>::new();
895 /// map.insert(1, "a");
896 /// map.insert(2, "b");
897 /// while let Some((key, _val)) = map.pop_last() {
898 /// assert!((&map).into_iter().all(|(k, _v)| *k < key));
899 /// }
900 /// assert!(map.is_empty());
901 /// ```
902 pub fn pop_last(&mut self) -> Option<(K, V)>
903 where
904 K: Ord,
905 {
906 self.bst.pop_last()
907 }
908
909 /// Returns the number of elements in the map.
910 ///
911 /// # Examples
912 ///
913 /// ```
914 /// use scapegoat::SgMap;
915 ///
916 /// let mut a = SgMap::<_, _, 10>::new();
917 /// assert_eq!(a.len(), 0);
918 /// a.insert(1, "a");
919 /// assert_eq!(a.len(), 1);
920 /// ```
921 pub fn len(&self) -> usize {
922 self.bst.len()
923 }
924
925 /// Gets the given key's corresponding entry in the map for in-place manipulation.
926 ///
927 /// # Examples
928 ///
929 /// Basic usage:
930 ///
931 /// ```
932 /// use scapegoat::SgMap;
933 ///
934 /// let mut count = SgMap::<&str, usize, 10>::new();
935 ///
936 /// // count the number of occurrences of letters in the vec
937 /// for x in vec!["a", "b", "a", "c", "a", "b"] {
938 /// *count.entry(x).or_insert(0) += 1;
939 /// }
940 ///
941 /// assert_eq!(count["a"], 3);
942 /// ```
943 pub fn entry(&mut self, key: K) -> Entry<'_, K, V, N> {
944 let ngh: NodeGetHelper<Idx> = self.bst.internal_get(None, &key);
945 match ngh.node_idx() {
946 Some(node_idx) => Entry::Occupied(OccupiedEntry {
947 node_idx,
948 table: self,
949 }),
950 None => Entry::Vacant(VacantEntry { key, table: self }),
951 }
952 }
953
954 /// Returns the first entry in the map for in-place manipulation.
955 /// The key of this entry is the minimum key in the map.
956 ///
957 /// # Examples
958 ///
959 /// ```
960 /// use scapegoat::SgMap;
961 ///
962 /// let mut map = SgMap::<_, _, 10>::new();
963 /// map.insert(1, "a");
964 /// map.insert(2, "b");
965 /// if let Some(mut entry) = map.first_entry() {
966 /// if *entry.key() > 0 {
967 /// entry.insert("first");
968 /// }
969 /// }
970 /// assert_eq!(*map.get(&1).unwrap(), "first");
971 /// assert_eq!(*map.get(&2).unwrap(), "b");
972 /// ```
973 pub fn first_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, N>> {
974 if self.is_empty() {
975 return None;
976 }
977
978 let node_idx = self.bst.min_idx;
979 Some(OccupiedEntry {
980 node_idx,
981 table: self,
982 })
983 }
984
985 /// Returns the last entry in the map for in-place manipulation.
986 /// The key of this entry is the maximum key in the map.
987 ///
988 /// # Examples
989 ///
990 /// ```
991 /// use scapegoat::SgMap;
992 ///
993 /// let mut map = SgMap::<_, _, 10>::new();
994 /// map.insert(1, "a");
995 /// map.insert(2, "b");
996 /// if let Some(mut entry) = map.last_entry() {
997 /// if *entry.key() > 0 {
998 /// entry.insert("last");
999 /// }
1000 /// }
1001 /// assert_eq!(*map.get(&1).unwrap(), "a");
1002 /// assert_eq!(*map.get(&2).unwrap(), "last");
1003 /// ```
1004 pub fn last_entry(&mut self) -> Option<OccupiedEntry<'_, K, V, N>> {
1005 if self.is_empty() {
1006 return None;
1007 }
1008
1009 let node_idx = self.bst.max_idx;
1010 Some(OccupiedEntry {
1011 node_idx,
1012 table: self,
1013 })
1014 }
1015
1016 /// Constructs a double-ended iterator over a sub-range of elements in the map.
1017 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1018 /// yield elements from min (inclusive) to max (exclusive).
1019 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1020 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1021 /// range from 4 to 10.
1022 ///
1023 /// # Panics
1024 ///
1025 /// Panics if range `start > end`.
1026 /// Panics if range `start == end` and both bounds are `Excluded`.
1027 ///
1028 /// # Examples
1029 ///
1030 /// Basic usage:
1031 ///
1032 /// ```
1033 /// use scapegoat::SgMap;
1034 /// use core::ops::Bound::Included;
1035 ///
1036 /// let mut map = SgMap::<_, _, 10>::new();
1037 /// map.insert(3, "a");
1038 /// map.insert(5, "b");
1039 /// map.insert(8, "c");
1040 /// for (&key, &value) in map.range((Included(&4), Included(&8))) {
1041 /// println!("{}: {}", key, value);
1042 /// }
1043 /// assert_eq!(Some((&5, &"b")), map.range(4..).next());
1044 /// ```
1045 pub fn range<T, R>(&self, range: R) -> Range<'_, K, V, N>
1046 where
1047 T: Ord + ?Sized,
1048 K: Borrow<T> + Ord,
1049 R: RangeBounds<T>,
1050 {
1051 SgTree::<K, V, N>::assert_valid_range(&range);
1052 Range {
1053 table: self,
1054 node_idx_iter: self.bst.range_search(&range).into_iter(),
1055 }
1056 }
1057
1058 /// Constructs a mutable single-ended iterator over a sub-range of elements in the map.
1059 /// The simplest way is to use the range syntax `min..max`, thus `range(min..max)` will
1060 /// yield elements from min (inclusive) to max (exclusive).
1061 /// The range may also be entered as `(Bound<T>, Bound<T>)`, so for example
1062 /// `range((Excluded(4), Included(10)))` will yield a left-exclusive, right-inclusive
1063 /// range from 4 to 10.
1064 ///
1065 /// # Panics
1066 ///
1067 /// Panics if range `start > end`.
1068 /// Panics if range `start == end` and both bounds are `Excluded`.
1069 ///
1070 /// # Examples
1071 ///
1072 /// Basic usage:
1073 ///
1074 /// ```
1075 /// use scapegoat::SgMap;
1076 ///
1077 /// let mut map: SgMap<_, _, 10> = ["Alice", "Bob", "Carol", "Cheryl"]
1078 /// .iter()
1079 /// .map(|&s| (s, 0))
1080 /// .collect();
1081 /// for (_, balance) in map.range_mut("B".."Cheryl") {
1082 /// *balance += 100;
1083 /// }
1084 /// for (name, balance) in &map {
1085 /// println!("{} => {}", name, balance);
1086 /// }
1087 ///
1088 /// assert_eq!(map["Alice"], 0);
1089 /// assert_eq!(map["Bob"], 100);
1090 /// ```
1091 pub fn range_mut<T, R>(&mut self, range: R) -> RangeMut<'_, K, V, N>
1092 where
1093 T: Ord + ?Sized,
1094 K: Borrow<T> + Ord,
1095 R: RangeBounds<T>,
1096 {
1097 SgTree::<K, V, N>::assert_valid_range(&range);
1098 RangeMut::new(self, &range)
1099 }
1100}
1101
1102// Convenience Traits --------------------------------------------------------------------------------------------------
1103
1104// Debug
1105impl<K: Default, V: Default, const N: usize> Debug for SgMap<K, V, N>
1106where
1107 K: Ord + Debug,
1108 V: Debug,
1109{
1110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1111 f.debug_map().entries(self.bst.iter()).finish()
1112 }
1113}
1114
1115// From array.
1116impl<K: Default, V: Default, const N: usize> From<[(K, V); N]> for SgMap<K, V, N>
1117where
1118 K: Ord,
1119{
1120 /// ```
1121 /// use scapegoat::SgMap;
1122 ///
1123 /// let map1 = SgMap::from([(1, 2), (3, 4)]);
1124 /// let map2: SgMap<_, _, 2> = [(1, 2), (3, 4)].into();
1125 /// assert_eq!(map1, map2);
1126 /// ```
1127 ///
1128 /// ### Warning
1129 ///
1130 /// [`TryFrom`](https://doc.rust-lang.org/stable/std/convert/trait.TryFrom.html) isn't implemented because it would collide with the blanket implementation.
1131 /// See [this open GitHub issue](https://github.com/rust-lang/rust/issues/50133#issuecomment-64690839) from 2018,
1132 /// this is a known Rust limitation that should be fixed via specialization in the future.
1133 #[doc(alias = "tryfrom")]
1134 #[doc(alias = "try_from")]
1135 #[doc(alias = "TryFrom")]
1136 fn from(arr: [(K, V); N]) -> Self {
1137 IntoIterator::into_iter(arr).collect()
1138 }
1139}
1140
1141// Indexing
1142impl<K: Default, V: Default, Q, const N: usize> Index<&Q> for SgMap<K, V, N>
1143where
1144 K: Borrow<Q> + Ord,
1145 Q: Ord + ?Sized,
1146{
1147 type Output = V;
1148
1149 /// Returns a reference to the value corresponding to the supplied key.
1150 ///
1151 /// # Panics
1152 ///
1153 /// Panics if the key is not present in the `SgMap`.
1154 fn index(&self, key: &Q) -> &Self::Output {
1155 &self.bst[key]
1156 }
1157}
1158
1159// Construct from iterator.
1160impl<K: Default, V: Default, const N: usize> FromIterator<(K, V)> for SgMap<K, V, N>
1161where
1162 K: Ord,
1163{
1164 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
1165 let mut sgm = SgMap::new();
1166 sgm.bst = SgTree::from_iter(iter);
1167 sgm
1168 }
1169}
1170
1171// Extension from iterator.
1172impl<K: Default, V: Default, const N: usize> Extend<(K, V)> for SgMap<K, V, N>
1173where
1174 K: Ord,
1175{
1176 fn extend<T: IntoIterator<Item = (K, V)>>(&mut self, iter: T) {
1177 self.bst.extend(iter);
1178 }
1179}
1180
1181// Extension from reference iterator.
1182impl<'a, K: Default, V: Default, const N: usize> Extend<(&'a K, &'a V)> for SgMap<K, V, N>
1183where
1184 K: Ord + Copy,
1185 V: Copy,
1186{
1187 fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
1188 self.extend(iter.into_iter().map(|(&key, &value)| (key, value)));
1189 }
1190}
1191
1192// General Iterators ---------------------------------------------------------------------------------------------------
1193
1194// Reference iterator
1195impl<'a, K: Ord + Default, V: Default, const N: usize> IntoIterator for &'a SgMap<K, V, N> {
1196 type Item = (&'a K, &'a V);
1197 type IntoIter = Iter<'a, K, V, N>;
1198
1199 fn into_iter(self) -> Self::IntoIter {
1200 self.iter()
1201 }
1202}
1203
1204// Consuming iterator
1205impl<K: Ord + Default, V: Default, const N: usize> IntoIterator for SgMap<K, V, N> {
1206 type Item = (K, V);
1207 type IntoIter = IntoIter<K, V, N>;
1208
1209 fn into_iter(self) -> Self::IntoIter {
1210 IntoIter::new(self)
1211 }
1212}