Skip to main content

Keyspace

Struct Keyspace 

Source
pub struct Keyspace { /* private fields */ }
Expand description

The core key-value store.

All operations are single-threaded per shard — no internal locking. Memory usage is tracked incrementally on every mutation.

Implementations§

Source§

impl Keyspace

Source

pub fn getbit(&mut self, key: &str, offset: u64) -> Result<u8, WrongType>

Returns the bit at offset in the string stored at key.

Bit ordering is big-endian: byte offset / 8, bit position 7 - (offset % 8). Returns 0 for missing keys or offsets beyond the string’s length.

Source

pub fn setbit( &mut self, key: &str, offset: u64, value: u8, ) -> Result<u8, WriteError>

Sets the bit at offset to value (0 or 1).

Extends the string with zero bytes when offset reaches beyond the current string length. Returns the old bit value.

Follows the same memory-tracking pattern as setrange.

Source

pub fn bitcount( &mut self, key: &str, range: Option<BitRange>, ) -> Result<u64, WrongType>

Counts set bits in the string at key.

When range is None, counts bits across the entire string. When range is Some(r), restricts to the given byte or bit range (negative indices count from the end of the string).

Returns 0 for missing keys.

Source

pub fn bitpos( &mut self, key: &str, bit: u8, range: Option<BitRange>, ) -> Result<i64, WrongType>

Returns the position of the first bit equal to bit (0 or 1).

range works the same as for bitcount. When no end is given for BITPOS 1, the search covers the whole string; for BITPOS 0, it also covers the virtual zero bits beyond the string’s end.

Returns -1 if the bit is not found (except for BITPOS 0 on a missing key, which returns 0).

Source

pub fn bitop( &mut self, op: BitOpKind, dest: String, keys: &[String], ) -> Result<usize, WriteError>

Performs a bitwise operation across keys and stores the result in dest.

Returns the length of the result string (equal to the longest source). Missing keys are treated as zero-filled strings of the same length. NOT requires exactly one source key (enforced at parse time).

Source§

impl Keyspace

Source

pub fn hset( &mut self, key: &str, fields: &[(String, Bytes)], ) -> Result<usize, WriteError>

Sets one or more field-value pairs in a hash.

Creates the hash if the key doesn’t exist. Returns the number of new fields added (fields that were updated don’t count).

Source

pub fn hget( &mut self, key: &str, field: &str, ) -> Result<Option<Bytes>, WrongType>

Gets the value of a field in a hash.

Returns None if the key or field doesn’t exist.

Source

pub fn hgetall(&mut self, key: &str) -> Result<Vec<(String, Bytes)>, WrongType>

Gets all field-value pairs from a hash.

Returns an empty vec if the key doesn’t exist.

Source

pub fn hdel( &mut self, key: &str, fields: &[String], ) -> Result<Vec<String>, WrongType>

Deletes one or more fields from a hash.

Returns the fields that were actually removed.

Source

pub fn hexists(&mut self, key: &str, field: &str) -> Result<bool, WrongType>

Checks if a field exists in a hash.

Source

pub fn hlen(&mut self, key: &str) -> Result<usize, WrongType>

Returns the number of fields in a hash.

Source

pub fn hincrby( &mut self, key: &str, field: &str, delta: i64, ) -> Result<i64, IncrError>

Increments a field’s integer value by the given amount.

Creates the hash and field if they don’t exist, starting from 0.

Source

pub fn hincrbyfloat( &mut self, key: &str, field: &str, delta: f64, ) -> Result<String, IncrFloatError>

Increments a field’s float value by the given amount.

If the field doesn’t exist, it is created with the increment as its value. The stored value must be a valid float or the call returns an error. Returns the new value as a formatted string.

Source

pub fn hkeys(&mut self, key: &str) -> Result<Vec<String>, WrongType>

Returns all field names in a hash.

Source

pub fn hvals(&mut self, key: &str) -> Result<Vec<Bytes>, WrongType>

Returns all values in a hash.

Source

pub fn scan_hash( &mut self, key: &str, cursor: u64, count: usize, pattern: Option<&str>, ) -> Result<(u64, Vec<(String, Bytes)>), WrongType>

