total_maps/nonzero.rs
1//! Maps that only store entries with nonzero values.
2//!
3//! These types are recommended whenever it is important that the common value is zero, even though
4//! most numeric types' [Default] implementations also yield a zero value.
5
6use num_traits::Zero;
7
8use crate::{Commonality, TotalBTreeMap, TotalHashMap};
9
10/// A hash map that only stores entries with non-zero values. All other keys are presumed to be
11/// associated with the zero value.
12pub type NonZeroHashMap<K, V> = TotalHashMap<K, V, ZeroCommonality>;
13
14/// An ordered map that only stores entries with non-zero values. All other keys are presumed to be
15/// associated with the zero value.
16pub type NonZeroBTreeMap<K, V> = TotalBTreeMap<K, V, ZeroCommonality>;
17
18/// A [commonality](Commonality) based on the [Zero] trait.
19///
20/// A [TotalHashMap] or [TotalBTreeMap] using this commonality only stores entries with nonzero
21/// values.
22pub struct ZeroCommonality(());
23
24impl<T: Zero> Commonality<T> for ZeroCommonality {
25 fn common() -> T {
26 T::zero()
27 }
28 fn is_common(value: &T) -> bool {
29 value.is_zero()
30 }
31}