pub struct ElasticShardSet<K, V> { /* private fields */ }Expand description
A set of shards that can grow and shrink at runtime.
Each shard is a FabricHashMap backed by its own
grafos_std::mem::MemLease.
Keys are routed to shards via hash(key) % shard_count.
§Example
use grafos_cache::elastic::ElasticShardSet;
let mut shards: ElasticShardSet<u32, u32> =
ElasticShardSet::new(2, 64, 8, 8)?;
shards.put(&1, &100)?;
shards.put(&2, &200)?;
assert_eq!(shards.get(&1)?, Some(100));
assert_eq!(shards.shard_count(), 2);
// Grow by one shard and redistribute
shards.add_shard()?;
shards.rehash()?;
assert_eq!(shards.shard_count(), 3);
assert_eq!(shards.get(&1)?, Some(100));Implementations§
Source§impl<K, V> ElasticShardSet<K, V>
impl<K, V> ElasticShardSet<K, V>
Sourcepub fn new(
initial_shards: usize,
buckets_per_shard: usize,
key_stride: usize,
val_stride: usize,
) -> Result<Self>
pub fn new( initial_shards: usize, buckets_per_shard: usize, key_stride: usize, val_stride: usize, ) -> Result<Self>
Create a new shard set with initial_shards shards.
Each shard is a FabricHashMap allocated via
grafos_std::mem::MemBuilder with
buckets_per_shard buckets. key_stride and val_stride control the
maximum serialized size of keys and values respectively.
§Errors
Returns FabricError::CapacityExceeded if the host cannot provide
enough memory for the requested shards.
Sourcepub fn get(&self, key: &K) -> Result<Option<V>>
pub fn get(&self, key: &K) -> Result<Option<V>>
Look up a value by key.
Hashes the key to select the correct shard, then performs a lookup within that shard.
Sourcepub fn put(&mut self, key: &K, value: &V) -> Result<()>
pub fn put(&mut self, key: &K, value: &V) -> Result<()>
Insert or update a key-value pair.
Hashes the key to select the correct shard, then inserts into that shard.
Sourcepub fn remove(&mut self, key: &K) -> Result<bool>
pub fn remove(&mut self, key: &K) -> Result<bool>
Remove a key-value pair. Returns true if the key existed.
Sourcepub fn add_shard(&mut self) -> Result<()>
pub fn add_shard(&mut self) -> Result<()>
Add one shard to the set.
The new shard is empty. Call rehash afterwards to
redistribute existing entries across all shards.
Sourcepub fn remove_shard(&mut self) -> Result<()>
pub fn remove_shard(&mut self) -> Result<()>
Remove the last shard from the set.
All entries across every shard are drained and redistributed among
the remaining shards (since hash % shard_count changes for all
keys when the shard count changes). The removed shard’s lease is
released on drop.
§Errors
Returns FabricError::CapacityExceeded if the set has only one
shard (cannot shrink below 1).
Sourcepub fn rehash(&mut self) -> Result<()>
pub fn rehash(&mut self) -> Result<()>
Redistribute all entries across the current shard set.
Drains every shard, then re-inserts all entries using the current
shard count. This is useful after add_shard to
balance load.
Sourcepub fn shard_count(&self) -> usize
pub fn shard_count(&self) -> usize
Number of shards in the set.