Incrementally iterates fields of a hash.

Returns the next cursor and a batch of field-value pairs. A returned cursor of 0 means the iteration is complete. Pattern matching (MATCH) filters on field names.

Source

pub fn hmget( &mut self, key: &str, fields: &[String], ) -> Result<Vec<Option<Bytes>>, WrongType>

Gets multiple field values from a hash.

Returns None for fields that don’t exist.

Source

pub fn hrandfield( &mut self, key: &str, count: Option<i64>, with_values: bool, ) -> Result<Vec<(String, Option<Bytes>)>, WrongType>

Returns random field(s) from a hash.

  • count = None: return one random field (no value, even if with_values is set)
  • count > 0: return up to count distinct fields
  • count < 0: return |count| fields, allowing duplicates

If with_values is true and count is Some, returns interleaved (field, Some(value)) pairs. When count is None, only the field name is returned as (field, None).

Source§

impl Keyspace

Source

pub fn lpush( &mut self, key: &str, values: &[Bytes], ) -> Result<usize, WriteError>

Pushes one or more values to the head (left) of a list.

Creates the list if the key doesn’t exist. Returns Err(WriteError::WrongType) if the key exists but holds a non-list value, or Err(WriteError::OutOfMemory) if the memory limit is reached. Returns the new length on success.

Source

pub fn rpush( &mut self, key: &str, values: &[Bytes], ) -> Result<usize, WriteError>

Pushes one or more values to the tail (right) of a list.

Creates the list if the key doesn’t exist. Returns Err(WriteError::WrongType) if the key exists but holds a non-list value, or Err(WriteError::OutOfMemory) if the memory limit is reached. Returns the new length on success.

Source

pub fn lpop(&mut self, key: &str) -> Result<Option<Bytes>, WrongType>

Pops a value from the head (left) of a list.

Returns Ok(None) if the key doesn’t exist. Removes the key if the list becomes empty. Returns Err(WrongType) on type mismatch.

Source

pub fn rpop(&mut self, key: &str) -> Result<Option<Bytes>, WrongType>

Pops a value from the tail (right) of a list.

Returns Ok(None) if the key doesn’t exist. Removes the key if the list becomes empty. Returns Err(WrongType) on type mismatch.

Source

pub fn lpop_count( &mut self, key: &str, count: usize, ) -> Result<Option<Vec<Bytes>>, WrongType>

Pops up to count values from the head of a list.

Returns Ok(None) if the key doesn’t exist or is empty. Returns Ok(Some(items)) with 1–count elements otherwise. Removes the key when the list becomes empty. Returns Err(WrongType) on type mismatch.

Source

pub fn rpop_count( &mut self, key: &str, count: usize, ) -> Result<Option<Vec<Bytes>>, WrongType>

Pops up to count values from the tail of a list.

Returns Ok(None) if the key doesn’t exist or is empty. Returns Ok(Some(items)) with 1–count elements otherwise. Removes the key when the list becomes empty. Returns Err(WrongType) on type mismatch.

Source

pub fn lrange( &mut self, key: &str, start: i64, stop: i64, ) -> Result<Vec<Bytes>, WrongType>

Returns a range of elements from a list by index.

Supports negative indices (e.g. -1 = last element). Out-of-bounds indices are clamped to the list boundaries. Returns Err(WrongType) on type mismatch. Missing keys return an empty vec.

Source

pub fn llen(&mut self, key: &str) -> Result<usize, WrongType>

Returns the length of a list, or 0 if the key doesn’t exist.

Returns Err(WrongType) on type mismatch.

Source

pub fn lindex( &mut self, key: &str, index: i64, ) -> Result<Option<Bytes>, WrongType>

Returns the element at index in the list, or None if out of bounds.

Negative indices count from the tail (-1 = last element). Returns Err(WrongType) if the key holds a non-list value.

Source

pub fn lset( &mut self, key: &str, index: i64, value: Bytes, ) -> Result<(), LsetError>

Sets the element at index to value.

