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
use crate::{utility::reflect_hasher, Enum, Reflect, ReflectRef, VariantType};
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
#[inline]
pub fn enum_hash<TEnum: Enum>(value: &TEnum) -> Option<u64> {
let mut hasher = reflect_hasher();
std::any::Any::type_id(value).hash(&mut hasher);
value.variant_name().hash(&mut hasher);
value.variant_type().hash(&mut hasher);
for field in value.iter_fields() {
hasher.write_u64(field.value().reflect_hash()?);
}
Some(hasher.finish())
}
#[inline]
pub fn enum_partial_eq<TEnum: Enum>(a: &TEnum, b: &dyn Reflect) -> Option<bool> {
let ReflectRef::Enum(b) = b.reflect_ref() else {
return Some(false);
};
if a.variant_name() != b.variant_name() {
return Some(false);
}
if !a.is_variant(b.variant_type()) {
return Some(false);
}
match a.variant_type() {
VariantType::Struct => {
for field in a.iter_fields() {
let field_name = field.name().unwrap();
if let Some(field_value) = b.field(field_name) {
if let Some(false) | None = field_value.reflect_partial_eq(field.value()) {
return Some(false);
}
} else {
return Some(false);
}
}
Some(true)
}
VariantType::Tuple => {
for (i, field) in a.iter_fields().enumerate() {
if let Some(field_value) = b.field_at(i) {
if let Some(false) | None = field_value.reflect_partial_eq(field.value()) {
return Some(false);
}
} else {
return Some(false);
}
}
Some(true)
}
_ => Some(true),
}
}
#[inline]
pub fn enum_debug(dyn_enum: &dyn Enum, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match dyn_enum.variant_type() {
VariantType::Unit => f.write_str(dyn_enum.variant_name()),
VariantType::Tuple => {
let mut debug = f.debug_tuple(dyn_enum.variant_name());
for field in dyn_enum.iter_fields() {
debug.field(&field.value() as &dyn Debug);
}
debug.finish()
}
VariantType::Struct => {
let mut debug = f.debug_struct(dyn_enum.variant_name());
for field in dyn_enum.iter_fields() {
debug.field(field.name().unwrap(), &field.value() as &dyn Debug);
}
debug.finish()
}
}
}