Module: Cdb

Defined in:
lib/cdb.rb,
lib/cdb/reader.rb,
lib/cdb/writer.rb,
lib/cdb/constants.rb

Overview

Cdb is a lightweight, pure-ruby reader/writer for DJ Bernstein’s cdb format (cr.yp.to/cdb.html).

Author

Olly Smith

License

Apache 2.0 (www.apache.org/licenses/LICENSE-2.0)

Cdbs are fast, immutable, on-disk hashtables. They’re great for storing modest (up to 4GB) amounts of arbitrary key-value pairs. They allow random lookup, but no enumeration or traversal.

file = File.new('table.cdb')
Cdb.writer(file) do |cdb|
  cdb['key1'] = 'value1'
  cdb['key2'] = 'value2'
  # ...
end
reader = Cdb.reader(file)
reader['key1']
# => "value1"

Defined Under Namespace

Classes: HashTable, HashTableEntry, Reader, Writer

Constant Summary collapse

HASHTABLE_MAX_FULLNESS =
0.75
INITIAL_HASH =
5381
NUM_HASHTABLES =
256

Class Method Summary collapse

Class Method Details

.create(file) {|writer| ... } ⇒ Object

Write data to a cdb in a file-like object.

Yields:

  • (writer)


26
27
28
29
30
# File 'lib/cdb.rb', line 26

def self.create(file)
  writer = Cdb::Writer.create(file)
  yield(writer)
  writer.close
end

.hash(key) ⇒ Object

Calculate a cdb hash value.

The cdb hash function is “h = ((h << 5) + h) ^ c”, with a starting hash of 5381.



41
42
43
44
45
# File 'lib/cdb.rb', line 41

def self.hash(key)
  key.bytes.inject(Cdb::INITIAL_HASH) do |h, c|
    0xffffffff & ((h << 5) + h) ^ c
  end
end

.open(file) ⇒ Object

Open a cdb for reading.



33
34
35
# File 'lib/cdb.rb', line 33

def self.open(file)
  Cdb::Reader.new(file)
end