-
Notifications
You must be signed in to change notification settings - Fork 19
/
mappable.rs
95 lines (80 loc) · 2.4 KB
/
mappable.rs
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
use crate::*;
use core::fmt;
pub trait Mappable: Valuable {
fn size_hint(&self) -> (usize, Option<usize>);
}
impl<M: ?Sized + Mappable> Mappable for &M {
fn size_hint(&self) -> (usize, Option<usize>) {
M::size_hint(*self)
}
}
#[cfg(feature = "alloc")]
impl<M: ?Sized + Mappable> Mappable for alloc::boxed::Box<M> {
fn size_hint(&self) -> (usize, Option<usize>) {
M::size_hint(&**self)
}
}
#[cfg(feature = "alloc")]
impl<M: ?Sized + Mappable> Mappable for alloc::rc::Rc<M> {
fn size_hint(&self) -> (usize, Option<usize>) {
M::size_hint(&**self)
}
}
#[cfg(not(valuable_no_atomic_cas))]
#[cfg(feature = "alloc")]
impl<M: ?Sized + Mappable> Mappable for alloc::sync::Arc<M> {
fn size_hint(&self) -> (usize, Option<usize>) {
M::size_hint(&**self)
}
}
#[cfg(feature = "std")]
impl<K: Valuable, V: Valuable> Valuable for std::collections::HashMap<K, V> {
fn as_value(&self) -> Value<'_> {
Value::Mappable(self)
}
fn visit(&self, visit: &mut dyn Visit) {
for (key, value) in self.iter() {
visit.visit_entry(key.as_value(), value.as_value());
}
}
}
#[cfg(feature = "std")]
impl<K: Valuable, V: Valuable> Mappable for std::collections::HashMap<K, V> {
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter().size_hint()
}
}
#[cfg(feature = "alloc")]
impl<K: Valuable, V: Valuable> Valuable for alloc::collections::BTreeMap<K, V> {
fn as_value(&self) -> Value<'_> {
Value::Mappable(self)
}
fn visit(&self, visit: &mut dyn Visit) {
for (key, value) in self.iter() {
visit.visit_entry(key.as_value(), value.as_value());
}
}
}
#[cfg(feature = "alloc")]
impl<K: Valuable, V: Valuable> Mappable for alloc::collections::BTreeMap<K, V> {
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter().size_hint()
}
}
impl fmt::Debug for dyn Mappable + '_ {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
struct DebugMappable<'a, 'b> {
fmt: fmt::DebugMap<'a, 'b>,
}
impl Visit for DebugMappable<'_, '_> {
fn visit_entry(&mut self, key: Value<'_>, value: Value<'_>) {
self.fmt.entry(&key, &value);
}
}
let mut debug = DebugMappable {
fmt: fmt.debug_map(),
};
self.visit(&mut debug);
debug.fmt.finish()
}
}