pear/input/
length.rs

1/// Trait implemented for types that have a length as required by the
2/// [`Input::Slice`](crate::input::Input::Slice) associated type.
3pub trait Length {
4    /// Returns the length of `self`.
5    ///
6    /// While the units of length are unspecified, the returned value must be
7    /// consistent with the use of `n` in the [`Input::slice()`] method. In
8    /// particular, if [`Input::slice(n)`] returns `Some(x)`, then `x.len()`
9    /// must return `n`.
10    ///
11    /// [`Input::slice()`]: crate::input::Input::slice()
12    /// [`Input::slice(n)`]: crate::input::Input::slice()
13    fn len(&self) -> usize;
14
15    /// Returns true iff the length of `self` is equal to zero.
16    fn is_empty(&self) -> bool { self.len() == 0 }
17}
18
19impl Length for str {
20    #[inline(always)]
21    fn len(&self) -> usize {
22        str::len(self)
23    }
24}
25
26impl<'a, T> Length for &'a [T] {
27    #[inline(always)]
28    fn len(&self) -> usize {
29        <[T]>::len(self)
30    }
31}
32
33macro_rules! impl_length_for_sized_slice {
34    ($($size:expr),*) => ($(
35        impl<'a, T> Length for &'a [T; $size] {
36            #[inline(always)] fn len(&self) -> usize { $size }
37        }
38    )*)
39}
40
41impl_length_for_sized_slice! {
42     0,  1,  2,  3,  4,  5,  6,  7,  8,  9,
43    10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
44    20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
45    30, 31, 32
46}
47
48impl<T> Length for [T] {
49    #[inline(always)]
50    fn len(&self) -> usize {
51        <[T]>::len(self)
52    }
53}
54
55impl<T> Length for Vec<T> {
56    #[inline(always)]
57    fn len(&self) -> usize {
58        <Vec<T>>::len(self)
59    }
60}
61
62impl<'a> Length for &'a str {
63    #[inline(always)]
64    fn len(&self) -> usize {
65        str::len(self)
66    }
67}
68
69impl Length for String {
70    #[inline(always)]
71    fn len(&self) -> usize {
72        String::len(self)
73    }
74}