Negative indices count from the tail. Returns an error if the key doesn’t exist, the index is out of range, or the key holds the wrong type.

Source

pub fn ltrim( &mut self, key: &str, start: i64, stop: i64, ) -> Result<(), WrongType>

Trims a list to keep only elements in the range [start, stop].

Supports negative indices. If the range is empty or inverted, the key is deleted. Missing keys are a no-op.

Source

pub fn linsert( &mut self, key: &str, before: bool, pivot: &[u8], value: Bytes, ) -> Result<i64, WriteError>

Inserts value before or after the first occurrence of pivot.

Returns the new list length on success, -1 if the pivot was not found, or 0 if the key doesn’t exist.

Source

pub fn lrem( &mut self, key: &str, count: i64, value: &[u8], ) -> Result<usize, WrongType>

Removes elements equal to value from the list.

  • count > 0: remove first count matches from head
  • count < 0: remove last |count| matches from tail
  • count == 0: remove all matches

Returns the number of elements removed.

Source

pub fn lpos( &mut self, key: &str, element: &[u8], rank: i64, count: usize, maxlen: usize, ) -> Result<Vec<i64>, WrongType>

Finds the positions of elements matching element in the list.

  • rank: 1-based. Positive scans from head, negative from tail. Rank 2 means “start from the 2nd match”.
  • count: 0 returns all matches, N returns at most N.
  • maxlen: limits the scan to the first (or last) N entries.
Source

pub fn lmove( &mut self, source: &str, destination: &str, src_left: bool, dst_left: bool, ) -> Result<Option<Bytes>, WriteError>

Atomically pops a value from source and pushes it to destination.

src_left controls whether to pop from the head (true) or tail (false) of the source. dst_left controls whether to push to the head (true) or tail (false) of the destination. Source and destination may be the same key (rotate). Returns Ok(None) if the source list is missing.

Source§

impl Keyspace

Source

pub fn sadd( &mut self, key: &str, members: &[String], ) -> Result<usize, WriteError>

Adds one or more members to a set.

Creates the set if the key doesn’t exist. Returns the number of new members added (existing members don’t count).

Source

pub fn srem( &mut self, key: &str, members: &[String], ) -> Result<usize, WrongType>

Removes one or more members from a set.

Returns the number of members that were actually removed.

Source

pub fn smembers(&mut self, key: &str) -> Result<Vec<String>, WrongType>

Returns all members of a set.

Source

pub fn sismember(&mut self, key: &str, member: &str) -> Result<bool, WrongType>

Checks if a member exists in a set.

Source

pub fn scan_set( &mut self, key: &str, cursor: u64, count: usize, pattern: Option<&str>, ) -> Result<(u64, Vec<String>), WrongType>

Incrementally iterates members of a set.

Returns the next cursor and a batch of members. A returned cursor of 0 means the iteration is complete. Pattern matching (MATCH) filters on member names.

Source

pub fn sunion(&mut self, keys: &[String]) -> Result<Vec<String>, WrongType>

Returns the union of all given sets.

Keys that don’t exist are treated as empty sets. Returns an error only if any key holds a non-set type.

Source

pub fn sinter(&mut self, keys: &[String]) -> Result<Vec<String>, WrongType>

Returns the intersection of all given sets.

If any key doesn’t exist, the result is empty. Returns an error only if any key holds a non-set type.

Source

pub fn sdiff(&mut self, keys: &[String]) -> Result<Vec<String>, WrongType>

Returns members of the first set that are not in any of the other sets.

If the first key doesn’t exist, the result is empty. Returns an error only if any key holds a non-set type.

Source

pub fn sunionstore( &mut self, dest: &str, keys: &[String], ) -> Result<(usize, Vec<String>), WriteError>

Stores the union of all source sets into dest.

Overwrites the destination if it already exists. Returns the cardinality and stored members (for AOF persistence).

Source

pub fn sinterstore( &mut self, dest: &str, keys: &[String], ) -> Result<(usize, Vec<String>), WriteError>

Stores the intersection of all source sets into dest.

Source

pub fn sdiffstore( &mut self, dest: &str, keys: &[String], ) -> Result<(usize, Vec<String>), WriteError>

