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
use crate::value::ValueType;
use std::fmt;
use std::hash::{BuildHasher as _, BuildHasherDefault, Hash as _, Hasher as _};
use twox_hash::XxHash64;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Hash(pub(crate) u64);
impl Hash {
pub const GLOBAL_MODULE: Hash = Hash(0);
const SEP: usize = 0x7f;
const TYPE: usize = 1;
const FUNCTION: usize = 2;
const INSTANCE_FUNCTION: usize = 3;
const OBJECT_KEYS: usize = 4;
pub fn of<T: std::hash::Hash>(thing: T) -> Self {
let mut hasher = BuildHasherDefault::<XxHash64>::default().build_hasher();
thing.hash(&mut hasher);
Self(hasher.finish())
}
pub fn object_keys<I>(keys: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
let mut hasher = BuildHasherDefault::<XxHash64>::default().build_hasher();
Self::OBJECT_KEYS.hash(&mut hasher);
for key in keys {
Self::SEP.hash(&mut hasher);
key.as_ref().hash(&mut hasher);
}
Self(hasher.finish())
}
fn path<I>(kind: usize, path: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
let mut hasher = BuildHasherDefault::<XxHash64>::default().build_hasher();
kind.hash(&mut hasher);
for part in path {
part.as_ref().hash(&mut hasher);
Self::SEP.hash(&mut hasher);
}
Self(hasher.finish())
}
pub fn of_type<I>(path: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
Self::path(Self::TYPE, path)
}
pub fn function<I>(path: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
Self::path(Self::FUNCTION, path)
}
pub fn instance_function(ty: ValueType, name: Hash) -> Self {
Self::of((Self::INSTANCE_FUNCTION, ty, Self::SEP, name))
}
}
impl fmt::Display for Hash {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "0x{:x}", self.0)
}
}
impl fmt::Debug for Hash {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(fmt, "Hash(0x{:x})", self.0)
}
}