dashmap/
util.rs

1//! This module is full of hackery and dark magic.
2//! Either spend a day fixing it and quietly submit a PR or don't mention it to anybody.
3use core::cell::UnsafeCell;
4use core::{mem, ptr};
5
6pub const fn ptr_size_bits() -> usize {
7    mem::size_of::<usize>() * 8
8}
9
10pub fn map_in_place_2<T, U, F: FnOnce(U, T) -> T>((k, v): (U, &mut T), f: F) {
11    unsafe {
12        // # Safety
13        //
14        // If the closure panics, we must abort otherwise we could double drop `T`
15        let promote_panic_to_abort = AbortOnPanic;
16
17        ptr::write(v, f(k, ptr::read(v)));
18
19        // If we made it here, the calling thread could have already have panicked, in which case
20        // We know that the closure did not panic, so don't bother checking.
21        std::mem::forget(promote_panic_to_abort);
22    }
23}
24
25/// A simple wrapper around `T`
26///
27/// This is to prevent UB when using `HashMap::get_key_value`, because
28/// `HashMap` doesn't expose an api to get the key and value, where
29/// the value is a `&mut T`.
30///
31/// See [#10](https://github.com/xacrimon/dashmap/issues/10) for details
32///
33/// This type is meant to be an implementation detail, but must be exposed due to the `Dashmap::shards`
34#[repr(transparent)]
35pub struct SharedValue<T> {
36    value: UnsafeCell<T>,
37}
38
39impl<T: Clone> Clone for SharedValue<T> {
40    fn clone(&self) -> Self {
41        let inner = self.get().clone();
42
43        Self {
44            value: UnsafeCell::new(inner),
45        }
46    }
47}
48
49unsafe impl<T: Send> Send for SharedValue<T> {}
50
51unsafe impl<T: Sync> Sync for SharedValue<T> {}
52
53impl<T> SharedValue<T> {
54    /// Create a new `SharedValue<T>`
55    pub const fn new(value: T) -> Self {
56        Self {
57            value: UnsafeCell::new(value),
58        }
59    }
60
61    /// Get a shared reference to `T`
62    pub fn get(&self) -> &T {
63        unsafe { &*self.value.get() }
64    }
65
66    /// Get an unique reference to `T`
67    pub fn get_mut(&mut self) -> &mut T {
68        unsafe { &mut *self.value.get() }
69    }
70
71    /// Unwraps the value
72    pub fn into_inner(self) -> T {
73        self.value.into_inner()
74    }
75
76    /// Get a mutable raw pointer to the underlying value
77    pub(crate) fn as_ptr(&self) -> *mut T {
78        self.value.get()
79    }
80}
81
82struct AbortOnPanic;
83
84impl Drop for AbortOnPanic {
85    fn drop(&mut self) {
86        if std::thread::panicking() {
87            std::process::abort()
88        }
89    }
90}