Stores the difference of sets (first minus the rest) into dest.

Source

pub fn srandmember( &mut self, key: &str, count: i64, ) -> Result<Vec<String>, WrongType>

Returns random members from a set without removing them.

  • count > 0: return up to count distinct members
  • count < 0: return |count| members, allowing duplicates
  • count == 0: return empty
Source

pub fn spop( &mut self, key: &str, count: usize, ) -> Result<Vec<String>, WrongType>

Removes and returns up to count random members from a set.

Source

pub fn smismember( &mut self, key: &str, members: &[String], ) -> Result<Vec<bool>, WrongType>

Checks membership for multiple members at once.

Returns a boolean for each member in the same order.

Source

pub fn smove( &mut self, source: &str, destination: &str, member: &str, ) -> Result<bool, WriteError>

Atomically moves member from source set to destination set.

Returns true if the member was moved, false if it wasn’t in the source set. Returns an error if either key holds a non-set value.

Both keys must hash to the same shard. The caller is responsible for enforcing that constraint before routing to this method.

Source

pub fn sintercard( &mut self, keys: &[String], limit: usize, ) -> Result<usize, WrongType>

Returns the cardinality of the intersection of all given sets.

If limit is nonzero, the count is capped at that value. Returns 0 if any key is missing. Returns an error if any key holds a non-set type.

Source

pub fn scard(&mut self, key: &str) -> Result<usize, WrongType>

Returns the cardinality (number of elements) of a set.

Source§

impl Keyspace

Source

pub fn get(&mut self, key: &str) -> Result<Option<Value>, WrongType>

Retrieves the string value for key, or None if missing/expired.

Returns Err(WrongType) if the key holds a non-string value. Expired keys are removed lazily on access. Successful reads update the entry’s last access time for LRU tracking.

Uses a single hash probe on the common (non-expired) path. The expired path (rare) does a second probe to remove.

Source

pub fn get_string(&mut self, key: &str) -> Result<Option<Bytes>, WrongType>

Retrieves the raw Bytes for a string key, avoiding the Value enum wrapper. Bytes::clone() is a cheap refcount increment.

Returns Err(WrongType) if the key holds a non-string value.

Uses a single hash probe on the common (non-expired) path.

Source

pub fn encoding(&mut self, key: &str) -> Option<&'static str>

Returns the internal encoding of the value at key, or None if missing.

Source

pub fn value_type(&mut self, key: &str) -> &'static str

Returns the type name of the value at key, or “none” if missing.

Source

pub fn set( &mut self, key: String, value: Bytes, expire: Option<Duration>, nx: bool, xx: bool, ) -> SetResult

Stores a key-value pair with optional NX/XX conditions.

  • nx: only set if the key does NOT already exist
  • xx: only set if the key DOES already exist

expire sets an optional TTL as a duration from now.

Uses a single lookup for the old entry to handle NX/XX checks, memory accounting, and expiry tracking together.

Source

pub fn incr(&mut self, key: &str) -> Result<i64, IncrError>

Increments the integer value of a key by 1.

If the key doesn’t exist, it’s initialized to 0 before incrementing. Returns the new value after the operation.

Source

pub fn decr(&mut self, key: &str) -> Result<i64, IncrError>

Decrements the integer value of a key by 1.

If the key doesn’t exist, it’s initialized to 0 before decrementing. Returns the new value after the operation.

Source

pub fn incr_by(&mut self, key: &str, delta: i64) -> Result<i64, IncrError>

Adds delta to the current integer value of the key, creating it if necessary. Used by INCR, DECR, INCRBY, and DECRBY.

Preserves the existing TTL when updating an existing key.

Source

pub fn incr_by_float( &mut self, key: &str, delta: f64, ) -> Result<String, IncrFloatError>

Adds a float delta to the current value of the key, creating it if necessary. Used by INCRBYFLOAT.

Preserves the existing TTL when updating an existing key. Returns the new value as a string (matching Redis behavior).

Source

pub fn getdel(&mut self, key: &str) -> Result<Option<Bytes>, WrongType>

