add Bdb::Simple

This commit is contained in:
Justin Balthrop 2009-08-06 14:19:00 -07:00
parent 6d5a78fd98
commit f28073fa9b
2 changed files with 76 additions and 1 deletions

View file

@ -2,7 +2,7 @@ BDB_SPEC = Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>=1.8.4' s.required_ruby_version = '>=1.8.4'
s.name = "bdb" s.name = "bdb"
s.version = "0.0.2" s.version = "0.0.3"
s.authors = ["Matt Bauer", "Dan Janowski"] s.authors = ["Matt Bauer", "Dan Janowski"]
s.email = "bauer@pedalbrain.com" s.email = "bauer@pedalbrain.com"
s.summary = "A Ruby interface to BerkeleyDB" s.summary = "A Ruby interface to BerkeleyDB"

75
lib/bdb/simple.rb Normal file
View file

@ -0,0 +1,75 @@
require 'bdb'
class Bdb::Simple
include Enumerable
def initialize(file, opts = {})
@dup = opts[:dup]
@file = file
end
def dup?
@dup
end
attr_reader :file
def db
if @db.nil?
@db = Bdb::Db.new
@db.flags = Bdb::DB_DUPSORT if dup?
@db.btree_compare = lambda do |db, key1, key2|
Marshal.load(key1) <=> Marshal.load(key2)
end
@db.open(nil, file, nil, Bdb::Db::BTREE, Bdb::DB_CREATE, 0)
end
@db
end
def []=(key, value)
db[Marshal.dump(key)] = Marshal.dump(value)
end
def [](key)
key = Marshal.dump(key)
if dup?
values = []
cursor = db.cursor(nil, 0)
data = cursor.get(key, nil, Bdb::DB_SET)
while data
values << Marshal.load(data[1])
data = cursor.get(nil, nil, Bdb::DB_NEXT_DUP)
end
cursor.close
values
else
Marshal.load(db.get(nil, key, nil, 0))
end
end
def each
cursor = db.cursor(nil, 0)
while data = cursor.get(nil, nil, Bdb::DB_NEXT)
key = Marshal.load(data[0])
value = Marshal.load(data[1])
yield(key, value)
end
cursor.close
end
def sync
db.sync
end
def clear
close
File.delete(file) if File.exists?(file)
nil
end
def close
db.close(0)
@db = nil
end
end