summaryrefslogtreecommitdiff
path: root/oryxc/src/hashtrie.rs
blob: 87c561e486ca9e34bf618b2d0d98dc5e449a2afd (plain) (blame)
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
use std::hash::{
	Hash,
	Hasher,
};
use std::ptr;
use std::sync::atomic::{
	AtomicPtr,
	Ordering,
};

use crate::arena::LocalArena;

struct FNV1a {
	state: u64,
}

impl FNV1a {
	const OFFSET_BASIS: u64 = 0xCBF29CE484222325;
	const PRIME: u64 = 0x00000100000001B3;

	fn new() -> Self {
		return Self {
			state: Self::OFFSET_BASIS,
		};
	}
}

impl Hasher for FNV1a {
	fn write(&mut self, bytes: &[u8]) {
		for &b in bytes {
			self.state ^= b as u64;
			self.state = self.state.wrapping_mul(Self::PRIME);
		}
	}

	fn finish(&self) -> u64 {
		return self.state;
	}
}

pub struct HTrieNode<K, V>
where
	K: Copy + Eq + Hash,
{
	sub: [AtomicPtr<HTrieNode<K, V>>; 4],
	key: K,
	val: AtomicPtr<V>,
}

impl<K, V> HTrieNode<K, V>
where
	K: Copy + Eq + Hash,
{
	fn new(key: K, valptr: *mut V) -> Self {
		return Self {
			sub: [
				AtomicPtr::new(ptr::null_mut()),
				AtomicPtr::new(ptr::null_mut()),
				AtomicPtr::new(ptr::null_mut()),
				AtomicPtr::new(ptr::null_mut()),
			],
			key,
			val: AtomicPtr::new(valptr),
		};
	}
}

#[derive(Debug)]
pub struct HTrie<K, V>
where
	K: Copy + Eq + Hash,
{
	root: AtomicPtr<HTrieNode<K, V>>,
}

impl<K, V> HTrie<K, V>
where
	K: Copy + Eq + Hash,
{
	pub fn new() -> Self {
		return Self {
			root: AtomicPtr::new(ptr::null_mut()),
		};
	}

	/// Lock-free insert into the hash-trie.
	///
	/// Returns `None` if the key was newly inserted.
	/// Returns `Some(val)` with the previous value if the key already
	/// existed.
	pub fn insert(&self, key: K, val: V, arena: &LocalArena) -> Option<V> {
		let mut h = {
			let mut h = FNV1a::new();
			key.hash(&mut h);
			h.finish()
		};

		let mut m = &self.root;
		let valptr = arena.alloc(val);

		loop {
			let mut n = m.load(Ordering::Acquire);

			if n.is_null() {
				let mark = arena.mark();
				let node = arena.alloc(HTrieNode::new(key, valptr));

				match m.compare_exchange(
					ptr::null_mut(),
					node as *mut HTrieNode<K, V>,
					Ordering::Release,
					Ordering::Acquire,
				) {
					Ok(_) => {
						return None;
					},
					Err(ptr) => {
						arena.restore(mark);
						n = ptr;
					},
				}
			}

			let n = unsafe { &*n };

			if n.key == key {
				let old_valptr = n.val.swap(valptr, Ordering::AcqRel);

				if old_valptr.is_null() {
					return None;
				} else {
					let old_val = unsafe { ptr::read(old_valptr) };
					return Some(old_val);
				}
			}

			m = &n.sub[(h >> 62) as usize];
			h <<= 2;
		}
	}

	/// Check if the given key exists in the hash-trie.
	pub fn contains(&self, key: K) -> bool {
		let mut h = {
			let mut h = FNV1a::new();
			key.hash(&mut h);
			h.finish()
		};

		let mut m = &self.root;

		loop {
			let n = m.load(Ordering::Acquire);
			if n.is_null() {
				return false;
			}
			let n = unsafe { &*n };
			if n.key == key {
				return !n.val.load(Ordering::Acquire).is_null();
			}
			m = &n.sub[(h >> 62) as usize];
			h <<= 2;
		}
	}
}

#[cfg(test)]
mod tests {
	use crate::arena::{
		GlobalArena,
		LocalArena,
	};
	use crate::hashtrie::HTrie;

	#[test]
	fn test_htrie_insert() {
		let ga = GlobalArena::new(128);
		let la = LocalArena::new(&ga);
		let ht = HTrie::new();

		assert_eq!(ht.insert("foo", "bar", &la), None);
		assert_eq!(ht.insert("hello", "sailor", &la), None);
		assert_eq!(ht.insert("thomas", "voss", &la), None);
	}

	#[test]
	fn test_htrie_overwrite() {
		let ga = GlobalArena::new(128);
		let la = LocalArena::new(&ga);
		let ht = HTrie::new();

		ht.insert("foo", "bar", &la);
		ht.insert("hello", "sailor", &la);
		ht.insert("thomas", "voss", &la);
		assert_eq!(ht.insert("foo", "bar-0", &la), Some("bar"));
		assert_eq!(ht.insert("hello", "sailor-0", &la), Some("sailor"));
		assert_eq!(ht.insert("thomas", "voss-0", &la), Some("voss"));
		assert_eq!(ht.insert("foo", "bar-1", &la), Some("bar-0"));
		assert_eq!(ht.insert("hello", "sailor-1", &la), Some("sailor-0"));
		assert_eq!(ht.insert("thomas", "voss-1", &la), Some("voss-0"));
	}

	#[test]
	fn test_htrie_contains() {
		let ga = GlobalArena::new(128);
		let la = LocalArena::new(&ga);
		let ht = HTrie::new();

		assert!(!ht.contains("foo"));
		assert!(!ht.contains("hello"));
		assert!(!ht.contains("thomas"));
		ht.insert("foo", "bar", &la);
		ht.insert("hello", "sailor", &la);
		ht.insert("thomas", "voss", &la);
		assert!(ht.contains("foo"));
		assert!(ht.contains("hello"));
		assert!(ht.contains("thomas"));
	}
}