class Cdb::Writer
Provides write-only access to a cdb.
Public Class Methods
create(file)
click to toggle source
Initializes an empty cdb for writing to the given file-like object.
# File lib/cdb/writer.rb, line 7 def self.create(file) file.truncate(0) file.write(empty_header) new(file) end
empty_header()
click to toggle source
Returns an empty header – NUM_HASHTABLES pairs of 32-bit integers, all containing zero.
# File lib/cdb/writer.rb, line 32 def self.empty_header "\0" * (Cdb::NUM_HASHTABLES * 8) end
new(file)
click to toggle source
# File lib/cdb/writer.rb, line 38 def initialize(file) @file = file.binmode @tables = (0...Cdb::NUM_HASHTABLES).map { HashTable.new } end
Public Instance Methods
[]=(key, value)
click to toggle source
Writes a key/value pair to the cdb.
Attempting to write the same key twice will cause an error.
# File lib/cdb/writer.rb, line 16 def []=(key, value) offset = append(key, value) index(key, offset) end
close()
click to toggle source
Finish writing the cdb.
This flushes the hash table structure to disk.
# File lib/cdb/writer.rb, line 24 def close lookups = @tables.map { |t| write_table(t) } @file.rewind @file.write(lookups.flatten.pack('V*')) end
Private Instance Methods
append(key, value)
click to toggle source
# File lib/cdb/writer.rb, line 43 def append(key, value) offset = @file.pos @file.write([key.length, value.length, key, value].pack('VVA*A*')) offset end
index(key, offset)
click to toggle source
# File lib/cdb/writer.rb, line 49 def index(key, offset) hash = Cdb.hash(key) table_for_hash(hash).put(HashTableEntry.new(hash, key, offset)) end
table_for_hash(hash)
click to toggle source
# File lib/cdb/writer.rb, line 61 def table_for_hash(hash) @tables[hash % Cdb::NUM_HASHTABLES] end
write_table(table)
click to toggle source
# File lib/cdb/writer.rb, line 54 def write_table(table) return [0, 0] if table.nil? offset = @file.pos @file.write(table.bytes) [offset, table.capacity] end