Cdb

Struct Cdb 

Source
pub struct Cdb<R, H> { /* private fields */ }
Expand description

Represents an open CDB database. It can only be used for reads.

A Cdb instance provides read-only access to the database. To create or modify a CDB database, use the CdbWriter.

The Cdb struct is generic over R: ReaderAt and H: Hasher + Default, allowing it to work with different underlying data sources (e.g., std::fs::File or in-memory buffers) as long as they implement the ReaderAt trait.

§Examples

Opening a CDB file and retrieving a value:

use cdb64::{Cdb, CdbWriter, CdbHash};
use std::fs::File;

fn main() -> std::io::Result<()> {
    let cdb = Cdb::<_, CdbHash>::open("test.cdb")?;
    if let Some(value) = cdb.get(b"key")? {
        println!("Value: {:?}", value);
    } else {
        println!("Key not found");
    }
    Ok(())
}

Implementations§

Source§

impl<H: Hasher + Default> Cdb<File, H>

Source

pub fn open(path: impl AsRef<Path>) -> Result<Self>

Opens an existing CDB database from a file at the given path.

This method initializes a Cdb instance with a std::fs::File as the reader and uses the specified Hasher (defaults to CdbHash).

Source§

impl<R: ReaderAt, H: Hasher + Default> Cdb<R, H>

Source

pub fn new(reader: R) -> Result<Self>

Creates a new CDB instance using the provided ReaderAt and a default hasher.

The hasher defaults to H::default().

Source

pub fn get(&self, key: &[u8]) -> Result<Option<Vec<u8>>>

Returns the value for a given key, or None if it can’t be found.

§Arguments
  • key: A byte slice representing the key to look up.
§Returns
  • Ok(Some(Vec<u8>)) if the key is found, containing the associated value.
  • Ok(None) if the key is not found in the database.
  • Err(io::Error) if an I/O error occurs during the lookup process.
§Performance

This operation has O(1) average-case time complexity (amortized constant time). In the worst case with many hash collisions, it may degrade to O(n) where n is the number of entries in a hash table bucket, but this is rare with good hash distribution.

§Duplicate Keys

If the database contains duplicate keys (inserted multiple times via CdbWriter::put), this method returns the first matching value encountered during the hash table probe. To retrieve all values for a key, use the iterator returned by iter().

§Process
  1. Hashes the provided key using the configured hasher_fn.
  2. Uses the first byte of the hash to select one of the 256 header table entries.
  3. If the selected table entry is empty (length is 0), the key is not found.
  4. Otherwise, probes the hash table pointed to by the header entry. The starting slot within this table is determined by (hash_value >> 8) % table_length.
  5. Iterates through the slots in a linear probing sequence:
    1. Reads the (entry_hash, data_offset) pair from the current slot.
    2. If both entry_hash and data_offset are zero, it signifies an empty slot, and the key is considered not found (as all entries in a chain must be contiguous).
    3. If entry_hash matches the hash of the input key:
      1. It reads the actual key-value pair from data_offset.
      2. If the stored key matches the input key, the associated value is returned.
      3. If the stored key does not match (hash collision), the probing continues.
    4. If entry_hash does not match, probing continues to the next slot.
  6. If the entire hash table chain is traversed without finding the key, it returns Ok(None).
Source

pub fn iter(&self) -> CdbIterator<'_, R, H>

Returns an iterator over all key-value pairs in the database.

The iterator borrows the Cdb immutably for its lifetime, so you can continue to use the Cdb while iterating.

Auto Trait Implementations§

§

impl<R, H> Freeze for Cdb<R, H>
where R: Freeze,

§

impl<R, H> RefUnwindSafe for Cdb<R, H>

§

impl<R, H> Send for Cdb<R, H>
where R: Send, H: Send,

§

impl<R, H> Sync for Cdb<R, H>
where R: Sync, H: Sync,

§

impl<R, H> Unpin for Cdb<R, H>
where R: Unpin, H: Unpin,

§

impl<R, H> UnwindSafe for Cdb<R, H>
where R: UnwindSafe, H: UnwindSafe,

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, 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, 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.