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 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
#![doc = include_str!("../README.md")]
#![allow(clippy::comparison_chain)]
#![allow(clippy::len_without_is_empty)]
#![cfg_attr(doc_cfg, feature(doc_cfg))]
#![feature(slice_ptr_get)]
#![feature(allocator_api)]
mod base_node;
mod error;
mod key;
mod lock;
mod node_16;
mod node_256;
mod node_4;
mod node_48;
mod node_ptr;
mod tree;
mod utils;
mod node_lock;
mod range_scan;
#[cfg(feature = "stats")]
mod stats;
#[cfg(test)]
mod tests;
use std::alloc::AllocError;
use std::alloc::Allocator;
use std::marker::PhantomData;
use error::OOMError;
use key::RawKey;
use key::UsizeKey;
use tree::RawTree;
/// Types needed to safely access shared data concurrently.
pub mod epoch {
pub use crossbeam_epoch::{pin, Guard};
}
#[derive(Clone)]
pub struct DefaultAllocator {}
unsafe impl Send for DefaultAllocator {}
unsafe impl Sync for DefaultAllocator {}
unsafe impl Allocator for DefaultAllocator {
fn allocate(&self, layout: std::alloc::Layout) -> Result<std::ptr::NonNull<[u8]>, AllocError> {
let ptr = unsafe { std::alloc::alloc(layout) };
let ptr_slice = std::ptr::slice_from_raw_parts_mut(ptr, layout.size());
Ok(std::ptr::NonNull::new(ptr_slice).unwrap())
}
unsafe fn deallocate(&self, ptr: std::ptr::NonNull<u8>, layout: std::alloc::Layout) {
std::alloc::dealloc(ptr.as_ptr(), layout);
}
}
/// The adaptive radix tree.
/// Currently we only support only one type of memory, the allocator must return the type of memory requested.
pub struct Art<
K: Clone + From<usize>,
V: Clone + From<usize>,
A: Allocator + Clone + 'static = DefaultAllocator,
> where
usize: From<K>,
usize: From<V>,
{
inner: RawTree<UsizeKey, A>,
pt_key: PhantomData<K>,
pt_val: PhantomData<V>,
}
impl<K: Clone + From<usize>, V: Clone + From<usize>> Default for Art<K, V>
where
usize: From<K>,
usize: From<V>,
{
fn default() -> Self {
Self::new(DefaultAllocator {})
}
}
impl<K: Clone + From<usize>, V: Clone + From<usize>, A: Allocator + Clone + Send> Art<K, V, A>
where
usize: From<K>,
usize: From<V>,
{
/// Returns a copy of the value corresponding to the key.
///
/// # Examples
///
/// ```
/// use congee::Art;
/// let tree = Art::default();
/// let guard = tree.pin();
///
/// tree.insert(1, 42, &guard);
/// assert_eq!(tree.get(&1, &guard).unwrap(), 42);
/// ```
#[inline]
pub fn get(&self, key: &K, guard: &epoch::Guard) -> Option<V> {
let key = UsizeKey::key_from(usize::from(key.clone()));
let v = self.inner.get(&key, guard)?;
Some(V::from(v))
}
/// Enters an epoch.
/// Note: this can be expensive, try to reuse it.
///
/// # Examples
///
/// ```
/// use congee::Art;
/// let tree = Art::<usize, usize>::default();
/// let guard = tree.pin();
/// ```
#[inline]
pub fn pin(&self) -> epoch::Guard {
crossbeam_epoch::pin()
}
/// Create an empty [Art] tree.
///
/// # Examples
///
/// ```
/// use congee::Art;
/// let tree = Art::<usize, usize>::default();
/// ```
#[inline]
pub fn new(allocator: A) -> Self {
Art {
inner: RawTree::new(allocator),
pt_key: PhantomData,
pt_val: PhantomData,
}
}
/// Removes key-value pair from the tree, returns the value if the key was found.
///
/// # Examples
///
/// ```
/// use congee::Art;
/// let tree = Art::default();
/// let guard = tree.pin();
///
/// tree.insert(1, 42, &guard);
/// let removed = tree.remove(&1, &guard);
/// assert_eq!(removed, Some(42));
/// assert!(tree.get(&1, &guard).is_none());
/// ```
#[inline]
pub fn remove(&self, k: &K, guard: &epoch::Guard) -> Option<V> {
let key = UsizeKey::key_from(usize::from(k.clone()));
let (old, new) = self.inner.compute_if_present(&key, &mut |_v| None, guard)?;
debug_assert!(new.is_none());
Some(V::from(old))
}
/// Insert a key-value pair to the tree, returns the previous value if the key was already present.
///
/// # Examples
///
/// ```
/// use congee::Art;
/// let tree = Art::default();
/// let guard = tree.pin();
///
/// tree.insert(1, 42, &guard);
/// assert_eq!(tree.get(&1, &guard).unwrap(), 42);
/// let old = tree.insert(1, 43, &guard).unwrap();
/// assert_eq!(old, Some(42));
/// ```
#[inline]
pub fn insert(&self, k: K, v: V, guard: &epoch::Guard) -> Result<Option<V>, OOMError> {
let key = UsizeKey::key_from(usize::from(k));
let val = self.inner.insert(key, usize::from(v), guard);
val.map(|inner| inner.map(|v| V::from(v)))
}
/// Scan the tree with the range of [start, end], write the result to the
/// `result` buffer.
/// It scans the length of `result` or the number of the keys within the range, whichever is smaller;
/// returns the number of the keys scanned.
///
/// # Examples
///
/// ```
/// use congee::Art;
/// let tree = Art::default();
/// let guard = tree.pin();
///
/// tree.insert(1, 42, &guard);
///
/// let low_key = 1;
/// let high_key = 2;
/// let mut result = [(0, 0); 2];
/// let scanned = tree.range(&low_key, &high_key, &mut result, &guard);
/// assert_eq!(scanned, 1);
/// assert_eq!(result, [(1, 42), (0, 0)]);
/// ```
#[inline]
pub fn range(
&self,
start: &K,
end: &K,
result: &mut [(usize, usize)],
guard: &epoch::Guard,
) -> usize {
let start = UsizeKey::key_from(usize::from(start.clone()));
let end = UsizeKey::key_from(usize::from(end.clone()));
self.inner.range(&start, &end, result, guard)
}
/// Compute and update the value if the key presents in the tree.
/// Returns the (old, new) value
///
/// Note that the function `f` is a FnMut and it must be safe to execute multiple times.
/// The `f` is expected to be short and fast as it will hold a exclusive lock on the leaf node.
///
/// # Examples
///
/// ```
/// use congee::Art;
/// let tree = Art::default();
/// let guard = tree.pin();
///
/// tree.insert(1, 42, &guard);
/// let old = tree.compute_if_present(&1, |v| Some(v+1), &guard).unwrap();
/// assert_eq!(old, (42, Some(43)));
/// let val = tree.get(&1, &guard).unwrap();
/// assert_eq!(val, 43);
/// ```
#[inline]
pub fn compute_if_present<F>(
&self,
key: &K,
mut f: F,
guard: &epoch::Guard,
) -> Option<(usize, Option<usize>)>
where
F: FnMut(usize) -> Option<usize>,
{
let u_key = UsizeKey::key_from(usize::from(key.clone()));
self.inner.compute_if_present(&u_key, &mut f, guard)
}
/// Compute or insert the value if the key is not in the tree.
/// Returns the Option(old) value
///
/// Note that the function `f` is a FnMut and it must be safe to execute multiple times.
/// The `f` is expected to be short and fast as it will hold a exclusive lock on the leaf node.
///
/// # Examples
///
/// ```
/// use congee::Art;
/// let tree = Art::default();
/// let guard = tree.pin();
///
/// tree.insert(1, 42, &guard);
/// let old = tree.compute_or_insert(1, |v| v.unwrap() + 1, &guard).unwrap().unwrap();
/// assert_eq!(old, 42);
/// let val = tree.get(&1, &guard).unwrap();
/// assert_eq!(val, 43);
///
/// let old = tree.compute_or_insert(2, |v| {
/// assert!(v.is_none());
/// 2
/// }, &guard).unwrap();
/// assert!(old.is_none());
/// let val = tree.get(&2, &guard).unwrap();
/// assert_eq!(val, 2);
/// ```
pub fn compute_or_insert<F>(
&self,
key: K,
mut f: F,
guard: &epoch::Guard,
) -> Result<Option<V>, OOMError>
where
F: FnMut(Option<usize>) -> usize,
{
let u_key = UsizeKey::key_from(usize::from(key));
let u_val = self.inner.compute_or_insert(u_key, &mut f, guard)?;
Ok(u_val.map(|v| V::from(v)))
}
/// Display the internal node statistics
#[cfg(feature = "stats")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "stats")))]
pub fn stats(&self) -> stats::NodeStats {
self.inner.stats()
}
/// Get a random value from the tree, perform the transformation `f`.
/// This is useful for randomized algorithms.
///
/// `f` takes key and value as input and return the new value, |key: usize, value: usize| -> usize.
///
/// Returns (key, old_value, new_value)
///
/// Note that the function `f` is a FnMut and it must be safe to execute multiple times.
/// The `f` is expected to be short and fast as it will hold a exclusive lock on the leaf node.
///
/// # Examples:
/// ```
/// use congee::Art;
/// let tree = Art::default();
/// let guard = tree.pin();
/// tree.insert(1, 42, &guard);
/// let mut rng = rand::thread_rng();
/// let (key, old_v, new_v) = tree.compute_on_random(&mut rng, |k, v| {
/// assert_eq!(k, 1);
/// assert_eq!(v, 42);
/// v + 1
/// }, &guard).unwrap();
/// assert_eq!(key, 1);
/// assert_eq!(old_v, 42);
/// assert_eq!(new_v, 43);
/// ```
#[cfg(feature = "db_extension")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "db_extension")))]
pub fn compute_on_random(
&self,
rng: &mut impl rand::Rng,
mut f: impl FnMut(K, V) -> V,
guard: &epoch::Guard,
) -> Option<(K, V, V)> {
let mut remapped = |key: usize, value: usize| -> usize {
let v = f(K::from(key), V::from(value));
usize::from(v)
};
let (key, old_v, new_v) = self.inner.compute_on_random(rng, &mut remapped, guard)?;
Some((K::from(key), V::from(old_v), V::from(new_v)))
}
/// Update the value if the old value matches with the new one.
/// Returns the current value.
///
/// # Examples:
/// ```
/// use congee::Art;
/// let tree = Art::default();
/// let guard = tree.pin();
/// tree.insert(1, 42, &guard);
///
///
/// let v = tree.compare_exchange(&1, &42, Some(43), &guard).unwrap();
/// assert_eq!(v, Some(43));
/// ```
pub fn compare_exchange(
&self,
key: &K,
old: &V,
new: Option<V>,
guard: &epoch::Guard,
) -> Result<Option<V>, Option<V>> {
let u_key = UsizeKey::key_from(usize::from(key.clone()));
let new_v = new.clone().map(|v| usize::from(v));
let mut fc = |v: usize| -> Option<usize> {
if v == usize::from(old.clone()) {
new_v
} else {
Some(v)
}
};
let v = self.inner.compute_if_present(&u_key, &mut fc, guard);
match v {
Some((actual_old, actual_new)) => {
if actual_old == usize::from(old.clone()) && actual_new == new_v {
Ok(new)
} else {
Err(actual_new.map(|v| V::from(v)))
}
}
None => Err(None),
}
}
}