Returns the value of a key and deletes it atomically.

Returns Ok(None) if the key does not exist or has expired. Returns Err(WrongType) if the key holds a non-string value.

Source

pub fn getset( &mut self, key: &str, value: Bytes, ) -> Result<Option<Bytes>, WrongType>

Atomically sets a key to a new value and returns the old value.

Equivalent to GET followed by SET in a single operation. The new value is always stored as a plain string with no expiry (any existing TTL is cleared, matching Redis behaviour for GETSET).

Returns Ok(None) if the key did not exist or had expired. Returns Err(WrongType) if the key holds a non-string value.

Source

pub fn msetnx(&mut self, pairs: &[(String, Bytes)]) -> bool

Sets multiple keys only if none of them already exist.

Checks all keys atomically before writing any. Returns true and writes all pairs if no key exists, false and writes nothing if any key is already present (including keys with a TTL that hasn’t expired yet).

Source

pub fn getex( &mut self, key: &str, expire: Option<Option<Duration>>, ) -> Result<Option<Bytes>, WrongType>

Returns the value of a key and optionally updates its expiry.

expire controls what happens to the TTL:

  • None — leave the TTL unchanged (plain GET semantics)
  • Some(None) — remove the TTL (PERSIST semantics)
  • Some(Some(duration)) — set a new TTL from now

Returns Ok(None) if the key does not exist or has expired. Returns Err(WrongType) if the key holds a non-string value.

Source

pub fn append(&mut self, key: &str, value: &[u8]) -> Result<usize, WriteError>

Appends a value to an existing string key, or creates a new key if it doesn’t exist. Returns the new string length.

Source

pub fn strlen(&mut self, key: &str) -> Result<usize, WrongType>

Returns the length of the string value stored at key. Returns 0 if the key does not exist.

Source

pub fn getrange( &mut self, key: &str, start: i64, end: i64, ) -> Result<Bytes, WrongType>

Returns a substring of the string stored at key, determined by the offsets start and end (both inclusive). Negative offsets count from the end of the string (-1 is the last character).

Returns an empty string if the key does not exist, or if the computed range is empty after clamping.

Source

pub fn setrange( &mut self, key: &str, offset: usize, value: &[u8], ) -> Result<usize, WriteError>

Overwrites part of the string stored at key, starting at the specified byte offset. If the offset is beyond the current string length, the string is zero-padded. Creates the key if it doesn’t exist. Returns the new string length.

Preserves the existing TTL.

Source§

impl Keyspace

Source

pub fn zadd( &mut self, key: &str, members: &[(f64, String)], flags: &ZAddFlags, ) -> Result<ZAddResult, WriteError>

Adds members with scores to a sorted set, with optional ZADD flags.

Creates the sorted set if the key doesn’t exist. Returns a ZAddResult containing the count for the client response and the list of members that were actually applied (for AOF correctness). Returns Err(WriteError::WrongType) on type mismatch, or Err(WriteError::OutOfMemory) if the memory limit is reached.

Source

pub fn zrem( &mut self, key: &str, members: &[String], ) -> Result<Vec<String>, WrongType>

Removes members from a sorted set. Returns the names of members that were actually removed (for AOF correctness). Deletes the key if the set becomes empty.

Returns Err(WrongType) if the key holds a non-sorted-set value.

Source

pub fn zscore( &mut self, key: &str, member: &str, ) -> Result<Option<f64>, WrongType>

Returns the score for a member in a sorted set.

Returns Ok(None) if the key or member doesn’t exist. Returns Err(WrongType) on type mismatch.

Source

pub fn zrank( &mut self, key: &str, member: &str, ) -> Result<Option<usize>, WrongType>

Returns the 0-based rank of a member in a sorted set (lowest score = 0).

Returns Ok(None) if the key or member doesn’t exist. Returns Err(WrongType) on type mismatch.

Source

pub fn zrange( &mut self, key: &str, start: i64, stop: i64, ) -> Result<Vec<(String, f64)>, WrongType>

Returns a range of members from a sorted set by rank.

