Add `shards_mut()` and `into_shards()` to `DashMap` and `shards()` to `ReadOnlyView` (#237)

This commit is contained in:
Arash Sahebolamri 2023-01-19 23:04:58 -08:00 committed by GitHub
parent 83a2cf46e0
commit 8a0149d31b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 68 additions and 0 deletions

View File

@ -318,11 +318,51 @@ impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone> DashMap<K, V, S> {
pub fn shards(&self) -> &[RwLock<HashMap<K, V, S>>] {
&self.shards
}
/// Provides mutable access to the inner shards that store your data.
/// You should probably not use this unless you know what you are doing.
///
/// Requires the `raw-api` feature to be enabled.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
/// use dashmap::SharedValue;
///
/// let mut map = DashMap::<i32, &'static str>::new();
/// let shard_ind = map.determine_map(&42);
/// map.shards_mut()[shard_ind].get_mut().insert(42, SharedValue::new("forty two"));
/// assert_eq!(*map.get(&42).unwrap(), "forty two");
/// ```
pub fn shards_mut(&mut self) -> &mut [RwLock<HashMap<K, V, S>>] {
&mut self.shards
}
/// Consumes this `DashMap` and returns the inner shards.
/// You should probably not use this unless you know what you are doing.
///
/// Requires the `raw-api` feature to be enabled.
///
/// See [`DashMap::shards()`] and [`DashMap::shards_mut()`] for more information.
pub fn into_shards(self) -> Box<[RwLock<HashMap<K, V, S>>]> {
self.shards
}
} else {
#[allow(dead_code)]
pub(crate) fn shards(&self) -> &[RwLock<HashMap<K, V, S>>] {
&self.shards
}
#[allow(dead_code)]
pub(crate) fn shards_mut(&mut self) -> &mut [RwLock<HashMap<K, V, S>>] {
&mut self.shards
}
#[allow(dead_code)]
pub(crate) fn into_shards(self) -> Box<[RwLock<HashMap<K, V, S>>]> {
self.shards
}
}
}

View File

@ -1,5 +1,7 @@
use crate::lock::RwLock;
use crate::t::Map;
use crate::{DashMap, HashMap};
use cfg_if::cfg_if;
use core::borrow::Borrow;
use core::fmt;
use core::hash::{BuildHasher, Hash};
@ -121,6 +123,32 @@ impl<'a, K: 'a + Eq + Hash, V: 'a, S: BuildHasher + Clone> ReadOnlyView<K, V, S>
.flat_map(|shard| shard.values())
.map(|v| v.get())
}
cfg_if! {
if #[cfg(feature = "raw-api")] {
/// Allows you to peek at the inner shards that store your data.
/// You should probably not use this unless you know what you are doing.
///
/// Requires the `raw-api` feature to be enabled.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
///
/// let map = DashMap::<(), ()>::new().into_read_only();
/// println!("Amount of shards: {}", map.shards().len());
/// ```
pub fn shards(&self) -> &[RwLock<HashMap<K, V, S>>] {
&self.map.shards
}
} else {
#[allow(dead_code)]
pub(crate) fn shards(&self) -> &[RwLock<HashMap<K, V, S>>] {
&self.map.shards
}
}
}
}
#[cfg(test)]