pub trait Mappable: Valuable {
// Required method
fn size_hint(&self) -> (usize, Option<usize>);
}
Expand description
A map-like Valuable
sub-type.
Implemented by Valuable
types that have a map-like shape. This includes
HashMap
and other Rust collection types. Values that implement
Mappable
must return Value::Mappable
from their Value::as_value
implementation.
Inspecting
Inspecting Mappable
entries is done by visiting the value. When visiting a
Mappable
, contained entries are passed one-by-one to the visitor by
repeatedly calling visit_entry()
.
See Visit
documentation for more details.
Implementing
Implementing Mappable
for a custom map type. The map is represented using
a Vec
of key/value pairs.
use valuable::{Mappable, Valuable, Value, Visit};
struct MyMap<K, V> {
entries: Vec<(K, V)>,
}
impl<K: Valuable, V: Valuable> Valuable for MyMap<K, V> {
fn as_value(&self) -> Value<'_> {
Value::Mappable(self)
}
fn visit(&self, visit: &mut dyn Visit) {
for (k, v) in &self.entries {
visit.visit_entry(k.as_value(), v.as_value());
}
}
}
impl<K: Valuable, V: Valuable> Mappable for MyMap<K, V> {
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.entries.len();
(len, Some(len))
}
}
Required Methods§
sourcefn size_hint(&self) -> (usize, Option<usize>)
fn size_hint(&self) -> (usize, Option<usize>)
Returns the bounds on the remaining length of the Mappable
.
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 Mappable
implementation yields the declared
number of elements. A buggy implementation 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 Mappable
, 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.
Examples
Basic usage:
use valuable::Mappable;
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("one", 1);
map.insert("two", 2);
map.insert("three", 3);
assert_eq!((3, Some(3)), map.size_hint());