Supports negative indices. If with_scores is true, the result includes (member, score) pairs; otherwise just members. Returns Err(WrongType) on type mismatch.

Source

pub fn scan_sorted_set( &mut self, key: &str, cursor: u64, count: usize, pattern: Option<&str>, ) -> Result<(u64, Vec<(String, f64)>), WrongType>

Incrementally iterates members of a sorted set.

Returns the next cursor and a batch of member-score pairs. A returned cursor of 0 means the iteration is complete. Pattern matching (MATCH) filters on member names.

Source

pub fn zrevrank( &mut self, key: &str, member: &str, ) -> Result<Option<usize>, WrongType>

Returns the reverse rank of a member (highest score = 0).

Returns Ok(None) if the key or member doesn’t exist. Returns Err(WrongType) on type mismatch.

Source

pub fn zrevrange( &mut self, key: &str, start: i64, stop: i64, ) -> Result<Vec<(String, f64)>, WrongType>

Returns a range of members in reverse rank order (highest first).

Source

pub fn zcount( &mut self, key: &str, min: ScoreBound, max: ScoreBound, ) -> Result<usize, WrongType>

Counts members with scores in the given bounds.

Source

pub fn zincrby( &mut self, key: &str, increment: f64, member: &str, ) -> Result<f64, WriteError>

Increments the score of a member in a sorted set. If the member doesn’t exist, it is added with the increment as its score. If the key doesn’t exist, a new sorted set is created.

Returns the new score.

Source

pub fn zrangebyscore( &mut self, key: &str, min: ScoreBound, max: ScoreBound, offset: usize, count: Option<usize>, ) -> Result<Vec<(String, f64)>, WrongType>

Returns members with scores in the given range, in ascending order.

Source

pub fn zrevrangebyscore( &mut self, key: &str, min: ScoreBound, max: ScoreBound, offset: usize, count: Option<usize>, ) -> Result<Vec<(String, f64)>, WrongType>

Returns members with scores in the given range, in descending order.

Source

pub fn zpopmin( &mut self, key: &str, count: usize, ) -> Result<Vec<(String, f64)>, WrongType>

Removes and returns up to count members with the lowest scores. Deletes the key if the set becomes empty.

Source

pub fn zpopmax( &mut self, key: &str, count: usize, ) -> Result<Vec<(String, f64)>, WrongType>

Removes and returns up to count members with the highest scores. Deletes the key if the set becomes empty.

Source

pub fn zcard(&mut self, key: &str) -> Result<usize, WrongType>

Returns the number of members in a sorted set, or 0 if the key doesn’t exist.

Returns Err(WrongType) on type mismatch.

Source

pub fn zdiff( &mut self, keys: &[String], ) -> Result<Vec<(String, f64)>, WrongType>

Returns members in the first sorted set that are not in any of the others.

Missing keys are treated as empty sets. Results are ordered by score then by member name.

Source

pub fn zinter( &mut self, keys: &[String], ) -> Result<Vec<(String, f64)>, WrongType>

Returns members present in all of the given sorted sets, with scores summed.

If any key is missing the result is empty. Results are ordered by score then member name.

Source

pub fn zunion( &mut self, keys: &[String], ) -> Result<Vec<(String, f64)>, WrongType>

Returns the union of all given sorted sets, with scores summed across keys.

Missing keys contribute no members. Results are ordered by score then member name.

Source

pub fn zdiffstore( &mut self, dest: &str, keys: &[String], ) -> Result<(usize, Vec<(f64, String)>), WrongType>

Computes the diff of sorted sets and stores the result in dest.

Equivalent to calling zdiff then writing the result to dest. Replaces any existing value at dest. Returns the count of stored members and the scored pairs (for AOF persistence).

Source

pub fn zinterstore( &mut self, dest: &str, keys: &[String], ) -> Result<(usize, Vec<(f64, String)>), WrongType>

Computes the intersection of sorted sets and stores the result in dest.

Equivalent to calling zinter then writing the result to dest. Replaces any existing value at dest. Returns the count of stored members and the scored pairs (for AOF persistence).

Source

