toad_len/
lib.rs

1//! This microcrate contains a `Len` trait that provides capacity and runtime length
2//! for collections.
3
4// docs
5#![doc(html_root_url = "https://docs.rs/toad-len/0.1.0")]
6#![cfg_attr(any(docsrs, feature = "docs"), feature(doc_cfg))]
7// -
8// style
9#![allow(clippy::unused_unit)]
10// -
11// deny
12#![deny(missing_docs)]
13#![deny(missing_debug_implementations)]
14#![deny(missing_copy_implementations)]
15#![cfg_attr(not(test), deny(unsafe_code))]
16// -
17// warnings
18#![cfg_attr(not(test), warn(unreachable_pub))]
19// -
20// features
21#![cfg_attr(not(feature = "std"), no_std)]
22
23#[cfg(feature = "alloc")]
24extern crate alloc as std_alloc;
25
26use core::hash::Hash;
27#[cfg(feature = "std")]
28use std::collections::HashMap;
29
30#[cfg(feature = "alloc")]
31use std_alloc::collections::BTreeMap;
32
33/// Get the runtime size of some data structure
34pub trait Len {
35  /// The maximum number of elements that this data structure can acommodate.
36  const CAPACITY: Option<usize>;
37
38  /// Get the runtime size (in bytes) of a struct
39  ///
40  /// For collections this is always equivalent to calling an inherent `len` method.
41  ///
42  /// ```
43  /// use toad_len::Len;
44  ///
45  /// assert_eq!(Len::len(&vec![1u8, 2]), 2)
46  /// ```
47  fn len(&self) -> usize;
48
49  /// Check if the runtime size is zero
50  ///
51  /// ```
52  /// use toad_len::Len;
53  ///
54  /// assert!(Len::is_empty(&Vec::<u8>::new()))
55  /// ```
56  fn is_empty(&self) -> bool {
57    self.len() == 0
58  }
59
60  /// Is there no room left in this collection?
61  ///
62  /// ```
63  /// use toad_len::Len;
64  ///
65  /// let array = tinyvec::ArrayVec::<[u8; 2]>::from([1, 2]);
66  ///
67  /// assert!(Len::is_full(&array))
68  /// ```
69  fn is_full(&self) -> bool;
70}
71
72#[cfg(feature = "alloc")]
73impl<T> Len for std_alloc::vec::Vec<T> {
74  const CAPACITY: Option<usize> = None;
75
76  fn len(&self) -> usize {
77    self.len()
78  }
79
80  fn is_full(&self) -> bool {
81    false
82  }
83}
84
85impl<A: tinyvec::Array> Len for tinyvec::ArrayVec<A> {
86  const CAPACITY: Option<usize> = Some(A::CAPACITY);
87
88  fn len(&self) -> usize {
89    self.len()
90  }
91
92  fn is_full(&self) -> bool {
93    self.len() >= self.capacity()
94  }
95}
96
97#[cfg(feature = "std")]
98impl<K: Eq + Hash, V> Len for HashMap<K, V> {
99  const CAPACITY: Option<usize> = None;
100
101  fn len(&self) -> usize {
102    self.len()
103  }
104
105  fn is_full(&self) -> bool {
106    false
107  }
108}
109
110#[cfg(feature = "alloc")]
111impl<K, V> Len for BTreeMap<K, V> {
112  const CAPACITY: Option<usize> = None;
113
114  fn len(&self) -> usize {
115    self.len()
116  }
117
118  fn is_full(&self) -> bool {
119    false
120  }
121}