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 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
use crate::*;
use core::fmt;
/// A list-like [`Valuable`] sub-type.
///
/// Implemented by [`Valuable`] types that have a list-like shape. This includes
/// [`Vec`] and other Rust [collection] types. `Listable` types may or may not
/// store items in contiguous memory. Any type that implements [`IntoIterator`]
/// may implement `Listable`. Values that implement `Listable` must return
/// [`Value::Listable`] from their [`Valuable::as_value`] implementation.
///
/// [collection]: https://doc.rust-lang.org/stable/std/collections/index.html
///
/// # Inspecting
///
/// Inspecting `Listable` items is done by visiting the collection. When
/// visiting a `Listable`, contained values are either passed one-by-one by
/// repeatedly calling [`visit_value()`] or all at once by calling
/// [`visit_primitive_slice()`]. The [`visit_primitive_slice()`] method has
/// lower overhead but can only be used when the `Listable` type contains
/// primitive values.
///
/// See [`Visit`] documentation for more details.
///
/// # Implementing
///
/// If the type stores values in slices internally, then those slices are passed
/// to [`Valuable::visit_slice`], which handles calling
/// [`visit_primitive_slice()`] if possible.
///
/// [`visit_value()`]: Visit::visit_value
/// [`visit_primitive_slice()`]: Visit::visit_primitive_slice
///
/// ```
/// use valuable::{Listable, Valuable, Value, Visit};
///
/// struct MyCollection<T> {
/// chunks: Vec<Vec<T>>,
/// }
///
/// impl<T: Valuable> Valuable for MyCollection<T> {
/// fn as_value(&self) -> Value<'_> {
/// Value::Listable(self)
/// }
///
/// fn visit(&self, visit: &mut dyn Visit) {
/// for chunk in &self.chunks {
/// // Handles visiting the slice
/// Valuable::visit_slice(chunk, visit);
/// }
/// }
/// }
///
/// impl<T: Valuable> Listable for MyCollection<T> {
/// fn size_hint(&self) -> (usize, Option<usize>) {
/// let len = self.chunks.iter().map(|chunk| chunk.len()).sum();
/// (len, Some(len))
/// }
/// }
/// ```
pub trait Listable: Valuable {
/// Returns the bounds on the remaining length of the `Listable`.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
/// A [`None`] here means that either there is no known upper bound, or the
/// upper bound is larger than [`usize`].
///
/// # Implementation notes
///
/// It is not enforced that a `Listable` implementation yields the declared
/// number of elements. A buggy iterator may yield less than the lower bound
/// or more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the `Listable`, but must not be
/// trusted to e.g., omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
/// That said, the implementation should provide a correct estimation,
/// because otherwise it would be a violation of the trait's protocol.
///
/// [`usize`]: type@usize
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use valuable::Listable;
///
/// let a = vec![1, 2, 3];
///
/// assert_eq!((3, Some(3)), a.size_hint());
/// ```
fn size_hint(&self) -> (usize, Option<usize>);
}
macro_rules! deref {
(
$(
$(#[$attrs:meta])*
$ty:ty,
)*
) => {
$(
$(#[$attrs])*
impl<T: ?Sized + Listable> Listable for $ty {
fn size_hint(&self) -> (usize, Option<usize>) {
T::size_hint(&**self)
}
}
)*
};
}
deref! {
&T,
&mut T,
#[cfg(feature = "alloc")]
alloc::boxed::Box<T>,
#[cfg(feature = "alloc")]
alloc::rc::Rc<T>,
#[cfg(not(valuable_no_atomic_cas))]
#[cfg(feature = "alloc")]
alloc::sync::Arc<T>,
}
macro_rules! slice {
(
$(
$(#[$attrs:meta])*
($($generics:tt)*) $ty:ty,
)*
) => {
$(
$(#[$attrs])*
impl<$($generics)*> Valuable for $ty {
fn as_value(&self) -> Value<'_> {
Value::Listable(self as &dyn Listable)
}
fn visit(&self, visit: &mut dyn Visit) {
T::visit_slice(self, visit);
}
}
$(#[$attrs])*
impl<$($generics)*> Listable for $ty {
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len(), Some(self.len()))
}
}
)*
};
}
slice! {
(T: Valuable) &'_ [T],
#[cfg(feature = "alloc")]
(T: Valuable) alloc::boxed::Box<[T]>,
#[cfg(feature = "alloc")]
(T: Valuable) alloc::rc::Rc<[T]>,
#[cfg(not(valuable_no_atomic_cas))]
#[cfg(feature = "alloc")]
(T: Valuable) alloc::sync::Arc<[T]>,
(T: Valuable, const N: usize) [T; N],
#[cfg(feature = "alloc")]
(T: Valuable) alloc::vec::Vec<T>,
}
macro_rules! collection {
(
$(
$(#[$attrs:meta])*
($($generics:tt)*) $ty:ty,
)*
) => {
$(
$(#[$attrs])*
impl<$($generics)*> Valuable for $ty {
fn as_value(&self) -> Value<'_> {
Value::Listable(self as &dyn Listable)
}
fn visit(&self, visit: &mut dyn Visit) {
for value in self.iter() {
visit.visit_value(value.as_value());
}
}
}
$(#[$attrs])*
impl<$($generics)*> Listable for $ty {
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len(), Some(self.len()))
}
}
)*
};
}
collection! {
#[cfg(feature = "alloc")]
(T: Valuable) alloc::collections::LinkedList<T>,
#[cfg(feature = "alloc")]
(T: Valuable + Ord) alloc::collections::BinaryHeap<T>,
#[cfg(feature = "alloc")]
(T: Valuable + Ord) alloc::collections::BTreeSet<T>,
#[cfg(feature = "std")]
(T: Valuable + Eq + std::hash::Hash, H: std::hash::BuildHasher) std::collections::HashSet<T, H>,
}
#[cfg(feature = "alloc")]
impl<T: Valuable> Valuable for alloc::collections::VecDeque<T> {
fn as_value(&self) -> Value<'_> {
Value::Listable(self as &dyn Listable)
}
fn visit(&self, visit: &mut dyn Visit) {
let (first, second) = self.as_slices();
T::visit_slice(first, visit);
T::visit_slice(second, visit);
}
}
#[cfg(feature = "alloc")]
impl<T: Valuable> Listable for alloc::collections::VecDeque<T> {
fn size_hint(&self) -> (usize, Option<usize>) {
(self.len(), Some(self.len()))
}
}
impl fmt::Debug for dyn Listable + '_ {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
struct DebugListable<'a, 'b> {
fmt: fmt::DebugList<'a, 'b>,
}
impl Visit for DebugListable<'_, '_> {
fn visit_value(&mut self, value: Value<'_>) {
self.fmt.entry(&value);
}
}
let mut debug = DebugListable {
fmt: fmt.debug_list(),
};
self.visit(&mut debug);
debug.fmt.finish()
}
}