pub fn zunionstore( &mut self, dest: &str, keys: &[String], ) -> Result<(usize, Vec<(f64, String)>), WrongType>

Computes the union of sorted sets and stores the result in dest.

Equivalent to calling zunion then writing the result to dest. Replaces any existing value at dest. Returns the count of stored members and the scored pairs (for AOF persistence).

Source

pub fn zrandmember( &mut self, key: &str, count: Option<i64>, with_scores: bool, ) -> Result<Vec<(String, Option<f64>)>, WrongType>

Returns random member(s) from a sorted set.

  • count = None: return one random member as a single string (no score)
  • count > 0: return up to count distinct members
  • count < 0: return |count| members, allowing duplicates

If with_scores is true and count is Some, returns (member, Some(score)) pairs. When count is None, the score field is always None.

Source§

impl Keyspace

Source

pub fn new() -> Self

Creates a new, empty keyspace with default config (no memory limit).

Source

pub fn with_config(config: ShardConfig) -> Self

Creates a new, empty keyspace with the given config.

Source

pub fn set_drop_handle(&mut self, handle: DropHandle)

Attaches a background drop handle for lazy free. When set, large values removed by del/eviction/expiration are dropped on a background thread instead of blocking the shard.

Source

pub fn key_version(&mut self, key: &str) -> Option<u64>

Returns the current version of a key, or None if the key is missing or expired. Used by WATCH/EXEC — cold path only.

If the key hasn’t been WATCHed yet, inserts the current next_version so that future mutations will be detected.

Source

pub fn clear_versions(&mut self)

Removes all version tracking entries. Called on UNWATCH/DISCARD or FLUSHDB.

Source

pub fn del(&mut self, key: &str) -> bool

Removes a key. Returns true if the key existed (and wasn’t expired).

When a drop handle is set, large values are dropped on the background thread instead of inline.

Removes a key like del, but always defers the value’s destructor to the background drop thread (when available). Semantically identical to DEL — the key is gone immediately, memory is accounted for immediately, but the actual deallocation happens off the hot path.

Source

pub fn exists(&mut self, key: &str) -> bool

Returns true if the key exists and hasn’t expired.

Source

pub fn random_key(&mut self) -> Option<String>

Returns a random key from the keyspace, or None if empty.

Uses reservoir sampling from the hash map iterator. Expired keys are skipped (and lazily cleaned up with bounded retries).

Source

pub fn touch(&mut self, key: &str) -> bool

Updates the last access time for a key. Returns true if the key exists.

Source

pub fn sort( &mut self, key: &str, desc: bool, alpha: bool, limit: Option<(i64, i64)>, ) -> Result<Vec<Bytes>, &'static str>

Sorts elements from a list, set, or sorted set.

Returns the sorted elements as byte strings, or an error if the key holds the wrong type or numeric parsing fails.

Source

pub fn expire(&mut self, key: &str, seconds: u64) -> bool

Sets an expiration on an existing key. Returns true if the key exists (and the TTL was set), false if the key doesn’t exist.

Source

pub fn ttl(&mut self, key: &str) -> TtlResult

Returns the TTL status for a key, following Redis semantics:

  • Seconds(n) if the key has a TTL
  • NoExpiry if the key exists without a TTL
  • NotFound if the key doesn’t exist
Source

pub fn memory_usage(&mut self, key: &str) -> Option<usize>

Returns the estimated memory usage in bytes for the given key, or None if the key does not exist or is expired.

Uses the cached value size for O(1) cost. The estimate covers the key string, the serialized value, and the per-entry overhead.

Source

pub fn persist(&mut self, key: &str) -> bool

Removes the expiration from a key.

Returns true if the key existed and had a timeout that was removed. Returns false if the key doesn’t exist or has no expiration.

Source

pub fn pttl(&mut self, key: &str) -> TtlResult

Returns the TTL status for a key in milliseconds, following Redis semantics:

  • Milliseconds(n) if the key has a TTL
  • NoExpiry if the key exists without a TTL
  • NotFound if the key doesn’t exist
Source

pub fn pexpire(&mut self, key: &str, millis: u64) -> bool

Sets an expiration on an existing key in milliseconds.

