-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathview.rs
371 lines (354 loc) · 10.7 KB
/
view.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
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
use std::borrow::Borrow;
use std::hash::{BuildHasher, Hash};
use std::ops::Deref;
use crate::util::BorrowHelper;
use crate::{Evicted, Leaked, Map, WriteGuard};
pub(crate) mod sealed {
pub trait ReadAccess {
type Map;
fn with_map<'read, F, R>(&'read self, op: F) -> R
where
F: FnOnce(&'read Self::Map) -> R;
}
}
/// Wraps a guard and provides a view into the map based on that guard.
///
/// This type is the proxy through which all read and write operations are performed on the map.
pub struct View<G> {
guard: G,
}
impl<G> View<G> {
#[inline]
pub(crate) fn new(guard: G) -> Self {
Self { guard }
}
}
impl<K, V, S, G> View<G>
where
G: sealed::ReadAccess<Map = Map<K, V, S>>,
S: BuildHasher,
{
/// Returns whether or not the underlying map is empty.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<u32, u32>();
///
/// // The map is empty
/// assert!(read.guard().is_empty());
///
/// // Add something to the map
/// write.guard().insert(10, 20);
///
/// // The map is no longer empty
/// assert!(!read.guard().is_empty());
/// ```
#[inline]
pub fn is_empty(&self) -> bool {
self.guard.with_map(Map::is_empty)
}
/// Returns the length of the map.
///
/// Note that this just returns the length of the snapshot this guard is viewing. This value
/// should not be relied upon for program correctness.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<u32, u32>();
///
/// // There are no entries in the map currently
/// assert_eq!(read.guard().len(), 0);
///
/// // Add two entires
/// let mut write_guard = write.guard();
/// write_guard.insert(1, 42);
/// write_guard.insert(2, 43);
/// write_guard.publish();
///
/// // Now new read guards will see those entries
/// assert_eq!(read.guard().len(), 2);
/// ```
#[inline]
pub fn len(&self) -> usize {
self.guard.with_map(Map::len)
}
/// Returns whether or not the map contains the given key.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<u32, u32>();
///
/// write.guard().insert(0, 0);
///
/// let guard = read.guard();
/// assert!(guard.contains_key(&0));
/// assert!(!guard.contains_key(&1));
/// ```
#[inline]
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
K: Borrow<Q> + Eq + Hash,
Q: Hash + Eq,
{
self.guard
.with_map(|map| map.contains_key(BorrowHelper::new_ref(key)))
}
/// Returns a reference to the value corresponding to the key.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<String, String>();
///
/// write.guard().insert("apples".to_owned(), "oranges".to_owned());
///
/// let guard = read.guard();
/// assert_eq!(guard.get("apples").unwrap(), "oranges");
/// assert!(guard.get("bananas").is_none());
/// ```
#[inline]
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q> + Eq + Hash,
Q: Hash + Eq,
{
self.guard
.with_map(|map| map.get(BorrowHelper::new_ref(key)).map(Deref::deref))
}
/// An iterator visiting all key-value pairs in arbitrary order.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<i8, i8>();
///
/// let mut guard = write.guard();
/// guard.insert(3, 5);
/// guard.insert(5, 7);
/// guard.insert(7, 11);
/// guard.publish();
///
/// let mut result = 0i8;
/// for (&key, &value) in read.guard().iter() {
/// result += key * value;
/// }
///
/// // 3*5 + 5*7 + 7*11 == 127 == i8::MAX
/// assert_eq!(result, i8::MAX);
/// ```
#[inline]
pub fn iter<'read>(&'read self) -> impl Iterator<Item = (&K, &V)> + '_
where
(K, V): 'read,
{
self.guard
.with_map(|map| map.iter().map(|(key, value)| (&**key, &**value)))
}
/// An iterator visiting all keys in arbitrary order.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<u32, String>();
///
/// let mut guard = write.guard();
/// guard.insert(1, "one".to_owned());
/// guard.insert(10, "ten".to_owned());
/// guard.insert(100, "one hundred".to_owned());
/// guard.publish();
///
/// let mut result = 0u32;
/// for &key in read.guard().keys() {
/// result += key;
/// }
///
/// // 1 + 10 + 100 == 111
/// assert_eq!(result, 111);
/// ```
#[inline]
pub fn keys<'read>(&'read self) -> impl Iterator<Item = &K> + '_
where
(K, V): 'read,
{
self.guard.with_map(|map| map.keys().map(Deref::deref))
}
/// An iterator visiting all values in arbitrary order.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<String, u32>();
///
/// let mut guard = write.guard();
/// guard.insert("one".to_owned(), 1);
/// guard.insert("ten".to_owned(), 10);
/// guard.insert("one hundred".to_owned(), 100);
/// guard.publish();
///
/// let mut result = 0u32;
/// for &key in read.guard().values() {
/// result += key;
/// }
///
/// // 1 + 10 + 100 == 111
/// assert_eq!(result, 111);
/// ```
#[inline]
pub fn values<'read>(&'read self) -> impl Iterator<Item = &V> + '_
where
(K, V): 'read,
{
self.guard.with_map(|map| map.values().map(Deref::deref))
}
}
// TODO: It would probably be nicer if the write functionality got abstracted out into traits, but
// that is a massive headache I don't want to deal with, so we're doing this for now.
impl<'guard, K, V, S> View<WriteGuard<'guard, K, V, S>>
where
K: Eq + Hash,
S: BuildHasher,
{
/// Inserts a key-value pair into the map.
///
/// If the map did not have this key present, then `None` is returned. If it did, then the
/// evicted value is returned. See [`Evicted`](crate::Evicted) for details.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<u32, String>();
/// let mut guard = write.guard();
///
/// assert!(guard.insert(17, "seven teen".to_owned()).is_none());
/// assert_eq!(&*guard.insert(17, "seventeen".to_owned()).unwrap(), "seven teen");
/// ```
#[inline]
pub fn insert<'ret>(&mut self, key: K, value: V) -> Option<Evicted<'ret, K, V>>
where
'guard: 'ret,
{
self.guard.insert(key, value)
}
/// Replaces the value associated with the given key according to the provided function.
///
/// If the key is not present, then the function is not called, and `None` is returned. If the
/// key is present, then the function is called with the current value provided as the argument,
/// the value in the map is replaced, and the evicted value is returned. See
/// [`Evicted`](crate::Evicted) for details.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<u32, String>();
/// let mut guard = write.guard();
///
/// guard.insert(1, "a".to_owned());
///
/// // The key 0 is not in the map, so nothing changes
/// assert!(guard.replace(0, |_| String::new()).is_none());
/// assert_eq!(guard.get(&1).unwrap(), "a");
///
/// // The key 1 is in the map, so the closure gets called
/// let evicted = guard.replace(1, |old| {
/// assert_eq!(old, "a");
/// "b".to_owned()
/// }).unwrap();
///
/// // We evicted the old value "a"
/// assert_eq!(&*evicted, "a");
///
/// // And now "b" is in the map
/// assert_eq!(guard.get(&1).unwrap(), "b");
/// ```
#[inline]
pub fn replace<'ret, F>(&mut self, key: K, op: F) -> Option<Evicted<'ret, K, V>>
where
F: FnOnce(&V) -> V,
'guard: 'ret,
{
self.guard.replace(key, op)
}
/// Removes a key from the map, returning the value at the key if the key was previously in the
/// map. See [`Evicted`](crate::Evicted) for details on accessing the removed value.
///
/// # Examples
///
/// ```
/// # use flashmap;
/// let (mut write, read) = flashmap::new::<u32, String>();
/// let mut guard = write.guard();
///
/// guard.insert(0, "a".to_owned());
///
/// assert_eq!(&*guard.remove(0).unwrap(), "a");
/// assert!(guard.remove(0).is_none());
/// assert!(guard.remove(1).is_none());
/// ```
#[inline]
pub fn remove<'ret>(&mut self, key: K) -> Option<Evicted<'ret, K, V>>
where
'guard: 'ret,
{
self.guard.remove(key)
}
/// Takes ownership of a leaked value and drops the inner value when it is safe to do so.
///
/// There are no guarantees regarding when the leaked value will be dropped. It is only
/// guaranteed that it will eventually be dropped provided that no handles or guards
/// associated with this map are leaked or forgotten.
///
/// # Panics
///
/// Panics if the provided leaked value came from a different map then the one this guard is
/// associated with. Note that it is **not** required that this method is called with the same
/// guard that created the leaked value.
///
/// # Examples
///
/// ```
/// # use flashmap::{self, Evicted};
/// let (mut write, read) = flashmap::new::<String, String>();
///
/// write.guard().insert("ferris".to_owned(), "crab".to_owned());
///
/// // ~~ stuff happens ~~
///
/// let mut guard = write.guard();
///
/// // Remove the value and leak it
/// let leaked = guard.remove("ferris".to_owned())
/// .map(Evicted::leak)
/// .unwrap();
/// assert_eq!(&*leaked, "crab");
///
/// // We decide we don't need to keep the leaked value around, so we tell the guard
/// // to drop it when it is safe to do so
/// guard.drop_lazily(leaked);
///
/// guard.publish();
/// ```
#[inline]
pub fn drop_lazily(&self, leaked: Leaked<V>) {
self.guard.drop_lazily(leaked)
}
/// Consumes this view and its guard, publishing all previous changes to the map.
///
/// This has the same effect as dropping the view. Note that the changes will only be visible
/// through newly created read or write guards.
#[inline]
pub fn publish(self) {
self.guard.publish()
}
}