concread/hashmap/impl.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
use crate::internals::hashmap::cursor::CursorReadOps;
use crate::internals::hashmap::cursor::{CursorRead, CursorWrite, SuperBlock};
use crate::internals::hashmap::iter::*;
use std::borrow::Borrow;
use crate::internals::lincowcell::LinCowCellCapable;
use std::fmt::Debug;
use std::hash::Hash;
use std::iter::FromIterator;
/// A concurrently readable map based on a modified B+Tree structured with fast
/// parallel hashed key lookup.
///
/// This structure can be used in locations where you would otherwise us
/// `RwLock<HashMap>` or `Mutex<HashMap>`.
///
/// This is a concurrently readable structure, meaning it has transactional
/// properties. Writers are serialised (one after the other), and readers
/// can exist in parallel with stable views of the structure at a point
/// in time.
///
/// This is achieved through the use of COW or MVCC. As a write occurs
/// subsets of the tree are cloned into the writer thread and then committed
/// later. This may cause memory usage to increase in exchange for a gain
/// in concurrent behaviour.
///
/// Transactions can be rolled-back (aborted) without penalty by dropping
/// the `HashMapWriteTxn` without calling `commit()`.
pub struct HashMap<K, V>
where
K: Hash + Eq + Clone + Debug + Sync + Send + 'static,
V: Clone + Sync + Send + 'static,
{
inner: LinCowCell<SuperBlock<K, V>, CursorRead<K, V>, CursorWrite<K, V>>,
}
unsafe impl<K: Hash + Eq + Clone + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static>
Send for HashMap<K, V>
{
}
unsafe impl<K: Hash + Eq + Clone + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static>
Sync for HashMap<K, V>
{
}
/// An active read transaction over a `HashMap`. The data in this tree
/// is guaranteed to not change and will remain consistent for the life
/// of this transaction.
pub struct HashMapReadTxn<'a, K, V>
where
K: Hash + Eq + Clone + Debug + Sync + Send + 'static,
V: Clone + Sync + Send + 'static,
{
inner: LinCowCellReadTxn<'a, SuperBlock<K, V>, CursorRead<K, V>, CursorWrite<K, V>>,
}
/// An active write transaction for a `HashMap`. The data in this tree
/// may be modified exclusively through this transaction without affecting
/// readers. The write may be rolledback/aborted by dropping this guard
/// without calling `commit()`. Once `commit()` is called, readers will be
/// able to access and perceive changes in new transactions.
pub struct HashMapWriteTxn<'a, K, V>
where
K: Hash + Eq + Clone + Debug + Sync + Send + 'static,
V: Clone + Sync + Send + 'static,
{
inner: LinCowCellWriteTxn<'a, SuperBlock<K, V>, CursorRead<K, V>, CursorWrite<K, V>>,
}
enum SnapshotType<'a, K, V>
where
K: Hash + Eq + Clone + Debug + Sync + Send + 'static,
V: Clone + Sync + Send + 'static,
{
R(&'a CursorRead<K, V>),
W(&'a CursorWrite<K, V>),
}
/// A point-in-time snapshot of the tree from within a read OR write. This is
/// useful for building other transactional types on top of this structure, as
/// you need a way to downcast both HashMapReadTxn or HashMapWriteTxn to
/// a singular reader type for a number of get_inner() style patterns.
///
/// This snapshot IS safe within the read thread due to the nature of the
/// implementation borrowing the inner tree to prevent mutations within the
/// same thread while the read snapshot is open.
pub struct HashMapReadSnapshot<'a, K, V>
where
K: Hash + Eq + Clone + Debug + Sync + Send + 'static,
V: Clone + Sync + Send + 'static,
{
inner: SnapshotType<'a, K, V>,
}
impl<K: Hash + Eq + Clone + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static> Default
for HashMap<K, V>
{
fn default() -> Self {
Self::new()
}
}
impl<K: Hash + Eq + Clone + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static>
FromIterator<(K, V)> for HashMap<K, V>
{
fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
let mut new_sblock = unsafe { SuperBlock::new() };
let prev = new_sblock.create_reader();
let mut cursor = new_sblock.create_writer();
cursor.extend(iter);
let _ = new_sblock.pre_commit(cursor, &prev);
HashMap {
inner: LinCowCell::new(new_sblock),
}
}
}
impl<K: Hash + Eq + Clone + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static>
Extend<(K, V)> for HashMapWriteTxn<'_, K, V>
{
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
self.inner.as_mut().extend(iter);
}
}
impl<K: Hash + Eq + Clone + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static>
HashMapWriteTxn<'_, K, V>
{
/*
pub(crate) fn prehash<Q>(&self, k: &Q) -> u64
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.inner.as_ref().hash_key(k)
}
*/
pub(crate) fn get_prehashed<Q>(&self, k: &Q, k_hash: u64) -> Option<&V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.inner.as_ref().search(k_hash, k)
}
/// Retrieve a value from the map. If the value exists, a reference is returned
/// as `Some(&V)`, otherwise if not present `None` is returned.
pub fn get<Q>(&self, k: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
let k_hash = self.inner.as_ref().hash_key(k);
self.get_prehashed(k, k_hash)
}
/// Assert if a key exists in the map.
pub fn contains_key<Q>(&self, k: &Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.get(k).is_some()
}
/// returns the current number of k:v pairs in the tree
pub fn len(&self) -> usize {
self.inner.as_ref().len()
}
/// Determine if the set is currently empty
pub fn is_empty(&self) -> bool {
self.inner.as_ref().len() == 0
}
/// Iterator over `(&K, &V)` of the set
pub fn iter(&self) -> Iter<K, V> {
self.inner.as_ref().kv_iter()
}
/// Iterator over &K
pub fn values(&self) -> ValueIter<K, V> {
self.inner.as_ref().v_iter()
}
/// Iterator over &V
pub fn keys(&self) -> KeyIter<K, V> {
self.inner.as_ref().k_iter()
}
/// Reset this map to an empty state. As this is within the transaction this
/// change only takes effect once committed. Once cleared, you can begin adding
/// new writes and changes, again, that will only be visible once committed.
pub fn clear(&mut self) {
self.inner.as_mut().clear()
}
/// Insert or update a value by key. If the value previously existed it is returned
/// as `Some(V)`. If the value did not previously exist this returns `None`.
pub fn insert(&mut self, k: K, v: V) -> Option<V> {
// Hash the key.
let k_hash = self.inner.as_ref().hash_key(&k);
self.inner.as_mut().insert(k_hash, k, v)
}
/// Remove a key if it exists in the tree. If the value exists, we return it as `Some(V)`,
/// and if it did not exist, we return `None`
pub fn remove(&mut self, k: &K) -> Option<V> {
let k_hash = self.inner.as_ref().hash_key(k);
self.inner.as_mut().remove(k_hash, k)
}
/// Get a mutable reference to a value in the tree. This is correctly, and
/// safely cloned before you attempt to mutate the value, isolating it from
/// other transactions.
pub fn get_mut(&mut self, k: &K) -> Option<&mut V> {
let k_hash = self.inner.as_ref().hash_key(k);
self.inner.as_mut().get_mut_ref(k_hash, k)
}
/// Create a read-snapshot of the current map. This does NOT guarantee the map may
/// not be mutated during the read, so you MUST guarantee that no functions of the
/// write txn are called while this snapshot is active.
pub fn to_snapshot(&self) -> HashMapReadSnapshot<K, V> {
HashMapReadSnapshot {
inner: SnapshotType::W(self.inner.as_ref()),
}
}
}
impl<K: Hash + Eq + Clone + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static>
HashMapReadTxn<'_, K, V>
{
pub(crate) fn get_prehashed<Q>(&self, k: &Q, k_hash: u64) -> Option<&V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.inner.search(k_hash, k)
}
/// Retrieve a value from the tree. If the value exists, a reference is returned
/// as `Some(&V)`, otherwise if not present `None` is returned.
pub fn get<Q>(&self, k: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
let k_hash = self.inner.as_ref().hash_key(k);
self.get_prehashed(k, k_hash)
}
/// Assert if a key exists in the tree.
pub fn contains_key<Q>(&self, k: &Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.get(k).is_some()
}
/// Returns the current number of k:v pairs in the tree
pub fn len(&self) -> usize {
self.inner.as_ref().len()
}
/// Determine if the set is currently empty
pub fn is_empty(&self) -> bool {
self.inner.as_ref().len() == 0
}
/// Iterator over `(&K, &V)` of the set
pub fn iter(&self) -> Iter<K, V> {
self.inner.as_ref().kv_iter()
}
/// Iterator over &K
pub fn values(&self) -> ValueIter<K, V> {
self.inner.as_ref().v_iter()
}
/// Iterator over &V
pub fn keys(&self) -> KeyIter<K, V> {
self.inner.as_ref().k_iter()
}
/// Create a read-snapshot of the current tree.
/// As this is the read variant, it IS safe, and guaranteed the tree will not change.
pub fn to_snapshot(&self) -> HashMapReadSnapshot<K, V> {
HashMapReadSnapshot {
inner: SnapshotType::R(self.inner.as_ref()),
}
}
}
impl<K: Hash + Eq + Clone + Debug + Sync + Send + 'static, V: Clone + Sync + Send + 'static>
HashMapReadSnapshot<'_, K, V>
{
/// Retrieve a value from the tree. If the value exists, a reference is returned
/// as `Some(&V)`, otherwise if not present `None` is returned.
pub fn get<Q>(&self, k: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
match self.inner {
SnapshotType::R(inner) => {
let k_hash = inner.hash_key(k);
inner.search(k_hash, k)
}
SnapshotType::W(inner) => {
let k_hash = inner.hash_key(k);
inner.search(k_hash, k)
}
}
}
/// Assert if a key exists in the tree.
pub fn contains_key<Q>(&self, k: &Q) -> bool
where
K: Borrow<Q>,
Q: Hash + Eq + ?Sized,
{
self.get(k).is_some()
}
/// Returns the current number of k:v pairs in the tree
pub fn len(&self) -> usize {
match self.inner {
SnapshotType::R(inner) => inner.len(),
SnapshotType::W(inner) => inner.len(),
}
}
/// Determine if the set is currently empty
pub fn is_empty(&self) -> bool {
self.len() == 0
}
// (adv) range
/// Iterator over `(&K, &V)` of the set
pub fn iter(&self) -> Iter<K, V> {
match self.inner {
SnapshotType::R(inner) => inner.kv_iter(),
SnapshotType::W(inner) => inner.kv_iter(),
}
}
/// Iterator over &K
pub fn values(&self) -> ValueIter<K, V> {
match self.inner {
SnapshotType::R(inner) => inner.v_iter(),
SnapshotType::W(inner) => inner.v_iter(),
}
}
/// Iterator over &V
pub fn keys(&self) -> KeyIter<K, V> {
match self.inner {
SnapshotType::R(inner) => inner.k_iter(),
SnapshotType::W(inner) => inner.k_iter(),
}
}
}