1use serde::de::{Deserialize, Deserializer, MapAccess, Visitor};
25use serde::ser::{Serialize, Serializer};
26use std::cmp::Ordering;
27use std::collections::{btree_map, BTreeMap};
28use std::fmt;
29use std::hash::{Hash, Hasher};
30use std::iter::{FusedIterator, Map};
31use std::marker::PhantomData;
32use std::ops::Index;
33
34pub const SMALL_MAX: usize = 32;
36pub const SMALL_MIN: usize = 16;
38
39#[derive(Clone)]
41pub struct SmallMap<V> {
42 repr: Repr<V>,
43}
44
45#[derive(Clone)]
46enum Repr<V> {
47 Small(Box<[(Box<str>, V)]>),
48 #[allow(clippy::box_collection)]
50 Large(Box<BTreeMap<Box<str>, V>>),
51}
52
53#[derive(Clone)]
55enum Either<A, B> {
56 A(A),
57 B(B),
58}
59
60impl<A: Iterator, B: Iterator<Item = A::Item>> Iterator for Either<A, B> {
61 type Item = A::Item;
62 fn next(&mut self) -> Option<A::Item> {
63 match self {
64 Either::A(a) => a.next(),
65 Either::B(b) => b.next(),
66 }
67 }
68 fn size_hint(&self) -> (usize, Option<usize>) {
69 match self {
70 Either::A(a) => a.size_hint(),
71 Either::B(b) => b.size_hint(),
72 }
73 }
74}
75
76impl<A: DoubleEndedIterator, B: DoubleEndedIterator<Item = A::Item>> DoubleEndedIterator for Either<A, B> {
77 fn next_back(&mut self) -> Option<A::Item> {
78 match self {
79 Either::A(a) => a.next_back(),
80 Either::B(b) => b.next_back(),
81 }
82 }
83}
84
85macro_rules! iterator {
87 ($(#[$doc:meta])* $name:ident<$($lt:lifetime,)? V>, $item:ty, $small:ty, $large:ty) => {
88 $(#[$doc])*
89 pub struct $name<$($lt,)? V>(Either<$small, $large>);
90 impl<$($lt,)? V> Iterator for $name<$($lt,)? V> {
91 type Item = $item;
92 fn next(&mut self) -> Option<$item> {
93 self.0.next()
94 }
95 fn size_hint(&self) -> (usize, Option<usize>) {
96 self.0.size_hint()
97 }
98 }
99 impl<$($lt,)? V> DoubleEndedIterator for $name<$($lt,)? V> {
100 fn next_back(&mut self) -> Option<$item> {
101 self.0.next_back()
102 }
103 }
104 impl<$($lt,)? V> ExactSizeIterator for $name<$($lt,)? V> {}
105 impl<$($lt,)? V> FusedIterator for $name<$($lt,)? V> {}
106 };
107}
108
109iterator!(
110 Iter<'a, V>, (&'a str, &'a V),
112 Map<std::slice::Iter<'a, (Box<str>, V)>, for<'x> fn(&'x (Box<str>, V)) -> (&'x str, &'x V)>,
113 Map<btree_map::Iter<'a, Box<str>, V>, for<'x> fn((&'x Box<str>, &'x V)) -> (&'x str, &'x V)>
114);
115iterator!(
116 IterMut<'a, V>, (&'a str, &'a mut V),
118 Map<std::slice::IterMut<'a, (Box<str>, V)>, for<'x> fn(&'x mut (Box<str>, V)) -> (&'x str, &'x mut V)>,
119 Map<btree_map::IterMut<'a, Box<str>, V>, for<'x> fn((&'x Box<str>, &'x mut V)) -> (&'x str, &'x mut V)>
120);
121iterator!(
122 Keys<'a, V>, &'a str,
124 Map<std::slice::Iter<'a, (Box<str>, V)>, for<'x> fn(&'x (Box<str>, V)) -> &'x str>,
125 Map<btree_map::Keys<'a, Box<str>, V>, for<'x> fn(&'x Box<str>) -> &'x str>
126);
127iterator!(
128 Values<'a, V>, &'a V,
130 Map<std::slice::Iter<'a, (Box<str>, V)>, for<'x> fn(&'x (Box<str>, V)) -> &'x V>,
131 btree_map::Values<'a, Box<str>, V>
132);
133iterator!(
134 ValuesMut<'a, V>, &'a mut V,
136 Map<std::slice::IterMut<'a, (Box<str>, V)>, for<'x> fn(&'x mut (Box<str>, V)) -> &'x mut V>,
137 btree_map::ValuesMut<'a, Box<str>, V>
138);
139iterator!(
140 IntoIter<V>, (Box<str>, V),
142 std::vec::IntoIter<(Box<str>, V)>,
143 btree_map::IntoIter<Box<str>, V>
144);
145
146impl<V> Clone for Iter<'_, V> {
147 fn clone(&self) -> Self {
148 Iter(self.0.clone())
149 }
150}
151impl<V> Clone for Keys<'_, V> {
152 fn clone(&self) -> Self {
153 Keys(self.0.clone())
154 }
155}
156impl<V> Clone for Values<'_, V> {
157 fn clone(&self) -> Self {
158 Values(self.0.clone())
159 }
160}
161
162fn entry_ref<V>(e: &(Box<str>, V)) -> (&str, &V) {
163 (&e.0, &e.1)
164}
165fn entry_mut<V>(e: &mut (Box<str>, V)) -> (&str, &mut V) {
166 (&e.0, &mut e.1)
167}
168fn entry_key<V>(e: &(Box<str>, V)) -> &str {
169 &e.0
170}
171fn entry_value<V>(e: &(Box<str>, V)) -> &V {
172 &e.1
173}
174fn entry_value_mut<V>(e: &mut (Box<str>, V)) -> &mut V {
175 &mut e.1
176}
177#[allow(clippy::borrowed_box)] fn tree_ref<'x, V>((k, v): (&'x Box<str>, &'x V)) -> (&'x str, &'x V) {
179 (k, v)
180}
181#[allow(clippy::borrowed_box)]
182fn tree_mut<'x, V>((k, v): (&'x Box<str>, &'x mut V)) -> (&'x str, &'x mut V) {
183 (k, v)
184}
185#[allow(clippy::borrowed_box)]
186fn tree_key(k: &Box<str>) -> &str {
187 k
188}
189
190fn sorted_last_wins<V>(mut v: Vec<(Box<str>, V)>) -> Vec<(Box<str>, V)> {
192 if v.windows(2).all(|w| w[0].0 < w[1].0) {
193 return v;
194 }
195 v.sort_by(|a, b| a.0.cmp(&b.0));
196 v.dedup_by(|later, kept| {
198 if later.0 == kept.0 {
199 std::mem::swap(&mut later.1, &mut kept.1);
200 true
201 } else {
202 false
203 }
204 });
205 v
206}
207
208impl<V> Default for SmallMap<V> {
209 fn default() -> SmallMap<V> {
210 SmallMap { repr: Repr::Small(Box::default()) }
211 }
212}
213
214impl<V> SmallMap<V> {
215 pub fn new() -> SmallMap<V> {
217 SmallMap::default()
218 }
219
220 pub(crate) fn from_sorted_vec(v: Vec<(Box<str>, V)>) -> SmallMap<V> {
222 let repr = if v.len() > SMALL_MAX { Repr::Large(Box::new(v.into_iter().collect())) } else { Repr::Small(v.into_boxed_slice()) };
223 SmallMap { repr }
224 }
225
226 #[doc(hidden)]
229 pub fn is_compact(&self) -> bool {
230 matches!(self.repr, Repr::Small(_))
231 }
232
233 fn find(s: &[(Box<str>, V)], key: &str) -> Result<usize, usize> {
234 s.binary_search_by(|(k, _)| (**k).cmp(key))
235 }
236
237 fn edit<R>(s: &mut Box<[(Box<str>, V)]>, f: impl FnOnce(&mut Vec<(Box<str>, V)>) -> R) -> R {
239 let mut v = std::mem::take(s).into_vec();
240 let r = f(&mut v);
241 *s = v.into_boxed_slice();
242 r
243 }
244
245 fn grow(&mut self) -> &mut BTreeMap<Box<str>, V> {
247 if let Repr::Small(s) = &mut self.repr {
248 let tree: BTreeMap<Box<str>, V> = std::mem::take(s).into_vec().into_iter().collect();
249 self.repr = Repr::Large(Box::new(tree));
250 }
251 match &mut self.repr {
252 Repr::Large(t) => t,
253 Repr::Small(_) => unreachable!("just grown"),
254 }
255 }
256
257 fn shrink(&mut self) {
259 if let Repr::Large(t) = &mut self.repr {
260 if t.len() <= SMALL_MIN {
261 let v: Vec<(Box<str>, V)> = std::mem::take(&mut **t).into_iter().collect();
262 self.repr = Repr::Small(v.into_boxed_slice());
263 }
264 }
265 }
266
267 pub fn len(&self) -> usize {
269 match &self.repr {
270 Repr::Small(s) => s.len(),
271 Repr::Large(t) => t.len(),
272 }
273 }
274
275 pub fn is_empty(&self) -> bool {
277 self.len() == 0
278 }
279
280 pub fn get(&self, key: &str) -> Option<&V> {
282 match &self.repr {
283 Repr::Small(s) => Self::find(s, key).ok().map(|i| &s[i].1),
284 Repr::Large(t) => t.get(key),
285 }
286 }
287
288 pub fn get_mut(&mut self, key: &str) -> Option<&mut V> {
290 match &mut self.repr {
291 Repr::Small(s) => Self::find(s, key).ok().map(|i| &mut s[i].1),
292 Repr::Large(t) => t.get_mut(key),
293 }
294 }
295
296 pub fn get_key_value(&self, key: &str) -> Option<(&str, &V)> {
298 match &self.repr {
299 Repr::Small(s) => Self::find(s, key).ok().map(|i| entry_ref(&s[i])),
300 Repr::Large(t) => t.get_key_value(key).map(tree_ref),
301 }
302 }
303
304 pub fn contains_key(&self, key: &str) -> bool {
306 self.get(key).is_some()
307 }
308
309 pub fn insert<K: AsRef<str> + Into<Box<str>>>(&mut self, key: K, value: V) -> Option<V> {
311 if let Repr::Small(s) = &mut self.repr {
312 let at = match s.last() {
314 Some((last, _)) if **last >= *key.as_ref() => Self::find(s, key.as_ref()),
315 _ => Err(s.len()),
316 };
317 match at {
318 Ok(i) => return Some(std::mem::replace(&mut s[i].1, value)),
319 Err(i) if s.len() < SMALL_MAX => {
320 Self::edit(s, |v| {
321 v.reserve_exact(1);
322 v.insert(i, (key.into(), value));
323 });
324 return None;
325 }
326 Err(_) => {}
327 }
328 }
329 let t = self.grow();
330 if let Some(slot) = t.get_mut(key.as_ref()) {
331 return Some(std::mem::replace(slot, value));
332 }
333 t.insert(key.into(), value)
334 }
335
336 pub fn remove(&mut self, key: &str) -> Option<V> {
338 match &mut self.repr {
339 Repr::Small(s) => {
340 let i = Self::find(s, key).ok()?;
341 Some(Self::edit(s, |v| v.remove(i)).1)
342 }
343 Repr::Large(t) => {
344 let out = t.remove(key);
345 self.shrink();
346 out
347 }
348 }
349 }
350
351 pub fn clear(&mut self) {
353 *self = SmallMap::new();
354 }
355
356 pub fn retain(&mut self, mut keep: impl FnMut(&str, &mut V) -> bool) {
358 match &mut self.repr {
359 Repr::Small(s) => Self::edit(s, |v| v.retain_mut(|(k, val)| keep(k, val))),
360 Repr::Large(t) => {
361 t.retain(|k, v| keep(k, v));
362 self.shrink();
363 }
364 }
365 }
366
367 pub fn get_or_insert_with<K: AsRef<str> + Into<Box<str>>>(&mut self, key: K, make: impl FnOnce() -> V) -> &mut V {
370 if let Repr::Small(s) = &self.repr {
371 match Self::find(s, key.as_ref()) {
372 Ok(i) => {
373 let Repr::Small(s) = &mut self.repr else { unreachable!("small") };
374 return &mut s[i].1;
375 }
376 Err(i) if s.len() < SMALL_MAX => {
377 let Repr::Small(s) = &mut self.repr else { unreachable!("small") };
378 let (k, v) = (key.into(), make());
379 Self::edit(s, |e| {
380 e.reserve_exact(1);
381 e.insert(i, (k, v));
382 });
383 return &mut s[i].1;
384 }
385 Err(_) => {}
386 }
387 }
388 let t = self.grow();
389 if t.contains_key(key.as_ref()) {
390 return t.get_mut(key.as_ref()).expect("present");
391 }
392 t.entry(key.into()).or_insert_with(make)
393 }
394
395 pub fn iter(&self) -> Iter<'_, V> {
397 Iter(match &self.repr {
398 Repr::Small(s) => Either::A(s.iter().map(entry_ref::<V> as _)),
399 Repr::Large(t) => Either::B(t.iter().map(tree_ref::<V> as _)),
400 })
401 }
402
403 pub fn iter_mut(&mut self) -> IterMut<'_, V> {
405 IterMut(match &mut self.repr {
406 Repr::Small(s) => Either::A(s.iter_mut().map(entry_mut::<V> as _)),
407 Repr::Large(t) => Either::B(t.iter_mut().map(tree_mut::<V> as _)),
408 })
409 }
410
411 pub fn keys(&self) -> Keys<'_, V> {
413 Keys(match &self.repr {
414 Repr::Small(s) => Either::A(s.iter().map(entry_key::<V> as _)),
415 Repr::Large(t) => Either::B(t.keys().map(tree_key as _)),
416 })
417 }
418
419 pub fn values(&self) -> Values<'_, V> {
421 Values(match &self.repr {
422 Repr::Small(s) => Either::A(s.iter().map(entry_value::<V> as _)),
423 Repr::Large(t) => Either::B(t.values()),
424 })
425 }
426
427 pub fn values_mut(&mut self) -> ValuesMut<'_, V> {
429 ValuesMut(match &mut self.repr {
430 Repr::Small(s) => Either::A(s.iter_mut().map(entry_value_mut::<V> as _)),
431 Repr::Large(t) => Either::B(t.values_mut()),
432 })
433 }
434}
435
436impl<V: PartialEq> PartialEq for SmallMap<V> {
437 fn eq(&self, other: &SmallMap<V>) -> bool {
439 self.len() == other.len() && self.iter().eq(other.iter())
440 }
441}
442
443impl<V: Eq> Eq for SmallMap<V> {}
444
445impl<V: PartialOrd> PartialOrd for SmallMap<V> {
446 fn partial_cmp(&self, other: &SmallMap<V>) -> Option<Ordering> {
448 self.iter().partial_cmp(other.iter())
449 }
450}
451
452impl<V: Ord> Ord for SmallMap<V> {
453 fn cmp(&self, other: &SmallMap<V>) -> Ordering {
454 self.iter().cmp(other.iter())
455 }
456}
457
458impl<V: Hash> Hash for SmallMap<V> {
459 fn hash<H: Hasher>(&self, h: &mut H) {
461 h.write_usize(self.len());
462 for (k, v) in self {
463 k.hash(h);
464 v.hash(h);
465 }
466 }
467}
468
469impl<V: fmt::Debug> fmt::Debug for SmallMap<V> {
470 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
472 f.debug_map().entries(self.iter()).finish()
473 }
474}
475
476impl<V, Q: AsRef<str> + ?Sized> Index<&Q> for SmallMap<V> {
477 type Output = V;
478 fn index(&self, key: &Q) -> &V {
480 self.get(key.as_ref()).expect("no entry found for key")
481 }
482}
483
484impl<'a, V> IntoIterator for &'a SmallMap<V> {
485 type Item = (&'a str, &'a V);
486 type IntoIter = Iter<'a, V>;
487 fn into_iter(self) -> Iter<'a, V> {
488 self.iter()
489 }
490}
491
492impl<'a, V> IntoIterator for &'a mut SmallMap<V> {
493 type Item = (&'a str, &'a mut V);
494 type IntoIter = IterMut<'a, V>;
495 fn into_iter(self) -> IterMut<'a, V> {
496 self.iter_mut()
497 }
498}
499
500impl<V> IntoIterator for SmallMap<V> {
501 type Item = (Box<str>, V);
502 type IntoIter = IntoIter<V>;
503 fn into_iter(self) -> IntoIter<V> {
504 IntoIter(match self.repr {
505 Repr::Small(s) => Either::A(s.into_vec().into_iter()),
506 Repr::Large(t) => Either::B(t.into_iter()),
507 })
508 }
509}
510
511impl<K: Into<Box<str>>, V> FromIterator<(K, V)> for SmallMap<V> {
512 fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> SmallMap<V> {
514 let v: Vec<(Box<str>, V)> = iter.into_iter().map(|(k, v)| (k.into(), v)).collect();
515 SmallMap::from_sorted_vec(sorted_last_wins(v))
516 }
517}
518
519impl<K: Into<Box<str>>, V> Extend<(K, V)> for SmallMap<V> {
520 fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
523 let s = match &mut self.repr {
524 Repr::Large(t) => {
525 for (k, v) in iter {
526 t.insert(k.into(), v);
527 }
528 return;
529 }
530 Repr::Small(s) => s,
531 };
532 let new = sorted_last_wins(iter.into_iter().map(|(k, v)| (k.into(), v)).collect::<Vec<_>>());
533 if new.is_empty() {
534 return;
535 }
536 let old = std::mem::take(s).into_vec();
537 let mut out = Vec::with_capacity(old.len() + new.len());
538 let (mut a, mut b) = (old.into_iter().peekable(), new.into_iter().peekable());
539 loop {
540 let take_old = match (a.peek(), b.peek()) {
541 (Some(x), Some(y)) => match x.0.cmp(&y.0) {
542 Ordering::Less => true,
543 Ordering::Equal => {
544 a.next();
545 false
546 }
547 Ordering::Greater => false,
548 },
549 (Some(_), None) => true,
550 (None, Some(_)) => false,
551 (None, None) => break,
552 };
553 out.extend(if take_old { a.next() } else { b.next() });
554 }
555 *self = SmallMap::from_sorted_vec(out);
556 }
557}
558
559impl<V> From<BTreeMap<String, V>> for SmallMap<V> {
560 fn from(m: BTreeMap<String, V>) -> SmallMap<V> {
562 SmallMap::from_sorted_vec(m.into_iter().map(|(k, v)| (k.into_boxed_str(), v)).collect())
563 }
564}
565
566impl<V> From<SmallMap<V>> for BTreeMap<String, V> {
567 fn from(m: SmallMap<V>) -> BTreeMap<String, V> {
568 m.into_iter().map(|(k, v)| (k.into_string(), v)).collect()
569 }
570}
571
572impl<V: Clone> From<&SmallMap<V>> for SmallMap<V> {
573 fn from(m: &SmallMap<V>) -> SmallMap<V> {
575 m.clone()
576 }
577}
578
579impl<K: Into<Box<str>>, V, const N: usize> From<[(K, V); N]> for SmallMap<V> {
580 fn from(a: [(K, V); N]) -> SmallMap<V> {
581 a.into_iter().collect()
582 }
583}
584
585impl<V: Serialize> Serialize for SmallMap<V> {
586 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
588 s.collect_map(self.iter())
589 }
590}
591
592impl<'de, V: Deserialize<'de>> Deserialize<'de> for SmallMap<V> {
593 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<SmallMap<V>, D::Error> {
595 struct V0<V>(PhantomData<V>);
596 impl<'de, V: Deserialize<'de>> Visitor<'de> for V0<V> {
597 type Value = SmallMap<V>;
598 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
599 f.write_str("a map")
600 }
601 fn visit_map<A: MapAccess<'de>>(self, mut m: A) -> Result<SmallMap<V>, A::Error> {
602 let mut v = Vec::with_capacity(m.size_hint().unwrap_or(0).min(64));
604 while let Some((k, val)) = m.next_entry::<Box<str>, V>()? {
605 v.push((k, val));
606 }
607 Ok(SmallMap::from_sorted_vec(sorted_last_wins(v)))
608 }
609 }
610 d.deserialize_map(V0(PhantomData))
611 }
612}
613
614#[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
618pub struct TextMap(SmallMap<Box<str>>);
619
620pub type TextIter<'a> = Map<Iter<'a, Box<str>>, for<'x> fn((&'x str, &'x Box<str>)) -> (&'x str, &'x str)>;
622pub type TextValues<'a> = Map<Values<'a, Box<str>>, for<'x> fn(&'x Box<str>) -> &'x str>;
624pub type TextIntoIter = IntoIter<Box<str>>;
626
627#[allow(clippy::borrowed_box)] fn text_pair<'x>((k, v): (&'x str, &'x Box<str>)) -> (&'x str, &'x str) {
629 (k, v)
630}
631#[allow(clippy::borrowed_box)]
632fn text_value(v: &Box<str>) -> &str {
633 v
634}
635
636impl TextMap {
637 pub fn new() -> TextMap {
639 TextMap::default()
640 }
641 pub fn len(&self) -> usize {
643 self.0.len()
644 }
645 pub fn is_empty(&self) -> bool {
647 self.0.is_empty()
648 }
649 pub fn get(&self, key: &str) -> Option<&str> {
651 self.0.get(key).map(|v| &**v)
652 }
653 pub fn contains_key(&self, key: &str) -> bool {
655 self.0.contains_key(key)
656 }
657 pub fn insert<K: AsRef<str> + Into<Box<str>>>(&mut self, key: K, value: impl Into<Box<str>>) -> Option<Box<str>> {
659 self.0.insert(key, value.into())
660 }
661 pub fn remove(&mut self, key: &str) -> Option<Box<str>> {
663 self.0.remove(key)
664 }
665 pub fn clear(&mut self) {
667 self.0.clear();
668 }
669 pub fn retain(&mut self, mut keep: impl FnMut(&str, &str) -> bool) {
671 self.0.retain(|k, v| keep(k, v));
672 }
673 pub fn get_or_insert_with<K: AsRef<str> + Into<Box<str>>, T: Into<Box<str>>>(&mut self, key: K, make: impl FnOnce() -> T) -> &str {
675 self.0.get_or_insert_with(key, || make().into())
676 }
677 pub fn iter(&self) -> TextIter<'_> {
679 self.0.iter().map(text_pair as _)
680 }
681 pub fn keys(&self) -> Keys<'_, Box<str>> {
683 self.0.keys()
684 }
685 pub fn values(&self) -> TextValues<'_> {
687 self.0.values().map(text_value as _)
688 }
689}
690
691impl fmt::Debug for TextMap {
692 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
694 f.debug_map().entries(self.iter()).finish()
695 }
696}
697
698impl<Q: AsRef<str> + ?Sized> Index<&Q> for TextMap {
699 type Output = str;
700 fn index(&self, key: &Q) -> &str {
702 self.get(key.as_ref()).expect("no entry found for key")
703 }
704}
705
706impl<'a> IntoIterator for &'a TextMap {
707 type Item = (&'a str, &'a str);
708 type IntoIter = TextIter<'a>;
709 fn into_iter(self) -> TextIter<'a> {
710 self.iter()
711 }
712}
713
714impl IntoIterator for TextMap {
715 type Item = (Box<str>, Box<str>);
716 type IntoIter = TextIntoIter;
717 fn into_iter(self) -> TextIntoIter {
718 self.0.into_iter()
719 }
720}
721
722impl<K: Into<Box<str>>, T: Into<Box<str>>> FromIterator<(K, T)> for TextMap {
723 fn from_iter<I: IntoIterator<Item = (K, T)>>(iter: I) -> TextMap {
725 TextMap(iter.into_iter().map(|(k, v)| (k, v.into())).collect())
726 }
727}
728
729impl<K: Into<Box<str>>, T: Into<Box<str>>> Extend<(K, T)> for TextMap {
730 fn extend<I: IntoIterator<Item = (K, T)>>(&mut self, iter: I) {
732 self.0.extend(iter.into_iter().map(|(k, v)| (k, v.into())));
733 }
734}
735
736impl From<BTreeMap<String, String>> for TextMap {
737 fn from(m: BTreeMap<String, String>) -> TextMap {
739 TextMap(SmallMap::from_sorted_vec(m.into_iter().map(|(k, v)| (k.into_boxed_str(), v.into_boxed_str())).collect()))
740 }
741}
742
743impl From<TextMap> for BTreeMap<String, String> {
744 fn from(m: TextMap) -> BTreeMap<String, String> {
745 m.into_iter().map(|(k, v)| (k.into_string(), v.into_string())).collect()
746 }
747}
748
749impl From<&TextMap> for TextMap {
750 fn from(m: &TextMap) -> TextMap {
752 m.clone()
753 }
754}
755
756impl<K: Into<Box<str>>, T: Into<Box<str>>, const N: usize> From<[(K, T); N]> for TextMap {
757 fn from(a: [(K, T); N]) -> TextMap {
758 a.into_iter().collect()
759 }
760}
761
762impl Serialize for TextMap {
763 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
765 self.0.serialize(s)
766 }
767}
768
769impl<'de> Deserialize<'de> for TextMap {
770 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<TextMap, D::Error> {
772 SmallMap::deserialize(d).map(TextMap)
773 }
774}
775
776#[cfg(test)]
777mod tests {
778 use super::*;
779 use std::iter::FusedIterator;
780
781 fn keys<V>(m: &SmallMap<V>) -> Vec<&str> {
782 m.keys().collect()
783 }
784
785 #[test]
786 fn new_and_default_allocate_nothing_and_are_empty() {
787 let m: SmallMap<u8> = SmallMap::new();
788 assert!(m.is_empty());
789 assert_eq!(m.len(), 0);
790 assert_eq!(m, SmallMap::default());
791 assert_eq!(std::mem::size_of::<SmallMap<u8>>(), 16);
792 assert_eq!(serde_json::to_string(&m).unwrap(), "{}");
793 }
794
795 #[test]
796 fn insert_keeps_order_and_replaces() {
797 let mut m = SmallMap::new();
798 assert_eq!(m.insert("b", 2), None);
799 assert_eq!(m.insert("d", 4), None); assert_eq!(m.insert("a", 1), None); assert_eq!(m.insert(String::from("c"), 3), None); assert_eq!(m.insert("b", 20), Some(2)); assert_eq!(keys(&m), ["a", "b", "c", "d"]);
804 assert_eq!(m.get("b"), Some(&20));
805 assert_eq!(m["d"], 4);
806 assert_eq!(m.len(), 4);
807 assert!(m.contains_key("c") && !m.contains_key("e"));
808 assert_eq!(m.get_key_value("c"), Some(("c", &3)));
809 }
810
811 #[test]
812 fn index_takes_str_string_and_box() {
813 let m = SmallMap::from([("k", 7)]);
814 let s = String::from("k");
815 let b: Box<str> = "k".into();
816 assert_eq!((m["k"], m[&s], m[&*s], m[&b]), (7, 7, 7, 7));
817 }
818
819 #[test]
820 #[should_panic(expected = "no entry found for key")]
821 fn index_panics_on_a_missing_key() {
822 let m: SmallMap<u8> = SmallMap::new();
823 let _ = m["x"];
824 }
825
826 #[test]
827 fn remove_clear_retain() {
828 let mut m: SmallMap<i32> = (0..10).map(|i| (format!("k{i}"), i)).collect();
829 assert_eq!(m.remove("k3"), Some(3));
830 assert_eq!(m.remove("k3"), None);
831 m.retain(|k, v| {
832 *v += 1;
833 k != "k5"
834 });
835 assert_eq!(m.values().copied().collect::<Vec<_>>(), [1, 2, 3, 5, 7, 8, 9, 10]);
836 m.clear();
837 assert!(m.is_empty());
838 }
839
840 #[test]
841 fn get_or_insert_with_inserts_once() {
842 let mut m: SmallMap<Vec<u8>> = SmallMap::new();
843 m.get_or_insert_with("x", Vec::new).push(1);
844 m.get_or_insert_with(String::from("x"), || panic!("present")).push(2);
845 m.get_or_insert_with("a", Vec::new).push(9);
846 assert_eq!(m["x"], [1, 2]);
847 assert_eq!(keys(&m), ["a", "x"]);
848 }
849
850 #[test]
851 fn mutable_access() {
852 let mut m = SmallMap::from([("a", 1), ("b", 2)]);
853 *m.get_mut("a").unwrap() += 10;
854 for (_, v) in m.iter_mut() {
855 *v *= 2;
856 }
857 for v in m.values_mut() {
858 *v += 1;
859 }
860 for (k, v) in &mut m {
861 if k == "b" {
862 *v = 0;
863 }
864 }
865 assert_eq!(m.iter().collect::<Vec<_>>(), [("a", &23), ("b", &0)]);
866 assert!(m.get_mut("z").is_none());
867 }
868
869 #[test]
870 fn collect_and_from_sort_and_last_wins() {
871 let m: SmallMap<u8> = vec![("b", 1), ("a", 2), ("b", 3), ("c", 4), ("a", 5)].into_iter().collect();
872 assert_eq!(m.iter().collect::<Vec<_>>(), [("a", &5), ("b", &3), ("c", &4)]);
873 let bt: BTreeMap<String, u8> = vec![("b", 1), ("a", 2), ("b", 3), ("c", 4), ("a", 5)].into_iter().map(|(k, v)| (k.to_string(), v)).collect();
874 assert_eq!(SmallMap::from(bt.clone()), m);
875 assert_eq!(BTreeMap::from(m.clone()), bt);
876 assert_eq!(SmallMap::from(&m), m);
877 }
878
879 #[test]
880 fn extend_merges_and_new_wins() {
881 let mut m = SmallMap::from([("b", 1), ("d", 2)]);
882 m.extend([("a", 10), ("d", 20), ("e", 30), ("a", 11)]);
883 assert_eq!(m.iter().collect::<Vec<_>>(), [("a", &11), ("b", &1), ("d", &20), ("e", &30)]);
884 m.extend(Vec::<(String, i32)>::new());
885 assert_eq!(m.len(), 4);
886 }
887
888 #[test]
889 fn owned_iteration_and_into_iter_ref() {
890 let m = SmallMap::from([("b", 2), ("a", 1)]);
891 let mut seen = vec![];
892 for (k, v) in &m {
893 seen.push((k.to_string(), *v));
894 }
895 assert_eq!(seen, [("a".to_string(), 1), ("b".to_string(), 2)]);
896 let owned: Vec<(Box<str>, i32)> = m.into_iter().rev().collect();
897 assert_eq!(&*owned[0].0, "b");
898 }
899
900 #[test]
901 fn iterators_are_exact_and_double_ended() {
902 let m = SmallMap::from([("a", 1), ("b", 2), ("c", 3)]);
903 assert_eq!(m.iter().len(), 3);
904 assert_eq!(m.keys().rev().collect::<Vec<_>>(), ["c", "b", "a"]);
905 assert_eq!(m.values().next_back(), Some(&3));
906 fn fused<I: FusedIterator>(_: I) {}
907 fused(m.iter());
908 }
909
910 #[test]
911 fn debug_matches_btreemap() {
912 let m = SmallMap::from([("b", "x"), ("a", "y")]);
913 let bt: BTreeMap<String, &str> = [("b".to_string(), "x"), ("a".to_string(), "y")].into();
914 assert_eq!(format!("{m:?}"), format!("{bt:?}"));
915 let t = TextMap::from([("b", "x"), ("a", "y")]);
916 assert_eq!(format!("{t:?}"), format!("{bt:?}"));
917 }
918
919 #[test]
920 fn serde_is_a_sorted_object_and_last_wins() {
921 let m = SmallMap::from([("z", 1), ("a", 2)]);
922 assert_eq!(serde_json::to_string(&m).unwrap(), r#"{"a":2,"z":1}"#);
923 let back: SmallMap<i32> = serde_json::from_str(r#"{"z":1,"a":2,"z":3}"#).unwrap();
924 assert_eq!(back.iter().collect::<Vec<_>>(), [("a", &2), ("z", &3)]);
925 let bt: BTreeMap<String, i32> = serde_json::from_str(r#"{"z":1,"a":2,"z":3}"#).unwrap();
926 assert_eq!(serde_json::to_string(&back).unwrap(), serde_json::to_string(&bt).unwrap());
927 let v = serde_json::json!({"b": 1, "a": 2});
929 let from_value: SmallMap<i32> = serde_json::from_value(v).unwrap();
930 assert_eq!(keys(&from_value), ["a", "b"]);
931 assert!(serde_json::from_str::<SmallMap<i32>>("[1]").is_err());
932 assert!(serde_json::from_str::<SmallMap<i32>>(r#"{"a":"x"}"#).is_err());
933 }
934
935 #[test]
936 fn keys_sort_in_str_order_like_string() {
937 let ks = ["b", "B", "_o", "~x", "$raw", "a1", "a10", "a2", "é", "z", "", "\u{10000}"];
940 let m: SmallMap<u8> = ks.iter().map(|k| (*k, 0)).collect();
941 let bt: BTreeMap<String, u8> = ks.iter().map(|k| (k.to_string(), 0)).collect();
942 assert_eq!(m.keys().collect::<Vec<_>>(), bt.keys().map(String::as_str).collect::<Vec<_>>());
943 assert_eq!(serde_json::to_string(&m).unwrap(), serde_json::to_string(&bt).unwrap());
944 }
945
946 #[test]
947 fn insert_in_order_appends_without_search() {
948 let mut m = SmallMap::new();
949 for i in 0..2000 {
950 assert_eq!(m.insert(format!("k{i:05}"), i), None);
951 }
952 assert_eq!(m.len(), 2000);
953 assert!(m.keys().zip(m.keys().skip(1)).all(|(a, b)| a < b));
954 for i in (0..2000).rev() {
955 assert_eq!(m.insert(format!("k{i:05}"), i + 1), Some(i));
956 }
957 }
958
959 #[test]
960 fn bulk_build_of_many_entries() {
961 let m: SmallMap<u32> = (0..50_000u32).rev().map(|i| (format!("{i:06}"), i)).collect();
963 assert_eq!(m.len(), 50_000);
964 assert_eq!(m["000123"], 123);
965 let mut e = SmallMap::from([("000001", 0u32)]);
966 e.extend((0..50_000u32).rev().map(|i| (format!("{i:06}"), i)));
967 assert_eq!(e, m);
968 }
969
970 fn hash_of<T: Hash>(t: &T) -> u64 {
971 let mut h = std::hash::DefaultHasher::new();
972 t.hash(&mut h);
973 h.finish()
974 }
975
976 #[test]
977 fn a_full_slice_moves_to_a_tree_and_back() {
978 let mut m = SmallMap::new();
979 for i in 0..SMALL_MAX {
980 m.insert(format!("k{i:02}"), i);
981 }
982 assert!(m.is_compact());
983 m.insert("k99", 99);
984 assert!(!m.is_compact());
985 assert_eq!(m.len(), SMALL_MAX + 1);
986 let keys: Vec<String> = m.keys().map(str::to_string).collect();
988 for k in &keys[..SMALL_MAX - SMALL_MIN] {
989 assert!(m.remove(k).is_some());
990 }
991 assert_eq!(m.len(), SMALL_MIN + 1);
992 assert!(!m.is_compact());
993 m.remove(&keys[SMALL_MAX - SMALL_MIN]);
994 assert!(m.is_compact());
995 assert_eq!(m.len(), SMALL_MIN);
996 let mut g: SmallMap<usize> = (0..SMALL_MAX).map(|i| (format!("{i}"), i)).collect();
998 assert!(g.is_compact());
999 *g.get_or_insert_with("new", || 0) += 1;
1000 assert!(!g.is_compact());
1001 assert_eq!(g["new"], 1);
1002 g.retain(|k, _| k.len() == 1);
1003 assert!(g.is_compact());
1004 assert_eq!(g.len(), 10);
1005 g.extend((0..SMALL_MAX).map(|i| (format!("x{i}"), i)));
1006 assert!(!g.is_compact());
1007 assert_eq!(g.len(), 10 + SMALL_MAX);
1008 let c: SmallMap<u8> = (0..=SMALL_MAX).map(|i| (format!("{i}"), 0)).collect();
1009 assert!(!c.is_compact());
1010 g.clear();
1011 assert!(g.is_compact() && g.is_empty());
1012 }
1013
1014 #[test]
1015 fn both_representations_look_the_same() {
1016 let big: SmallMap<u32> = (0..40).map(|i| (format!("k{i}"), i)).collect();
1017 let mut tree = big.clone();
1018 for i in 20..40 {
1019 tree.remove(&format!("k{i}"));
1020 }
1021 let slice: SmallMap<u32> = (0..20).map(|i| (format!("k{i}"), i)).collect();
1022 assert!(!tree.is_compact() && slice.is_compact());
1023 assert_eq!(tree, slice);
1024 assert_eq!(slice, tree);
1025 assert_eq!(hash_of(&tree), hash_of(&slice));
1026 assert_eq!(tree.cmp(&slice), Ordering::Equal);
1027 assert_eq!(tree.partial_cmp(&slice), Some(Ordering::Equal));
1028 assert_eq!(format!("{tree:?}"), format!("{slice:?}"));
1029 assert_eq!(serde_json::to_string(&tree).unwrap(), serde_json::to_string(&slice).unwrap());
1030 assert_eq!(tree.iter().collect::<Vec<_>>(), slice.iter().collect::<Vec<_>>());
1031 assert_eq!(tree.iter().rev().collect::<Vec<_>>(), slice.iter().rev().collect::<Vec<_>>());
1032 assert_eq!(tree.keys().len(), 20);
1033 assert_eq!(tree.values().sum::<u32>(), slice.values().sum::<u32>());
1034 assert_eq!(tree.get_key_value("k3"), slice.get_key_value("k3"));
1035 assert_eq!(tree.clone().into_iter().collect::<Vec<_>>(), slice.clone().into_iter().collect::<Vec<_>>());
1036 assert_eq!(BTreeMap::from(tree.clone()), BTreeMap::from(slice.clone()));
1037 let mut other = slice.clone();
1038 other.insert("k0", 100);
1039 assert_eq!(tree.cmp(&other), slice.cmp(&other));
1040 assert_ne!(tree, other);
1041 let t = TextMap::from_iter((0..40).map(|i| (format!("k{i}"), "v")));
1042 assert_eq!(serde_json::to_string(&t).unwrap(), serde_json::to_string(&BTreeMap::from(t.clone())).unwrap());
1043 }
1044
1045 #[test]
1046 #[should_panic(expected = "no entry found for key")]
1047 fn index_panics_the_same_on_a_tree() {
1048 let m: SmallMap<u8> = (0..100).map(|i| (format!("{i}"), 0)).collect();
1049 assert!(!m.is_compact());
1050 let _ = m["x"];
1051 }
1052
1053 #[test]
1054 fn json_picks_the_representation_by_size() {
1055 let body: Vec<String> = (0..50).rev().map(|i| format!("\"{i}\":{i}")).collect();
1056 let m: SmallMap<u32> = serde_json::from_str(&format!("{{{}}}", body.join(","))).unwrap();
1057 assert!(!m.is_compact());
1058 let bt: BTreeMap<String, u32> = serde_json::from_str(&format!("{{{}}}", body.join(","))).unwrap();
1059 assert_eq!(serde_json::to_string(&m).unwrap(), serde_json::to_string(&bt).unwrap());
1060 assert!(SmallMap::from(BTreeMap::from([("a".to_string(), 1)])).is_compact());
1061 assert!(!SmallMap::from(bt).is_compact());
1062 }
1063
1064 #[test]
1065 fn text_map_reads_and_writes_str() {
1066 let mut t = TextMap::new();
1067 assert!(t.is_empty());
1068 assert_eq!(t.insert("part", "slide1.xml"), None);
1069 assert_eq!(t.insert(String::from("cells"), String::from("A1")), None);
1070 assert_eq!(t.insert("part", "slide2.xml").as_deref(), Some("slide1.xml"));
1071 assert_eq!(t.get("part"), Some("slide2.xml"));
1072 assert_eq!(&t["cells"], "A1");
1073 assert_eq!(t.len(), 2);
1074 assert!(t.contains_key("cells"));
1075 assert_eq!(t.iter().collect::<Vec<_>>(), [("cells", "A1"), ("part", "slide2.xml")]);
1076 assert_eq!(t.keys().collect::<Vec<_>>(), ["cells", "part"]);
1077 assert_eq!(t.values().collect::<Vec<_>>(), ["A1", "slide2.xml"]);
1078 assert_eq!(t.get_or_insert_with("cells", || "B2"), "A1");
1079 assert_eq!(t.get_or_insert_with("new", String::new), "");
1080 t.retain(|k, _| k != "new");
1081 t.extend([("a", "1")]);
1082 assert_eq!(serde_json::to_string(&t).unwrap(), r#"{"a":"1","cells":"A1","part":"slide2.xml"}"#);
1083 assert_eq!(t.remove("a").as_deref(), Some("1"));
1084 let bt = BTreeMap::from(t.clone());
1085 assert_eq!(TextMap::from(bt), t);
1086 assert_eq!(TextMap::from(&t), t);
1087 let back: TextMap = serde_json::from_str(r#"{"b":"x","a":"y","b":"z"}"#).unwrap();
1088 assert_eq!(back.iter().collect::<Vec<_>>(), [("a", "y"), ("b", "z")]);
1089 let mut n = 0;
1090 for (_, v) in &back {
1091 n += v.len();
1092 }
1093 assert_eq!(n, 2);
1094 t.clear();
1095 assert!(t.is_empty());
1096 assert_eq!(back.into_iter().count(), 2);
1097 }
1098}