1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
//! This microcrate contains a `Len` trait that provides capacity and runtime length
//! for collections.

// docs
#![doc(html_root_url = "https://docs.rs/toad-len/0.1.0")]
#![cfg_attr(any(docsrs, feature = "docs"), feature(doc_cfg))]
// -
// style
#![allow(clippy::unused_unit)]
// -
// deny
#![deny(missing_docs)]
#![deny(missing_debug_implementations)]
#![deny(missing_copy_implementations)]
#![cfg_attr(not(test), deny(unsafe_code))]
// -
// warnings
#![cfg_attr(not(test), warn(unreachable_pub))]
// -
// features
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(feature = "alloc")]
extern crate alloc as std_alloc;

use core::hash::Hash;
#[cfg(feature = "std")]
use std::collections::HashMap;

#[cfg(feature = "alloc")]
use std_alloc::collections::BTreeMap;

/// Get the runtime size of some data structure
pub trait Len {
  /// The maximum number of elements that this data structure can acommodate.
  const CAPACITY: Option<usize>;

  /// Get the runtime size (in bytes) of a struct
  ///
  /// For collections this is always equivalent to calling an inherent `len` method.
  ///
  /// ```
  /// use toad_len::Len;
  ///
  /// assert_eq!(Len::len(&vec![1u8, 2]), 2)
  /// ```
  fn len(&self) -> usize;

  /// Check if the runtime size is zero
  ///
  /// ```
  /// use toad_len::Len;
  ///
  /// assert!(Len::is_empty(&Vec::<u8>::new()))
  /// ```
  fn is_empty(&self) -> bool {
    self.len() == 0
  }

  /// Is there no room left in this collection?
  ///
  /// ```
  /// use toad_len::Len;
  ///
  /// let array = tinyvec::ArrayVec::<[u8; 2]>::from([1, 2]);
  ///
  /// assert!(Len::is_full(&array))
  /// ```
  fn is_full(&self) -> bool;
}

#[cfg(feature = "alloc")]
impl<T> Len for std_alloc::vec::Vec<T> {
  const CAPACITY: Option<usize> = None;

  fn len(&self) -> usize {
    self.len()
  }

  fn is_full(&self) -> bool {
    false
  }
}

impl<A: tinyvec::Array> Len for tinyvec::ArrayVec<A> {
  const CAPACITY: Option<usize> = Some(A::CAPACITY);

  fn len(&self) -> usize {
    self.len()
  }

  fn is_full(&self) -> bool {
    self.len() >= self.capacity()
  }
}

#[cfg(feature = "std")]
impl<K: Eq + Hash, V> Len for HashMap<K, V> {
  const CAPACITY: Option<usize> = None;

  fn len(&self) -> usize {
    self.len()
  }

  fn is_full(&self) -> bool {
    false
  }
}

#[cfg(feature = "alloc")]
impl<K, V> Len for BTreeMap<K, V> {
  const CAPACITY: Option<usize> = None;

  fn len(&self) -> usize {
    self.len()
  }

  fn is_full(&self) -> bool {
    false
  }
}