Returns true if the key exists (and the TTL was set), false if the key doesn’t exist.

Source

pub fn expireat(&mut self, key: &str, unix_secs: u64) -> bool

Sets an expiration at an absolute Unix timestamp (seconds).

Returns true if the key exists and the expiry was set, false if the key doesn’t exist.

Source

pub fn pexpireat(&mut self, key: &str, unix_ms: u64) -> bool

Sets an expiration at an absolute Unix timestamp (milliseconds).

Returns true if the key exists and the expiry was set, false if the key doesn’t exist.

Source

pub fn expiretime(&mut self, key: &str) -> i64

Returns the absolute Unix timestamp (seconds) when the key expires.

Returns -2 if the key doesn’t exist, -1 if it has no expiry.

Source

pub fn pexpiretime(&mut self, key: &str) -> i64

Returns the absolute Unix timestamp (milliseconds) when the key expires.

Returns -2 if the key doesn’t exist, -1 if it has no expiry.

Source

pub fn keys(&self, pattern: &str) -> Vec<String>

Returns all keys matching a glob pattern.

Warning: O(n) scan of the entire keyspace. Use SCAN for production workloads with large key counts.

Source

pub fn count_keys_in_slot(&self, slot: u16) -> usize

Counts live keys in this keyspace that hash to the given cluster slot.

O(n) scan over all entries — same cost as KEYS.

Source

pub fn get_keys_in_slot(&self, slot: u16, count: usize) -> Vec<String>

Returns up to count live keys that hash to the given cluster slot.

O(n) scan over all entries — same cost as KEYS.

Source

pub fn rename(&mut self, key: &str, newkey: &str) -> Result<(), RenameError>

Renames a key to a new name. Returns an error if the source key doesn’t exist. If the destination key already exists, it is overwritten.

Source

pub fn copy( &mut self, source: &str, dest: &str, replace: bool, ) -> Result<bool, CopyError>

Copies the value at source to destination. If replace is false and the destination already exists, returns Ok(false). Returns Ok(true) on success.

Source

pub fn update_memory_config( &mut self, max_memory: Option<usize>, eviction_policy: EvictionPolicy, )

Updates the memory limit and eviction policy in-place.

Takes effect immediately for all subsequent write commands. track_access is synchronized with the new policy so LRU sampling stays consistent.

Source

pub fn stats(&self) -> KeyspaceStats

Returns aggregated stats for this keyspace.

All fields are tracked incrementally — this is O(1).

Source

pub fn len(&self) -> usize

Returns the number of live keys.

Source

pub fn clear(&mut self)

Removes all keys from the keyspace.

Source

pub fn is_empty(&self) -> bool

Returns true if the keyspace has no entries.

Source

pub fn scan_keys( &self, cursor: u64, count: usize, pattern: Option<&str>, ) -> (u64, Vec<String>)

Scans keys starting from a cursor position.

Returns the next cursor (0 if scan complete) and a batch of keys. The pattern argument supports glob-style matching (*, ?, [abc]).

Source

pub fn dump(&mut self, key: &str) -> Option<(&Value, i64)>

Returns the value and remaining TTL in milliseconds for a single key.

Returns None if the key doesn’t exist or is expired. TTL is -1 for entries with no expiration. Used by MIGRATE/DUMP to serialize a key for transfer to another node.

Source

pub fn iter_entries(&self) -> impl Iterator<Item = (&str, &Value, i64)>

Iterates over all live (non-expired) entries, yielding the key, a clone of the value, and the remaining TTL in milliseconds (-1 for entries with no expiration). Used by snapshot and AOF rewrite.

Source

pub fn restore(&mut self, key: String, value: Value, ttl: Option<Duration>)

Restores an entry during recovery, bypassing memory limits.

ttl is the remaining time-to-live. If None, the key has no expiry. This is used only during shard startup when loading from snapshot/AOF — normal writes should go through set().

Trait Implementations§

Source§

impl Default for Keyspace

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> OptionalSend for T
where T: Send + ?Sized,

Source§

impl<T> OptionalSync for T
where T: Sync + ?Sized,