kyotocabinet-ruby-1.32/0000755000175000017500000000000011757457117014132 5ustar mikiomikiokyotocabinet-ruby-1.32/kyotocabinet.gemspec0000644000175000017500000000163211757455777020206 0ustar mikiomikiorequire 'rubygems' spec = Gem::Specification.new do |s| s.name = "kyotocabinet" s.version = "1.32" s.author = "FAL Labs" s.email = "info@fallabs.com" s.homepage = "http://fallabs.com/kyotocabinet/" s.summary = "Kyoto Cabinet: a straightforward implementation of DBM." s.description = "Kyoto Cabinet is a library of routines for managing a database. The database is a simple data file containing records, each is a pair of a key and a value. Every key and value is serial bytes with variable length. Both binary data and character string can be used as a key and a value. Each key must be unique within a database. There is neither concept of data tables nor data types. Records are organized in hash table or B+ tree." s.files = [ "kyotocabinet.cc", "extconf.rb" ] s.require_path = "." s.extensions = [ "extconf.rb" ] end if $0 == __FILE__ Gem::manage_gems Gem::Builder.new(spec).build end kyotocabinet-ruby-1.32/README0000644000175000017500000000126611420710427014776 0ustar mikiomikio================================================================ Kyoto Cabinet: a straightforward implementation of DBM Copyright (C) 2009-2010 FAL Labs ================================================================ Please read the following documents with a WWW browser. How to install Kyoto Cabinet is explained in the API document. README - this file COPYING - license doc/index.html - index of documents Kyoto Cabinet is released under the terms of the GNU General Public License version 3. See the file `COPYING' for details. Kyoto Cabinet was written by FAL Labs. You can contact the author by e-mail to `info@fallabs.com'. Thanks. == END OF FILE == kyotocabinet-ruby-1.32/kctest.rb0000755000175000017500000007241111750225361015747 0ustar mikiomikio#! /usr/bin/ruby -w # -*- coding: utf-8 -*- #------------------------------------------------------------------------------------------------- # The test cases of the Ruby binding # Copyright (C) 2009-2010 FAL Labs # This file is part of Kyoto Cabinet. # This program is free software: you can redistribute it and/or modify it under the terms of # the GNU General Public License as published by the Free Software Foundation, either version # 3 of the License, or any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program. # If not, see . #------------------------------------------------------------------------------------------------- require 'kyotocabinet' require 'fileutils' include KyotoCabinet # main routine def main ARGV.length >= 1 || usage if ARGV[0] == "order" rv = runorder elsif ARGV[0] == "wicked" rv = runwicked elsif ARGV[0] == "misc" rv = runmisc else usage end GC.start return rv end # print the usage and exit def usage STDERR.printf("%s: test cases of the Ruby binding\n", $progname) STDERR.printf("\n") STDERR.printf("usage:\n") STDERR.printf(" %s order [-cc] [-th num] [-rnd] [-etc] path rnum\n", $progname) STDERR.printf(" %s wicked [-cc] [-th num] [-it num] path rnum\n", $progname) STDERR.printf(" %s misc path\n", $progname) STDERR.printf("\n") exit(1) end # print the error message of the database def dberrprint(db, func) err = db.error printf("%s: %s: %d: %s: %s\n", $progname, func, err.code, err.name, err.message) end # print members of a database def dbmetaprint(db, verbose) if verbose status = db.status if status status.each { |name, value| printf("%s: %s\n", name, value) } end else printf("count: %d\n", db.count) printf("size: %d\n", db.size) end end # parse arguments of order command def runorder path = nil rnum = nil gopts = 0 thnum = 1 rnd = false etc = false i = 1 while i < ARGV.length arg = ARGV[i] if !path && arg =~ /^-/ if arg == "-cc" gopts |= DB::GCONCURRENT elsif arg == "-th" i += 1 usage if i >= ARGV.length thnum = ARGV[i].to_i elsif arg == "-rnd" rnd = true elsif arg == "-etc" etc = true else usage end elsif !path path = arg elsif !rnum rnum = arg.to_i else usage end i += 1 end usage if !path || !rnum || rnum < 1 || thnum < 1 rv = procorder(path, rnum, gopts, thnum, rnd, etc) return rv end # parse arguments of wicked command def runwicked path = nil rnum = nil gopts = 0 thnum = 1 itnum = 1 i = 1 while i < ARGV.length arg = ARGV[i] if !path && arg =~ /^-/ if arg == "-cc" gopts |= DB::GCONCURRENT elsif arg == "-th" i += 1 usage if i >= ARGV.length thnum = ARGV[i].to_i elsif arg == "-it" i += 1 usage if i >= ARGV.length itnum = ARGV[i].to_i else usage end elsif !path path = arg elsif !rnum rnum = arg.to_i else usage end i += 1 end usage if !path || !rnum || rnum < 1 || thnum < 1 || itnum < 1 rv = procwicked(path, rnum, gopts, thnum, itnum) return rv end # parse arguments of wicked command def runmisc path = nil i = 1 while i < ARGV.length arg = ARGV[i] if !path && arg =~ /^-/ usage elsif !path path = arg else usage end i += 1 end usage if !path rv = procmisc(path) return rv end # perform order command def procorder(path, rnum, gopts, thnum, rnd, etc) printf("\n path=%s rnum=%d gopts=%d thnum=%d rnd=%s etc=%s\n\n", path, rnum, gopts, thnum, rnd, etc) err = false db = DB::new(gopts) db.tune_exception_rule([ Error::SUCCESS, Error::NOIMPL, Error::MISC ]) db.tune_encoding("utf-8") printf("opening the database:\n") stime = Time::now if !db.open(path, DB::OWRITER | DB::OCREATE | DB::OTRUNCATE) dberrprint(db, "DB::open") err = true end etime = Time::now printf("time: %.3f\n", etime - stime) printf("setting records:\n") stime = Time::now threads = Array::new for thid in 0...thnum th = Thread::new(thid) { |id| base = id * rnum range = rnum * thnum for i in 1..rnum break if err key = sprintf("%08d", rnd ? rand(range) + 1 : base + i) if !db.set(key, key) dberrprint(db, "DB::set") err = true end if id < 1 && rnum > 250 && i % (rnum / 250) == 0 print(".") if i == rnum || i % (rnum / 10) == 0 printf(" (%08d)\n", i) end end end } threads.push(th) end threads.each { |jth| jth.join } etime = Time::now dbmetaprint(db, false) printf("time: %.3f\n", etime - stime) if etc printf("adding records:\n") stime = Time::now threads = Array::new for thid in 0...thnum th = Thread::new(thid) { |id| base = id * rnum range = rnum * thnum for i in 1..rnum break if err key = sprintf("%08d", rnd ? rand(range) + 1 : base + i) if !db.add(key, key) && db.error != Error::DUPREC dberrprint(db, "DB::add") err = true end if id < 1 && rnum > 250 && i % (rnum / 250) == 0 print(".") if i == rnum || i % (rnum / 10) == 0 printf(" (%08d)\n", i) end end end } threads.push(th) end threads.each { |jth| jth.join } etime = Time::now dbmetaprint(db, false) printf("time: %.3f\n", etime - stime) end if etc printf("appending records:\n") stime = Time::now threads = Array::new for thid in 0...thnum th = Thread::new(thid) { |id| base = id * rnum range = rnum * thnum for i in 1..rnum break if err key = sprintf("%08d", rnd ? rand(range) + 1 : base + i) if !db.append(key, key) dberrprint(db, "DB::append") err = true end if id < 1 && rnum > 250 && i % (rnum / 250) == 0 print(".") if i == rnum || i % (rnum / 10) == 0 printf(" (%08d)\n", i) end end end } threads.push(th) end threads.each { |jth| jth.join } etime = Time::now dbmetaprint(db, false) printf("time: %.3f\n", etime - stime) end if etc && !(gopts & DB::GCONCURRENT) printf("accepting visitors:\n") stime = Time::now threads = Array::new for thid in 0...thnum th = Thread::new(thid) { |id| me = Thread::current me[:rnd] = rnd me[:cnt] = 0 def me.visit_full(key, value) self[:cnt] += 1 Thread::pass if self[:cnt] % 100 == 0 rv = Visitor::NOP if self[:rnd] case rand(7) when 0 rv = self[:cnt] when 1 rv = Visitor::REMOVE end end return rv end def me.visit_empty(key) return visit_full(key, key) end base = id * rnum range = rnum * thnum for i in 1..rnum break if err key = sprintf("%08d", rnd ? rand(range) + 1 : base + i) if !db.accept(key, me, rnd) dberrprint(db, "DB::accept") err = true end if id < 1 && rnum > 250 && i % (rnum / 250) == 0 print(".") if i == rnum || i % (rnum / 10) == 0 printf(" (%08d)\n", i) end end end } threads.push(th) end threads.each { |jth| jth.join } etime = Time::now dbmetaprint(db, false) printf("time: %.3f\n", etime - stime) end printf("getting records:\n") stime = Time::now threads = Array::new for thid in 0...thnum th = Thread::new(thid) { |id| base = id * rnum range = rnum * thnum for i in 1..rnum break if err key = sprintf("%08d", rnd ? rand(range) + 1 : base + i) if !db.get(key) && db.error != Error::NOREC dberrprint(db, "DB::get") err = true end if id < 1 && rnum > 250 && i % (rnum / 250) == 0 print(".") if i == rnum || i % (rnum / 10) == 0 printf(" (%08d)\n", i) end end end } threads.push(th) end threads.each { |jth| jth.join } etime = Time::now dbmetaprint(db, false) printf("time: %.3f\n", etime - stime) if etc && !(gopts & DB::GCONCURRENT) printf("traversing the database by the inner iterator:\n") stime = Time::now threads = Array::new for thid in 0...thnum th = Thread::new(thid) { |id| me = Thread::current me[:id] = id me[:rnum] = rnum me[:rnd] = rnd me[:cnt] = 0 def me.visit_full(key, value) self[:cnt] += 1 Thread::pass if self[:cnt] % 100 == 0 rv = Visitor::NOP if self[:rnd] case rand(7) when 0 rv = self[:cnt].to_s * 2 when 1 rv = Visitor::REMOVE end end if self[:id] < 1 && self[:rnum] > 250 && self[:cnt] % (self[:rnum] / 250) == 0 print(".") if self[:cnt] == self[:rnum] || self[:cnt] % (self[:rnum] / 10) == 0 printf(" (%08d)\n", self[:cnt]) end end return rv end def me.visit_empty(key) return Visitor::NOP end if !db.iterate(me, rnd) dberrprint(db, "DB::iterate") err = true end } threads.push(th) end threads.each { |jth| jth.join } printf(" (end)\n") if rnd etime = Time::now dbmetaprint(db, false) printf("time: %.3f\n", etime - stime) end if etc && !(gopts & DB::GCONCURRENT) printf("traversing the database by the outer cursor:\n") stime = Time::now threads = Array::new for thid in 0...thnum th = Thread::new(thid) { |id| me = Thread::current me[:id] = id me[:rnum] = rnum me[:rnd] = rnd me[:cnt] = 0 def me.visit_full(key, value) self[:cnt] += 1 Thread::pass if self[:cnt] % 100 == 0 rv = Visitor::NOP if self[:rnd] case rand(7) when 0 rv = self[:cnt].to_s * 2 when 1 rv = Visitor::REMOVE end end if self[:id] < 1 && self[:rnum] > 250 && self[:cnt] % (self[:rnum] / 250) == 0 print(".") if self[:cnt] == self[:rnum] || self[:cnt] % (self[:rnum] / 10) == 0 printf(" (%08d)\n", self[:cnt]) end end return rv end def me.visit_empty(key) return Visitor::NOP end cur = db.cursor if !cur.jump && db.error != Error::NOREC dberrprint(db, "Cursor::jump") err = true end while cur.accept(me, rnd, false) if !cur.step && db.error != Error::NOREC dberrprint(db, "Cursor::step") err = true end end if db.error != Error::NOREC dberrprint(db, "Cursor::accept") err = true end cur.disable if !rnd || rand(2) == 0 } threads.push(th) end threads.each { |jth| jth.join } printf(" (end)\n") if rnd etime = Time::now dbmetaprint(db, false) printf("time: %.3f\n", etime - stime) end printf("removing records:\n") stime = Time::now threads = Array::new for thid in 0...thnum th = Thread::new(thid) { |id| base = id * rnum range = rnum * thnum for i in 1..rnum break if err key = sprintf("%08d", rnd ? rand(range) + 1 : base + i) if !db.remove(key) && db.error != Error::NOREC dberrprint(db, "DB::remove") err = true end if id < 1 && rnum > 250 && i % (rnum / 250) == 0 print(".") if i == rnum || i % (rnum / 10) == 0 printf(" (%08d)\n", i) end end end } threads.push(th) end threads.each { |jth| jth.join } etime = Time::now dbmetaprint(db, true) printf("time: %.3f\n", etime - stime) printf("closing the database:\n") stime = Time::now if !db.close dberrprint(db, "DB::close") err = true end etime = Time::now printf("time: %.3f\n", etime - stime) printf("%s\n\n", err ? "error" : "ok") return err ? 1 : 0 end # perform wicked command def procwicked(path, rnum, gopts, thnum, itnum) printf("\n path=%s rnum=%d gopts=%d thnum=%d itnum=%d\n\n", path, rnum, gopts, thnum, itnum) err = false db = DB::new(gopts) db.tune_exception_rule([ Error::SUCCESS, Error::NOIMPL, Error::MISC ]) db.tune_encoding("utf-8") if rand(2) == 0 for itcnt in 1..itnum printf("iteration %d:\n", itcnt) if itnum > 1 stime = Time::now omode = DB::OWRITER | DB::OCREATE omode |= DB::OTRUNCATE if itcnt == 1 if !db.open(path, omode) dberrprint(db, "DB::open") err = true end threads = Array::new for thid in 0...thnum th = Thread::new(thid) { |id| me = Thread::current me[:cnt] = 0 def me.visit_full(key, value) self[:cnt] += 1 Thread::pass if self[:cnt] % 100 == 0 rv = Visitor::NOP if self[:rnd] case rand(7) when 0 rv = self[:cnt] when 1 rv = Visitor::REMOVE end end return rv end def me.visit_empty(key) return visit_full(key, key) end cur = db.cursor range = rnum * thnum for i in 1..rnum break if err tran = rand(100) == 0 if tran && !db.begin_transaction(rand(rnum) == 0) dberrprint(db, "DB::begin_transaction") tran = false err = true end key = sprintf("%08d", rand(range) + 1) case rand(12) when 0 if !db.set(key, key) dberrprint(db, "DB::set") err = true end when 1 if !db.add(key, key) && db.error != Error::DUPREC dberrprint(db, "DB::add") err = true end when 2 if !db.replace(key, key) && db.error != Error::NOREC dberrprint(db, "DB::replace") err = true end when 3 if !db.append(key, key) dberrprint(db, "DB::append") err = true end when 4 if rand(2) == 0 if !db.increment(key, rand(10)) && db.error != Error::LOGIC dberrprint(db, "DB::increment") err = true end else if !db.increment_double(key, rand() * 10) && db.error != Error::LOGIC dberrprint(db, "DB::increment_double") err = true end end when 5 if !db.cas(key, key, key) && db.error != Error::LOGIC dberrprint(db, "DB::cas") err = true end when 6 if !db.remove(key) && db.error != Error::NOREC dberrprint(db, "DB::remove") err = true end when 7 if !db.accept(key, me, true) && (!(gopts & DB::GCONCURRENT) || db.error != Error::INVALID) dberrprint(db, "DB::accept") err = true end when 8 if rand(10) == 0 if rand(4) == 0 begin if !cur.jump_back(key) && db.error != Error::NOREC dberrprint(db, "Cursor::jump_back") err = true end rescue Error::XNOIMPL end else if !cur.jump(key) && db.error != Error::NOREC dberrprint(db, "Cursor::jump") err = true end end else case rand(6) when 0 if !cur.get_key && db.error != Error::NOREC dberrprint(db, "Cursor::get_key") err = true end when 1 if !cur.get_value && db.error != Error::NOREC dberrprint(db, "Cursor::get_value") err = true end when 2 if !cur.get && db.error != Error::NOREC dberrprint(db, "Cursor::get") err = true end when 3 if !cur.remove && db.error != Error::NOREC dberrprint(db, "Cursor::remove") err = true end else if !cur.accept(me, true, rand(2) == 0) && db.error != Error::NOREC && (!(gopts & DB::GCONCURRENT) || db.error != Error::INVALID) dberrprint(db, "Cursor::accept") err = true end end end if rand(2) == 0 if !cur.step && db.error != Error::NOREC dberrprint(db, "Cursor::step") err = true end end if rand(rnum / 50 + 1) == 0 prefix = key[0,key.length-1] if !db.match_prefix(prefix, rand(10)) dberrprint(db, "DB::match_prefix") err = true end end if rand(rnum / 50 + 1) == 0 regex = key[0,key.length-1] if !db.match_regex(regex, rand(10)) dberrprint(db, "DB::match_regex") err = true end end if rand(rnum / 50 + 1) == 0 origin = key[0,key.length-1] if !db.match_similar(origin, 3, rand(10)) dberrprint(db, "DB::match_similar") err = true end end if rand(10) == 0 paracur = db.cursor paracur.jump(key) if !paracur.accept(me, true, rand(2) == 0) && db.error != Error::NOREC && (!(gopts & DB::GCONCURRENT) || db.error != Error::INVALID) dberrprint(db, "Cursor::accept") err = true end paracur.disable end else if !db.get(key) && db.error != Error::NOREC dberrprint(db, "DB::get") err = true end end if tran Thread::pass if rand(10) == 0 if !db.end_transaction(rand(10) > 0) dberrprint(db, "DB::end_transaction") err = true end end if id < 1 && rnum > 250 && i % (rnum / 250) == 0 print(".") if i == rnum || i % (rnum / 10) == 0 printf(" (%08d)\n", i) end end end cur.disable if rand(2) == 0 } threads.push(th) end threads.each { |jth| jth.join } dbmetaprint(db, itcnt == itnum) if !db.close dberrprint(db, "DB::close") err = true end etime = Time::now printf("time: %.3f\n", etime - stime) end printf("%s\n\n", err ? "error" : "ok") return err ? 1 : 0 end # perform misc command def procmisc(path) printf("\n path=%s\n\n", path) err = false if conv_str(:mikio) != "mikio" || conv_str(123.45) != "123.45" printf("%s: conv_str: error\n", $progname) err = true end printf("calling utility functions:\n") atoi("123.456mikio") atoix("123.456mikio") atof("123.456mikio") hash_murmur(path) hash_fnv(path) levdist(path, "casket") dcurs = Array::new printf("opening the database by iterator:\n") dberr = DB::process(path, DB::OWRITER | DB::OCREATE | DB::OTRUNCATE) { |db| db.tune_exception_rule([ Error::SUCCESS, Error::NOIMPL, Error::MISC ]) db.tune_encoding("utf-8") db.to_s db.inspect rnum = 10000 printf("setting records:\n") for i in 0...rnum db[i] = i end if db.count != rnum dberrprint(db, "DB::count") err = true end printf("deploying cursors:\n") for i in 1..100 cur = db.cursor if !cur.jump(i) dberrprint(db, "Cursor::jump") err = true end case i % 3 when 0 dcurs.push(cur) when 1 cur.disable end cur.to_s cur.inspect end printf("getting records:\n") dcurs.each { |tcur| if !tcur.get_key dberrprint(db, "Cursor::get_key") err = true end } printf("accepting visitor:\n") def db.visit_full(key, value) rv = Visitor::NOP case key.to_i % 3 when 0 rv = sprintf("full:%s", key) when 1 rv = Visitor::REMOVE end return rv end def db.visit_empty(key) rv = Visitor::NOP case key.to_i % 3 when 0 rv = sprintf("empty:%s", key) when 1 rv = Visitor::REMOVE end return rv end for i in 0...(rnum * 2) if !db.accept(i, db, true) dberrprint(db, "DB::access") err = true end end for i in 0...(rnum * 2) if !db.accept(i) { |key, value| rv = Visitor::NOP case key.to_i % 5 when 0 rv = sprintf("block:%s", key) when 1 rv = Visitor::REMOVE end rv } dberrprint(db, "DB::access") err = true end end printf("accepting visitor by iterator:\n") def dcurs.visit_full(key, value) Visitor::NOP end if !db.iterate(dcurs, false) dberrprint(db, "DB::iterate") err = true end if !db.iterate { |key, value| value.upcase } dberrprint(db, "DB::iterate") err = true end printf("accepting visitor with a cursor:\n") cur = db.cursor def cur.visit_full(key, value) rv = Visitor::NOP case key.to_i % 7 when 0 rv = sprintf("cur:full:%s", key) when 1 rv = Visitor::REMOVE end return rv end begin if !cur.jump_back dberrprint(db, "Cursor::jump_back") err = true end while cur.accept(cur, true) cur.step_back end rescue Error::XNOIMPL if !cur.jump dberrprint(db, "Cursor::jump") err = true end while cur.accept(cur, true) cur.step end end cur.jump while cur.accept { |key, value| rv = Visitor::NOP case key.to_i % 11 when 0 rv = sprintf("cur:block:%s", key) when 1 rv = Visitor::REMOVE end rv } cur.step end printf("accepting visitor in bulk:\n") keys = [] for i in 1..10 keys.push(i) end if not db.accept_bulk(keys, db, true) dberrprint(db, "DB::accept_bulk") err = true end recs = {} for i in 1..10 recs[i] = sprintf("[%d]", i) end if db.set_bulk(recs) < 0 dberrprint(db, "DB::set_bulk") err = true end if not db.get_bulk(keys) dberrprint(db, "DB::get_bulk") err = true end if db.remove_bulk(keys) < 0 dberrprint(db, "DB::remove_bulk") err = true end printf("synchronizing the database:\n") def db.process(path, count, size) true end if !db.synchronize(false, db) dberrprint(db, "DB::synchronize") err = true end if !db.synchronize { |tpath, count, size| true } dberrprint(db, "DB::synchronize") err = true end if !db.occupy(false, db) dberrprint(db, "DB::occupy") err = true end if !db.occupy { |tpath, count, size| true } dberrprint(db, "DB::occupy") err = true end printf("performing transaction:\n") if !db.transaction { db["tako"] = "ika" true } dberrprint(db, "DB::transaction") err = true end if db["tako"] != "ika" dberrprint(db, "DB::transaction") err = true end db.delete("tako") cnt = db.count if !db.transaction { db["tako"] = "ika" db["kani"] = "ebi" false } dberrprint(db, "DB::transaction") err = true end if db["tako"] || db["kani"] || db.count != cnt dberrprint(db, "DB::transaction") err = true end printf("closing the database:\n") } if dberr printf("%s: DB::process: %s\n", $progname, dberr) err = true end printf("accessing dead cursors:\n") dcurs.each { |cur| cur.get_key } printf("checking the exceptional mode:\n") db = DB::new(DB::GEXCEPTIONAL) begin db.open("hoge") rescue Error::XINVALID => e if e.code != Error::INVALID dberrprint(db, "DB::open") err = true end else dberrprint(db, "DB::open") err = true end printf("re-opening the database as a reader:\n") db = DB::new if !db.open(path, DB::OREADER) dberrprint(db, "DB::open") err = true end printf("traversing records by iterator:\n") keys = Array::new db.each { |key, value| keys.push([key, value]) if !value.index(key) dberrprint(db, "Cursor::each") err = true end } printf("checking records:\n") keys.each { |pair| if db.get(pair[0]) != pair[1] dberrprint(db, "DB::get") err = true end } printf("closing the database:\n") if !db.close dberrprint(db, "DB::close") err = true end printf("re-opening the database in the concurrent mode:\n") db = DB::new(DB::GCONCURRENT) if !db.open(path, DB::OWRITER) dberrprint(db, "DB::open") err = true end if !db.set("tako", "ika") dberrprint(db, "DB::set") err = true end if db.accept("tako") { |key, value| } != nil || db.error != Error::INVALID dberrprint(db, "DB::accept") err = true end printf("removing records by cursor:\n") cur = db.cursor if !cur.jump dberrprint(db, "Cursor::jump") err = true end cnt = 0 while key = cur.get_key(true) if cnt % 10 != 0 if !db.remove(key) dberrprint(db, "DB::remove") err = true end end cnt += 1 end if db.error != Error::NOREC dberrprint(db, "Cursor::get_key") err = true end cur.disable printf("processing a cursor by iterator:\n") db.cursor_process { |tcur| if !tcur.jump dberrprint(db, "Cursor::jump") err = true end value = sprintf("[%s]", tcur.get_value) if !tcur.set_value(value) dberrprint(db, "Cursor::set_value") err = true end if tcur.get_value != value dberrprint(db, "Cursor::get_value") err = true end } printf("dumping records into snapshot:\n") snappath = db.path if snappath =~ /.(kch|kct)$/ snappath = snappath + ".kcss" else snappath = "kctest.kcss" end if !db.dump_snapshot(snappath) dberrprint(db, "DB::dump_snapshot") err = true end cnt = db.count printf("clearing the database:\n") if !db.clear dberrprint(db, "DB::clear") err = true end printf("loading records from snapshot:\n") if !db.load_snapshot(snappath) dberrprint(db, "DB::load_snapshot") err = true end if db.count != cnt dberrprint(db, "DB::load_snapshot") err = true end File::unlink(snappath) copypath = db.path suffix = nil if copypath.end_with?(".kch") suffix = ".kch" elsif copypath.end_with?(".kct") suffix = ".kct" elsif copypath.end_with?(".kcd") suffix = ".kcd" elsif copypath.end_with?(".kcf") suffix = ".kcf" end if suffix printf("performing copy and merge:\n") copypaths = [] for i in 0...2 copypaths.push(sprintf("%s.%d%s", copypath, i + 1, suffix)) end srcary = [] copypaths.each do |cpath| if !db.copy(cpath) dberrprint(db, "DB::copy") err = true end srcdb = DB::new if !srcdb.open(cpath, DB::OREADER) dberrprint(srcdb, "DB::open") err = true end srcary.push(srcdb) end if !db.merge(srcary, DB::MAPPEND) dberrprint(srcdb, "DB::merge") err = true end srcary.each do |srcdb| if !srcdb.close dberrprint(srcdb, "DB::close") err = true end end copypaths.each do |cpath| FileUtils::remove_entry_secure(cpath, true) end end printf("shifting records:\n") ocnt = db.count cnt = 0 while db.shift cnt += 1 end if db.error != Error::NOREC dberrprint(db, "DB::shift") err = true end if db.count != 0 || cnt != ocnt dberrprint(db, "DB::shift") err = true end printf("closing the database:\n") if !db.close dberrprint(db, "DB::close") err = true end db.to_s db.inspect printf("%s\n\n", err ? "error" : "ok") return err ? 1 : 0 end # execute main STDOUT.sync = true $progname = $0.dup $progname.gsub!(/.*\//, "") srand exit(main) # END OF FILE kyotocabinet-ruby-1.32/COPYING0000644000175000017500000010451311350435302015146 0ustar mikiomikio GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . kyotocabinet-ruby-1.32/test.rb0000755000175000017500000000320711466431534015433 0ustar mikiomikio#! /usr/bin/ruby require 'rbconfig' confs = [ [ ":", 10000 ], [ "*", 10000 ], [ "%", 10000 ], [ "casket.kch", 10000 ], [ "casket.kct", 10000 ], [ "casket.kcd", 1000 ], [ "casket.kcf", 10000 ], ] formats = [ "kctest.rb order '%s' '%d'", "kctest.rb order -rnd '%s' '%d'", "kctest.rb order -etc '%s' '%d'", "kctest.rb order -rnd -etc '%s' '%d'", "kctest.rb order -th 4 '%s' '%d'", "kctest.rb order -th 4 -rnd '%s' '%d'", "kctest.rb order -th 4 -etc '%s' '%d'", "kctest.rb order -th 4 -rnd -etc '%s' '%d'", "kctest.rb order -cc -th 4 -rnd -etc '%s' '%d'", "kctest.rb wicked '%s' '%d'", "kctest.rb wicked -it 4 '%s' '%d'", "kctest.rb wicked -th 4 '%s' '%d'", "kctest.rb wicked -th 4 -it 4 '%s' '%d'", "kctest.rb wicked -cc -th 4 -it 4 '%s' '%d'", "kctest.rb misc '%s'", ] system("rm -rf casket*") rubycmd = Config::CONFIG["bindir"] + "/" + RbConfig::CONFIG['ruby_install_name'] all = confs.size * formats.size cnt = 0 oknum = 0 confs.each do |conf| path = conf[0] rnum = conf[1] formats.each do |format| cnt += 1 command = sprintf(format, path, rnum) printf("%03d/%03d: %s: ", cnt, all, command) rv = system("#{rubycmd} -I. #{command} >/dev/null") if rv oknum += 1 printf("ok\n") else printf("failed\n") end end end system("rm -rf casket*") if oknum == cnt printf("%d tests were all ok\n", cnt) else printf("%d/%d tests failed\n", cnt - oknum, cnt) end kyotocabinet-ruby-1.32/example/0000755000175000017500000000000011425314640015546 5ustar mikiomikiokyotocabinet-ruby-1.32/example/memsize.rb0000644000175000017500000000142311425314611017542 0ustar mikiomikiorequire 'kyotocabinet' include KyotoCabinet def memoryusage() rss = -1 file = open('/proc/self/status') file.each do |line| if line =~ /^VmRSS:/ line.gsub!(/.*:\s*(\d+).*/, '\1') rss = line.to_i / 1024.0 break end end return rss end GC.start musage = memoryusage rnum = 1000000 if ARGV.length > 0 rnum = ARGV[0].to_i end if ARGV.length > 1 hash = DB::new hash.open(ARGV[1], DB::OWRITER | DB::OCREATE | DB::OTRUNCATE) || raise("open failed") else hash = Hash.new end stime = Time.now (0...rnum).each do |i| key = sprintf("%08d", i) value = sprintf("%08d", i) hash[key] = value end etime = Time.now GC.start printf("Count: %d\n", hash.count) printf("Time: %.3f sec.\n", etime - stime) printf("Usage: %.3f MB\n", memoryusage - musage) kyotocabinet-ruby-1.32/example/kcdbex2.rb0000644000175000017500000000163411370205614017420 0ustar mikiomikiorequire 'kyotocabinet' include KyotoCabinet # create the database object db = DB::new # open the database unless db.open('casket.kch', DB::OREADER) STDERR.printf("open error: %s\n", db.error) end # define the visitor class VisitorImpl < Visitor # call back function for an existing record def visit_full(key, value) printf("%s:%s\n", key, value) return NOP end # call back function for an empty record space def visit_empty(key) STDERR.printf("%s is missing\n", key) return NOP end end visitor = VisitorImpl::new # retrieve a record with visitor unless db.accept("foo", visitor, false) and db.accept("dummy", visitor, false) STDERR.printf("accept error: %s\n", db.error) end # traverse records with visitor unless db.iterate(visitor, false) STDERR.printf("iterate error: %s\n", db.error) end # close the database unless db.close STDERR.printf("close error: %s\n", db.error) end kyotocabinet-ruby-1.32/example/kcdbex3.rb0000644000175000017500000000166411372731466017437 0ustar mikiomikiorequire 'kyotocabinet' include KyotoCabinet # process the database by iterator DB::process('casket.kch') { |db| # set the encoding of external strings db.set_encoding('utf-8') # store records db['foo'] = 'hop'; # string is fundamental db[:bar] = 'step'; # symbol is also ok db[3] = 'jump'; # number is also ok # retrieve a record value printf("%s\n", db['foo']) # update records in transaction db.transaction { db['foo'] = 2.71828 true } # multiply a record value db.accept('foo') { |key, value| value.to_f * 2 } # traverse records by iterator db.each { |key, value| printf("%s:%s\n", key, value) } # upcase values by iterator db.iterate { |key, value| value.upcase } # traverse records by cursor db.cursor_process { |cur| cur.jump while cur.accept { |key, value| printf("%s:%s\n", key, value) Visitor::NOP } cur.step end } } kyotocabinet-ruby-1.32/example/kcdbex1.rb0000644000175000017500000000130511370203455017413 0ustar mikiomikiorequire 'kyotocabinet' include KyotoCabinet # create the database object db = DB::new # open the database unless db.open('casket.kch', DB::OWRITER | DB::OCREATE) STDERR.printf("open error: %s\n", db.error) end # store records unless db.set('foo', 'hop') and db.set('bar', 'step') and db.set('baz', 'jump') STDERR.printf("set error: %s\n", db.error) end # retrieve records value = db.get('foo') if value printf("%s\n", value) else STDERR.printf("get error: %s\n", db.error) end # traverse records cur = db.cursor cur.jump while rec = cur.get(true) printf("%s:%s\n", rec[0], rec[1]) end cur.disable # close the database unless db.close STDERR.printf("close error: %s\n", db.error) end kyotocabinet-ruby-1.32/MANIFEST0000644000175000017500000000020511375735744015261 0ustar mikiomikioMANIFEST extconf.rb kyotocabinet.cc kyotocabinet-doc.rb kctest.rb test.rb makedoc.rb makedist.sh kyotocabinet.gemspec COPYING README kyotocabinet-ruby-1.32/kyotocabinet.cc0000644000175000017500000034750411757456670017154 0ustar mikiomikio/************************************************************************************************* * Ruby binding of Kyoto Cabinet * Copyright (C) 2009-2010 FAL Labs * This file is part of Kyoto Cabinet. * This program is free software: you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation, either version * 3 of the License, or any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see . *************************************************************************************************/ #include namespace kc = kyotocabinet; extern "C" { #include #if RUBY_VM >= 1 #define _KC_YARV_ #endif // precedent type declaration class CursorBurrow; struct SoftCursor; class SoftVisitor; class SoftBlockVisitor; class SoftEachVisitor; class SoftEachKeyVisitor; class SoftEachValueVisitor; class SoftFileProcessor; class SoftBlockFileProcessor; class NativeFunction; typedef std::map StringMap; typedef std::vector StringVector; typedef VALUE (*METHOD)(...); // function prototypes void Init_kyotocabinet(); static VALUE StringValueEx(VALUE vobj); static int64_t vatoi(VALUE vobj); static double vatof(VALUE vobj); static VALUE rb_str_new_ex(VALUE vdb, const char* ptr, size_t size); static VALUE rb_str_new_ex2(VALUE vdb, const char* str); static VALUE findclass(const char* name); static VALUE findclass_impl(VALUE args); static VALUE maptovhash(VALUE vdb, const StringMap* map); static VALUE vectortovarray(VALUE vdb, const StringVector* vec); static void define_module(); static VALUE kc_conv_str(VALUE vself, VALUE vstr); static VALUE kc_atoi(VALUE vself, VALUE vstr); static VALUE kc_atoix(VALUE vself, VALUE vstr); static VALUE kc_atof(VALUE vself, VALUE vstr); static VALUE kc_hash_murmur(VALUE vself, VALUE vstr); static VALUE kc_hash_fnv(VALUE vself, VALUE vstr); static VALUE kc_levdist(int argc, VALUE* argv, VALUE vself); static void threadyield(); static void define_err(); static void err_define_child(const char* name, uint32_t code); static VALUE err_initialize(int argc, VALUE* argv, VALUE vself); static VALUE err_set(VALUE vself, VALUE vcode, VALUE vmessage); static VALUE err_code(VALUE vself); static VALUE err_name(VALUE vself); static VALUE err_message(VALUE vself); static VALUE err_to_s(VALUE vself); static VALUE err_inspect(VALUE vself); static VALUE err_op_eq(VALUE vself, VALUE vright); static VALUE err_op_ne(VALUE vself, VALUE vright); static void define_vis(); static VALUE vis_magic_initialize(VALUE vself, VALUE vnum); static VALUE vis_visit_full(VALUE vself, VALUE vkey, VALUE vvalue); static VALUE vis_visit_empty(VALUE vself, VALUE vkey); static void define_fproc(); static VALUE fproc_process(VALUE vself, VALUE vpath); static void define_cur(); static VALUE cur_new(VALUE cls); static void cur_del(void* ptr); static VALUE cur_initialize(VALUE vself, VALUE vdb); static VALUE cur_disable(VALUE vself); static VALUE cur_accept(int argc, VALUE* argv, VALUE vself); static VALUE cur_set_value(int argc, VALUE* argv, VALUE vself); static VALUE cur_remove(VALUE vself); static VALUE cur_get_key(int argc, VALUE* argv, VALUE vself); static VALUE cur_get_value(int argc, VALUE* argv, VALUE vself); static VALUE cur_get(int argc, VALUE* argv, VALUE vself); static VALUE cur_seize(VALUE vself); static VALUE cur_jump(int argc, VALUE* argv, VALUE vself); static VALUE cur_jump_back(int argc, VALUE* argv, VALUE vself); static VALUE cur_step(VALUE vself); static VALUE cur_step_back(VALUE vself); static VALUE cur_db(VALUE vself); static VALUE cur_error(VALUE vself); static VALUE cur_to_s(VALUE vself); static VALUE cur_inspect(VALUE vself); static void define_db(); static VALUE db_new(VALUE cls); static void db_del(void* ptr); static void db_raise(VALUE vself); static VALUE db_initialize(int argc, VALUE* argv, VALUE vself); static VALUE db_error(VALUE vself); static VALUE db_open(int argc, VALUE* argv, VALUE vself); static VALUE db_close(VALUE vself); static VALUE db_accept(int argc, VALUE* argv, VALUE vself); static VALUE db_accept_bulk(int argc, VALUE* argv, VALUE vself); static VALUE db_iterate(int argc, VALUE* argv, VALUE vself); static VALUE db_set(VALUE vself, VALUE vkey, VALUE vvalue); static VALUE db_add(VALUE vself, VALUE vkey, VALUE vvalue); static VALUE db_replace(VALUE vself, VALUE vkey, VALUE vvalue); static VALUE db_append(VALUE vself, VALUE vkey, VALUE vvalue); static VALUE db_increment(int argc, VALUE* argv, VALUE vself); static VALUE db_increment_double(int argc, VALUE* argv, VALUE vself); static VALUE db_cas(VALUE vself, VALUE vkey, VALUE voval, VALUE vnval); static VALUE db_remove(VALUE vself, VALUE vkey); static VALUE db_get(VALUE vself, VALUE vkey); static VALUE db_check(VALUE vself, VALUE vkey); static VALUE db_seize(VALUE vself, VALUE vkey); static VALUE db_set_bulk(int argc, VALUE* argv, VALUE vself); static VALUE db_remove_bulk(int argc, VALUE* argv, VALUE vself); static VALUE db_get_bulk(int argc, VALUE* argv, VALUE vself); static VALUE db_clear(VALUE vself); static VALUE db_synchronize(int argc, VALUE* argv, VALUE vself); static VALUE db_occupy(int argc, VALUE* argv, VALUE vself); static VALUE db_copy(VALUE vself, VALUE vdest); static VALUE db_begin_transaction(int argc, VALUE* argv, VALUE vself); static VALUE db_end_transaction(int argc, VALUE* argv, VALUE vself); static VALUE db_transaction(int argc, VALUE* argv, VALUE vself); static VALUE db_transaction_body(VALUE args); static VALUE db_transaction_ensure(VALUE args); static VALUE db_dump_snapshot(VALUE vself, VALUE vdest); static VALUE db_load_snapshot(VALUE vself, VALUE vsrc); static VALUE db_count(VALUE vself); static VALUE db_size(VALUE vself); static VALUE db_path(VALUE vself); static VALUE db_status(VALUE vself); static VALUE db_match_prefix(int argc, VALUE* argv, VALUE vself); static VALUE db_match_regex(int argc, VALUE* argv, VALUE vself); static VALUE db_match_similar(int argc, VALUE* argv, VALUE vself); static VALUE db_merge(int argc, VALUE* argv, VALUE vself); static VALUE db_cursor(VALUE vself); static VALUE db_cursor_process(VALUE vself); static VALUE db_cursor_process_body(VALUE vargs); static VALUE db_cursor_process_ensure(VALUE vargs); static VALUE db_tune_exception_rule(VALUE vself, VALUE vcodes); static VALUE db_tune_encoding(VALUE vself, VALUE vencname); static VALUE db_tune_encoding_impl(VALUE args); static VALUE db_to_s(VALUE vself); static VALUE db_inspect(VALUE vself); static VALUE db_shift(VALUE vself); static char* db_shift_impl(kc::PolyDB* db, size_t* ksp, const char** vbp, size_t* vsp); static VALUE db_each(VALUE vself); static VALUE db_each_key(VALUE vself); static VALUE db_each_value(VALUE vself); static VALUE db_process(int argc, VALUE* argv, VALUE vself); static VALUE db_process_body(VALUE args); static VALUE db_process_ensure(VALUE args); // global variables const int32_t VISMAGICNOP = kc::INT32MAX / 4 + 0; const int32_t VISMAGICREMOVE = kc::INT32MAX / 4 + 1; VALUE mod_kc; VALUE cls_ex; VALUE cls_str; VALUE cls_enc; VALUE cls_th; VALUE cls_mtx; VALUE cls_err; VALUE cls_err_children[(int)kc::PolyDB::Error::MISC+1]; VALUE cls_vis; VALUE cls_vis_magic; VALUE cls_fproc; VALUE cls_cur; VALUE cls_db; ID id_str_force_encoding; ID id_enc_find; ID id_th_pass; ID id_mtx_lock; ID id_mtx_unlock; ID id_obj_to_str; ID id_obj_to_s; ID id_hash_keys; ID id_err_code; ID id_err_message; ID id_vis_magic; ID id_vis_nop; ID id_vis_remove; ID id_vis_visit_full; ID id_vis_visit_empty; ID id_fproc_process; ID id_cur_db; ID id_cur_disable; ID id_db_error; ID id_db_open; ID id_db_close; ID id_db_begin_transaction; ID id_db_end_transaction; ID id_db_exbits; ID id_db_mutex; ID id_db_enc; /** * Generic options. */ enum GenericOption { GEXCEPTIONAL = 1 << 0, GCONCURRENT = 1 << 1 }; /** * Burrow of cursors no longer in use. */ class CursorBurrow { private: typedef std::vector CursorList; public: explicit CursorBurrow() : dcurs_() {} ~CursorBurrow() { sweap(); } void sweap() { if (dcurs_.size() > 0) { CursorList::iterator dit = dcurs_.begin(); CursorList::iterator ditend = dcurs_.end(); while (dit != ditend) { kc::PolyDB::Cursor* cur = *dit; delete cur; dit++; } dcurs_.clear(); } } void deposit(kc::PolyDB::Cursor* cur) { dcurs_.push_back(cur); } private: CursorList dcurs_; } g_curbur; /** * Wrapper of a cursor. */ struct SoftCursor { kc::PolyDB::Cursor* cur_; SoftCursor() : cur_(NULL) {} ~SoftCursor() { if (cur_) g_curbur.deposit(cur_); } }; /** * Wrapper of a visitor. */ class SoftVisitor : public kc::PolyDB::Visitor { public: explicit SoftVisitor(VALUE vdb, VALUE vvisitor, bool writable) : vdb_(vdb), vvisitor_(vvisitor), writable_(writable), emsg_(NULL) {} const char* emsg() { return emsg_; } private: const char* visit_full(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz, size_t* sp) { volatile VALUE vkey = rb_str_new_ex(vdb_, kbuf, ksiz); volatile VALUE vvalue = rb_str_new_ex(vdb_, vbuf, vsiz); volatile VALUE args = rb_ary_new3(3, vvisitor_, vkey, vvalue); int result = 0; volatile VALUE vrv = rb_protect(visit_full_impl, args, &result); const char* rv; if (result) { emsg_ = "exception occurred during call back function"; rv = NOP; } else if (rb_obj_is_kind_of(vrv, cls_vis_magic)) { volatile VALUE vmagic = rb_ivar_get(vrv, id_vis_magic); int32_t num = NUM2INT(vmagic); if (num == VISMAGICREMOVE) { if (writable_) { rv = kc::PolyDB::Visitor::REMOVE; } else { emsg_ = "confliction with the read-only parameter"; rv = NOP; } } else { rv = kc::PolyDB::Visitor::NOP; } } else if (vrv == Qnil || vrv == Qfalse) { rv = NOP; } else if (!writable_) { emsg_ = "confliction with the read-only parameter"; rv = NOP; } else { vrv = StringValueEx(vrv); rv = RSTRING_PTR(vrv); *sp = RSTRING_LEN(vrv); } return rv; } const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp) { volatile VALUE vkey = rb_str_new_ex(vdb_, kbuf, ksiz); volatile VALUE args = rb_ary_new3(2, vvisitor_, vkey); int result = 0; volatile VALUE vrv = rb_protect(visit_empty_impl, args, &result); const char* rv; if (result) { emsg_ = "exception occurred during call back function"; rv = NOP; } else if (rb_obj_is_kind_of(vrv, cls_vis_magic)) { volatile VALUE vmagic = rb_ivar_get(vrv, id_vis_magic); int32_t num = NUM2INT(vmagic); if (num == VISMAGICREMOVE) { if (writable_) { rv = kc::PolyDB::Visitor::REMOVE; } else { emsg_ = "confliction with the read-only parameter"; rv = NOP; } } else { rv = kc::PolyDB::Visitor::NOP; } } else if (vrv == Qnil || vrv == Qfalse) { rv = NOP; } else if (!writable_) { emsg_ = "confliction with the read-only parameter"; rv = NOP; } else { vrv = StringValueEx(vrv); rv = RSTRING_PTR(vrv); *sp = RSTRING_LEN(vrv); } return rv; } static VALUE visit_full_impl(VALUE args) { volatile VALUE vvisitor = rb_ary_shift(args); volatile VALUE vkey = rb_ary_shift(args); volatile VALUE vvalue = rb_ary_shift(args); return rb_funcall(vvisitor, id_vis_visit_full, 2, vkey, vvalue); } static VALUE visit_empty_impl(VALUE args) { volatile VALUE vvisitor = rb_ary_shift(args); volatile VALUE vkey = rb_ary_shift(args); return rb_funcall(vvisitor, id_vis_visit_empty, 1, vkey); } volatile VALUE vdb_; volatile VALUE vvisitor_; bool writable_; const char* emsg_; }; /** * Wrapper of a visitor of the block paramter. */ class SoftBlockVisitor : public kc::PolyDB::Visitor { public: explicit SoftBlockVisitor(VALUE vdb, bool writable) : vdb_(vdb), writable_(writable), emsg_(NULL) {} const char* emsg() { return emsg_; } private: const char* visit_full(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz, size_t* sp) { volatile VALUE vkey = rb_str_new_ex(vdb_, kbuf, ksiz); volatile VALUE vvalue = rb_str_new_ex(vdb_, vbuf, vsiz); volatile VALUE args = rb_ary_new3(2, vkey, vvalue); int result = 0; volatile VALUE vrv = rb_protect(visit_impl, args, &result); const char* rv; if (result) { emsg_ = "exception occurred during call back function"; rv = NOP; } else if (rb_obj_is_kind_of(vrv, cls_vis_magic)) { volatile VALUE vmagic = rb_ivar_get(vrv, id_vis_magic); int32_t num = NUM2INT(vmagic); if (num == VISMAGICREMOVE) { if (writable_) { rv = kc::PolyDB::Visitor::REMOVE; } else { emsg_ = "confliction with the read-only parameter"; rv = NOP; } } else { rv = kc::PolyDB::Visitor::NOP; } } else if (vrv == Qnil || vrv == Qfalse) { rv = NOP; } else if (!writable_) { emsg_ = "confliction with the read-only parameter"; rv = NOP; } else { vrv = StringValueEx(vrv); rv = RSTRING_PTR(vrv); *sp = RSTRING_LEN(vrv); } return rv; } const char* visit_empty(const char* kbuf, size_t ksiz, size_t* sp) { volatile VALUE vkey = rb_str_new_ex(vdb_, kbuf, ksiz); volatile VALUE args = rb_ary_new3(2, vkey, Qnil); int result = 0; volatile VALUE vrv = rb_protect(visit_impl, args, &result); const char* rv; if (result) { emsg_ = "exception occurred during call back function"; rv = NOP; } else if (rb_obj_is_kind_of(vrv, cls_vis_magic)) { volatile VALUE vmagic = rb_ivar_get(vrv, id_vis_magic); int32_t num = NUM2INT(vmagic); if (num == VISMAGICREMOVE) { if (writable_) { rv = kc::PolyDB::Visitor::REMOVE; } else { emsg_ = "confliction with the read-only parameter"; rv = NOP; } } else { rv = kc::PolyDB::Visitor::NOP; } } else if (vrv == Qnil || vrv == Qfalse) { rv = NOP; } else if (!writable_) { emsg_ = "confliction with the read-only parameter"; rv = NOP; } else { vrv = StringValueEx(vrv); rv = RSTRING_PTR(vrv); *sp = RSTRING_LEN(vrv); } return rv; } static VALUE visit_impl(VALUE args) { return rb_yield(args); } volatile VALUE vdb_; bool writable_; const char* emsg_; }; /** * Wrapper of a visitor for the each method. */ class SoftEachVisitor : public kc::PolyDB::Visitor { public: explicit SoftEachVisitor(VALUE vdb) : vdb_(vdb), emsg_(NULL) {} const char* emsg() { return emsg_; } private: const char* visit_full(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz, size_t* sp) { volatile VALUE vkey = rb_str_new_ex(vdb_, kbuf, ksiz); volatile VALUE vvalue = rb_str_new_ex(vdb_, vbuf, vsiz); volatile VALUE args = rb_ary_new3(2, vkey, vvalue); int result = 0; rb_protect(visit_full_impl, args, &result); if (result) emsg_ = "exception occurred during call back function"; return NOP; } static VALUE visit_full_impl(VALUE args) { return rb_yield(args); } volatile VALUE vdb_; const char* emsg_; }; /** * Wrapper of a visitor for the each_key method. */ class SoftEachKeyVisitor : public kc::PolyDB::Visitor { public: explicit SoftEachKeyVisitor(VALUE vdb) : vdb_(vdb), emsg_(NULL) {} const char* emsg() { return emsg_; } private: const char* visit_full(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz, size_t* sp) { volatile VALUE vkey = rb_str_new_ex(vdb_, kbuf, ksiz); volatile VALUE args = rb_ary_new3(1, vkey); int result = 0; rb_protect(visit_full_impl, args, &result); if (result) emsg_ = "exception occurred during call back function"; return NOP; } static VALUE visit_full_impl(VALUE args) { return rb_yield(args); } volatile VALUE vdb_; const char* emsg_; }; /** * Wrapper of a visitor for the each_value method. */ class SoftEachValueVisitor : public kc::PolyDB::Visitor { public: explicit SoftEachValueVisitor(VALUE vdb) : vdb_(vdb), emsg_(NULL) {} const char* emsg() { return emsg_; } private: const char* visit_full(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz, size_t* sp) { volatile VALUE vvalue = rb_str_new_ex(vdb_, vbuf, vsiz); volatile VALUE args = rb_ary_new3(1, vvalue); int result = 0; rb_protect(visit_full_impl, args, &result); if (result) emsg_ = "exception occurred during call back function"; return NOP; } static VALUE visit_full_impl(VALUE args) { return rb_yield(args); } volatile VALUE vdb_; const char* emsg_; }; /** * Wrapper of a file processor. */ class SoftFileProcessor : public kc::PolyDB::FileProcessor { public: explicit SoftFileProcessor(VALUE vdb, VALUE vproc) : vdb_(vdb), vproc_(vproc), emsg_(NULL) {} const char* emsg() { return emsg_; } private: bool process(const std::string& path, int64_t count, int64_t size) { volatile VALUE vpath = rb_str_new_ex2(vdb_, path.c_str()); volatile VALUE vcount = LL2NUM(count); volatile VALUE vsize = LL2NUM(size); volatile VALUE args = rb_ary_new3(4, vproc_, vpath, vcount, vsize); int result = 0; volatile VALUE vrv = rb_protect(process_impl, args, &result); if (result) emsg_ = "exception occurred during call back function"; return !result && vrv != Qnil && vrv != Qfalse; } static VALUE process_impl(VALUE args) { volatile VALUE vproc = rb_ary_shift(args); volatile VALUE vpath = rb_ary_shift(args); volatile VALUE vcount = rb_ary_shift(args); volatile VALUE vsize = rb_ary_shift(args); return rb_funcall(vproc, id_fproc_process, 3, vpath, vcount, vsize); } volatile VALUE vdb_; volatile VALUE vproc_; const char* emsg_; }; /** * Wrapper of a file processor of the block parameter. */ class SoftBlockFileProcessor : public kc::PolyDB::FileProcessor { public: explicit SoftBlockFileProcessor(VALUE vdb) : vdb_(vdb), emsg_(NULL) {} const char* emsg() { return emsg_; } private: bool process(const std::string& path, int64_t count, int64_t size) { volatile VALUE vpath = rb_str_new_ex2(vdb_, path.c_str()); volatile VALUE vcount = LL2NUM(count); volatile VALUE vsize = LL2NUM(size); volatile VALUE args = rb_ary_new3(3, vpath, vcount, vsize); int result = 0; volatile VALUE vrv = rb_protect(process_impl, args, &result); if (result) emsg_ = "exception occurred during call back function"; return !result && vrv != Qnil && vrv != Qfalse; } static VALUE process_impl(VALUE args) { return rb_yield(args); } volatile VALUE vdb_; const char* emsg_; }; /** * Wrapper of a native function. */ class NativeFunction { public: virtual ~NativeFunction() {} virtual void operate() = 0; static void execute(NativeFunction* func) { #if defined(_KC_YARV_) rb_thread_blocking_region(execute_impl, func, RUBY_UBF_IO, NULL); #else func->operate(); #endif } private: static VALUE execute_impl(void* ptr) { NativeFunction* func = (NativeFunction*)ptr; func->operate(); return Qnil; } }; /** * Entry point of the library. */ void Init_kyotocabinet() { define_module(); define_err(); define_vis(); define_fproc(); define_cur(); define_db(); } /** * Generate a string expression of an arbitrary object. */ static VALUE StringValueEx(VALUE vobj) { switch (TYPE(vobj)) { case T_STRING: { return vobj; } case T_FIXNUM: { char kbuf[kc::NUMBUFSIZ]; size_t ksiz = std::sprintf(kbuf, "%d", (int)FIX2INT(vobj)); return rb_str_new(kbuf, ksiz); } case T_NIL: { return rb_str_new("", 0); } } if (rb_respond_to(vobj, id_obj_to_str)) return StringValue(vobj); if (rb_respond_to(vobj, id_obj_to_s)) return rb_funcall(vobj, id_obj_to_s, 0); char kbuf[kc::NUMBUFSIZ*2]; std::sprintf(kbuf, "#", (long long)rb_obj_id(vobj)); return rb_str_new2(kbuf); } /** * Convert a numeric parameter to an integer. */ static int64_t vatoi(VALUE vobj) { switch (TYPE(vobj)) { case T_FIXNUM: { return FIX2INT(vobj); } case T_BIGNUM: { return NUM2LL(vobj); } case T_FLOAT: { double dnum = NUM2DBL(vobj); if (kc::chknan(dnum)) { return kc::INT64MIN; } else if (kc::chkinf(dnum)) { return dnum < 0 ? kc::INT64MIN : kc::INT64MAX; } return dnum; } case T_TRUE: { return 1; } case T_STRING: { const char* str = RSTRING_PTR(vobj); double dnum = kc::atof(str); if (kc::chknan(dnum)) { return kc::INT64MIN; } else if (kc::chkinf(dnum)) { return dnum < 0 ? kc::INT64MIN : kc::INT64MAX; } return dnum; } } return 0; } /** * Convert a numeric parameter to a real number. */ static double vatof(VALUE vobj) { switch (TYPE(vobj)) { case T_FIXNUM: { return FIX2INT(vobj); } case T_BIGNUM: { return NUM2LL(vobj); } case T_FLOAT: { return NUM2DBL(vobj); } case T_TRUE: { return 1.0; } case T_STRING: { const char* str = RSTRING_PTR(vobj); return kc::atof(str); } } return 0.0; } /** * Generate a string object with the internal encoding of the database. */ static VALUE rb_str_new_ex(VALUE vdb, const char* ptr, size_t size) { volatile VALUE venc = rb_ivar_get(vdb, id_db_enc); if (venc == Qnil) return rb_str_new(ptr, size); volatile VALUE vstr = rb_str_new(ptr, size); rb_funcall(vstr, id_str_force_encoding, 1, venc); return vstr; } /** * Generate a string object with the internal encoding of the database. */ static VALUE rb_str_new_ex2(VALUE vdb, const char* str) { volatile VALUE venc = rb_ivar_get(vdb, id_db_enc); if (venc == Qnil) return rb_str_new2(str); volatile VALUE vstr = rb_str_new2(str); rb_funcall(vstr, id_str_force_encoding, 1, venc); return vstr; } /** * Find the class object of a name. */ static VALUE findclass(const char* name) { volatile VALUE vname = rb_str_new2(name); volatile VALUE args = rb_ary_new3(1, vname); int result = 0; volatile VALUE cls = rb_protect(findclass_impl, args, &result); if (result) return Qnil; return cls; } /** * Find the class object of a name. */ static VALUE findclass_impl(VALUE args) { volatile VALUE vname = rb_ary_shift(args); return rb_path2class(RSTRING_PTR(vname)); } /** * Convert an internal map to a Ruby hash. */ static VALUE maptovhash(VALUE vdb, const StringMap* map) { volatile VALUE vhash = rb_hash_new(); StringMap::const_iterator it = map->begin(); StringMap::const_iterator itend = map->end(); while (it != itend) { volatile VALUE vkey = rb_str_new_ex(vdb, it->first.data(), it->first.size()); volatile VALUE vvalue = rb_str_new_ex(vdb, it->second.data(), it->second.size()); rb_hash_aset(vhash, vkey, vvalue); it++; } return vhash; } /** * Convert an internal vector to a Ruby array. */ static VALUE vectortovarray(VALUE vdb, const StringVector* vec) { volatile VALUE vary = rb_ary_new2(vec->size()); StringVector::const_iterator it = vec->begin(); StringVector::const_iterator itend = vec->end(); while (it != itend) { volatile VALUE vstr = rb_str_new_ex(vdb, it->data(), it->size()); rb_ary_push(vary, vstr); it++; } return vary; } /** * Pass the current execution state. */ static void threadyield() { rb_funcall(cls_th, id_th_pass, 0); } /** * Define objects of the module. */ static void define_module() { mod_kc = rb_define_module("KyotoCabinet"); rb_require("thread"); rb_define_const(mod_kc, "VERSION", rb_str_new2(kc::VERSION)); rb_define_module_function(mod_kc, "conv_str", (METHOD)kc_conv_str, 1); rb_define_module_function(mod_kc, "atoi", (METHOD)kc_atoi, 1); rb_define_module_function(mod_kc, "atoix", (METHOD)kc_atoix, 1); rb_define_module_function(mod_kc, "atof", (METHOD)kc_atof, 1); rb_define_module_function(mod_kc, "hash_murmur", (METHOD)kc_hash_murmur, 1); rb_define_module_function(mod_kc, "hash_fnv", (METHOD)kc_hash_fnv, 1); rb_define_module_function(mod_kc, "levdist", (METHOD)kc_levdist, -1); cls_ex = findclass("RuntimeError"); cls_str = findclass("String"); id_str_force_encoding = rb_intern("force_encoding"); cls_enc = findclass("Encoding"); id_enc_find = rb_intern("find"); cls_th = findclass("Thread"); id_th_pass = rb_intern("pass"); cls_mtx = findclass("Mutex"); id_mtx_lock = rb_intern("lock"); id_mtx_unlock = rb_intern("unlock"); id_obj_to_str = rb_intern("to_str"); id_obj_to_s = rb_intern("to_s"); id_hash_keys = rb_intern("keys"); } /** * Implementation of conv_str. */ static VALUE kc_conv_str(VALUE vself, VALUE vstr) { return StringValueEx(vstr); } /** * Implementation of atoi. */ static VALUE kc_atoi(VALUE vself, VALUE vstr) { vstr = StringValueEx(vstr); int64_t num = kc::atoi(RSTRING_PTR(vstr)); return LL2NUM(num); } /** * Implementation of atoix. */ static VALUE kc_atoix(VALUE vself, VALUE vstr) { vstr = StringValueEx(vstr); int64_t num = kc::atoix(RSTRING_PTR(vstr)); return LL2NUM(num); } /** * Implementation of atof. */ static VALUE kc_atof(VALUE vself, VALUE vstr) { vstr = StringValueEx(vstr); double num = kc::atof(RSTRING_PTR(vstr)); return rb_float_new(num); } /** * Implementation of hash_murmur. */ static VALUE kc_hash_murmur(VALUE vself, VALUE vstr) { vstr = StringValueEx(vstr); uint64_t hash = kc::hashmurmur(RSTRING_PTR(vstr), RSTRING_LEN(vstr)); return ULL2NUM(hash); } /** * Implementation of hash_fnv. */ static VALUE kc_hash_fnv(VALUE vself, VALUE vstr) { vstr = StringValueEx(vstr); uint64_t hash = kc::hashfnv(RSTRING_PTR(vstr), RSTRING_LEN(vstr)); return ULL2NUM(hash); } /** * Implementation of levdist. */ static VALUE kc_levdist(int argc, VALUE* argv, VALUE vself) { volatile VALUE va, vb, vutf; rb_scan_args(argc, argv, "21", &va, &vb, &vutf); va = StringValueEx(va); const char* abuf = RSTRING_PTR(va); size_t asiz = RSTRING_LEN(va); vb = StringValueEx(vb); const char* bbuf = RSTRING_PTR(vb); size_t bsiz = RSTRING_LEN(vb); bool utf = vutf != Qnil && vutf != Qfalse; size_t dist; if (utf) { uint32_t astack[128]; uint32_t* aary = asiz > sizeof(astack) / sizeof(*astack) ? new uint32_t[asiz] : astack; size_t anum; kc::strutftoucs(abuf, asiz, aary, &anum); uint32_t bstack[128]; uint32_t* bary = bsiz > sizeof(bstack) / sizeof(*bstack) ? new uint32_t[bsiz] : bstack; size_t bnum; kc::strutftoucs(bbuf, bsiz, bary, &bnum); dist = kc::strucsdist(aary, anum, bary, bnum); if (bary != bstack) delete[] bary; if (aary != astack) delete[] aary; } else { dist = kc::memdist(abuf, asiz, bbuf, bsiz); } return INT2FIX((int)dist); } /** * Define objects of the Error class. */ static void define_err() { cls_err = rb_define_class_under(mod_kc, "Error", cls_ex); for (size_t i = 0; i < sizeof(cls_err_children) / sizeof(*cls_err_children); i++) { cls_err_children[i] = Qnil; } err_define_child("SUCCESS", kc::PolyDB::Error::SUCCESS); err_define_child("NOIMPL", kc::PolyDB::Error::NOIMPL); err_define_child("INVALID", kc::PolyDB::Error::INVALID); err_define_child("NOREPOS", kc::PolyDB::Error::NOREPOS); err_define_child("NOPERM", kc::PolyDB::Error::NOPERM); err_define_child("BROKEN", kc::PolyDB::Error::BROKEN); err_define_child("DUPREC", kc::PolyDB::Error::DUPREC); err_define_child("NOREC", kc::PolyDB::Error::NOREC); err_define_child("LOGIC", kc::PolyDB::Error::LOGIC); err_define_child("SYSTEM", kc::PolyDB::Error::SYSTEM); err_define_child("MISC", kc::PolyDB::Error::MISC); rb_define_private_method(cls_err, "initialize", (METHOD)err_initialize, -1); rb_define_method(cls_err, "set", (METHOD)err_set, 2); rb_define_method(cls_err, "code", (METHOD)err_code, 0); rb_define_method(cls_err, "name", (METHOD)err_name, 0); rb_define_method(cls_err, "message", (METHOD)err_message, 0); rb_define_method(cls_err, "to_i", (METHOD)err_code, 0); rb_define_method(cls_err, "to_s", (METHOD)err_to_s, 0); rb_define_method(cls_err, "inspect", (METHOD)err_inspect, 0); rb_define_method(cls_err, "==", (METHOD)err_op_eq, 1); rb_define_method(cls_err, "!=", (METHOD)err_op_ne, 1); id_err_code = rb_intern("@code"); id_err_message = rb_intern("@message"); } /** * Define the constant and the subclass of an error code. */ static void err_define_child(const char* name, uint32_t code) { rb_define_const(cls_err, name, INT2FIX(code)); char xname[kc::NUMBUFSIZ]; sprintf(xname, "X%s", name); cls_err_children[code] = rb_define_class_under(cls_err, xname, cls_err); } /** * Implementation of initialize. */ static VALUE err_initialize(int argc, VALUE* argv, VALUE vself) { volatile VALUE vcode, vmessage; rb_scan_args(argc, argv, "02", &vcode, &vmessage); if (argc == 1 && TYPE(vcode) == T_STRING) { const char* expr = RSTRING_PTR(vcode); uint32_t code = kc::atoi(expr); const char* rp = std::strchr(expr, ':'); if (rp) expr = rp + 1; while (*expr == ' ') { expr++; } vcode = INT2FIX(code); vmessage = rb_str_new2(expr); } else { if (vcode == Qnil) vcode = INT2FIX(kc::PolyDB::Error::SUCCESS); if (vmessage == Qnil) vmessage = rb_str_new2("error"); } rb_ivar_set(vself, id_err_code, vcode); rb_ivar_set(vself, id_err_message, vmessage); return Qnil; } /** * Implementation of set. */ static VALUE err_set(VALUE vself, VALUE vcode, VALUE vmessage) { rb_ivar_set(vself, id_err_code, vcode); rb_ivar_set(vself, id_err_message, vmessage); return Qnil; } /** * Implementation of code. */ static VALUE err_code(VALUE vself) { return rb_ivar_get(vself, id_err_code); } /** * Implementation of name. */ static VALUE err_name(VALUE vself) { int32_t code = FIX2INT(rb_ivar_get(vself, id_err_code)); return rb_str_new2(kc::PolyDB::Error::codename((kc::PolyDB::Error::Code)code)); } /** * Implementation of message. */ static VALUE err_message(VALUE vself) { return rb_ivar_get(vself, id_err_message); } /** * Implementation of to_s. */ static VALUE err_to_s(VALUE vself) { int32_t code = NUM2INT(rb_ivar_get(vself, id_err_code)); volatile VALUE vmessage = rb_ivar_get(vself, id_err_message); const char* message = RSTRING_PTR(vmessage); std::string str = kc::strprintf("%s: %s", kc::PolyDB::Error::codename((kc::PolyDB::Error::Code)code), message); return rb_str_new(str.data(), str.size()); } /** * Implementation of inspect. */ static VALUE err_inspect(VALUE vself) { int32_t code = NUM2INT(rb_ivar_get(vself, id_err_code)); volatile VALUE vmessage = rb_ivar_get(vself, id_err_message); const char* message = RSTRING_PTR(vmessage); std::string str = kc::strprintf("#", code, kc::PolyDB::Error::codename((kc::PolyDB::Error::Code)code), message); return rb_str_new(str.data(), str.size()); } /** * Implementation of op_eq. */ static VALUE err_op_eq(VALUE vself, VALUE vright) { if (vright == Qnil) return Qfalse; if (TYPE(vright) == T_FIXNUM) return NUM2INT(rb_ivar_get(vself, id_err_code)) == FIX2INT(vright) ? Qtrue : Qfalse; return NUM2INT(rb_ivar_get(vself, id_err_code)) == NUM2INT(rb_ivar_get(vright, id_err_code)) ? Qtrue : Qfalse; } /** * Implementation of op_ne. */ static VALUE err_op_ne(VALUE vself, VALUE vright) { if (vright == Qnil) return Qtrue; if (TYPE(vright) == T_FIXNUM) return NUM2INT(rb_ivar_get(vself, id_err_code)) != FIX2INT(vright) ? Qtrue : Qfalse; return NUM2INT(rb_ivar_get(vself, id_err_code)) != NUM2INT(rb_ivar_get(vright, id_err_code)) ? Qtrue : Qfalse; } /** * Define objects of the Visitor class. */ static void define_vis() { cls_vis = rb_define_class_under(mod_kc, "Visitor", rb_cObject); cls_vis_magic = rb_define_class_under(mod_kc, "VisitorMagic", rb_cObject); rb_define_private_method(cls_vis_magic, "initialize", (METHOD)vis_magic_initialize, 1); id_vis_magic = rb_intern("@magic_"); volatile VALUE vnopnum = INT2FIX(VISMAGICNOP); volatile VALUE vnop = rb_class_new_instance(1, (VALUE*)&vnopnum, cls_vis_magic); rb_define_const(cls_vis, "NOP", vnop); volatile VALUE vremovenum = INT2FIX(VISMAGICREMOVE); volatile VALUE vremove = rb_class_new_instance(1, (VALUE*)&vremovenum, cls_vis_magic); rb_define_const(cls_vis, "REMOVE", vremove); rb_define_method(cls_vis, "visit_full", (METHOD)vis_visit_full, 2); rb_define_method(cls_vis, "visit_empty", (METHOD)vis_visit_empty, 1); id_vis_nop = rb_intern("NOP"); id_vis_remove = rb_intern("REMOVE"); id_vis_visit_full = rb_intern("visit_full"); id_vis_visit_empty = rb_intern("visit_empty"); } /** * Implementation of magic_initialize. */ static VALUE vis_magic_initialize(VALUE vself, VALUE vnum) { rb_ivar_set(vself, id_vis_magic, vnum); return Qnil; } /** * Implementation of visit_full. */ static VALUE vis_visit_full(VALUE vself, VALUE vkey, VALUE vvalue) { return rb_const_get(cls_vis, id_vis_nop); } /** * Implementation of visit_empty. */ static VALUE vis_visit_empty(VALUE vself, VALUE vkey) { return rb_const_get(cls_vis, id_vis_nop); } /** * Define objects of the FileProcessor class. */ static void define_fproc() { cls_fproc = rb_define_class_under(mod_kc, "FileProcessor", rb_cObject); rb_define_method(cls_fproc, "process", (METHOD)fproc_process, 1); id_fproc_process = rb_intern("process"); } /** * Implementation of process. */ static VALUE fproc_process(VALUE vself, VALUE vpath) { return Qtrue; } /** * Define objects of the Cursor class. */ static void define_cur() { cls_cur = rb_define_class_under(mod_kc, "Cursor", rb_cObject); rb_define_alloc_func(cls_cur, cur_new); rb_define_private_method(cls_cur, "initialize", (METHOD)cur_initialize, 1); rb_define_method(cls_cur, "disable", (METHOD)cur_disable, 0); rb_define_method(cls_cur, "accept", (METHOD)cur_accept, -1); rb_define_method(cls_cur, "set_value", (METHOD)cur_set_value, -1); rb_define_method(cls_cur, "remove", (METHOD)cur_remove, 0); rb_define_method(cls_cur, "get_key", (METHOD)cur_get_key, -1); rb_define_method(cls_cur, "get_value", (METHOD)cur_get_value, -1); rb_define_method(cls_cur, "get", (METHOD)cur_get, -1); rb_define_method(cls_cur, "seize", (METHOD)cur_seize, 0); rb_define_method(cls_cur, "jump", (METHOD)cur_jump, -1); rb_define_method(cls_cur, "jump_back", (METHOD)cur_jump_back, -1); rb_define_method(cls_cur, "step", (METHOD)cur_step, 0); rb_define_method(cls_cur, "step_back", (METHOD)cur_step_back, 0); rb_define_method(cls_cur, "db", (METHOD)cur_db, 0); rb_define_method(cls_cur, "error", (METHOD)cur_error, 0); rb_define_method(cls_cur, "to_s", (METHOD)cur_to_s, 0); rb_define_method(cls_cur, "inspect", (METHOD)cur_inspect, 0); id_cur_db = rb_intern("@db_"); id_cur_disable= rb_intern("disable"); } /** * Implementation of new. */ static VALUE cur_new(VALUE cls) { SoftCursor* cur = new SoftCursor; return Data_Wrap_Struct(cls_cur, 0, cur_del, cur); } /** * Implementation of del. */ static void cur_del(void* ptr) { delete (SoftCursor*)ptr; } /** * Implementation of initialize. */ static VALUE cur_initialize(VALUE vself, VALUE vdb) { SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); if (!rb_obj_is_kind_of(vdb, cls_db)) return Qnil; kc::PolyDB* db; Data_Get_Struct(vdb, kc::PolyDB, db); volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { g_curbur.sweap(); cur->cur_ = db->cursor(); } else { rb_funcall(vmutex, id_mtx_lock, 0); g_curbur.sweap(); cur->cur_ = db->cursor(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (cur->cur_) { rb_ivar_set(vself, id_cur_db, vdb); } else { rb_ivar_set(vself, id_cur_db, Qnil); } return Qnil; } /** * Implementation of disable. */ static VALUE cur_disable(VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qnil; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { delete cur->cur_; cur->cur_ = NULL; } else { rb_funcall(vmutex, id_mtx_lock, 0); delete cur->cur_; cur->cur_ = NULL; rb_funcall(vmutex, id_mtx_unlock, 0); } rb_ivar_set(vself, id_cur_db, Qnil); return Qnil; } /** * Implementation of accept. */ static VALUE cur_accept(int argc, VALUE* argv, VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qfalse; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); volatile VALUE vvisitor, vwritable, vstep; rb_scan_args(argc, argv, "03", &vvisitor, &vwritable, &vstep); volatile VALUE vrv; if (vvisitor == Qnil) { bool writable = vwritable != Qfalse; bool step = vstep != Qnil && vstep != Qfalse; SoftBlockVisitor visitor(vdb, writable); volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { cur->cur_->db()->set_error(kc::PolyDB::Error::INVALID, "unsuppotred method"); db_raise(vdb); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = cur->cur_->accept(&visitor, writable, step); const char *emsg = visitor.emsg(); if (emsg) { cur->cur_->db()->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vdb); } } else { bool writable = vwritable != Qfalse; bool step = vstep != Qnil && vstep != Qfalse; SoftVisitor visitor(vdb, vvisitor, writable); volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { cur->cur_->db()->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vdb); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = cur->cur_->accept(&visitor, writable, step); const char *emsg = visitor.emsg(); if (emsg) { cur->cur_->db()->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vdb); } } return vrv; } /** * Implementation of set_value. */ static VALUE cur_set_value(int argc, VALUE* argv, VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qfalse; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); volatile VALUE vvalue, vstep; rb_scan_args(argc, argv, "11", &vvalue, &vstep); vvalue = StringValueEx(vvalue); const char* vbuf = RSTRING_PTR(vvalue); size_t vsiz = RSTRING_LEN(vvalue); bool step = vstep != Qnil && vstep != Qfalse; bool rv; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur, const char* vbuf, size_t vsiz, bool step) : cur_(cur), vbuf_(vbuf), vsiz_(vsiz), step_(step), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = cur_->set_value(vbuf_, vsiz_, step_); } kc::PolyDB::Cursor* cur_; const char* vbuf_; size_t vsiz_; bool step_; bool rv_; } func(cur->cur_, vbuf, vsiz, step); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = cur->cur_->set_value(vbuf, vsiz, step); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vdb); return Qfalse; } /** * Implementation of remove. */ static VALUE cur_remove(VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qfalse; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); bool rv; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur) : cur_(cur), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = cur_->remove(); } kc::PolyDB::Cursor* cur_; bool rv_; } func(cur->cur_); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = cur->cur_->remove(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vdb); return Qfalse; } /** * Implementation of get_key. */ static VALUE cur_get_key(int argc, VALUE* argv, VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qnil; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); volatile VALUE vstep; rb_scan_args(argc, argv, "01", &vstep); bool step = vstep != Qnil && vstep != Qfalse; char* kbuf; size_t ksiz; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur, bool step) : cur_(cur), step_(step), kbuf_(NULL), ksiz_(0) {} char* rv(size_t* ksp) { *ksp = ksiz_; return kbuf_; } private: void operate() { kbuf_ = cur_->get_key(&ksiz_, step_); } kc::PolyDB::Cursor* cur_; bool step_; char* kbuf_; size_t ksiz_; } func(cur->cur_, step); NativeFunction::execute(&func); kbuf = func.rv(&ksiz); } else { rb_funcall(vmutex, id_mtx_lock, 0); kbuf = cur->cur_->get_key(&ksiz, step); rb_funcall(vmutex, id_mtx_unlock, 0); } volatile VALUE vrv; if (kbuf) { vrv = rb_str_new_ex(vdb, kbuf, ksiz); delete[] kbuf; } else { vrv = Qnil; db_raise(vdb); } return vrv; } /** * Implementation of get_value. */ static VALUE cur_get_value(int argc, VALUE* argv, VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qnil; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); volatile VALUE vstep; rb_scan_args(argc, argv, "01", &vstep); bool step = vstep != Qnil && vstep != Qfalse; char* vbuf; size_t vsiz; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur, bool step) : cur_(cur), step_(step), vbuf_(NULL), vsiz_(0) {} char* rv(size_t* vsp) { *vsp = vsiz_; return vbuf_; } private: void operate() { vbuf_ = cur_->get_value(&vsiz_, step_); } kc::PolyDB::Cursor* cur_; bool step_; char* vbuf_; size_t vsiz_; } func(cur->cur_, step); NativeFunction::execute(&func); vbuf = func.rv(&vsiz); } else { rb_funcall(vmutex, id_mtx_lock, 0); vbuf = cur->cur_->get_value(&vsiz, step); rb_funcall(vmutex, id_mtx_unlock, 0); } volatile VALUE vrv; if (vbuf) { vrv = rb_str_new_ex(vdb, vbuf, vsiz); delete[] vbuf; } else { vrv = Qnil; db_raise(vdb); } return vrv; } /** * Implementation of get. */ static VALUE cur_get(int argc, VALUE* argv, VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qnil; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); volatile VALUE vstep; rb_scan_args(argc, argv, "01", &vstep); bool step = vstep != Qnil && vstep != Qfalse; char* kbuf; const char* vbuf; size_t ksiz, vsiz; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur, bool step) : cur_(cur), step_(step), kbuf_(NULL), ksiz_(0), vbuf_(NULL), vsiz_(0) {} char* rv(size_t* ksp, const char** vbp, size_t* vsp) { *ksp = ksiz_; *vbp = vbuf_; *vsp = vsiz_; return kbuf_; } private: void operate() { kbuf_ = cur_->get(&ksiz_, &vbuf_, &vsiz_, step_); } kc::PolyDB::Cursor* cur_; bool step_; char* kbuf_; size_t ksiz_; const char* vbuf_; size_t vsiz_; } func(cur->cur_, step); NativeFunction::execute(&func); kbuf = func.rv(&ksiz, &vbuf, &vsiz); } else { rb_funcall(vmutex, id_mtx_lock, 0); kbuf = cur->cur_->get(&ksiz, &vbuf, &vsiz, step); rb_funcall(vmutex, id_mtx_unlock, 0); } volatile VALUE vrv; if (kbuf) { volatile VALUE vkey = rb_str_new_ex(vdb, kbuf, ksiz); volatile VALUE vvalue = rb_str_new_ex(vdb, vbuf, vsiz); vrv = rb_ary_new3(2, vkey, vvalue); delete[] kbuf; } else { vrv = Qnil; db_raise(vdb); } return vrv; } /** * Implementation of seize. */ static VALUE cur_seize(VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qnil; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); char* kbuf; const char* vbuf; size_t ksiz, vsiz; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur) : cur_(cur), kbuf_(NULL), ksiz_(0), vbuf_(NULL), vsiz_(0) {} char* rv(size_t* ksp, const char** vbp, size_t* vsp) { *ksp = ksiz_; *vbp = vbuf_; *vsp = vsiz_; return kbuf_; } private: void operate() { kbuf_ = cur_->seize(&ksiz_, &vbuf_, &vsiz_); } kc::PolyDB::Cursor* cur_; char* kbuf_; size_t ksiz_; const char* vbuf_; size_t vsiz_; } func(cur->cur_); NativeFunction::execute(&func); kbuf = func.rv(&ksiz, &vbuf, &vsiz); } else { rb_funcall(vmutex, id_mtx_lock, 0); kbuf = cur->cur_->seize(&ksiz, &vbuf, &vsiz); rb_funcall(vmutex, id_mtx_unlock, 0); } volatile VALUE vrv; if (kbuf) { volatile VALUE vkey = rb_str_new_ex(vdb, kbuf, ksiz); volatile VALUE vvalue = rb_str_new_ex(vdb, vbuf, vsiz); vrv = rb_ary_new3(2, vkey, vvalue); delete[] kbuf; } else { vrv = Qnil; db_raise(vdb); } return vrv; } /** * Implementation of jump. */ static VALUE cur_jump(int argc, VALUE* argv, VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qfalse; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); volatile VALUE vkey; rb_scan_args(argc, argv, "01", &vkey); volatile VALUE vrv; if (vkey == Qnil) { bool rv; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur) : cur_(cur), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = cur_->jump(); } kc::PolyDB::Cursor* cur_; bool rv_; } func(cur->cur_); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = cur->cur_->jump(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vdb); } } else { vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); bool rv; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur, const char*kbuf, size_t ksiz) : cur_(cur), kbuf_(kbuf), ksiz_(ksiz), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = cur_->jump(kbuf_, ksiz_); } kc::PolyDB::Cursor* cur_; const char* kbuf_; size_t ksiz_; bool rv_; } func(cur->cur_, kbuf, ksiz); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = cur->cur_->jump(kbuf, ksiz); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vdb); } } return vrv; } /** * Implementation of jump_back. */ static VALUE cur_jump_back(int argc, VALUE* argv, VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qfalse; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); volatile VALUE vkey; rb_scan_args(argc, argv, "01", &vkey); volatile VALUE vrv; if (vkey == Qnil) { bool rv; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur) : cur_(cur), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = cur_->jump_back(); } kc::PolyDB::Cursor* cur_; bool rv_; } func(cur->cur_); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = cur->cur_->jump_back(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vdb); } } else { vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); bool rv; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur, const char*kbuf, size_t ksiz) : cur_(cur), kbuf_(kbuf), ksiz_(ksiz), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = cur_->jump_back(kbuf_, ksiz_); } kc::PolyDB::Cursor* cur_; const char* kbuf_; size_t ksiz_; bool rv_; } func(cur->cur_, kbuf, ksiz); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = cur->cur_->jump_back(kbuf, ksiz); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vdb); } } return vrv; } /** * Implementation of step. */ static VALUE cur_step(VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qfalse; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); bool rv; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur) : cur_(cur), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = cur_->step(); } kc::PolyDB::Cursor* cur_; bool rv_; } func(cur->cur_); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = cur->cur_->step(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vdb); return Qfalse; } /** * Implementation of step_back. */ static VALUE cur_step_back(VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qfalse; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); bool rv; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB::Cursor* cur) : cur_(cur), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = cur_->step_back(); } kc::PolyDB::Cursor* cur_; bool rv_; } func(cur->cur_); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = cur->cur_->step_back(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vdb); return Qfalse; } /** * Implementation of db. */ static VALUE cur_db(VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qnil; return vdb; } /** * Implementation of error. */ static VALUE cur_error(VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return Qnil; SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); kc::PolyDB::Error err = cur->cur_->error(); volatile VALUE args[2]; args[0] = INT2FIX(err.code()); args[1] = rb_str_new_ex2(vdb, err.message()); return rb_class_new_instance(2, (VALUE*)args, cls_err); } /** * Implementation of to_s. */ static VALUE cur_to_s(VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return rb_str_new2("(disabled)"); SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); std::string str; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { kc::PolyDB* db = cur->cur_->db(); std::string path = db->path(); if (path.size() < 1) path = "(nil)"; kc::strprintf(&str, "%s: ", path.c_str()); size_t ksiz; char* kbuf = cur->cur_->get_key(&ksiz); if (kbuf) { str.append(kbuf, ksiz); delete[] kbuf; } else { str.append("(nil)"); } } else { rb_funcall(vmutex, id_mtx_lock, 0); kc::PolyDB* db = cur->cur_->db(); std::string path = db->path(); if (path.size() < 1) path = "(nil)"; kc::strprintf(&str, "%s: ", path.c_str()); size_t ksiz; char* kbuf = cur->cur_->get_key(&ksiz); if (kbuf) { str.append(kbuf, ksiz); delete[] kbuf; } else { str.append("(nil)"); } rb_funcall(vmutex, id_mtx_unlock, 0); } return rb_str_new_ex2(vdb, str.c_str()); } /** * Implementation of inspect. */ static VALUE cur_inspect(VALUE vself) { volatile VALUE vdb = rb_ivar_get(vself, id_cur_db); if (vdb == Qnil) return rb_str_new2("#"); SoftCursor* cur; Data_Get_Struct(vself, SoftCursor, cur); std::string str; volatile VALUE vmutex = rb_ivar_get(vdb, id_db_mutex); if (vmutex == Qnil) { kc::PolyDB* db = cur->cur_->db(); std::string path = db->path(); if (path.size() < 1) path = "(nil)"; kc::strprintf(&str, "#cur_->get_key(&ksiz); if (kbuf) { str.append(kbuf, ksiz); delete[] kbuf; } else { str.append("(nil)"); } kc::strprintf(&str, ">"); } else { rb_funcall(vmutex, id_mtx_lock, 0); kc::PolyDB* db = cur->cur_->db(); std::string path = db->path(); if (path.size() < 1) path = "(nil)"; kc::strprintf(&str, "#cur_->get_key(&ksiz); if (kbuf) { str.append(kbuf, ksiz); delete[] kbuf; } else { str.append("(nil)"); } kc::strprintf(&str, ">"); rb_funcall(vmutex, id_mtx_unlock, 0); } return rb_str_new_ex2(vdb, str.c_str()); } /** * Define objects of the DB class. */ static void define_db() { cls_db = rb_define_class_under(mod_kc, "DB", rb_cObject); rb_define_alloc_func(cls_db, db_new); rb_define_const(cls_db, "GEXCEPTIONAL", INT2FIX(GEXCEPTIONAL)); rb_define_const(cls_db, "GCONCURRENT", INT2FIX(GCONCURRENT)); rb_define_const(cls_db, "OREADER", INT2FIX(kc::PolyDB::OREADER)); rb_define_const(cls_db, "OWRITER", INT2FIX(kc::PolyDB::OWRITER)); rb_define_const(cls_db, "OCREATE", INT2FIX(kc::PolyDB::OCREATE)); rb_define_const(cls_db, "OTRUNCATE", INT2FIX(kc::PolyDB::OTRUNCATE)); rb_define_const(cls_db, "OAUTOTRAN", INT2FIX(kc::PolyDB::OAUTOTRAN)); rb_define_const(cls_db, "OAUTOSYNC", INT2FIX(kc::PolyDB::OAUTOSYNC)); rb_define_const(cls_db, "ONOLOCK", INT2FIX(kc::PolyDB::ONOLOCK)); rb_define_const(cls_db, "OTRYLOCK", INT2FIX(kc::PolyDB::OTRYLOCK)); rb_define_const(cls_db, "ONOREPAIR", INT2FIX(kc::PolyDB::ONOREPAIR)); rb_define_const(cls_db, "MSET", INT2FIX(kc::PolyDB::MSET)); rb_define_const(cls_db, "MADD", INT2FIX(kc::PolyDB::MADD)); rb_define_const(cls_db, "MREPLACE", INT2FIX(kc::PolyDB::MREPLACE)); rb_define_const(cls_db, "MAPPEND", INT2FIX(kc::PolyDB::MAPPEND)); rb_define_private_method(cls_db, "initialize", (METHOD)db_initialize, -1); rb_define_method(cls_db, "error", (METHOD)db_error, 0); rb_define_method(cls_db, "open", (METHOD)db_open, -1); rb_define_method(cls_db, "close", (METHOD)db_close, 0); rb_define_method(cls_db, "accept", (METHOD)db_accept, -1); rb_define_method(cls_db, "accept_bulk", (METHOD)db_accept_bulk, -1); rb_define_method(cls_db, "iterate", (METHOD)db_iterate, -1); rb_define_method(cls_db, "set", (METHOD)db_set, 2); rb_define_method(cls_db, "add", (METHOD)db_add, 2); rb_define_method(cls_db, "replace", (METHOD)db_replace, 2); rb_define_method(cls_db, "append", (METHOD)db_append, 2); rb_define_method(cls_db, "increment", (METHOD)db_increment, -1); rb_define_method(cls_db, "increment_double", (METHOD)db_increment_double, -1); rb_define_method(cls_db, "cas", (METHOD)db_cas, 3); rb_define_method(cls_db, "remove", (METHOD)db_remove, 1); rb_define_method(cls_db, "get", (METHOD)db_get, 1); rb_define_method(cls_db, "check", (METHOD)db_check, 1); rb_define_method(cls_db, "seize", (METHOD)db_seize, 1); rb_define_method(cls_db, "set_bulk", (METHOD)db_set_bulk, -1); rb_define_method(cls_db, "remove_bulk", (METHOD)db_remove_bulk, -1); rb_define_method(cls_db, "get_bulk", (METHOD)db_get_bulk, -1); rb_define_method(cls_db, "clear", (METHOD)db_clear, 0); rb_define_method(cls_db, "synchronize", (METHOD)db_synchronize, -1); rb_define_method(cls_db, "occupy", (METHOD)db_occupy, -1); rb_define_method(cls_db, "copy", (METHOD)db_copy, 1); rb_define_method(cls_db, "begin_transaction", (METHOD)db_begin_transaction, -1); rb_define_method(cls_db, "end_transaction", (METHOD)db_end_transaction, -1); rb_define_method(cls_db, "transaction", (METHOD)db_transaction, -1); rb_define_method(cls_db, "dump_snapshot", (METHOD)db_dump_snapshot, 1); rb_define_method(cls_db, "load_snapshot", (METHOD)db_load_snapshot, 1); rb_define_method(cls_db, "count", (METHOD)db_count, 0); rb_define_method(cls_db, "size", (METHOD)db_size, 0); rb_define_method(cls_db, "path", (METHOD)db_path, 0); rb_define_method(cls_db, "status", (METHOD)db_status, 0); rb_define_method(cls_db, "match_prefix", (METHOD)db_match_prefix, -1); rb_define_method(cls_db, "match_regex", (METHOD)db_match_regex, -1); rb_define_method(cls_db, "match_similar", (METHOD)db_match_similar, -1); rb_define_method(cls_db, "merge", (METHOD)db_merge, -1); rb_define_method(cls_db, "cursor", (METHOD)db_cursor, 0); rb_define_method(cls_db, "cursor_process", (METHOD)db_cursor_process, 0); rb_define_method(cls_db, "tune_exception_rule", (METHOD)db_tune_exception_rule, 1); rb_define_method(cls_db, "tune_encoding", (METHOD)db_tune_encoding, 1); rb_define_method(cls_db, "to_s", (METHOD)db_to_s, 0); rb_define_method(cls_db, "inspect", (METHOD)db_inspect, 0); rb_define_method(cls_db, "[]", (METHOD)db_get, 1); rb_define_method(cls_db, "[]=", (METHOD)db_set, 2); rb_define_method(cls_db, "store", (METHOD)db_set, 2); rb_define_method(cls_db, "delete", (METHOD)db_remove, 1); rb_define_method(cls_db, "fetch", (METHOD)db_set, 1); rb_define_method(cls_db, "shift", (METHOD)db_shift, 0); rb_define_method(cls_db, "length", (METHOD)db_count, 0); rb_define_method(cls_db, "each", (METHOD)db_each, 0); rb_define_method(cls_db, "each_pair", (METHOD)db_each, 0); rb_define_method(cls_db, "each_key", (METHOD)db_each_key, 0); rb_define_method(cls_db, "each_value", (METHOD)db_each_value, 0); id_db_error = rb_intern("error"); id_db_open = rb_intern("open"); id_db_close = rb_intern("close"); id_db_begin_transaction = rb_intern("begin_transaction"); id_db_end_transaction = rb_intern("end_transaction"); id_db_exbits = rb_intern("@exbits_"); id_db_mutex = rb_intern("@mutex_"); id_db_enc = rb_intern("@enc_"); rb_define_singleton_method(cls_db, "process", (METHOD)db_process, -1); } /** * Implementation of new. */ static VALUE db_new(VALUE cls) { kc::PolyDB* db = new kc::PolyDB(); return Data_Wrap_Struct(cls_db, 0, db_del, db); } /** * Implementation of del. */ static void db_del(void* ptr) { delete (kc::PolyDB*)ptr; } /** * Raise the exception of an error code. */ static void db_raise(VALUE vself) { volatile VALUE vexbits = rb_ivar_get(vself, id_db_exbits); if (vexbits == Qnil) return; uint32_t exbits = NUM2INT(vexbits); kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); kc::PolyDB::Error err = db->error(); uint32_t code = err.code(); if (exbits & (1 << code)) rb_raise(cls_err_children[code], "%u: %s", code, err.message()); } /** * Implementation of initialize. */ static VALUE db_initialize(int argc, VALUE* argv, VALUE vself) { volatile VALUE vopts; rb_scan_args(argc, argv, "01", &vopts); int32_t opts = TYPE(vopts) == T_FIXNUM ? FIX2INT(vopts) : 0; volatile VALUE vexbits = Qnil; if (opts & GEXCEPTIONAL) { uint32_t exbits = 0; exbits |= 1 << kc::PolyDB::Error::NOIMPL; exbits |= 1 << kc::PolyDB::Error::INVALID; exbits |= 1 << kc::PolyDB::Error::NOREPOS; exbits |= 1 << kc::PolyDB::Error::NOPERM; exbits |= 1 << kc::PolyDB::Error::BROKEN; exbits |= 1 << kc::PolyDB::Error::SYSTEM; exbits |= 1 << kc::PolyDB::Error::MISC; vexbits = INT2FIX(exbits); } rb_ivar_set(vself, id_db_exbits, vexbits); volatile VALUE vmutex = (opts & GCONCURRENT) ? Qnil : rb_class_new_instance(0, NULL, cls_mtx); rb_ivar_set(vself, id_db_mutex, vmutex); rb_ivar_set(vself, id_db_enc, Qnil); rb_ivar_set(vself, id_db_enc, Qnil); return Qnil; } /** * Implementation of error. */ static VALUE db_error(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); kc::PolyDB::Error err = db->error(); uint32_t code = err.code(); volatile VALUE args[2]; args[0] = INT2FIX(code); args[1] = rb_str_new_ex2(vself, err.message()); return rb_class_new_instance(2, (VALUE*)args, cls_err_children[code]); } /** * Implementation of open. */ static VALUE db_open(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vpath, vmode; rb_scan_args(argc, argv, "02", &vpath, &vmode); if (vpath == Qnil) vpath = rb_str_new2(":"); vpath = StringValueEx(vpath); const char* path = RSTRING_PTR(vpath); uint32_t mode = vmode == Qnil ? kc::PolyDB::OWRITER | kc::PolyDB::OCREATE : NUM2INT(vmode); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* path, uint32_t mode) : db_(db), path_(path), mode_(mode), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->open(path_, mode_); } kc::PolyDB* db_; const char* path_; uint32_t mode_; bool rv_; } func(db, path, mode); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->open(path, mode); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of close. */ static VALUE db_close(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db) : db_(db), rv_(false) {} bool rv() { return rv_; } private: void operate() { g_curbur.sweap(); rv_ = db_->close(); } kc::PolyDB* db_; bool rv_; } func(db); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); g_curbur.sweap(); rv = db->close(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of accept. */ static VALUE db_accept(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vkey, vvisitor, vwritable; rb_scan_args(argc, argv, "12", &vkey, &vvisitor, &vwritable); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); volatile VALUE vrv; if (vvisitor == Qnil) { bool writable = vwritable != Qfalse; SoftBlockVisitor visitor(vself, writable); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->accept(kbuf, ksiz, &visitor, writable); const char *emsg = visitor.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } else { bool writable = vwritable != Qfalse; SoftVisitor visitor(vself, vvisitor, writable); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->accept(kbuf, ksiz, &visitor, writable); const char *emsg = visitor.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } return vrv; } /** * Implementation of accept_bulk. */ static VALUE db_accept_bulk(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vkeys, vvisitor, vwritable; rb_scan_args(argc, argv, "12", &vkeys, &vvisitor, &vwritable); StringVector keys; if (TYPE(vkeys) == T_ARRAY) { int32_t knum = RARRAY_LEN(vkeys); for (int32_t i = 0; i < knum; i++) { volatile VALUE vkey = rb_ary_entry(vkeys, i); vkey = StringValueEx(vkey); keys.push_back(std::string(RSTRING_PTR(vkey), RSTRING_LEN(vkey))); } } volatile VALUE vrv; if (vvisitor == Qnil) { bool writable = vwritable != Qfalse; SoftBlockVisitor visitor(vself, writable); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->accept_bulk(keys, &visitor, writable); const char *emsg = visitor.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } else { bool writable = vwritable != Qfalse; SoftVisitor visitor(vself, vvisitor, writable); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->accept_bulk(keys, &visitor, writable); const char *emsg = visitor.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } return vrv; } /** * Implementation of iterate. */ static VALUE db_iterate(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vvisitor, vwritable; rb_scan_args(argc, argv, "02", &vvisitor, &vwritable); volatile VALUE vrv; if (vvisitor == Qnil) { bool writable = vwritable != Qfalse; SoftBlockVisitor visitor(vself, writable); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->iterate(&visitor, writable); const char *emsg = visitor.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } else { bool writable = vwritable != Qfalse; SoftVisitor visitor(vself, vvisitor, writable); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->iterate(&visitor, writable); const char *emsg = visitor.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } return vrv; } /** * Implementation of set. */ static VALUE db_set(VALUE vself, VALUE vkey, VALUE vvalue) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); vvalue = StringValueEx(vvalue); const char* vbuf = RSTRING_PTR(vvalue); size_t vsiz = RSTRING_LEN(vvalue); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz) : db_(db), kbuf_(kbuf), ksiz_(ksiz), vbuf_(vbuf), vsiz_(vsiz), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->set(kbuf_, ksiz_, vbuf_, vsiz_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; const char* vbuf_; size_t vsiz_; bool rv_; } func(db, kbuf, ksiz, vbuf, vsiz); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->set(kbuf, ksiz, vbuf, vsiz); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of add. */ static VALUE db_add(VALUE vself, VALUE vkey, VALUE vvalue) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); vvalue = StringValueEx(vvalue); const char* vbuf = RSTRING_PTR(vvalue); size_t vsiz = RSTRING_LEN(vvalue); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz) : db_(db), kbuf_(kbuf), ksiz_(ksiz), vbuf_(vbuf), vsiz_(vsiz), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->add(kbuf_, ksiz_, vbuf_, vsiz_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; const char* vbuf_; size_t vsiz_; bool rv_; } func(db, kbuf, ksiz, vbuf, vsiz); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->add(kbuf, ksiz, vbuf, vsiz); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of replace. */ static VALUE db_replace(VALUE vself, VALUE vkey, VALUE vvalue) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); vvalue = StringValueEx(vvalue); const char* vbuf = RSTRING_PTR(vvalue); size_t vsiz = RSTRING_LEN(vvalue); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz) : db_(db), kbuf_(kbuf), ksiz_(ksiz), vbuf_(vbuf), vsiz_(vsiz), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->replace(kbuf_, ksiz_, vbuf_, vsiz_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; const char* vbuf_; size_t vsiz_; bool rv_; } func(db, kbuf, ksiz, vbuf, vsiz); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->replace(kbuf, ksiz, vbuf, vsiz); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of append. */ static VALUE db_append(VALUE vself, VALUE vkey, VALUE vvalue) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); vvalue = StringValueEx(vvalue); const char* vbuf = RSTRING_PTR(vvalue); size_t vsiz = RSTRING_LEN(vvalue); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz) : db_(db), kbuf_(kbuf), ksiz_(ksiz), vbuf_(vbuf), vsiz_(vsiz), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->append(kbuf_, ksiz_, vbuf_, vsiz_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; const char* vbuf_; size_t vsiz_; bool rv_; } func(db, kbuf, ksiz, vbuf, vsiz); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->append(kbuf, ksiz, vbuf, vsiz); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of increment. */ static VALUE db_increment(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vkey, vnum, vorig; rb_scan_args(argc, argv, "12", &vkey, &vnum, &vorig); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); int64_t num = vnum == Qnil ? 0 : vatoi(vnum); int64_t orig = vorig == Qnil ? 0 : vatoi(vorig); volatile VALUE vrv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz, int64_t num, int64_t orig) : db_(db), kbuf_(kbuf), ksiz_(ksiz), num_(num), orig_(orig) {} int64_t rv() { return num_; } private: void operate() { num_ = db_->increment(kbuf_, ksiz_, num_, orig_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; int64_t num_; int64_t orig_; } func(db, kbuf, ksiz, num, orig); NativeFunction::execute(&func); num = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); num = db->increment(kbuf, ksiz, num, orig); rb_funcall(vmutex, id_mtx_unlock, 0); } if (num == kc::INT64MIN) { vrv = Qnil; db_raise(vself); } else { vrv = LL2NUM(num); } return vrv; } /** * Implementation of increment_double. */ static VALUE db_increment_double(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vkey, vnum, vorig; rb_scan_args(argc, argv, "12", &vkey, &vnum, &vorig); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); double num = vnum == Qnil ? 0.0 : vatof(vnum); double orig = vorig == Qnil ? 0.0 : vatof(vorig); volatile VALUE vrv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz, double num, double orig) : db_(db), kbuf_(kbuf), ksiz_(ksiz), num_(num), orig_(orig) {} double rv() { return num_; } private: void operate() { num_ = db_->increment_double(kbuf_, ksiz_, num_, orig_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; double num_; double orig_; } func(db, kbuf, ksiz, num, orig); NativeFunction::execute(&func); num = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); num = db->increment_double(kbuf, ksiz, num, orig); rb_funcall(vmutex, id_mtx_unlock, 0); } if (kc::chknan(num)) { vrv = Qnil; db_raise(vself); } else { vrv = rb_float_new(num); } return vrv; } /** * Implementation of cas. */ static VALUE db_cas(VALUE vself, VALUE vkey, VALUE voval, VALUE vnval) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); const char* ovbuf = NULL; size_t ovsiz = 0; if (voval != Qnil) { voval = StringValueEx(voval); ovbuf = RSTRING_PTR(voval); ovsiz = RSTRING_LEN(voval); } const char* nvbuf = NULL; size_t nvsiz = 0; if (vnval != Qnil) { vnval = StringValueEx(vnval); nvbuf = RSTRING_PTR(vnval); nvsiz = RSTRING_LEN(vnval); } bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz, const char* ovbuf, size_t ovsiz, const char* nvbuf, size_t nvsiz) : db_(db), kbuf_(kbuf), ksiz_(ksiz), ovbuf_(ovbuf), ovsiz_(ovsiz), nvbuf_(nvbuf), nvsiz_(nvsiz), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->cas(kbuf_, ksiz_, ovbuf_, ovsiz_, nvbuf_, nvsiz_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; const char* ovbuf_; size_t ovsiz_; const char* nvbuf_; size_t nvsiz_; bool rv_; } func(db, kbuf, ksiz, ovbuf, ovsiz, nvbuf, nvsiz); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->cas(kbuf, ksiz, ovbuf, ovsiz, nvbuf, nvsiz); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of remove. */ static VALUE db_remove(VALUE vself, VALUE vkey) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz) : db_(db), kbuf_(kbuf), ksiz_(ksiz), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->remove(kbuf_, ksiz_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; bool rv_; } func(db, kbuf, ksiz); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->remove(kbuf, ksiz); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue;; db_raise(vself); return Qfalse; } /** * Implementation of get. */ static VALUE db_get(VALUE vself, VALUE vkey) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); char* vbuf; size_t vsiz; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz) : db_(db), kbuf_(kbuf), ksiz_(ksiz), vbuf_(NULL), vsiz_(0) {} char* rv(size_t* vsp) { *vsp = vsiz_; return vbuf_; } private: void operate() { vbuf_ = db_->get(kbuf_, ksiz_, &vsiz_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; char* vbuf_; size_t vsiz_; } func(db, kbuf, ksiz); NativeFunction::execute(&func); vbuf = func.rv(&vsiz); } else { rb_funcall(vmutex, id_mtx_lock, 0); vbuf = db->get(kbuf, ksiz, &vsiz); rb_funcall(vmutex, id_mtx_unlock, 0); } volatile VALUE vrv; if (vbuf) { vrv = rb_str_new_ex(vself, vbuf, vsiz); delete[] vbuf; } else { vrv = Qnil; db_raise(vself); } return vrv; } /** * Implementation of check. */ static VALUE db_check(VALUE vself, VALUE vkey) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); int32_t vsiz; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz) : db_(db), kbuf_(kbuf), ksiz_(ksiz), vsiz_(-1) {} int32_t rv() { return vsiz_; } private: void operate() { vsiz_ = db_->check(kbuf_, ksiz_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; int32_t vsiz_; } func(db, kbuf, ksiz); NativeFunction::execute(&func); vsiz = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); vsiz = db->check(kbuf, ksiz); rb_funcall(vmutex, id_mtx_unlock, 0); } if (vsiz < 0) db_raise(vself); return LL2NUM(vsiz); } /** * Implementation of seize. */ static VALUE db_seize(VALUE vself, VALUE vkey) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vkey = StringValueEx(vkey); const char* kbuf = RSTRING_PTR(vkey); size_t ksiz = RSTRING_LEN(vkey); char* vbuf; size_t vsiz; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* kbuf, size_t ksiz) : db_(db), kbuf_(kbuf), ksiz_(ksiz), vbuf_(NULL), vsiz_(0) {} char* rv(size_t* vsp) { *vsp = vsiz_; return vbuf_; } private: void operate() { vbuf_ = db_->seize(kbuf_, ksiz_, &vsiz_); } kc::PolyDB* db_; const char* kbuf_; size_t ksiz_; char* vbuf_; size_t vsiz_; } func(db, kbuf, ksiz); NativeFunction::execute(&func); vbuf = func.rv(&vsiz); } else { rb_funcall(vmutex, id_mtx_lock, 0); vbuf = db->seize(kbuf, ksiz, &vsiz); rb_funcall(vmutex, id_mtx_unlock, 0); } volatile VALUE vrv; if (vbuf) { vrv = rb_str_new_ex(vself, vbuf, vsiz); delete[] vbuf; } else { vrv = Qnil; db_raise(vself); } return vrv; } /** * Implementation of set_bulk. */ static VALUE db_set_bulk(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vrecs, vatomic; rb_scan_args(argc, argv, "11", &vrecs, &vatomic); StringMap recs; if (TYPE(vrecs) == T_HASH) { VALUE vkeys = rb_funcall(vrecs, id_hash_keys, 0); int32_t knum = RARRAY_LEN(vkeys); for (int32_t i = 0; i < knum; i++) { volatile VALUE vkey = rb_ary_entry(vkeys, i); volatile VALUE vvalue = rb_hash_aref(vrecs, vkey); vkey = StringValueEx(vkey); vvalue = StringValueEx(vvalue); recs[std::string(RSTRING_PTR(vkey), RSTRING_LEN(vkey))] = std::string(RSTRING_PTR(vvalue), RSTRING_LEN(vvalue)); } } bool atomic = vatomic != Qfalse; int64_t rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const StringMap* recs, bool atomic) : db_(db), recs_(recs), atomic_(atomic), rv_(0) {} int64_t rv() { return rv_; } private: void operate() { rv_ = db_->set_bulk(*recs_, atomic_); } kc::PolyDB* db_; const StringMap* recs_; bool atomic_; int64_t rv_; } func(db, &recs, atomic); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->set_bulk(recs, atomic); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv < 0) { db_raise(vself); return LL2NUM(-1); } return LL2NUM(rv); } /** * Implementation of remove_bulk. */ static VALUE db_remove_bulk(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vkeys, vatomic; rb_scan_args(argc, argv, "11", &vkeys, &vatomic); StringVector keys; if (TYPE(vkeys) == T_ARRAY) { int32_t knum = RARRAY_LEN(vkeys); for (int32_t i = 0; i < knum; i++) { volatile VALUE vkey = rb_ary_entry(vkeys, i); vkey = StringValueEx(vkey); keys.push_back(std::string(RSTRING_PTR(vkey), RSTRING_LEN(vkey))); } } bool atomic = vatomic != Qfalse; int64_t rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const StringVector* keys, bool atomic) : db_(db), keys_(keys), atomic_(atomic), rv_(0) {} int64_t rv() { return rv_; } private: void operate() { rv_ = db_->remove_bulk(*keys_, atomic_); } kc::PolyDB* db_; const StringVector* keys_; bool atomic_; int64_t rv_; } func(db, &keys, atomic); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->remove_bulk(keys, atomic); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv < 0) { db_raise(vself); return LL2NUM(-1); } return LL2NUM(rv); } /** * Implementation of get_bulk. */ static VALUE db_get_bulk(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vkeys, vatomic; rb_scan_args(argc, argv, "11", &vkeys, &vatomic); StringVector keys; if (TYPE(vkeys) == T_ARRAY) { int32_t knum = RARRAY_LEN(vkeys); for (int32_t i = 0; i < knum; i++) { volatile VALUE vkey = rb_ary_entry(vkeys, i); vkey = StringValueEx(vkey); keys.push_back(std::string(RSTRING_PTR(vkey), RSTRING_LEN(vkey))); } } bool atomic = vatomic != Qfalse; StringMap recs; int64_t rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const StringVector* keys, StringMap* recs, bool atomic) : db_(db), keys_(keys), recs_(recs), atomic_(atomic), rv_(0) {} int64_t rv() { return rv_; } private: void operate() { rv_ = db_->get_bulk(*keys_, recs_, atomic_); } kc::PolyDB* db_; const StringVector* keys_; StringMap* recs_; bool atomic_; int64_t rv_; } func(db, &keys, &recs, atomic); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->get_bulk(keys, &recs, atomic); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv < 0) { db_raise(vself); return Qnil; } return maptovhash(vself, &recs); } /** * Implementation of clear. */ static VALUE db_clear(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db) : db_(db), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->clear(); } kc::PolyDB* db_; bool rv_; } func(db); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->clear(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of synchronize. */ static VALUE db_synchronize(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vhard, vproc; rb_scan_args(argc, argv, "02", &vhard, &vproc); bool hard = vhard != Qnil && vhard != Qfalse; volatile VALUE vrv; if (rb_respond_to(vproc, id_fproc_process)) { SoftFileProcessor proc(vself, vproc); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->synchronize(hard, &proc); const char *emsg = proc.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } else if (rb_block_given_p()) { SoftBlockFileProcessor proc(vself); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->synchronize(hard, &proc); const char *emsg = proc.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } else { bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, bool hard) : db_(db), hard_(hard), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->synchronize(hard_, NULL); } kc::PolyDB* db_; bool hard_; bool rv_; } func(db, hard); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->synchronize(hard, NULL); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } return vrv; } /** * Implementation of occupy. */ static VALUE db_occupy(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vwritable, vproc; rb_scan_args(argc, argv, "02", &vwritable, &vproc); bool writable = vwritable != Qnil && vwritable != Qfalse; volatile VALUE vrv; if (rb_respond_to(vproc, id_fproc_process)) { SoftFileProcessor proc(vself, vproc); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->occupy(writable, &proc); const char *emsg = proc.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } else if (rb_block_given_p()) { SoftBlockFileProcessor proc(vself); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->occupy(writable, &proc); const char *emsg = proc.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } else { bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, bool writable) : db_(db), writable_(writable), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->occupy(writable_, NULL); } kc::PolyDB* db_; bool writable_; bool rv_; } func(db, writable); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->occupy(writable, NULL); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) { vrv = Qtrue; } else { vrv = Qfalse; db_raise(vself); } } return vrv; } /** * Implementation of copy. */ static VALUE db_copy(VALUE vself, VALUE vdest) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vdest = StringValueEx(vdest); const char* dest = RSTRING_PTR(vdest); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* dest) : db_(db), dest_(dest), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->copy(dest_); } kc::PolyDB* db_; const char* dest_; bool rv_; } func(db, dest); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->copy(dest); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of begin_transaction. */ static VALUE db_begin_transaction(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vhard; rb_scan_args(argc, argv, "01", &vhard); bool hard = vhard != Qnil && vhard != Qfalse; bool err = false; while (true) { bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { rv = db->begin_transaction_try(hard); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->begin_transaction_try(hard); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) break; if (db->error() != kc::PolyDB::Error::LOGIC) { err = true; break; } threadyield(); } if (err) { db_raise(vself); return Qfalse; } return Qtrue; } /** * Implementation of end_transaction. */ static VALUE db_end_transaction(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vcommit; rb_scan_args(argc, argv, "01", &vcommit); bool commit = vcommit != Qfalse; bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { rv = db->end_transaction(commit); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->end_transaction(commit); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of transaction. */ static VALUE db_transaction(int argc, VALUE* argv, VALUE vself) { volatile VALUE vhard; rb_scan_args(argc, argv, "01", &vhard); volatile VALUE vrv = rb_funcall(vself, id_db_begin_transaction, 1, vhard); if (vrv == Qnil || vrv == Qfalse) return Qfalse; volatile VALUE vbargs = rb_ary_new3(1, vself); volatile VALUE veargs = rb_ary_new3(2, vself, vbargs); rb_ensure((METHOD)db_transaction_body, vbargs, (METHOD)db_transaction_ensure, veargs); return rb_ary_pop(veargs); } /** * Implementation of transaction_body. */ static VALUE db_transaction_body(VALUE vargs) { volatile VALUE vdb = rb_ary_shift(vargs); rb_ary_push(vargs, rb_yield(vdb)); return Qnil; } /** * Implementation of transaction_ensure. */ static VALUE db_transaction_ensure(VALUE vargs) { volatile VALUE vdb = rb_ary_shift(vargs); volatile VALUE vbargs = rb_ary_shift(vargs); volatile VALUE vrv = rb_ary_shift(vbargs); volatile VALUE vcommit = vrv != Qnil && vrv != Qfalse ? Qtrue : Qfalse; vrv = rb_funcall(vdb, id_db_end_transaction, 1, vcommit); rb_ary_push(vargs, vrv); return Qnil; } /** * Implementation of dump_snapshot. */ static VALUE db_dump_snapshot(VALUE vself, VALUE vdest) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vdest = StringValueEx(vdest); const char* dest = RSTRING_PTR(vdest); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* dest) : db_(db), dest_(dest), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->dump_snapshot(dest_); } kc::PolyDB* db_; const char* dest_; bool rv_; } func(db, dest); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->dump_snapshot(dest); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of load_snapshot. */ static VALUE db_load_snapshot(VALUE vself, VALUE vsrc) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); vsrc = StringValueEx(vsrc); const char* src = RSTRING_PTR(vsrc); bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* src) : db_(db), src_(src), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->load_snapshot(src_); } kc::PolyDB* db_; const char* src_; bool rv_; } func(db, src); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->load_snapshot(src); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of count. */ static VALUE db_count(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); int64_t count; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { count = db->count(); } else { rb_funcall(vmutex, id_mtx_lock, 0); count = db->count(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (count < 0) db_raise(vself); return LL2NUM(count); } /** * Implementation of size. */ static VALUE db_size(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); int64_t size; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { size = db->size(); } else { rb_funcall(vmutex, id_mtx_lock, 0); size = db->size(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (size < 0) db_raise(vself); return LL2NUM(size); } /** * Implementation of path. */ static VALUE db_path(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); std::string path; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { path = db->path(); } else { rb_funcall(vmutex, id_mtx_lock, 0); path = db->path(); rb_funcall(vmutex, id_mtx_unlock, 0); } if (path.size() < 1) { db_raise(vself); return Qnil; } return rb_str_new_ex2(vself, path.c_str()); } /** * Implementation of status. */ static VALUE db_status(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); StringMap status; bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { rv = db->status(&status); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->status(&status); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv) return maptovhash(vself, &status); db_raise(vself); return Qnil; } /** * Implementation of match_prefix. */ static VALUE db_match_prefix(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vprefix, vmax; rb_scan_args(argc, argv, "11", &vprefix, &vmax); vprefix = StringValueEx(vprefix); const char* pbuf = RSTRING_PTR(vprefix); size_t psiz = RSTRING_LEN(vprefix); int64_t max = vmax == Qnil ? -1 : vatoi(vmax); volatile VALUE vrv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); StringVector keys; int64_t rv; if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* pbuf, size_t psiz, StringVector* keys, int64_t max) : db_(db), pbuf_(pbuf), psiz_(psiz), keys_(keys), max_(max), rv_(0) {} int64_t rv() { return rv_; } private: void operate() { rv_ = db_->match_prefix(std::string(pbuf_, psiz_), keys_, max_); } kc::PolyDB* db_; const char* pbuf_; size_t psiz_; StringVector* keys_; int64_t max_; int64_t rv_; } func(db, pbuf, psiz, &keys, max); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->match_prefix(std::string(pbuf, psiz), &keys, max); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv >= 0) { vrv = vectortovarray(vself, &keys); } else { vrv = Qnil; db_raise(vself); } return vrv; } /** * Implementation of match_regex. */ static VALUE db_match_regex(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vregex, vmax; rb_scan_args(argc, argv, "11", &vregex, &vmax); vregex = StringValueEx(vregex); const char* rbuf = RSTRING_PTR(vregex); size_t rsiz = RSTRING_LEN(vregex); int64_t max = vmax == Qnil ? -1 : vatoi(vmax); volatile VALUE vrv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); StringVector keys; int64_t rv; if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* rbuf, size_t rsiz, StringVector* keys, int64_t max) : db_(db), rbuf_(rbuf), rsiz_(rsiz), keys_(keys), max_(max), rv_(0) {} int64_t rv() { return rv_; } private: void operate() { rv_ = db_->match_regex(std::string(rbuf_, rsiz_), keys_, max_); } kc::PolyDB* db_; const char* rbuf_; size_t rsiz_; StringVector* keys_; int64_t max_; int64_t rv_; } func(db, rbuf, rsiz, &keys, max); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->match_regex(std::string(rbuf, rsiz), &keys, max); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv >= 0) { vrv = vectortovarray(vself, &keys); } else { vrv = Qnil; db_raise(vself); } return vrv; } /** * Implementation of match_similar. */ static VALUE db_match_similar(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vorigin, vrange, vutf, vmax; rb_scan_args(argc, argv, "13", &vorigin, &vrange, &vutf, &vmax); vorigin = StringValueEx(vorigin); const char* obuf = RSTRING_PTR(vorigin); size_t osiz = RSTRING_LEN(vorigin); int64_t range = vrange == Qnil ? 1 : vatoi(vrange); bool utf = vutf != Qnil && vutf != Qfalse; int64_t max = vmax == Qnil ? -1 : vatoi(vmax); volatile VALUE vrv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); StringVector keys; int64_t rv; if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, const char* obuf, size_t osiz, int64_t range, bool utf, StringVector* keys, int64_t max) : db_(db), obuf_(obuf), osiz_(osiz), range_(range), utf_(utf), keys_(keys), max_(max), rv_(0) {} int64_t rv() { return rv_; } private: void operate() { rv_ = db_->match_similar(std::string(obuf_, osiz_), range_, utf_, keys_, max_); } kc::PolyDB* db_; const char* obuf_; size_t osiz_; size_t range_; bool utf_; StringVector* keys_; int64_t max_; int64_t rv_; } func(db, obuf, osiz, range, utf, &keys, max); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->match_similar(std::string(obuf, osiz), range, utf, &keys, max); rb_funcall(vmutex, id_mtx_unlock, 0); } if (rv >= 0) { vrv = vectortovarray(vself, &keys); } else { vrv = Qnil; db_raise(vself); } return vrv; } /** * Implementation of merge. */ static VALUE db_merge(int argc, VALUE* argv, VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); volatile VALUE vsrcary, vmode; rb_scan_args(argc, argv, "11", &vsrcary, &vmode); if (TYPE(vsrcary) != T_ARRAY) return Qfalse; uint32_t mode = vmode == Qnil ? kc::PolyDB::MSET : NUM2INT(vmode); int32_t num = RARRAY_LEN(vsrcary); if (num < 1) return Qtrue; kc::BasicDB** srcary = new kc::BasicDB*[num]; size_t srcnum = 0; for (int32_t i = 0; i < num; i++) { volatile VALUE vsrcdb = rb_ary_entry(vsrcary, i); if (rb_obj_is_kind_of(vsrcdb, cls_db)) { kc::PolyDB* srcdb; Data_Get_Struct(vsrcdb, kc::PolyDB, srcdb); srcary[srcnum++] = srcdb; } } bool rv; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db, kc::BasicDB** srcary, size_t srcnum, uint32_t mode) : db_(db), srcary_(srcary), srcnum_(srcnum), mode_(mode), rv_(false) {} bool rv() { return rv_; } private: void operate() { rv_ = db_->merge(srcary_, srcnum_, (kc::PolyDB::MergeMode)mode_); } kc::PolyDB* db_; kc::BasicDB** srcary_; size_t srcnum_; uint32_t mode_; bool rv_; } func(db, srcary, srcnum, mode); NativeFunction::execute(&func); rv = func.rv(); } else { rb_funcall(vmutex, id_mtx_lock, 0); rv = db->merge(srcary, srcnum, (kc::PolyDB::MergeMode)mode); rb_funcall(vmutex, id_mtx_unlock, 0); } delete[] srcary; if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of cursor. */ static VALUE db_cursor(VALUE vself) { return rb_class_new_instance(1, &vself, cls_cur); } /** * Implementation of cursor_process. */ static VALUE db_cursor_process(VALUE vself) { volatile VALUE vcur = rb_class_new_instance(1, &vself, cls_cur); volatile VALUE vbargs = rb_ary_new3(1, vcur); volatile VALUE veargs = rb_ary_new3(1, vcur); rb_ensure((METHOD)db_cursor_process_body, vbargs, (METHOD)db_cursor_process_ensure, veargs); return Qnil; } /** * Implementation of cursor_process_body. */ static VALUE db_cursor_process_body(VALUE vargs) { volatile VALUE vcur = rb_ary_shift(vargs); rb_yield(vcur); return Qnil; } /** * Implementation of cursor_process_ensure. */ static VALUE db_cursor_process_ensure(VALUE vargs) { volatile VALUE vcur = rb_ary_shift(vargs); rb_funcall(vcur, id_cur_disable, 0); return Qnil; } /** * Implementation of tune_exception_rule. */ static VALUE db_tune_exception_rule(VALUE vself, VALUE vcodes) { if (TYPE(vcodes) != T_ARRAY) return Qfalse; uint32_t exbits = 0; int32_t num = RARRAY_LEN(vcodes); for (int32_t i = 0; i < num; i++) { volatile VALUE vcode = rb_ary_entry(vcodes, i); uint32_t code = NUM2INT(vcode); if (code <= kc::PolyDB::Error::MISC) exbits |= 1 << code; } volatile VALUE vexbits = exbits > 0 ? INT2FIX(exbits) : Qnil; rb_ivar_set(vself, id_db_exbits, vexbits); return Qtrue; } /** * Implementation of tune_encoding. */ static VALUE db_tune_encoding(VALUE vself, VALUE venc) { if (cls_enc == Qnil) return Qfalse; if (venc == Qnil) { rb_ivar_set(vself, id_db_enc, Qnil); } else if (rb_obj_is_instance_of(venc, cls_enc)) { rb_ivar_set(vself, id_db_enc, venc); } else { venc = StringValueEx(venc); volatile VALUE args = rb_ary_new3(1, venc); int result = 0; venc = rb_protect(db_tune_encoding_impl, args, &result); if (result) return Qfalse; rb_ivar_set(vself, id_db_enc, venc); } return Qtrue; } /** * Implementation of tune_encoding_impl. */ static VALUE db_tune_encoding_impl(VALUE args) { volatile VALUE venc = rb_ary_shift(args); return rb_funcall(cls_enc, id_enc_find, 1, venc); } /** * Implementation of to_s. */ static VALUE db_to_s(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); std::string str; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { std::string path = db->path(); if (path.size() < 1) path = "(nil)"; kc::strprintf(&str, "%s: %lld: %lld", path.c_str(), (long long)db->count(), (long long)db->size()); } else { rb_funcall(vmutex, id_mtx_lock, 0); std::string path = db->path(); if (path.size() < 1) path = "(nil)"; kc::strprintf(&str, "%s: %lld: %lld", path.c_str(), (long long)db->count(), (long long)db->size()); rb_funcall(vmutex, id_mtx_unlock, 0); } return rb_str_new_ex2(vself, str.c_str()); } /** * Implementation of inspect. */ static VALUE db_inspect(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); std::string str; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { std::string path = db->path(); if (path.size() < 1) path = "(nil)"; kc::strprintf(&str, "#", db, path.c_str(), (long long)db->count(), (long long)db->size()); } else { rb_funcall(vmutex, id_mtx_lock, 0); std::string path = db->path(); if (path.size() < 1) path = "(nil)"; kc::strprintf(&str, "#", db, path.c_str(), (long long)db->count(), (long long)db->size()); rb_funcall(vmutex, id_mtx_unlock, 0); } return rb_str_new_ex2(vself, str.c_str()); } /** * Implementation of shift. */ static VALUE db_shift(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); char* kbuf; const char* vbuf; size_t ksiz, vsiz; volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { class FuncImpl : public NativeFunction { public: explicit FuncImpl(kc::PolyDB* db) : db_(db), kbuf_(NULL), ksiz_(0), vbuf_(NULL), vsiz_(0) {} char* rv(size_t* ksp, const char** vbp, size_t* vsp) { *ksp = ksiz_; *vbp = vbuf_; *vsp = vsiz_; return kbuf_; } private: void operate() { kbuf_ = db_shift_impl(db_, &ksiz_, &vbuf_, &vsiz_); } kc::PolyDB* db_; char* kbuf_; size_t ksiz_; const char* vbuf_; size_t vsiz_; } func(db); NativeFunction::execute(&func); kbuf = func.rv(&ksiz, &vbuf, &vsiz); } else { rb_funcall(vmutex, id_mtx_lock, 0); kbuf = db_shift_impl(db, &ksiz, &vbuf, &vsiz); rb_funcall(vmutex, id_mtx_unlock, 0); } volatile VALUE vrv; if (kbuf) { volatile VALUE vkey = rb_str_new_ex(vself, kbuf, ksiz); volatile VALUE vvalue = rb_str_new_ex(vself, vbuf, vsiz); vrv = rb_ary_new3(2, vkey, vvalue); delete[] kbuf; } else { vrv = Qnil; db_raise(vself); } return vrv; } static char* db_shift_impl(kc::PolyDB* db, size_t* ksp, const char** vbp, size_t* vsp) { kc::PolyDB::Cursor cur(db); if (!cur.jump()) return NULL; class VisitorImpl : public kc::PolyDB::Visitor { public: explicit VisitorImpl() : kbuf_(NULL), ksiz_(0), vbuf_(NULL), vsiz_(0) {} char* rv(size_t* ksp, const char** vbp, size_t* vsp) { *ksp = ksiz_; *vbp = vbuf_; *vsp = vsiz_; return kbuf_; } private: const char* visit_full(const char* kbuf, size_t ksiz, const char* vbuf, size_t vsiz, size_t* sp) { size_t rsiz = ksiz + 1 + vsiz + 1; kbuf_ = new char[rsiz]; std::memcpy(kbuf_, kbuf, ksiz); kbuf_[ksiz] = '\0'; ksiz_ = ksiz; vbuf_ = kbuf_ + ksiz + 1; std::memcpy(vbuf_, vbuf, vsiz); vbuf_[vsiz] = '\0'; vsiz_ = vsiz; return REMOVE; } char* kbuf_; size_t ksiz_; char* vbuf_; size_t vsiz_; } visitor; if (!cur.accept(&visitor, true, false)) return NULL; return visitor.rv(ksp, vbp, vsp); } /** * Implementation of each. */ static VALUE db_each(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); SoftEachVisitor visitor(vself); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->iterate(&visitor, false); const char *emsg = visitor.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of each_key. */ static VALUE db_each_key(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); SoftEachKeyVisitor visitor(vself); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->iterate(&visitor, false); const char *emsg = visitor.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of each_value. */ static VALUE db_each_value(VALUE vself) { kc::PolyDB* db; Data_Get_Struct(vself, kc::PolyDB, db); SoftEachValueVisitor visitor(vself); volatile VALUE vmutex = rb_ivar_get(vself, id_db_mutex); if (vmutex == Qnil) { db->set_error(kc::PolyDB::Error::INVALID, "unsupported method"); db_raise(vself); return Qnil; } rb_funcall(vmutex, id_mtx_lock, 0); bool rv = db->iterate(&visitor, false); const char *emsg = visitor.emsg(); if (emsg) { db->set_error(kc::PolyDB::Error::LOGIC, emsg); rv = false; } rb_funcall(vmutex, id_mtx_unlock, 0); if (rv) return Qtrue; db_raise(vself); return Qfalse; } /** * Implementation of process. */ static VALUE db_process(int argc, VALUE* argv, VALUE vself) { volatile VALUE vpath, vmode, vopts; rb_scan_args(argc, argv, "03", &vpath, &vmode, &vopts); volatile VALUE vdb = rb_class_new_instance(1, (VALUE*)&vopts, cls_db); volatile VALUE vrv = rb_funcall(vdb, id_db_open, 2, vpath, vmode); if (vrv == Qnil || vrv == Qfalse) return rb_funcall(vdb, id_db_error, 0); volatile VALUE vbargs = rb_ary_new3(1, vdb); volatile VALUE veargs = rb_ary_new3(1, vdb); rb_ensure((METHOD)db_process_body, vbargs, (METHOD)db_process_ensure, veargs); return rb_ary_pop(veargs); } /** * Implementation of process_body. */ static VALUE db_process_body(VALUE vargs) { volatile VALUE vdb = rb_ary_shift(vargs); rb_yield(vdb); return Qnil; } /** * Implementation of process_ensure. */ static VALUE db_process_ensure(VALUE vargs) { volatile VALUE vdb = rb_ary_shift(vargs); volatile VALUE vrv = rb_funcall(vdb, id_db_close, 0); if (vrv != Qtrue) rb_ary_push(vargs, rb_funcall(vdb, id_db_error, 0)); return Qnil; } } // END OF FILE kyotocabinet-ruby-1.32/kyotocabinet-doc.rb0000644000175000017500000007563411757456112017726 0ustar mikiomikio#-- # Ruby binding of Kyoto Cabinet # Copyright (C) 2009-2010 FAL Labs # This file is part of Kyoto Cabinet. # This program is free software: you can redistribute it and/or modify it under the terms of # the GNU General Public License as published by the Free Software Foundation, either version # 3 of the License, or any later version. # This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with this program. # If not, see . #++ #:include:overview.rd # Namespace of Kyoto Cabinet. module KyotoCabinet # The version information VERSION = "x.y.z" # Convert any object to a string. # @param obj the object. # @return the result string. def conv_str(obj) # (native code) end # Convert a string to an integer. # @param str the string. # @return the integer. If the string does not contain numeric expression, 0 is returned. def atoi(str) # (native code) end # Convert a string with a metric prefix to an integer. # @param str the string, which can be trailed by a binary metric prefix. "K", "M", "G", "T", "P", and "E" are supported. They are case-insensitive. # @return the integer. If the string does not contain numeric expression, 0 is returned. If the integer overflows the domain, INT64_MAX or INT64_MIN is returned according to the sign. def atoix(str) # (native code) end # Convert a string to a real number. # @param str the string. # @return the real number. If the string does not contain numeric expression, 0.0 is returned. def atof(str) # (native code) end # Get the hash value of a string by MurMur hashing. # @param str the string. # @return the hash value. def hash_murmur(str) # (native code) end # Get the hash value of a string by FNV hashing. # @param str the string. # @return the hash value. def hash_fnv(str) # (native code) end # Calculate the levenshtein distance of two strings. # @param a one string. # @param b the other string. # @param utf flag to treat keys as UTF-8 strings. # @return the levenshtein distance. def levdist(a, b, utf) # (native code) end # # Error data. # class Error < RuntimeError # error code: success SUCCESS = 0 # error code: not implemented NOIMPL = 1 # error code: invalid operation INVALID = 2 # error code: no repository NOREPOS = 3 # error code: no permission NOPERM = 4 # error code: broken file BROKEN = 5 # error code: record duplication DUPREC = 6 # error code: no record NOREC = 7 # error code: logical inconsistency LOGIC = 8 # error code: system error SYSTEM = 9 # error code: miscellaneous error MISC = 15 # Create an error object. # @param code the error code. # @param message the supplement message. # @return the error object. def initialize(code, message) # (native code) end # Set the error information. # @param code the error code. # @param message the supplement message. # @return always nil. def set(code, message) # (native code) end # Get the error code. # @return the error code. def code() # (native code) end # Get the readable string of the code. # @return the readable string of the code. def name() # (native code) end # Get the supplement message. # @return the supplement message. def message() # (native code) end # Get the string expression. # @return the string expression. def to_s() # (native code) end # Get the inspection string. # @return the inspection string. def inspect() # (native code) end # Equality operator. # @param right an error object or an error code. # @return true for the both operands are equal, or false if not. def ==(right) # (native code) end # Negation equality operator. # @param right an error object or an error code. # @return false for the both operands are equal, or true if not. def !=(right) # (native code) end end # # Interface to access a record. # class Visitor # magic data: no operation NOP = "(magic data)" # magic data: remove the record REMOVE = "(magic data)" # Visit a record. # @param key the key. # @param value the value. # @return If it is a string, the value is replaced by the content. If it is Visitor::NOP, nothing is modified. If it is Visitor::REMOVE, the record is removed. def visit_full(key, value) # (native code) end # Visit a empty record space. # @param key the key. # @return If it is a string, the value is replaced by the content. If it is Visitor::NOP or Visitor::REMOVE, nothing is modified. def visit_empty(key) # (native code) end end # # Interface to process the database file. # class FileProcessor # Process the database file. # @param path the path of the database file. # @param count the number of records. # @param size the size of the available region. # @return true on success, or false on failure. def process(path, count, size) # (native code) end end # # Interface of cursor to indicate a record. # class Cursor # Disable the cursor. # @return always nil. # @note This method should be called explicitly when the cursor is no longer in use. def disable() # (native code) end # Accept a visitor to the current record. # @param visitor a visitor object which implements the Visitor interface. If it is omitted, the block parameter is evaluated. # @param writable true for writable operation, or false for read-only operation. # @param step true to move the cursor to the next record, or false for no move. # @block If it is specified, the block is called as the visitor. # @return true on success, or false on failure. # @note The operation for each record is performed atomically and other threads accessing the same record are blocked. To avoid deadlock, any explicit database operation must not be performed in this method. def accept(visitor, writable = true, step = false) # (native code) end # Set the value of the current record. # @param value the value. # @param step true to move the cursor to the next record, or false for no move. # @return true on success, or false on failure. def set_value(value, step = false) # (native code) end # Remove the current record. # @return true on success, or false on failure. # @note If no record corresponds to the key, false is returned. The cursor is moved to the next record implicitly. def remove() # (native code) end # Get the key of the current record. # @param step true to move the cursor to the next record, or false for no move. # @return the key of the current record, or nil on failure. # @note If the cursor is invalidated, nil is returned. def get_key(step = false) # (native code) end # Get the value of the current record. # @param step true to move the cursor to the next record, or false for no move. # @return the value of the current record, or nil on failure. # @note If the cursor is invalidated, nil is returned. def get_value(step = false) # (native code) end # Get a pair of the key and the value of the current record. # @param step true to move the cursor to the next record, or false for no move. # @return a pair of the key and the value of the current record, or nil on failure. # @note If the cursor is invalidated, nil is returned. def get(step = false) # (native code) end # Get a pair of the key and the value of the current record and remove it atomically. # @return a pair of the key and the value of the current record, or nil on failure. # @note If the cursor is invalidated, nil is returned. The cursor is moved to the next record implicitly. def seize() # (native code) end # Jump the cursor to a record for forward scan. # @param key the key of the destination record. If it is nil, the destination is the first record. # @return true on success, or false on failure. def jump(key = nil) # (native code) end # Jump the cursor to a record for backward scan. # @param key the key of the destination record. If it is nil, the destination is the last record. # @return true on success, or false on failure. # @note This method is dedicated to tree databases. Some database types, especially hash databases, will provide a dummy implementation. def jump_back(key = nil) # (native code) end # Step the cursor to the next record. # @return true on success, or false on failure. def step() # (native code) end # Step the cursor to the previous record. # @return true on success, or false on failure. # @note This method is dedicated to tree databases. Some database types, especially hash databases, may provide a dummy implementation. def step_back() # (native code) end # Get the database object. # @return the database object. def db() # (native code) end # Get the last happened error. # @return the last happened error. def error() # (native code) end # Get the string expression. # @return the string expression. def to_s() # (native code) end # Get the inspection string. # @return the inspection string. def inspect() # (native code) end end # # Interface of database abstraction. # class DB # generic mode: exceptional mode GEXCEPTIONAL = 1 << 0 # generic mode: concurrent mode GCONCURRENT = 1 << 1 # open mode: open as a reader OREADER = 1 << 0 # open mode: open as a writer OWRITER = 1 << 1 # open mode: writer creating OCREATE = 1 << 2 # open mode: writer truncating OTRUNCATE = 1 << 3 # open mode: auto transaction OAUTOTRAN = 1 << 4 # open mode: auto synchronization OAUTOSYNC = 1 << 5 # open mode: open without locking ONOLOCK = 1 << 6 # open mode: lock without blocking OTRYLOCK = 1 << 7 # open mode: open without auto repair ONOREPAIR = 1 << 8 # merge mode: overwrite the existing value MSET = 0 # merge mode: keep the existing value MADD = 1 # merge mode: modify the existing record only MREPLACE = 2 # merge mode: append the new value MAPPEND = 3 # Create a database object. # @param opts the optional features by bitwise-or: DB::GEXCEPTIONAL for the exceptional mode, DB::GCONCURRENT for the concurrent mode. # @return the database object. # @note The exceptional mode means that fatal errors caused by methods are reported by exceptions raised. The concurrent mode means that database operations by multiple threads are performed concurrently without the giant VM lock. However, it has a side effect that such methods with call back of Ruby code as DB#accept, DB#accept_bulk, DB#iterate, DB#each, DB#each_key, DB#each_value, Cursor#accept are disabled. def initialize(opts = 0) # (native code) end # Get the last happened error. # @return the last happened error. def error() # (native code) end # Open a database file. # @param path the path of a database file. If it is "-", the database will be a prototype hash database. If it is "+", the database will be a prototype tree database. If it is ":", the database will be a stash database. If it is "*", the database will be a cache hash database. If it is "%", the database will be a cache tree database. If its suffix is ".kch", the database will be a file hash database. If its suffix is ".kct", the database will be a file tree database. If its suffix is ".kcd", the database will be a directory hash database. If its suffix is ".kcf", the database will be a directory tree database. If its suffix is ".kcx", the database will be a plain text database. Otherwise, this function fails. Tuning parameters can trail the name, separated by "#". Each parameter is composed of the name and the value, separated by "=". If the "type" parameter is specified, the database type is determined by the value in "-", "+", ":", "*", "%", "kch", "kct", "kcd", kcf", and "kcx". All database types support the logging parameters of "log", "logkinds", and "logpx". The prototype hash database and the prototype tree database do not support any other tuning parameter. The stash database supports "bnum". The cache hash database supports "opts", "bnum", "zcomp", "capcnt", "capsiz", and "zkey". The cache tree database supports all parameters of the cache hash database except for capacity limitation, and supports "psiz", "rcomp", "pccap" in addition. The file hash database supports "apow", "fpow", "opts", "bnum", "msiz", "dfunit", "zcomp", and "zkey". The file tree database supports all parameters of the file hash database and "psiz", "rcomp", "pccap" in addition. The directory hash database supports "opts", "zcomp", and "zkey". The directory tree database supports all parameters of the directory hash database and "psiz", "rcomp", "pccap" in addition. The plain text database does not support any other tuning parameter. # @param mode the connection mode. DB::OWRITER as a writer, DB::OREADER as a reader. The following may be added to the writer mode by bitwise-or: DB::OCREATE, which means it creates a new database if the file does not exist, DB::OTRUNCATE, which means it creates a new database regardless if the file exists, DB::OAUTOTRAN, which means each updating operation is performed in implicit transaction, DB::OAUTOSYNC, which means each updating operation is followed by implicit synchronization with the file system. The following may be added to both of the reader mode and the writer mode by bitwise-or: DB::ONOLOCK, which means it opens the database file without file locking, DB::OTRYLOCK, which means locking is performed without blocking, DB::ONOREPAIR, which means the database file is not repaired implicitly even if file destruction is detected. # @return true on success, or false on failure. # @note The tuning parameter "log" is for the original "tune_logger" and the value specifies the path of the log file, or "-" for the standard output, or "+" for the standard error. "logkinds" specifies kinds of logged messages and the value can be "debug", "info", "warn", or "error". "logpx" specifies the prefix of each log message. "opts" is for "tune_options" and the value can contain "s" for the small option, "l" for the linear option, and "c" for the compress option. "bnum" corresponds to "tune_bucket". "zcomp" is for "tune_compressor" and the value can be "zlib" for the ZLIB raw compressor, "def" for the ZLIB deflate compressor, "gz" for the ZLIB gzip compressor, "lzo" for the LZO compressor, "lzma" for the LZMA compressor, or "arc" for the Arcfour cipher. "zkey" specifies the cipher key of the compressor. "capcnt" is for "cap_count". "capsiz" is for "cap_size". "psiz" is for "tune_page". "rcomp" is for "tune_comparator" and the value can be "lex" for the lexical comparator, "dec" for the decimal comparator, "lexdesc" for the lexical descending comparator, or "decdesc" for the decimal descending comparator. "pccap" is for "tune_page_cache". "apow" is for "tune_alignment". "fpow" is for "tune_fbp". "msiz" is for "tune_map". "dfunit" is for "tune_defrag". Every opened database must be closed by the PolyDB::close method when it is no longer in use. It is not allowed for two or more database objects in the same process to keep their connections to the same database file at the same time. def open(path = ":", mode = DB::OWRITER | DB::OCREATE) # (native code) end # Close the database file. # @return true on success, or false on failure. def close() # (native code) end # Accept a visitor to a record. # @param key the key. # @param visitor a visitor object which implements the Visitor interface. If it is omitted, the block parameter is evaluated. # @param writable true for writable operation, or false for read-only operation. # @block If it is specified, the block is called as the visitor. # @return true on success, or false on failure. # @note The operation for each record is performed atomically and other threads accessing the same record are blocked. To avoid deadlock, any explicit database operation must not be performed in this method. def accept(key, visitor = nil, writable = true) # (native code) end # Accept a visitor to multiple records at once. # @param keys specifies an array of the keys. # @param visitor a visitor object which implements the Visitor interface, or a function object which receives the key and the value. # @param writable true for writable operation, or false for read-only operation. # @return true on success, or false on failure. # @note The operations for specified records are performed atomically and other threads accessing the same records are blocked. To avoid deadlock, any explicit database operation must not be performed in this method. def accept_bulk(keys, visitor = nil, writable = true) # (native code) end # Iterate to accept a visitor for each record. # @param visitor a visitor object which implements the Visitor interface. If it is omitted, the block parameter is evaluated. # @param writable true for writable operation, or false for read-only operation. # @block If it is specified, the block is called as the visitor. # @return true on success, or false on failure. # @note The whole iteration is performed atomically and other threads are blocked. To avoid deadlock, any explicit database operation must not be performed in this method. def iterate(visitor, writable = true) # (native code) end # Set the value of a record. # @param key the key. # @param value the value. # @return true on success, or false on failure. # @note If no record corresponds to the key, a new record is created. If the corresponding record exists, the value is overwritten. def set(key, value) # (native code) end # Add a record. # @param key the key. # @param value the value. # @return true on success, or false on failure. # @note If no record corresponds to the key, a new record is created. If the corresponding record exists, the record is not modified and false is returned. def add(key, value) # (native code) end # Replace the value of a record. # @param key the key. # @param value the value. # @return true on success, or false on failure. # @note If no record corresponds to the key, no new record is created and false is returned. If the corresponding record exists, the value is modified. def replace(key, value) # (native code) end # Append the value of a record. # @param key the key. # @param value the value. # @return true on success, or false on failure. # @note If no record corresponds to the key, a new record is created. If the corresponding record exists, the given value is appended at the end of the existing value. def append(key, value) # (native code) end # Add a number to the numeric integer value of a record. # @param key the key. # @param num the additional number. # @param orig the origin number if no record corresponds to the key. If it is negative infinity and no record corresponds, this method fails. If it is positive infinity, the value is set as the additional number regardless of the current value. # @return the result value, or nil on failure. # @note The value is serialized as an 8-byte binary integer in big-endian order, not a decimal string. If existing value is not 8-byte, this method fails. def increment(key, num = 0, orig = 0) # (native code) end # Add a number to the numeric double value of a record. # @param key the key. # @param num the additional number. # @param orig the origin number if no record corresponds to the key. If it is negative infinity and no record corresponds, this method fails. If it is positive infinity, the value is set as the additional number regardless of the current value. # @return the result value, or nil on failure. # @note The value is serialized as an 16-byte binary fixed-point number in big-endian order, not a decimal string. If existing value is not 16-byte, this method fails. def increment_double(key, num = 0, orig = 0) # (native code) end # Perform compare-and-swap. # @param key the key. # @param oval the old value. nil means that no record corresponds. # @param nval the new value. nil means that the record is removed. # @return true on success, or false on failure. def cas(key, oval, nval) # (native code) end # Remove a record. # @param key the key. # @return true on success, or false on failure. # @note If no record corresponds to the key, false is returned. def remove(key) # (native code) end # Retrieve the value of a record. # @param key the key. # @return the value of the corresponding record, or nil on failure. def get(key) # (native code) end # Check the existence of a record. # @param key the key. # @return the size of the value, or -1 on failure. def check(key) # (native code) end # Retrieve the value of a record and remove it atomically. # @param key the key. # @return the value of the corresponding record, or nil on failure. def seize(key) # (native code) end # Store records at once. # @param recs a hash of the records to store. # @param atomic true to perform all operations atomically, or false for non-atomic operations. # @return the number of stored records, or -1 on failure. def set_bulk(recs, atomic = true) # (native code) end # Remove records at once. # @param keys an array of the keys of the records to remove. # @param atomic true to perform all operations atomically, or false for non-atomic operations. # @return the number of removed records, or -1 on failure. def remove_bulk(keys, atomic = true) # (native code) end # Retrieve records at once. # @param keys an array of the keys of the records to retrieve. # @param atomic true to perform all operations atomically, or false for non-atomic operations. # @return a hash of retrieved records, or nil on failure. def get_bulk(keys, atomic = true) # (native code) end # Remove all records. # @return true on success, or false on failure. def clear() # (native code) end # Synchronize updated contents with the file and the device. # @param hard true for physical synchronization with the device, or false for logical synchronization with the file system. # @param proc a postprocessor object which implements the FileProcessor interface. If it is nil, no postprocessing is performed. # @block If it is specified, the block is called for postprocessing. # @return true on success, or false on failure. # @note The operation of the processor is performed atomically and other threads accessing the same record are blocked. To avoid deadlock, any explicit database operation must not be performed in this method. def synchronize(hard = false, proc = nil) # (native code) end # Occupy database by locking and do something meanwhile. # @param writable true to use writer lock, or false to use reader lock. # @param proc a processor object which implements the FileProcessor interface. If it is nil, no processing is performed. # @return true on success, or false on failure. # @note The operation of the processor is performed atomically and other threads accessing the same record are blocked. To avoid deadlock, any explicit database operation must not be performed in this method. def occupy(writable = false, proc = nil) # (native code) end # Create a copy of the database file. # @param dest the path of the destination file. # @return true on success, or false on failure. def copy(dest) # (native code) end # Begin transaction. # @param hard true for physical synchronization with the device, or false for logical synchronization with the file system. # @return true on success, or false on failure. def begin_transaction(hard = false) # (native code) end # End transaction. # @param commit true to commit the transaction, or false to abort the transaction. # @return true on success, or false on failure. def end_transaction(commit = true) # (native code) end # Perform entire transaction by the block parameter. # @param hard true for physical synchronization with the device, or false for logical synchronization with the file system. # @block a block including operations during transaction. If the block returns true, the transaction is committed. If the block returns false or an exception is thrown, the transaction is aborted. # @return true on success, or false on failure. def transaction(hard = false) # (native code) end # Dump records into a snapshot file. # @param dest the name of the destination file. # @return true on success, or false on failure. def dump_snapshot(dest) # (native code) end # Load records from a snapshot file. # @param src the name of the source file. # @return true on success, or false on failure. def load_snapshot(src) # (native code) end # Get the number of records. # @return the number of records, or -1 on failure. def count() # (native code) end # Get the size of the database file. # @return the size of the database file in bytes, or -1 on failure. def size() # (native code) end # Get the path of the database file. # @return the path of the database file, or nil on failure. def path() # (native code) end # Get the miscellaneous status information. # @return a hash of the status information, or nil on failure. def status() # (native code) end # Get keys matching a prefix string. # @param prefix the prefix string. # @param max the maximum number to retrieve. If it is negative, no limit is specified. # @return an array of matching keys, or nil on failure. def match_prefix(prefix, max = -1) # (native code) end # Get keys matching a regular expression string. # @param regex the regular expression string. # @param max the maximum number to retrieve. If it is negative, no limit is specified. # @return an array of matching keys, or nil on failure. def match_regex(regex, max = -1) # (native code) end # Get keys similar to a string in terms of the levenshtein distance. # @param origin the origin string. # @param range the maximum distance of keys to adopt. # @param utf flag to treat keys as UTF-8 strings. # @param max the maximum number to retrieve. If it is negative, no limit is specified. # @return an array of matching keys, or nil on failure. def match_similar(origin, range = 1, utf = false, max = -1) # (native code) end # Merge records from other databases. # @param srcary an array of the source detabase objects. # @param mode the merge mode. DB::MSET to overwrite the existing value, DB::MADD to keep the existing value, DB::MAPPEND to append the new value. # @return true on success, or false on failure. def merge(srcary, mode = DB::MSET) # (native code) end # Create a cursor object. # @return the return value is the created cursor object. Each cursor should be disabled with the Cursor#disable method when it is no longer in use. def cursor() # (native code) end # Process a cursor by the block parameter. # @block a block including operations for the cursor. The cursor is disabled implicitly after the block. # @return always nil. def cursor_process() # (native code) end # Set the rule about throwing exception. # @param codes an array of error codes. If each method occurs an error corresponding to one of the specified codes, the error is thrown as an exception. # @return true on success, or false on failure. def tune_exception_rule(codes) # (native code) end # Set the encoding of external strings. # @param enc the name of the encoding or its encoding object. # @note The default encoding of external strings is Encoding::ASCII_8BIT. # @return true on success, or false on failure. def tune_encoding(enc) # (native code) end # Get the string expression. # @return the string expression. def to_s() # (native code) end # Get the inspection string. # @return the inspection string. def inspect() # (native code) end # An alias of DB#get. def [](key) # (native code) end # An alias of DB#store. def []=(key, value) # (native code) end # An alias of DB#store. def store(key, value) # (native code) end # An alias of DB#remove. def delete(key, value) # (native code) end # An alias of DB#get. def fetch(key, value) # (native code) end # Remove the first record. # @return a pair of the key and the value of the removed record, or nil on failure. def shift() # (native code) end # An alias of DB#count. def length() # (native code) end # Process each records with a iterator block. # @block the iterator to receive the key and the value of each record. # @return true on success, or false on failure. def each() # (native code) end # Process the key of each record with a iterator block. # @block the iterator to receive the key of each record. # @return true on success, or false on failure. def each_key() # (native code) end # Process the value of each record with a iterator block. # @block the iterator to receive the value of each record. # @return true on success, or false on failure. def each_value() # (native code) end # Process a database by the block parameter. # @param path the same to the one of the open method. # @param mode the same to the one of the open method. # @param opts the optional features by bitwise-or: DB::GCONCURRENT for the concurrent mode. # @block a block including operations for the database. The block receives the database object. The database is opened with the given parameters before the block and is closed implicitly after the block. # @return nil on success, or an error object on failure. def DB.process(path = "*", mode = DB::OWRITER | DB::OCREATE, opts = 0) # (native code) end end end kyotocabinet-ruby-1.32/makedoc.rb0000755000175000017500000000233011750224350016043 0ustar mikiomikio#! /usr/bin/ruby system("rm -rf doc") File::open("kyotocabinet-doc.rb") { |ifile| File::open("kyotocabinet.rb", "w") { |ofile| ifile.each { |line| line = line.chomp line = line.sub(/# +@param +(\w+) +/, '# - @param \\1 ') line = line.sub(/# +@(\w+) +/, '# - @\\1 ') ofile.printf("%s\n", line) } } } system('rdoc --title "Kyoto Cabinet" --main kyotocabinet.rb -o doc kyotocabinet.rb') IO::popen("find doc") { |list| list.each { |path| path = path.chomp if path =~ /\.html$/ File::open(path) { |ifile| tmppath = path + ".tmp" File::open(tmppath, "w") { |ofile| ifile.each { |line| line = line.chomp next if line =~ /\[Validate\]<\/a>/ ofile.printf("%s\n", line) } } File::unlink(path) File::rename(tmppath, path) } end } } File::open("doc/rdoc.css", "a") { |file| file.printf("\n") file.printf("pre { background: none #ddddee; border: solid 1px #dddddd; }\n") file.printf(".method-description ul { margin: 0ex 0ex 1ex 2ex; padding: 0ex; }\n") file.printf(".method-description ul li { list-style-type: none; }\n") } system("rm -f kyotocabinet.rb") kyotocabinet-ruby-1.32/overview.rd0000644000175000017500000001453711420710300016306 0ustar mikiomikio= Ruby Binding of Kyoto Cabinet Kyoto Cabinet: a straightforward implementation of DBM == Introduction Kyoto Cabinet is a library of routines for managing a database. The database is a simple data file containing records, each is a pair of a key and a value. Every key and value is serial bytes with variable length. Both binary data and character string can be used as a key and a value. Each key must be unique within a database. There is neither concept of data tables nor data types. Records are organized in hash table or B+ tree. The following access methods are provided to the database: storing a record with a key and a value, deleting a record by a key, retrieving a record by a key. Moreover, traversal access to every key are provided. These access methods are similar to ones of the original DBM (and its followers: NDBM and GDBM) library defined in the UNIX standard. Kyoto Cabinet is an alternative for the DBM because of its higher performance. Each operation of the hash database has the time complexity of "O(1)". Therefore, in theory, the performance is constant regardless of the scale of the database. In practice, the performance is determined by the speed of the main memory or the storage device. If the size of the database is less than the capacity of the main memory, the performance will seem on-memory speed, which is faster than std::map of STL. Of course, the database size can be greater than the capacity of the main memory and the upper limit is 8 exabytes. Even in that case, each operation needs only one or two seeking of the storage device. Each operation of the B+ tree database has the time complexity of "O(log N)". Therefore, in theory, the performance is logarithmic to the scale of the database. Although the performance of random access of the B+ tree database is slower than that of the hash database, the B+ tree database supports sequential access in order of the keys, which realizes forward matching search for strings and range search for integers. The performance of sequential access is much faster than that of random access. This library wraps the polymorphic database of the C++ API. So, you can select the internal data structure by specifying the database name in runtime. This library is thread-safe on Ruby 1.9.x (YARV) though it is not thread-safe on Ruby 1.8.x. == Installation Install the latest version of Kyoto Cabinet beforehand and get the package of the Ruby binding of Kyoto Cabinet. Enter the directory of the extracted package then perform installation. ruby extconf.rb make ruby test.rb su make install The package `kyotocabinet' should be loaded in each source file of application programs. require 'kyotocabinet' All symbols of Kyoto Cabinet are defined in the module `KyotoCabinet'. You can access them without any prefix by including the module. include KyotoCabinet An instance of the class `DB' is used in order to handle a database. You can store, delete, and retrieve records with the instance. == Example The following code is a typical example to use a database. require 'kyotocabinet' include KyotoCabinet # create the database object db = DB::new # open the database unless db.open('casket.kch', DB::OWRITER | DB::OCREATE) STDERR.printf("open error: %s\n", db.error) end # store records unless db.set('foo', 'hop') and db.set('bar', 'step') and db.set('baz', 'jump') STDERR.printf("set error: %s\n", db.error) end # retrieve records value = db.get('foo') if value printf("%s\n", value) else STDERR.printf("get error: %s\n", db.error) end # traverse records cur = db.cursor cur.jump while rec = cur.get(true) printf("%s:%s\n", rec[0], rec[1]) end cur.disable # close the database unless db.close STDERR.printf("close error: %s\n", db.error) end The following code is a more complex example, which uses the Visitor pattern. require 'kyotocabinet' include KyotoCabinet # create the database object db = DB::new # open the database unless db.open('casket.kch', DB::OREADER) STDERR.printf("open error: %s\n", db.error) end # define the visitor class VisitorImpl < Visitor # call back function for an existing record def visit_full(key, value) printf("%s:%s\n", key, value) return NOP end # call back function for an empty record space def visit_empty(key) STDERR.printf("%s is missing\n", key) return NOP end end visitor = VisitorImpl::new # retrieve a record with visitor unless db.accept("foo", visitor, false) and db.accept("dummy", visitor, false) STDERR.printf("accept error: %s\n", db.error) end # traverse records with visitor unless db.iterate(visitor, false) STDERR.printf("iterate error: %s\n", db.error) end # close the database unless db.close STDERR.printf("close error: %s\n", db.error) end The following code is also a complex example, which is suited to the Ruby style. require 'kyotocabinet' include KyotoCabinet # process the database by iterator DB::process('casket.kch') { |db| # set the encoding of external strings db.set_encoding('utf-8') # store records db['foo'] = 'hop'; # string is fundamental db[:bar] = 'step'; # symbol is also ok db[3] = 'jump'; # number is also ok # retrieve a record value printf("%s\n", db['foo']) # update records in transaction db.transaction { db['foo'] = 2.71828 true } # multiply a record value db.accept('foo') { |key, value| value.to_f * 2 } # traverse records by iterator db.each { |key, value| printf("%s:%s\n", key, value) } # upcase values by iterator db.iterate { |key, value| value.upcase } # traverse records by cursor db.cursor_process { |cur| cur.jump while cur.accept { |key, value| printf("%s:%s\n", key, value) Visitor::NOP } cur.step end } } == License Copyright (C) 2009-2010 FAL Labs All rights reserved. Kyoto Cabinet is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Kyoto Cabinet is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. kyotocabinet-ruby-1.32/doc/0000755000175000017500000000000011757456735014704 5ustar mikiomikiokyotocabinet-ruby-1.32/doc/rdoc.css0000644000175000017500000003306211757456735016351 0ustar mikiomikio/* * "Darkfish" Rdoc CSS * $Id: rdoc.css 54 2009-01-27 01:09:48Z deveiant $ * * Author: Michael Granger * */ /* Base Green is: #6C8C22 */ *{ padding: 0; margin: 0; } body { background: #efefef; font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; } body.class, body.module, body.file { margin-left: 40px; } body.file-popup { font-size: 90%; margin-left: 0; } h1 { font-size: 300%; text-shadow: rgba(135,145,135,0.65) 2px 2px 3px; color: #6C8C22; } h2,h3,h4 { margin-top: 1.5em; } :link, :visited { color: #6C8C22; text-decoration: none; } :link:hover, :visited:hover { border-bottom: 1px dotted #6C8C22; } pre { background: #ddd; padding: 0.5em 0; } /* @group Generic Classes */ .initially-hidden { display: none; } .quicksearch-field { width: 98%; background: #ddd; border: 1px solid #aaa; height: 1.5em; -webkit-border-radius: 4px; } .quicksearch-field:focus { background: #f1edba; } .missing-docs { font-size: 120%; background: white url(images/wrench_orange.png) no-repeat 4px center; color: #ccc; line-height: 2em; border: 1px solid #d00; opacity: 1; padding-left: 20px; text-indent: 24px; letter-spacing: 3px; font-weight: bold; -webkit-border-radius: 5px; -moz-border-radius: 5px; } .target-section { border: 2px solid #dcce90; border-left-width: 8px; padding: 0 1em; background: #fff3c2; } /* @end */ /* @group Index Page, Standalone file pages */ body.indexpage { margin: 1em 3em; } body.indexpage p, body.indexpage div, body.file p { margin: 1em 0; } .indexpage .rdoc-list p, .file .rdoc-list p { margin: 0em 0; } .indexpage ol, .file #documentation ol { line-height: 160%; } .indexpage ul, .file #documentation ul { line-height: 160%; list-style: none; } .indexpage ul :link, .indexpage ul :visited { font-size: 16px; } .indexpage li, .file #documentation li { padding-left: 20px; } .indexpage ol, .file #documentation ol { margin-left: 20px; } .indexpage ol > li, .file #documentation ol > li { padding-left: 0; } .indexpage ul > li, .file #documentation ul > li { background: url(images/bullet_black.png) no-repeat left 4px; } .indexpage li.module { background: url(images/package.png) no-repeat left 4px; } .indexpage li.class { background: url(images/ruby.png) no-repeat left 4px; } .indexpage li.file { background: url(images/page_white_text.png) no-repeat left 4px; } .file li p, .indexpage li p { margin: 0 0; } /* @end */ /* @group Top-Level Structure */ .class #metadata, .file #metadata, .module #metadata { float: left; width: 260px; } .class #documentation, .file #documentation, .module #documentation { margin: 2em 1em 5em 300px; min-width: 340px; } .file #metadata { margin: 0.8em; } #validator-badges { clear: both; margin: 1em 1em 2em; } /* @end */ /* @group Metadata Section */ #metadata .section { background-color: #dedede; -moz-border-radius: 5px; -webkit-border-radius: 5px; border: 1px solid #aaa; margin: 0 8px 16px; font-size: 90%; overflow: hidden; } #metadata h3.section-header { margin: 0; padding: 2px 8px; background: #ccc; color: #666; -moz-border-radius-topleft: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-bottom: 1px solid #aaa; } #metadata #home-section h3.section-header { border-bottom: 0; } #metadata ul, #metadata dl, #metadata p { padding: 8px; list-style: none; } #file-metadata ul { padding-left: 28px; list-style-image: url(images/page_green.png); } dl.svninfo { color: #666; margin: 0; } dl.svninfo dt { font-weight: bold; } ul.link-list li { white-space: nowrap; } ul.link-list .type { font-size: 8px; text-transform: uppercase; color: white; background: #969696; padding: 2px 4px; -webkit-border-radius: 5px; } /* @end */ /* @group Project Metadata Section */ #project-metadata { margin-top: 3em; } .file #project-metadata { margin-top: 0em; } #project-metadata .section { border: 1px solid #aaa; } #project-metadata h3.section-header { border-bottom: 1px solid #aaa; position: relative; } #project-metadata h3.section-header .search-toggle { position: absolute; right: 5px; } #project-metadata form { color: #777; background: #ccc; padding: 8px 8px 16px; border-bottom: 1px solid #bbb; } #project-metadata fieldset { border: 0; } #no-class-search-results { margin: 0 auto 1em; text-align: center; font-size: 14px; font-weight: bold; color: #aaa; } /* @end */ /* @group Documentation Section */ .description { font-size: 100%; color: #333; } .description p { margin: 1em 0.4em; } .description li p { margin: 0; } .description ul { margin-left: 1.5em; } .description ul li { line-height: 1.4em; } .description dl, #documentation dl { margin: 8px 1.5em; border: 1px solid #ccc; } .description dl { font-size: 14px; } .description dt, #documentation dt { padding: 2px 4px; font-weight: bold; background: #ddd; } .description dd, #documentation dd { padding: 2px 12px; } .description dd + dt, #documentation dd + dt { margin-top: 0.7em; } #documentation .section { font-size: 90%; } #documentation h2.section-header { margin-top: 2em; padding: 0.75em 0.5em; background: #ccc; color: #333; font-size: 175%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #documentation h3.section-header { margin-top: 2em; padding: 0.25em 0.5em; background-color: #dedede; color: #333; font-size: 150%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } #constants-list > dl, #attributes-list > dl { margin: 1em 0 2em; border: 0; } #constants-list > dl dt, #attributes-list > dl dt { padding-left: 0; font-weight: bold; font-family: Monaco, "Andale Mono"; background: inherit; } #constants-list > dl dt a, #attributes-list > dl dt a { color: inherit; } #constants-list > dl dd, #attributes-list > dl dd { margin: 0 0 1em 0; padding: 0; color: #666; } .documentation-section h2 { position: relative; } .documentation-section h2 a { position: absolute; top: 8px; right: 10px; font-size: 12px; color: #9b9877; visibility: hidden; } .documentation-section h2:hover a { visibility: visible; } /* @group Method Details */ #documentation .method-source-code { display: none; } #documentation .method-detail { margin: 0.5em 0; padding: 0.5em 0; cursor: pointer; } #documentation .method-detail:hover { background-color: #f1edba; } #documentation .method-heading { position: relative; padding: 2px 4px 0 20px; font-size: 125%; font-weight: bold; color: #333; background: url(images/brick.png) no-repeat left bottom; } #documentation .method-heading :link, #documentation .method-heading :visited { color: inherit; } #documentation .method-click-advice { position: absolute; top: 2px; right: 5px; font-size: 10px; color: #9b9877; visibility: hidden; padding-right: 20px; line-height: 20px; background: url(images/zoom.png) no-repeat right top; } #documentation .method-detail:hover .method-click-advice { visibility: visible; } #documentation .method-alias .method-heading { color: #666; background: url(images/brick_link.png) no-repeat left bottom; } #documentation .method-description, #documentation .aliases { margin: 0 20px; color: #666; } #documentation .method-description p, #documentation .aliases p { line-height: 1.2em; } #documentation .aliases { padding-top: 4px; font-style: italic; cursor: default; } #documentation .method-description p { padding: 0; } #documentation .method-description p + p { margin-bottom: 0.5em; } #documentation .method-description ul { margin-left: 1.5em; } #documentation .attribute-method-heading { background: url(images/tag_green.png) no-repeat left bottom; } #documentation #attribute-method-details .method-detail:hover { background-color: transparent; cursor: default; } #documentation .attribute-access-type { font-size: 60%; text-transform: uppercase; vertical-align: super; padding: 0 2px; } /* @end */ /* @end */ /* @group Source Code */ div.method-source-code { background: #262626; color: #efefef; margin: 1em; padding: 0.5em; border: 1px dashed #999; overflow: hidden; } div.method-source-code pre { background: inherit; padding: 0; color: white; overflow: auto; } /* @group Ruby keyword styles */ .ruby-constant { color: #7fffd4; background: transparent; } .ruby-keyword { color: #00ffff; background: transparent; } .ruby-ivar { color: #eedd82; background: transparent; } .ruby-operator { color: #00ffee; background: transparent; } .ruby-identifier { color: #ffdead; background: transparent; } .ruby-node { color: #ffa07a; background: transparent; } .ruby-comment { color: #b22222; font-weight: bold; background: transparent; } .ruby-regexp { color: #ffa07a; background: transparent; } .ruby-value { color: #7fffd4; background: transparent; } /* @end */ /* @end */ /* @group File Popup Contents */ .file #metadata, .file-popup #metadata { } .file-popup dl { font-size: 80%; padding: 0.75em; background-color: #dedede; color: #333; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } .file dt { font-weight: bold; padding-left: 22px; line-height: 20px; background: url(images/page_white_width.png) no-repeat left top; } .file dt.modified-date { background: url(images/date.png) no-repeat left top; } .file dt.requires { background: url(images/plugin.png) no-repeat left top; } .file dt.scs-url { background: url(images/wrench.png) no-repeat left top; } .file dl dd { margin: 0 0 1em 0; } .file #metadata dl dd ul { list-style: circle; margin-left: 20px; padding-top: 0; } .file #metadata dl dd ul li { } .file h2 { margin-top: 2em; padding: 0.75em 0.5em; background-color: #dedede; color: #333; font-size: 120%; border: 1px solid #bbb; -moz-border-radius: 3px; -webkit-border-radius: 3px; } /* @end */ /* @group ThickBox Styles */ #TB_window { font: 12px Arial, Helvetica, sans-serif; color: #333333; } #TB_secondLine { font: 10px Arial, Helvetica, sans-serif; color:#666666; } #TB_window :link, #TB_window :visited { color: #666666; } #TB_window :link:hover, #TB_window :visited:hover { color: #000; } #TB_window :link:active, #TB_window :visited:active { color: #666666; } #TB_window :link:focus, #TB_window :visited:focus { color: #666666; } #TB_overlay { position: fixed; z-index:100; top: 0px; left: 0px; height:100%; width:100%; } .TB_overlayMacFFBGHack {background: url(images/macFFBgHack.png) repeat;} .TB_overlayBG { background-color:#000; filter:alpha(opacity=75); -moz-opacity: 0.75; opacity: 0.75; } * html #TB_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_window { position: fixed; background: #ffffff; z-index: 102; color:#000000; display:none; border: 4px solid #525252; text-align:left; top:50%; left:50%; } * html #TB_window { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_window img#TB_Image { display:block; margin: 15px 0 0 15px; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; border-top: 1px solid #666; border-left: 1px solid #666; } #TB_caption{ height:25px; padding:7px 30px 10px 25px; float:left; } #TB_closeWindow{ height:25px; padding:11px 25px 10px 0; float:right; } #TB_closeAjaxWindow{ padding:7px 10px 5px 0; margin-bottom:1px; text-align:right; float:right; } #TB_ajaxWindowTitle{ float:left; padding:7px 0 5px 10px; margin-bottom:1px; font-size: 22px; } #TB_title{ background-color: #6C8C22; color: #dedede; height:40px; } #TB_title :link, #TB_title :visited { color: white !important; border-bottom: 1px dotted #dedede; } #TB_ajaxContent{ clear:both; padding:2px 15px 15px 15px; overflow:auto; text-align:left; line-height:1.4em; } #TB_ajaxContent.TB_modal{ padding:15px; } #TB_ajaxContent p{ padding:5px 0px 5px 0px; } #TB_load{ position: fixed; display:none; height:13px; width:208px; z-index:103; top: 50%; left: 50%; margin: -6px 0 0 -104px; /* -height/2 0 0 -width/2 */ } * html #TB_load { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_HideSelect{ z-index:99; position:fixed; top: 0; left: 0; background-color:#fff; border:none; filter:alpha(opacity=0); -moz-opacity: 0; opacity: 0; height:100%; width:100%; } * html #TB_HideSelect { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_iframeContent{ clear:both; border:none; margin-bottom:-1px; margin-top:1px; _margin-bottom:1px; } /* @end */ /* @group Debugging Section */ #debugging-toggle { text-align: center; } #debugging-toggle img { cursor: pointer; } #rdoc-debugging-section-dump { display: none; margin: 0 2em 2em; background: #ccc; border: 1px solid #999; } /* @end */ pre { background: none #ddddee; border: solid 1px #dddddd; } .method-description ul { margin: 0ex 0ex 1ex 2ex; padding: 0ex; } .method-description ul li { list-style-type: none; } kyotocabinet-ruby-1.32/doc/kyotocabinet_rb.html0000644000175000017500000001754611757456735020765 0ustar mikiomikio File: kyotocabinet.rb [Kyoto Cabinet]
Last Modified
2012-05-25 01:12:12 +0900
Requires

Description

Ruby Binding of Kyoto Cabinet

Kyoto Cabinet: a straightforward implementation of DBM

Introduction

Kyoto Cabinet is a library of routines for managing a database. The database is a simple data file containing records, each is a pair of a key and a value. Every key and value is serial bytes with variable length. Both binary data and character string can be used as a key and a value. Each key must be unique within a database. There is neither concept of data tables nor data types. Records are organized in hash table or B+ tree.

The following access methods are provided to the database: storing a record with a key and a value, deleting a record by a key, retrieving a record by a key. Moreover, traversal access to every key are provided. These access methods are similar to ones of the original DBM (and its followers: NDBM and GDBM) library defined in the UNIX standard. Kyoto Cabinet is an alternative for the DBM because of its higher performance.

Each operation of the hash database has the time complexity of “O(1)â€. Therefore, in theory, the performance is constant regardless of the scale of the database. In practice, the performance is determined by the speed of the main memory or the storage device. If the size of the database is less than the capacity of the main memory, the performance will seem on-memory speed, which is faster than std::map of STL. Of course, the database size can be greater than the capacity of the main memory and the upper limit is 8 exabytes. Even in that case, each operation needs only one or two seeking of the storage device.

Each operation of the B+ tree database has the time complexity of “O(log N)â€. Therefore, in theory, the performance is logarithmic to the scale of the database. Although the performance of random access of the B+ tree database is slower than that of the hash database, the B+ tree database supports sequential access in order of the keys, which realizes forward matching search for strings and range search for integers. The performance of sequential access is much faster than that of random access.

This library wraps the polymorphic database of the C++ API. So, you can select the internal data structure by specifying the database name in runtime. This library is thread-safe on Ruby 1.9.x (YARV) though it is not thread-safe on Ruby 1.8.x.

Installation

Install the latest version of Kyoto Cabinet beforehand and get the package of the Ruby binding of Kyoto Cabinet.

Enter the directory of the extracted package then perform installation.

ruby extconf.rb
make
ruby test.rb
su
make install

The package `kyotocabinet’ should be loaded in each source file of application programs.

require 'kyotocabinet'

All symbols of Kyoto Cabinet are defined in the module `KyotoCabinet’. You can access them without any prefix by including the module.

include KyotoCabinet

An instance of the class `DB’ is used in order to handle a database. You can store, delete, and retrieve records with the instance.

Example

The following code is a typical example to use a database.

require 'kyotocabinet'
include KyotoCabinet

# create the database object
db = DB::new

# open the database
unless db.open('casket.kch', DB::OWRITER | DB::OCREATE)
  STDERR.printf("open error: %s\n", db.error)
end

# store records
unless db.set('foo', 'hop') and
    db.set('bar', 'step') and
    db.set('baz', 'jump')
  STDERR.printf("set error: %s\n", db.error)
end

# retrieve records
value = db.get('foo')
if value
  printf("%s\n", value)
else
  STDERR.printf("get error: %s\n", db.error)
end

# traverse records
cur = db.cursor
cur.jump
while rec = cur.get(true)
  printf("%s:%s\n", rec[0], rec[1])
end
cur.disable

# close the database
unless db.close
  STDERR.printf("close error: %s\n", db.error)
end

The following code is a more complex example, which uses the Visitor pattern.

require 'kyotocabinet'
include KyotoCabinet

# create the database object
db = DB::new

# open the database
unless db.open('casket.kch', DB::OREADER)
  STDERR.printf("open error: %s\n", db.error)
end

# define the visitor
class VisitorImpl < Visitor
  # call back function for an existing record
  def visit_full(key, value)
    printf("%s:%s\n", key, value)
    return NOP
  end
  # call back function for an empty record space
  def visit_empty(key)
    STDERR.printf("%s is missing\n", key)
    return NOP
  end
end
visitor = VisitorImpl::new

# retrieve a record with visitor
unless db.accept("foo", visitor, false) and
    db.accept("dummy", visitor, false)
  STDERR.printf("accept error: %s\n", db.error)
end

# traverse records with visitor
unless db.iterate(visitor, false)
  STDERR.printf("iterate error: %s\n", db.error)
end

# close the database
unless db.close
  STDERR.printf("close error: %s\n", db.error)
end

The following code is also a complex example, which is suited to the Ruby style.

require 'kyotocabinet'
include KyotoCabinet

# process the database by iterator
DB::process('casket.kch') { |db|

  # set the encoding of external strings
  db.set_encoding('utf-8')

  # store records
  db['foo'] = 'hop';  # string is fundamental
  db[:bar] = 'step';  # symbol is also ok
  db[3] = 'jump';     # number is also ok

  # retrieve a record value
  printf("%s\n", db['foo'])

  # update records in transaction
  db.transaction {
    db['foo'] = 2.71828
    true
  }

  # multiply a record value
  db.accept('foo') { |key, value|
    value.to_f * 2
  }

  # traverse records by iterator
  db.each { |key, value|
    printf("%s:%s\n", key, value)
  }

  # upcase values by iterator
  db.iterate { |key, value|
    value.upcase
  }

  # traverse records by cursor
  db.cursor_process { |cur|
    cur.jump
    while cur.accept { |key, value|
        printf("%s:%s\n", key, value)
        Visitor::NOP
      }
      cur.step
    end
  }

}

License

Copyright (C) 2009-2010 FAL Labs
All rights reserved.

Kyoto Cabinet is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.

Kyoto Cabinet is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

kyotocabinet-ruby-1.32/doc/created.rid0000644000175000017500000000012011757456735017004 0ustar mikiomikioFri, 25 May 2012 01:12:13 +0900 kyotocabinet.rb Fri, 25 May 2012 01:12:12 +0900 kyotocabinet-ruby-1.32/doc/KyotoCabinet.html0000644000175000017500000003343311757456735020173 0ustar mikiomikio Module: KyotoCabinet

KyotoCabinet

Namespace of Kyoto Cabinet.

Constants

VERSION

The version information

Public Instance Methods

atof(str) click to toggle source

Convert a string to a real number.

  • @param str the string.

  • @return the real number. If the string does not contain numeric expression, 0.0 is returned.

# File kyotocabinet.rb, line 42
def atof(str)
  # (native code)
end
atoi(str) click to toggle source

Convert a string to an integer.

  • @param str the string.

  • @return the integer. If the string does not contain numeric expression, 0 is returned.

# File kyotocabinet.rb, line 30
def atoi(str)
  # (native code)
end
atoix(str) click to toggle source

Convert a string with a metric prefix to an integer.

  • @param str the string, which can be trailed by a binary metric prefix. "K", "M", "G", "T", "P", and "E" are supported. They are case-insensitive.

  • @return the integer. If the string does not contain numeric expression, 0 is returned. If the integer overflows the domain, INT64_MAX or INT64_MIN is returned according to the sign.

# File kyotocabinet.rb, line 36
def atoix(str)
  # (native code)
end
conv_str(obj) click to toggle source

Convert any object to a string.

  • @param obj the object.

  • @return the result string.

# File kyotocabinet.rb, line 24
def conv_str(obj)
  # (native code)
end
hash_fnv(str) click to toggle source

Get the hash value of a string by FNV hashing.

  • @param str the string.

  • @return the hash value.

# File kyotocabinet.rb, line 54
def hash_fnv(str)
  # (native code)
end
hash_murmur(str) click to toggle source

Get the hash value of a string by MurMur hashing.

  • @param str the string.

  • @return the hash value.

# File kyotocabinet.rb, line 48
def hash_murmur(str)
  # (native code)
end
levdist(a, b, utf) click to toggle source

Calculate the levenshtein distance of two strings.

  • @param a one string.

  • @param b the other string.

  • @param utf flag to treat keys as UTF-8 strings.

  • @return the levenshtein distance.

# File kyotocabinet.rb, line 62
def levdist(a, b, utf)
  # (native code)
end

Generated with the Darkfish Rdoc Generator 2.

kyotocabinet-ruby-1.32/doc/images/0000755000175000017500000000000011757456735016151 5ustar mikiomikiokyotocabinet-ruby-1.32/doc/images/package.png0000644000175000017500000000152511757456735020255 0ustar mikiomikio‰PNG  IHDRóÿagAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<çIDAT8Ë}“Kh\u…¿{gîÌ4ÃL¦’”)‰BŸ1>Òn\ÔâF²±)µ¡PAD¨  Q¤TWf!”"ØŠ¸®Š¦` ¡HC0ijC“1ͳ“ÌL›fwîëÿû¹(v!ƒg}ø6ß9–ªÒ)wyc‘/T4«"žœ˜ëÔ³þ X˜8Ñ«¢¨Èû»÷Ì›v‡Ë×›*ú¹ôÜØõû‹WGU}[E>ÉîÙß7ø&¶šåœt‚Ji’Gë³+*rQE¾>û{û `áêè¢Ò=ÃÇûŸÂí9o/rorœþgaw=MЪ²Uš¥QŸVcƾ;}ź;qâDÎ>µÌr Ïã7jìTç1a“¨U&mì8þ6‰îl7K½¼ÀVio{åǤ9sðÕËVÔ¨Ñ,O"a´WÅ«—©¯mptìkœÌ.h-£­V}ÝÅÈàÖ¯K§“*ÒR¬\ÊM“- Юޡ«'O¾'CüU0)ð7 ½†·9Msù&î3§P#­¤Š€V 'w'Å¯Ì Í N,ïo°•póú#âLRi4ŠQ’j„Ç hÉ]¸½GˆS\ÿ²ù;QƒØíƤ³ˆB¬H£Æ`«1…ª‰@<Ѐd÷^²{â9¦]â Æø!Æó‰¼‰"Ô¶ŠdlÇDÔ @|0mp‹Ä Ä ‰›QÓÇÉ a+¨ˆk«‘K7¾¢½½ é"$ºÀ„  h$?$öB©r‡N#&Cif ™N¼7ÚÿS°³²V[¼6¶…lßaìL/HbFå6ºt÷¿ŽåX¿=Çֽɕد}ŽÈGO¦|ë»—zUäC5r®øâh¾8üD>õµ)4VÊwþâÁêͦŠ|«"—޶´ÑñL\>2¤FΫÈ[û^yÇjW–¹?ÿ'q{ýgùBiîßøo¦.¨È§ˆ¤TäËcç¯têýܲÂ^&ýÈIEND®B`‚kyotocabinet-ruby-1.32/doc/images/brick.png0000644000175000017500000000070411757456735017752 0ustar mikiomikio‰PNG  IHDRµú7êgAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<VIDATÁ?HTàïݦ’^ÙŸÍ ju ¢±É¥±Á¢ÖpOhi/ˆ¢¡8Ô©½!‡p*Áˆ0ã‚ÐŽ¼²;ßûõ}E¬,tnîM2¾Ó|13 "by¢ÕK’$iõ^NFD±²Ð™Ý;«Ö4eZ|òU‡j|«ùjf^´’$ig)kYËbÚI’¤uõKÏêWâ¸øìPÛcJ'U>ê4ÞMKý‹®B݆€eSúºJ›‡µtO9­iÔ„ •ʆíé—n#2à·ëèÛu` *ÃÎø£òÓ_£ ¥R4Êášè+õ*‡Ž€žB¥ªåíªŽu• ñϘšMY­U×·o½ùòAaL¥žGµ­Û½›kEð|"÷2wþØ9¥m…[ûy’Gw¾SðôBæ3{¹øeÛþrÜ~À㫹ŸÁ<œ{ @ÀÓ¹% ó@ÆIEND®B`‚kyotocabinet-ruby-1.32/doc/images/page_white_text.png0000644000175000017500000000052611757456735022042 0ustar mikiomikio‰PNG  IHDRµú7êgAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<èIDATÁ1nSAÀÙÇž4A¸‚Ž‚(¡I“Sp.KPp"„ÒQÒAŠ7%Žƒßþû1Ó¢;ó°ó+„‹çýZ######Ïù´µ±DWk=æCù›?ù‘û|ÞÚX‚æjä˜9昇ì³ËÈSóekMs9¾•¯NNV«ÕG@ÿà¶‹kD)ÃÞ4¼hn­†“¡”éÐ.Q¦@ønJ)1]:À;1@ø¡ ÓT˜Þ:Àt€Ÿ¦išÞ:ˆö€I²$fM³ž-Ú+g”]îþ´•Ï^LvIEND®B`‚kyotocabinet-ruby-1.32/doc/images/bullet_black.png0000644000175000017500000000032311757456735021300 0ustar mikiomikio‰PNG  IHDRµú7êgAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<eIDAT(ÏcøÏ€2 .ŠRŠ òWe®Š7JaWÐõ¿ëÛÿäÿ\ XÈ]íúŸþ?öãæ«XH^íøŸô?ìÝì „þ7¥Ãÿ3`·‚[Š­á*60H ÚÄÑþs–õàVIEND®B`‚kyotocabinet-ruby-1.32/doc/images/ruby.png0000644000175000017500000000112011757456735017632 0ustar mikiomikio‰PNG  IHDRóÿagAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<âIDAT8ËÍ“ÝK“QÇ÷ ºï&*z™ó­( zÑ2—Ë4«ØrÃ!«á\e7§7ÞV"‚x!bT7åR*¨c¦ âö<§¹|öâó|:[WADá>—ßï9ßßï{L€i'˜v‡ñ Ó%IID=zÀ/¶;îŠÂÛ"ïõˆ\k«ÈÞ¸)´k±u¹9™¹xÉ]2§$ÃëW0= óóÂÒú»·$‡‡Q††H¢>}F|`€øãn6ϜϤkN7 >òâ9LLÀè(,.ÂÜŒ¡ƒÄ}>Ö¼^‡ ·›OMM|éí%꿨:/T]F$ ò6VW)©)t‡ƒ5»õÆF¾K–ëêøÜÓò·Qq"¡©r–f óî‘y_êOºa| ˜Åp¹HJ¡*MT›X8Ì×[^Dùñ˜r¸²ò·-|íæ|[Ûäv(33°°€!Ÿ.êëÉ44°Ñ×ÇŠ«eÇbÊ¡rëטu¹Íšóúd¾+ôË@Î S[K¶¿Ÿo~TKõºrÐjýk¶®´˜ØìoraŒŒPˆDPîy5å@YË?ióÜ…½éSg£¹@'š˼Zj¿Åù_MÕ5™÷½Ì»’Úwôê.ÿ ;á'5ãÚ¿_ªãÊIEND®B`‚kyotocabinet-ruby-1.32/doc/images/wrench.png0000644000175000017500000000114211757456735020143 0ustar mikiomikio‰PNG  IHDRóÿagAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<ôIDAT8Ë•“ËoQÅù_ü[ŒcŒ+W.]‹Ñ…¤išá5  g  m°–ÖJ[FÔq†—Éè¤#_Ð)ÚqÕ¸ÓÓ;,“¶@÷‘{ó;ßùÎÍupL©TÊ™H$¢(Z‚ XÿßM„“ɤ“€Ýn¦i"ã\nt:ôû}äóyD£Ñó ðøØåÏ0 ¹\ ÃÚ–IUËãñ4(Šrž‘¶áÍ úHM°k̈À_¿ßá4·Ç_z—üŠ€iy€'¯"[ý êén1Æû³rMž¥Ž_ïAú`béíñõ=$Ikå_p-¶qÃS~¦À²=li~3ÀBv"q²ZâAªëԧ̸—r¸[ØÔöG–¹—]<&áeÔ!î'Ú¸67 Üyôôºq‹$OÚX!ð=_™Ý~1ÍGsÜ~øE³ƒZQ†x&qWøŽK3ÓÁÇ!Þ¤ëu®Înã¢kzØGrjùQûn»IEND®B`‚kyotocabinet-ruby-1.32/doc/images/bullet_toggle_minus.png0000644000175000017500000000031711757456735022723 0ustar mikiomikio‰PNG  IHDRµú7êgAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<aIDAT(ÏcøÏ€2ÐQÁ‘½ûÿïú¿åÿúÿ+ÿ/Þ‹EÁÞÿ‡àpÖ, ¶%Ö‚á¡ÿ°)X”€€CÿÛ±)XŒdB=6³ÜP†MÁ„u]ÿ[€z+ÿ—üÏ_70!I¶È“zS5¯…IEND®B`‚kyotocabinet-ruby-1.32/doc/images/zoom.png0000644000175000017500000000126411757456735017646 0ustar mikiomikio‰PNG  IHDRóÿagAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<FIDAT8ËÒKHÔAÀñï̪-–ŠK¾C=Ø ¡CmÒfuîP–‰)D—êB§"ÂK»$A„ e¤¦t¶¨¤ð ô‚JŒÍZÿyuÙmüÁ0ø}f~3#œsLÞ²|!!|g-V©9­¼Që鎺³ýc¬`²ïT«™C8*¬—èô£5Þb¬F'âÎR!DÆÐ‹› ­kbâ^sPÈÌ!«½»²¾«¨ÊLocÂgÀע≣‡.=^uéíÖ˜ˆ¬ïê[ €¨ê65ôÞ¶FG´§• !§Ô P ä%wN5•\«Òq=(¡t@ȀѶ(t2)Õ§ "«L?Bþ2¬uXcY‘äV$¦ÆÚƒÔ&ý´çÍa]còÂt²¥€Ô<â *¡æÒã©QçÄ1àð}E )h˜’Y—­§§Ò„ê°Ž’…æ6` øDXr<:=UR½Íï÷ÌžáóûO®úÎ9žÝ8Ò*}òªV&b==h”é·ÖqÙÜ+;¶ËœâJT<ÆÔÓçüúò­øø­—³ËÀÈõÃA !CÎ:”§£¾Ì¼Êú}änAHÉ~0bM”ž¸36» ü+†/ç——ö”ƒøsóIĢ̾™àÉÀ«ÏEkÿ ž …óJ {ÊvíÄ!ùùé=_ßMÏyKªb]Àö½aµ¤{6W°03ñDÔ¬Ÿ?§ÉR;óÎc’ÉéÁË}÷žsÞ}W ”b{{ûûÊÊJlffæ™`ÌÜ[µÿ%ÊÜn÷Js.—ëÛ/„ZAËËË8>>F¡P@>ŸÇáá¡ÌñŽ5¬}q$ {ö_µËËKx<„B!‰ùùy™+q”•‹‹‹IEÂçóauuN§S‚1st“ËåpppöLMM¹¡”;99ßïG ŠT/=/Žö÷÷±µµ… LNNæaOÍd2H$8;;Ãùù9ÄûpzzZtÄxggáp^¯W" bbbBUæææ$A:Æíí-"‘ˆ´»··WœU9D6nnnJÐíøø¸ÊJUUqssƒd2‰X,&Uù´ÝÝ]ÙHËtF'$ €ÍfSñ·÷÷÷Ð4 ñx\>C¢¿¿v»½½½XZZÂÚÚúúúdÎjµr€Ê*³³³^²G£Q¤R)ŒŒŒð×××’ŒcÃÀÀ€tÄ]±Æl6GñMïÅr˜¦§§ŽŽŽ¢££±8¨­­…ÉdÂðð0ÚÛÛe\SSÃÆß$immMWÒáp”544øzzzžIpuu½^õõu90¾_¬9ªªªžººº>’ »»ûáÕ^WTT|ì ššš ÓéP]]ºº: Æ$¨¯¯ÿA‚æææ»WŸÄ¶Ãƒƒƒwâ{5nÛØØZZZÐÖÖ&cæÄ]Š5¬}EP^^þ®²²ò³Á`¸0¿,˃ÀcccãW/"Ö˜ãkXû §ùùY®j–IEND®B`‚kyotocabinet-ruby-1.32/doc/images/loadingAnimation.gif0000644000175000017500000001337611757456735022127 0ustar mikiomikioGIF89aÐ Äûûû÷÷÷óóóïïïêêêæææâââÞÞÞÚÚÚÖÖÖÒÒÒÎÎÎÊÊÊÅÅÅÁÁÁ½½½¹¹¹µµµ±±±©©©ÿÿÿ!ÿ NETSCAPE2.0!ù ,Ð ÿ Å@Rižhª®lë¾p,Ïtm¿#6NÏüŒÒ+ör‹¤rD4ÊhÓé@F“Cjz]LÖë×–j·]﹬ÌRÙØñ3-ÃÁH$wƒPy‡ |KI†ˆ‰‹ŒŽŠ\K“ˆŠŒ Q\˜‡•]PžšI–¢Ÿ  ¬¨¥°¤’~$² ~Æ ÁËÁÃÅÇÈÊÌÁ–ÐÒÓÖÇØÌÕÏ×ÓÔÛÆÝËÕJÇÉâÕÐåìÚéÆëâÚàÜìßï æÀ%:`–Á@ XÈP@AO 2|ø(¢D‡º**¼H‘E‰}láF=ÿž$¹Æ‹@\9±åL˜ J(ÈÕ)?‚ ``ÁÏC…=š4èRO@›>}5éTDU‡^=”U©Q¨H¥~¥ÖêX¬eµžåšÖ«Î‚:<…Š!€»æžb`¯^O àõ»v”àÁy ':<ø/%Æ„éòEœ˜n`ÊŽ3A¾›ÙðÂÆŠë~¾`îÛ¸Rf*Ð4µLÀ¬›ªE3èìDZœ[öí±“ÞFUÛõëÕºg*>|AoáÊGªë4QÅ]ïÀÞV;÷¤Þ™ <€íG)Ÿç®}ùñëÓSvOÖ<}´í¿ž&p ðæÄyôØ]†Xg Xà‡ ¢`€"1š A˜ fJh!æ’B2§8'‘m ”øuÑ™tbj)ò–œŠºÅH s6.7ãL;jÔ£J?Š´‘p6æÐ‚l¨@k[‚ “Ø-)–’Pº„V•X™¥”fQ9å{fýÄ¥Z^v &™é0 l¶éæ›pÆ)g 9P!ù ,Î ÿ EMb¹œTŠŽ5+…ªkûÆslãyíò‹”Î[õJ;žÐw3iH¢Ê’:—QªèXÕR$ÚÃâà511™ç@¯Ôeg;=Ž›(gúÚ™×Ùn%pf"ƒ|…‡w}‚ˆzv[xE%` +•% ‰š‰Ÿ¤1" ¡¨ª ¦ª¨¤²1›°¶™©ª¬§£½ ·¯½­Ã‰±Æ·È1ŸË+ +Õ'i 1Ö˜~ ÛÔ×~ÚÜãÓåá%Ýtæâ±îë"íßóÖéŽïìèòçäöÝ«'ð–$|dЉ'Ná7o%pèDzõ:ð)†DŠö©è€HŒ$ÅÿœD˜ò€Eétl¨±äÌ‘5żlP•4 #Žóy€”5Ÿí—SåRzC>¥ j¹©U›šœz›Ò§]ß$åjÕQM ʆķÀ˜772à1@Ü’üDH¼;Ü‹%Ð…º²ïÀq€ÞÛ›XÆÀ‰‰MÆg·±ßŒNά®gÝMWz!`¤›îdÓÏÝÑ¥]þØôuj™€a×Î}ûa ݸ÷6;»5Õ¬D•zT«h,5ä~¶z~“@y[µ:­3Mú7²g‚Gª]„ÛðÒáqÿ=@c5 4ÿu·¹ò¿†ñ탟5_ÇÜÀ_9“½—_A˜Mt B\ý—K ⵘ}" @lÔÕD›iÜ·Quç+bøaq&²Ò{#'¢L²HÇjz¢"$&˜¢ Ò$B!ù ,Î ÿ EIäˆè²@*žPãR*;ò[·®ãðºÕÍL­ŠÜl7DÒŽÍ%³G‰I0)´÷Ëm½ÒIÔ²º‡ÅØØ`ÌÐI©Ã}>ăí·}-RÍõwFu}y„|Oˆ(pŠ*Œ"Žrt{R‘“A>( Š^( •"£ª4¨®± ±³® °3²´½¶®¬ºÁ½¹À©3£¿3ÅÊÌ.Î.¤µ·ÆÐ§Éž v.*o 3àâu æßá zëçîzåò»ðì(è øöüêùDìë×.¥zÿ Ha ÀïÚÑ€§P €‰ê*6¼ñÌ=‰%¥Ñ£¥ú8ÿêA%ϤH”]J‚¹Q&–ߨÙ2äL z¡ë…†AÉ”>50j(‚ ]éT¦.„s µ*­IÑ@m:n¬Tx^7†}šv(ÚHÀy’!8º/í À«4^Ö¹ÅðGi`zùÚAˆ"àÂ?l§8]É'STÒ§X’*3Π@X¾¤MS<@µèœ®-¡.íùÀìØ/Aï¤Ùy5ìÚ|žU×vëÛ¬ÆÏ°VÏrä4<A:\à4Å×bmœüdv®i›ç{Ë¿ÐÓ›òWê'7†ïþnü…Ìé×aÜÐq{ù"8V™_úÌu_^òØâž2ö•Ø_ÔÆ[k‚¡oâ¦Tpbp :¦áM ‚sákóx_"VØ“‡™!ù ,Î ÿ %R4ž yŠÔ¬Ô¢®í»Ê\ÃK®û·Ù©ÅÃýl'#ÍÅÓQˆ<àP:’é A*É4¤ G‡…£™Z…ÇÁòéL†±ÓnqÛ,‡ÓÑI‡\ÏïEoIUzqx#)Šƒ_"" „‘“ •0„š0› +¢0¤#ž¨#¦I­"«£ž¯'±ª¬µ„2 0›  qÈ+ÃËtÍ'ÏÌ ÐkÇÖØ`ÚÎ×nÞÓàÑÉÜ€â#äÙÒêì|î2çaqôVkÊÂûøþñãoE€f NC¸ž})TÇ`¾Š€R8±Ðć=žû5ÀÚ&ëõ¥D9ìÛ¦ ZŽ{¹@æ»—1M†Û´Ž¦Í‡)ÃüTy²¦N39]Ʊé A°oôÂØV jÕ>Z0Õ V©TËyºÀÝïeÍ]U‡¶ë4´f!P c0z® kW+_½ û^´«Ñž`v£"ãÅŠa@x:@O,žÈ¬tç™K5ózÙsRÐtH5Úy3ëÊ¥ª>yz=„3[/÷Z|‹&¼°âÝx @ŽŽ7nÝÃGd…nÜ óBé^‡©|{Z¯C£Nñ°3ñZó&$’p¾{f®;^C}Cö÷ÃoŸ þù÷%!ù ,Î ÿ %Š$5£¸,%”:„¦kùÂ.]ç#>µ”Èá ƒB"ÈZRpÇ]2öS±’ÊhkÔ9ŸE­-õe<Í©Ãá¬k Gj6Ó-ŒÃtŽ·ÈÍ××wsz|mƒ…‚OQti€Œ‡x‘‹41 ) ƒU" œžƒ ›B §£ª¬Q ¤¦´°¦¢¤»B§©ª¿À¹)¶À¨¦±·Æ#«¼ ¡ B+uÖØÚ  ×)ÙÛŽÞåÚ é#æìèäïëíó"æáŽãß úpÜág¯ß¿=ïQÈÇÁšPüa QÜÁ…*Ö‘XŽb<88ÒÓÁÅl$áÿ˜œ˜’ÐQ,?î y2£Ì=0ÕµT#ràΗ5æ Õ ˜9`jLmgTÒJ2í‡ÁMŒWy6ÍjukÕ«K÷y·0©iºŽP0J¡Cg&(`ðÏÜoq]Þ혗']u}C*  ð‚¿ïà^\sx¢a·…GtKpeÈaô¤@›jòvþl›gÐVêD­z$êÍ£Q‹>m÷bìÚ1ÿ´öùÚ6í}ó4 @•lñ´`Ѫ¼zvsêGt® 2yÖÀš/V+½ùSëßÇŠ=^˜ƒ‡ï"ä+Y  09Ú›>0}ŸòÞLjËî`ŠùíabøqÃO „õ'8^ÛXŸdû’Û|5 […¬ahW€Y¸á7Ö‘W6!‚Ÿi¤ÍÇ!‰²qHXŠ&®(@‰3í&B!ù ,Î ÿ Q$é@RS’Ë"®Ô ©k;ÂÎ Sö]æ3X'¢•†+àζS ŸéõŒâtUi¬˜½k ëîé`À‡mÒ0¯ÐêcÌ]‚—×÷wÚñlŸ÷dt$v}‚„k~zq,l†ˆryu€x”?)B†† œž†¢   ¢©«; ¨0¯0±©Ÿ°£;ª¦·¼µ+ ¤¹Â­À¬²³ÁG† 0-gÑÓ+Õ ÒÔÖ.zàÛâßÚ%Üã“åêçäé$ÜÞz òôèáÝûæýñøÕ+l’(jxü9hN¡†ê²tâ<‰; 8O€Ã7óyœxH#Ç|ÿž¬ö‘bH–$ѼLipåȅѹ ¨Ö2"ØÉ-ã¢A¿í(ª”ŸP’$µ·tj»@{­Ús(W£Ó$( ðÏ=„!u’5—ö(¾jmÏn wmĸo­ô™ A»ñÂ@w/·…ý…¢ àdÔ1+:'ÂÊØl¶´1Üf™š#‡|,z2æš0HgœùÙäåÒÇ@1}ãÕ©Ù¯·[¥¸3ëS+|çþ7UÛǃï.Ù{¹Î Påµ0ʶc=+PL‚0õ3î:~ÿ‹Öpøë'¸ÕÎýúv{ÓßO’ûn<Åó׿¶~)À@ÏòuäŸP6 ¨Òk (’¨™Ã K'všK Vó`I9(Z…LÈG!!ù ,Î ÿ ÕPeRN*'µ,Ô¢äìÂv*Ïo<ë¶ÞîäÁ†¦bKøs M½œ3ˆk>o¾–òÄÔR® ÆsAE1f‡m):·Òk®­vîÜÎväM{wl ƒ…r‡tqPmŒ|ŠˆuF~?W a3ƒ& ƒŸA¢6 š ©«›œª6 §-¤ƒ ´­²3º¨¥- ¬œž¸.»,Áµ¶É6o 3/hÑÓ-Õ×oÒÔÖ ØàÛâäÚ'ÜdÐåêÖìzÙáÝzßé&ÜãÞîùçüø(èCGo߉OÒä¢Àaá¾9ÑœD= ækOOEuj(à¢Ç‘ÕLÿʱãÊþT¦IR&K‹.ÕØHŠÛÎ=­ý š“§ ŸtˆþtI’©Â£Bé0E:qjÔªP°êÔáhªYÖ܉ ʾëBíF¶dÃŽT0@¸ÜK!Aݽ_âaw°9¸ÞhP (”!Ñ¢,é”fÊÊ“mZ¦,rÆâÆ[|.ª˜1é‘£wZŽŒæh%Í.Í:›^mÙRiç¶½7VÞ¿}c\ÛÄâÃuï;oà‰ý>oý—ÖüÓõu+],Eìb›ƒd]/\îæù.¨®€àá¹âû*h3ô;¤é߯¬ß~ûþÎ’ ˜“|HoXgƒ€¼6’] ¡¡‰ !!ù ,Î ÿ E9Ž$ž#%5(µ,Ô’rûÖ(iÚ0.ê¼ÞÌáÝŠ´`lXtÁ†D%´ydJ­6ÆîÇH¡^.êpðžÀâÙl¤„[kï=.Ë¿î´(>×Søx~€gypv}‡lNtjˆx{e> ‚( ™~~ ›Ÿ¡Ÿ- šª¤ª¬-¨ª  £,-°(¨¥¢±®˜¦¿·¯µ­Ä¹¾±ž ' Ÿe -/pÐÔ(ÖØu Û'ÝÍßá"Ý ‡ÓÕ×éuëÜí‡àì îŽôñöêæãóýþ•«GN„ ƒìãÀÅ¡LÕ”1žÃ:ÅI<„àÞ9uŒ’¢G 'ÿþ9ñcÉ•-Q¾$ÓÚL–'lDÁàÎ7UÝT‘ùTª×„ štÞѦï€BUƒ@%J«ªJŪð)W?LÝS¤¾Y ¤b“ŒZvm®ÕÞ‰êÎý¸Ð‘]xõF¬0ïI·{ýV—XgÜ|â´-Bf¤E¬–#ßÌ|.@•4O†ýüP4Òu8S g Ö¥_Ÿnö;Ó¨Õž­(›Õ¢Që)µŠó³wÇ®<.Ü(Š°Ê³2?ëôÈÖeGïÚ|L•Õ…"xØ/…ƒ-¢÷Û/ìy€ƒ+,ßp=Eúï1Ž›  dùQ€øÙ·Ü~¢€2Kê”›$ªáõàr `m*YsáC zFn¶ ak}¶“nn˜ÚI#Š—“…´Q!ù ,Î ÿ %R4žŽÔœ"CA,åÀñÑ(~Úº8׼دööDAÖ•Ì2hs´ÜÝŒµ+Áp]¬ÃÂˤ€ObòÎKÛãw8^>Üu¸z´`Ï÷H~htkv"x…m†€|1Z, †‘–-™‚#œ5•1"£1’¢™™¨' ¦¯'¡[´#¶”–˜,œ Š¥,}, Â'Ä pÊ#ÄÆhÉ1 ÒwÔà ÍaÚË×ÁÕáÞÏ"ÖÝÓæÑâÛéw ëÄÀ#Èpð"bù1°âV- ¿akèc—ÉB€) °P@Ã;ÿ]Xq£ÄŒ#Nìˆ-A¿"ß²Syr›©–àL¥4eM¦Êšph²\@ÌeÎq/oªœ ô§ÏÍD2(𯘳q ÅÌs:gªÒu@ª«Fu+‹¬QåAUÄôÝÓ¯ZãÍ#xbRŒ‡‹‘4Åv™G1 ˆì M¯¬ˆüÎÉ»—ðÁš;8FâˆP`BÛ©3he£11O~™ çœËŸ‹†>z‚(éC¦3—©úA=¯Ë\ŸýZ-×Ú‡¾A“í­ì‰¼aïÆ-qiSâR“­Üö°Ym¢G„(‹1¾çî¦Í¾—¸Å½€µ=dtïqëB‹[ÞîÞ!ù ,Ð ÿ %Ždižhª®lë¾p,Ï4É0T:”Ô”‹…n瘂9â„\Ч¨©< ¥P)…JÊZ“Ýè+^«fð(û³-N …Ǥ4¥Ãan¾ç÷t#o~$z|u„#†Svx…€@އ‚“•‰"‹'›ˆŠ‘¢% £#m# ±«³S³µ·%± ¸³± À¼$¨Å%µÂ§ ¿ËÁ¸²ÑÇ#¨ÐËÖ°ÊËͽÙ$Ò& AÑŒ"µæÈÏ% ©… ï$ñó§ªø#úôH݃'/ 9óü“ðßBH EdèOâC)L„˜q#F‚o– ØògŸB’bÿDIʤC–œ¸´Ô•'C’ÂùRgÌ™Gú´ 4^M=F\¸dd‹“3 Xæå ™KlžüÙ£ˆÌŠ@«@¸†ÝTöë?}¥æIVÂöUT+¯öõ»öì’Æo§l­|gr· T·e»öluÅÓ­ßÕÞ’úvì×Gä]l<Ý‘æ»sg¥Š_D ›)4EØQÀã÷ñúÒ_i¸Š)ÀPi#¦÷!h Da %¸’€.@ÕÛqËMØÜOQ `€pnˆ„yHW‡ÂC¡"Ø$¢s* ¢›]hp$ÄèV 8æ¨ãŽ<öèc !;kyotocabinet-ruby-1.32/doc/images/bullet_toggle_plus.png0000644000175000017500000000032111757456735022546 0ustar mikiomikio‰PNG  IHDRµú7êgAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<cIDAT(ÏcøÏ€2ÐQÁ‘½ûÿïú¿åÿúÿ+ÿ/Þ‹EÁÞÿ‡àpÖ, ¶%ÖþÿćþOÀ¦` PýoǦ`1’ õØÌBrC6Öuýoê­ü_ò?ÝÀ„$Ù }J ƦgIEND®B`‚kyotocabinet-ruby-1.32/doc/images/tag_green.png0000644000175000017500000000114511757456735020613 0ustar mikiomikio‰PNG  IHDRóÿagAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<÷IDAT8Ë…“Ia†ûOÌUÿ éø{æbFcôªN4FMtÜnîñÆÒ-=ì6c li4ÈBH!Ñ(ÚdXòúÕ—ÐÂâ¡.Uõ>õÖ×ÕBµZE¥RA¹\F©TB±XD¡P€®ëÈçó„}!†år¹½^C2™Ì^ˆ@“I`š&ŸÜétlå˜ $“É,S3M£D.—Ó'“ æó9Ï0NCÓ´­¦®™øœY6§Ó)F?»ˆ2¯µÛm$ Äb± ˆ@“W–‹H<þõÏN¯ã‘tÍx­Õj‘ D"‘5ˆÀv´Æã1ošÍfþèâäô^¹÷g÷ðœVf³I.lˆÍf¯°­ÑhÄ›¾™9<–ñV½‹OÚC|8»¿i4ä>ŸC8%•J‰lGk8ò¦z·€§¾#¼Smȉr„XÉÅëµZ\@’¤{—x<.²­Á`°ùøõ^oâ¥r óÅŒ»…Bðx<—×^”í'ªªjõû}òäóU¼ðßÀ›è1þüý}Qì°W¸ÑhT ‡Ã]"·kêL|ÓsË»Ýn‡ýˆÛŽ# Š~¿ß¢K\}b³üšx'€BQ'{i‹¬^¯oïPȲìôz½‰].—cë)ÿïweSL|iWýù(«ÓSIEND®B`‚kyotocabinet-ruby-1.32/doc/images/plugin.png0000644000175000017500000000111711757456735020155 0ustar mikiomikio‰PNG  IHDRóÿagAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<áIDAT8Ë¥’=H•qƯf~\?‘Ä,ˆ›yoX£{KCµ´7ÑPcM´5º4EkS$¤8V*w²¸‚ŠJÝB%Ëî{žs^1㪋g9ðçœçžß9IDp8´Ûラ»%w%I¯ =¹´—@]móvœbS?ù–|bÒÐ~ÔÜ?ÿøGÕªi¤lT70³™ý’ˆàáô½p’£,Ç@Û™Äܘ^žY3“$Õ™O¯Ø};®žÎxøú3o}~ÛW½tÜ ªÎ$™ÖS³jôbjLEMa8¿»¶÷Äy÷Þ¿µÝww>†¡ ¡­J«Òª´*m*¿ÿuÓ=g6=WÞ|êvÓjz :@BŸ(%UÆZéë4¿\‹“1ãÄÓ÷m©Þfèôj"‚j¥A¦Æš6Ê“hT‚*J ‚ V šZJZ $@‡1“0PHZÃ(} )B”e°  Ã‘„ @)zcàÔŠeè° –Á0Â2FH±ššùdÆ#±ÿåËà±W?³9 Ãÿî¥WªêñÈi!ˆGcŒï{sþéûÞŽl6ÕIEND®B`‚kyotocabinet-ruby-1.32/doc/images/wrench_orange.png0000644000175000017500000000111011757456735021471 0ustar mikiomikio‰PNG  IHDRóÿagAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<ÚIDAT8Ë•“»kSQÇó8H)N]uA,¥ƒˆ“w“ÒjÍûazcbb6ÖêÅ&­ Qcn^b4b2e l„ x¥W„ }$çÅçûûžï9ÇX¦µt:­$“Én"‘0âñ¸ñÿÞT8•J)N†Ã!ãñ˜h4ʉîF£ù|žp8|2X,f˜Õ[­ªª–͵`0ˆßïÇçóSÄòï~¿OµZ% } º¦iôz=Ün÷ñ‘Hä‚XÞët:4 ŠÅ"…Br¹L¥RÁétv‡_ÝT'™-±lÔëušÍ&f_«ÕÐuR©„Ãá˜Øl6å ¼u]e× Ù5~lÞ¢Ýn“Ëåðz½{¦e©jØíö®ÕjU†¸iÂwáÛ|}šÂøÉç§Ëåš?Ìíþ$³¬²³&°€ÀûûÐx ËürŸû|TNÿà%•ì*4ŸÃ‡ l‹Ð;'T^ëÙ—G <»¦²½"pFªà­Œwì Ç!yÖÏhÇÝ”…Ôeø²E±üæ6äî ø ܙצ½ ‘‹P—³îJÕì:”C\DWç^ÏòÑ,<<ß4ƒú –A쬜ž Þѹð]‚ËsŸš6ÛÞ‘øéî×—IEND®B`‚kyotocabinet-ruby-1.32/doc/images/bug.png0000644000175000017500000000140611757456735017435 0ustar mikiomikio‰PNG  IHDRóÿagAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<˜IDAT8Ë“ÉOSQÆù\^[ ØªtzïŠ% l$–*“**”2:  iRpˆ¦Š´¶ c0ÑèÆÄ…Kw&&`44Äðù‰(¦eáâKîɽçwÎwrO€¸XÊ\¦‘¹HiÙsÆcUQz@¹ýï›ö™šø;Ö„Id„TaË€ž¯ö)jèù·C'ÙŠKTóï8=¨Š¨ýʯæ9Þ‚^z›“í–ØÔΘ͹™1OFöZ[ô¬”WÊ-GçzÖ?‡Ð®&­%*€ñ©M¤„ÆGnæN!øaO>Nc॒[ɨX·ÿõ0NôÅqg*¤1SužÜb|î{g|îfz)̾»ž§&\ — 5\ Í0 ‰3¦i² DŸö;`|î0>A?Tx4^òËÙ`¼oûqs©ö`>ʦ²`ôÂ÷fC«v§@m†X ¦å¤[r\†ÀûAt.–¢) G™[ ÃŒ÷×°Ïð`¥’N1Ä¢ï)­B룲ˆÑW×s+ý:”Nd¡Øs÷V»a*DÕX.pBÜ&B²]°›ÔH@TÏÿ3@ÕPÚÚ  wVÚP6™3yp-¶ÃâÑÃ4š Ǽ “$ÙH®'ް9„™{m@ßUô¥¹$èZjCñ¸®…XÜ:TŽä gÎ꺢ËLÕ:¢:æ?õ[#š¹{1ˆ®P=.2 ž¹F\™i°ŽA-D 7Â7qš£XI¯Š×¤b4¸ka÷ÔAjï% ͼj&QË«HÜä–&€s.žˆ `•j¹“¬üŸ‚KLE3ü*ΫX wØ6²â_àlðÊÁ=Ÿ@ü€Ç¿“hˆßŠv÷ ·,qq‚úIEND®B`‚kyotocabinet-ruby-1.32/doc/images/date.png0000644000175000017500000000116211757456735017574 0ustar mikiomikio‰PNG  IHDRóÿagAMA¯È7ŠétEXtSoftwareAdobe ImageReadyqÉe<IDAT8Ë•RmkA~î¼Ô‹çK$‚ˆ5X¤%¢ íÇ‚!àó³¿#?PŠ…@PZ(*EúAÅ#¾Ü¹Û™w˜Ô:ð0»;3ϼì@J ‰–Íf?W«Õo™LæŠî¿í` …OµZí+ûð›§M“¿Øëæçù<†ww• ^ãIؼ½Å›ËKü¼¿ÇæúZÙÒRjºFÂNV0+Ãv»E8Çq €¸®+˜äbF"ÊvÂÜs¬¾;Ã4 tåÔíõ ˆÄ>9ckšèt»ÊÖyxð àõØDŒ²7ÎÎгm\Pöµ¦S€t¬]ßIo…@ô#Ù/ÝØ¯àÃé)Þ[äf—œƒÈ^Ñ»£#dHk„àbG"õ«¨×ëÒuÝ¿Âq¹\.Xøc8ÖÀY¯×h·ÛH§Óè÷ûª÷ù|Žr¹ì}¹/ú!FˆÐäs¹R©B¡(³è÷˜§]ð…ÑjµT5”ª£Vü˜?ZxYâl6ƒ Ésðd2Qg†çwpûdÜ­¶šC2™äåÁp8„A¿ÆÕ厊”Ø®Ð*³©X,¢¯å¬<}" úW›„Ž‚ ûаæ 8s"‘ÀjµR-ù-tiMÉ1ÊeýK¼ ˜¬Ùl¢T*=L§Ó/Fã#þCè7~°þ -:MW1¹ùIEND®B`‚kyotocabinet-ruby-1.32/doc/index.html0000644000175000017500000004330311757456735016704 0ustar mikiomikio Kyoto Cabinet

Kyoto Cabinet

Kyoto Cabinet: a straightforward implementation of DBM

Introduction

Kyoto Cabinet is a library of routines for managing a database. The database is a simple data file containing records, each is a pair of a key and a value. Every key and value is serial bytes with variable length. Both binary data and character string can be used as a key and a value. Each key must be unique within a database. There is neither concept of data tables nor data types. Records are organized in hash table or B+ tree.

The following access methods are provided to the database: storing a record with a key and a value, deleting a record by a key, retrieving a record by a key. Moreover, traversal access to every key are provided. These access methods are similar to ones of the original DBM (and its followers: NDBM and GDBM) library defined in the UNIX standard. Kyoto Cabinet is an alternative for the DBM because of its higher performance.

Each operation of the hash database has the time complexity of “O(1)â€. Therefore, in theory, the performance is constant regardless of the scale of the database. In practice, the performance is determined by the speed of the main memory or the storage device. If the size of the database is less than the capacity of the main memory, the performance will seem on-memory speed, which is faster than std::map of STL. Of course, the database size can be greater than the capacity of the main memory and the upper limit is 8 exabytes. Even in that case, each operation needs only one or two seeking of the storage device.

Each operation of the B+ tree database has the time complexity of “O(log N)â€. Therefore, in theory, the performance is logarithmic to the scale of the database. Although the performance of random access of the B+ tree database is slower than that of the hash database, the B+ tree database supports sequential access in order of the keys, which realizes forward matching search for strings and range search for integers. The performance of sequential access is much faster than that of random access.

This library wraps the polymorphic database of the C++ API. So, you can select the internal data structure by specifying the database name in runtime. This library is thread-safe on Ruby 1.9.x (YARV) though it is not thread-safe on Ruby 1.8.x.

Installation

Install the latest version of Kyoto Cabinet beforehand and get the package of the Ruby binding of Kyoto Cabinet.

Enter the directory of the extracted package then perform installation.

ruby extconf.rb
make
ruby test.rb
su
make install

The package `kyotocabinet’ should be loaded in each source file of application programs.

require 'kyotocabinet'

All symbols of Kyoto Cabinet are defined in the module `KyotoCabinet’. You can access them without any prefix by including the module.

include KyotoCabinet

An instance of the class `DB’ is used in order to handle a database. You can store, delete, and retrieve records with the instance.

Example

The following code is a typical example to use a database.

require 'kyotocabinet'
include KyotoCabinet

# create the database object
db = DB::new

# open the database
unless db.open('casket.kch', DB::OWRITER | DB::OCREATE)
  STDERR.printf("open error: %s\n", db.error)
end

# store records
unless db.set('foo', 'hop') and
    db.set('bar', 'step') and
    db.set('baz', 'jump')
  STDERR.printf("set error: %s\n", db.error)
end

# retrieve records
value = db.get('foo')
if value
  printf("%s\n", value)
else
  STDERR.printf("get error: %s\n", db.error)
end

# traverse records
cur = db.cursor
cur.jump
while rec = cur.get(true)
  printf("%s:%s\n", rec[0], rec[1])
end
cur.disable

# close the database
unless db.close
  STDERR.printf("close error: %s\n", db.error)
end

The following code is a more complex example, which uses the Visitor pattern.

require 'kyotocabinet'
include KyotoCabinet

# create the database object
db = DB::new

# open the database
unless db.open('casket.kch', DB::OREADER)
  STDERR.printf("open error: %s\n", db.error)
end

# define the visitor
class VisitorImpl < Visitor
  # call back function for an existing record
  def visit_full(key, value)
    printf("%s:%s\n", key, value)
    return NOP
  end
  # call back function for an empty record space
  def visit_empty(key)
    STDERR.printf("%s is missing\n", key)
    return NOP
  end
end
visitor = VisitorImpl::new

# retrieve a record with visitor
unless db.accept("foo", visitor, false) and
    db.accept("dummy", visitor, false)
  STDERR.printf("accept error: %s\n", db.error)
end

# traverse records with visitor
unless db.iterate(visitor, false)
  STDERR.printf("iterate error: %s\n", db.error)
end

# close the database
unless db.close
  STDERR.printf("close error: %s\n", db.error)
end

The following code is also a complex example, which is suited to the Ruby style.

require 'kyotocabinet'
include KyotoCabinet

# process the database by iterator
DB::process('casket.kch') { |db|

  # set the encoding of external strings
  db.set_encoding('utf-8')

  # store records
  db['foo'] = 'hop';  # string is fundamental
  db[:bar] = 'step';  # symbol is also ok
  db[3] = 'jump';     # number is also ok

  # retrieve a record value
  printf("%s\n", db['foo'])

  # update records in transaction
  db.transaction {
    db['foo'] = 2.71828
    true
  }

  # multiply a record value
  db.accept('foo') { |key, value|
    value.to_f * 2
  }

  # traverse records by iterator
  db.each { |key, value|
    printf("%s:%s\n", key, value)
  }

  # upcase values by iterator
  db.iterate { |key, value|
    value.upcase
  }

  # traverse records by cursor
  db.cursor_process { |cur|
    cur.jump
    while cur.accept { |key, value|
        printf("%s:%s\n", key, value)
        Visitor::NOP
      }
      cur.step
    end
  }

}

License

Copyright (C) 2009-2010 FAL Labs
All rights reserved.

Kyoto Cabinet is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.

Kyoto Cabinet is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

Classes/Modules

Methods

Generated with the Darkfish Rdoc Generator 2.

kyotocabinet-ruby-1.32/doc/KyotoCabinet/0000755000175000017500000000000011757456735017277 5ustar mikiomikiokyotocabinet-ruby-1.32/doc/KyotoCabinet/Error.html0000644000175000017500000004027111757456735021262 0ustar mikiomikio Class: KyotoCabinet::Error

KyotoCabinet::Error

Error data.

Constants

BROKEN

error code: broken file

DUPREC

error code: record duplication

INVALID

error code: invalid operation

LOGIC

error code: logical inconsistency

MISC

error code: miscellaneous error

NOIMPL

error code: not implemented

NOPERM

error code: no permission

NOREC

error code: no record

NOREPOS

error code: no repository

SUCCESS

error code: success

SYSTEM

error code: system error

Public Class Methods

new(code, message) click to toggle source

Create an error object.

  • @param code the error code.

  • @param message the supplement message.

  • @return the error object.

# File kyotocabinet.rb, line 95
def initialize(code, message)
  # (native code)
end

Public Instance Methods

!=(right) click to toggle source

Negation equality operator.

  • @param right an error object or an error code.

  • @return false for the both operands are equal, or true if not.

# File kyotocabinet.rb, line 139
def !=(right)
  # (native code)
end
==(right) click to toggle source

Equality operator.

  • @param right an error object or an error code.

  • @return true for the both operands are equal, or false if not.

# File kyotocabinet.rb, line 133
def ==(right)
  # (native code)
end
code() click to toggle source

Get the error code.

  • @return the error code.

# File kyotocabinet.rb, line 107
def code()
  # (native code)
end
inspect() click to toggle source

Get the inspection string.

  • @return the inspection string.

# File kyotocabinet.rb, line 127
def inspect()
  # (native code)
end
message() click to toggle source

Get the supplement message.

  • @return the supplement message.

# File kyotocabinet.rb, line 117
def message()
  # (native code)
end
name() click to toggle source

Get the readable string of the code.

  • @return the readable string of the code.

# File kyotocabinet.rb, line 112
def name()
  # (native code)
end
set(code, message) click to toggle source

Set the error information.

  • @param code the error code.

  • @param message the supplement message.

  • @return always nil.

# File kyotocabinet.rb, line 102
def set(code, message)
  # (native code)
end
to_s() click to toggle source

Get the string expression.

  • @return the string expression.

# File kyotocabinet.rb, line 122
def to_s()
  # (native code)
end

Generated with the Darkfish Rdoc Generator 2.

kyotocabinet-ruby-1.32/doc/KyotoCabinet/FileProcessor.html0000644000175000017500000001310611757456735022745 0ustar mikiomikio Class: KyotoCabinet::FileProcessor

KyotoCabinet::FileProcessor

Interface to process the database file.

Public Instance Methods

process(path, count, size) click to toggle source

Process the database file.

  • @param path the path of the database file.

  • @param count the number of records.

  • @param size the size of the available region.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 174
def process(path, count, size)
  # (native code)
end

Generated with the Darkfish Rdoc Generator 2.

kyotocabinet-ruby-1.32/doc/KyotoCabinet/Visitor.html0000644000175000017500000001641311757456735021631 0ustar mikiomikio Class: KyotoCabinet::Visitor

KyotoCabinet::Visitor

Interface to access a record.

Constants

NOP

magic data: no operation

REMOVE

magic data: remove the record

Public Instance Methods

visit_empty(key) click to toggle source

Visit a empty record space.

  • @param key the key.

  • @return If it is a string, the value is replaced by the content. If it is Visitor::NOP or Visitor::REMOVE, nothing is modified.

# File kyotocabinet.rb, line 161
def visit_empty(key)
  # (native code)
end
visit_full(key, value) click to toggle source

Visit a record.

  • @param key the key.

  • @param value the value.

  • @return If it is a string, the value is replaced by the content. If it is Visitor::NOP, nothing is modified. If it is Visitor::REMOVE, the record is removed.

# File kyotocabinet.rb, line 155
def visit_full(key, value)
  # (native code)
end

Generated with the Darkfish Rdoc Generator 2.

kyotocabinet-ruby-1.32/doc/KyotoCabinet/Cursor.html0000644000175000017500000006103711757456735021451 0ustar mikiomikio Class: KyotoCabinet::Cursor

KyotoCabinet::Cursor

Interface of cursor to indicate a record.

Public Instance Methods

accept(visitor, writable = true, step = false) click to toggle source

Accept a visitor to the current record.

  • @param visitor a visitor object which implements the Visitor interface. If it is omitted, the block parameter is evaluated.

  • @param writable true for writable operation, or false for read-only operation.

  • @param step true to move the cursor to the next record, or false for no move.

  • @block If it is specified, the block is called as the visitor.

  • @return true on success, or false on failure.

  • @note The operation for each record is performed atomically and other threads accessing the same record are blocked. To avoid deadlock, any explicit database operation must not be performed in this method.

# File kyotocabinet.rb, line 195
def accept(visitor, writable = true, step = false)
  # (native code)
end
db() click to toggle source

Get the database object.

  • @return the database object.

# File kyotocabinet.rb, line 264
def db()
  # (native code)
end
disable() click to toggle source

Disable the cursor.

  • @return always nil.

  • @note This method should be called explicitly when the cursor is no longer in use.

# File kyotocabinet.rb, line 185
def disable()
  # (native code)
end
error() click to toggle source

Get the last happened error.

  • @return the last happened error.

# File kyotocabinet.rb, line 269
def error()
  # (native code)
end
get(step = false) click to toggle source

Get a pair of the key and the value of the current record.

  • @param step true to move the cursor to the next record, or false for no move.

  • @return a pair of the key and the value of the current record, or nil on failure.

  • @note If the cursor is invalidated, nil is returned.

# File kyotocabinet.rb, line 229
def get(step = false)
  # (native code)
end
get_key(step = false) click to toggle source

Get the key of the current record.

  • @param step true to move the cursor to the next record, or false for no move.

  • @return the key of the current record, or nil on failure.

  • @note If the cursor is invalidated, nil is returned.

# File kyotocabinet.rb, line 215
def get_key(step = false)
  # (native code)
end
get_value(step = false) click to toggle source

Get the value of the current record.

  • @param step true to move the cursor to the next record, or false for no move.

  • @return the value of the current record, or nil on failure.

  • @note If the cursor is invalidated, nil is returned.

# File kyotocabinet.rb, line 222
def get_value(step = false)
  # (native code)
end
inspect() click to toggle source

Get the inspection string.

  • @return the inspection string.

# File kyotocabinet.rb, line 279
def inspect()
  # (native code)
end
jump(key = nil) click to toggle source

Jump the cursor to a record for forward scan.

  • @param key the key of the destination record. If it is nil, the destination is the first record.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 241
def jump(key = nil)
  # (native code)
end
jump_back(key = nil) click to toggle source

Jump the cursor to a record for backward scan.

  • @param key the key of the destination record. If it is nil, the destination is the last record.

  • @return true on success, or false on failure.

  • @note This method is dedicated to tree databases. Some database types, especially hash databases, will provide a dummy implementation.

# File kyotocabinet.rb, line 248
def jump_back(key = nil)
  # (native code)
end
remove() click to toggle source

Remove the current record.

  • @return true on success, or false on failure.

  • @note If no record corresponds to the key, false is returned. The cursor is moved to the next record implicitly.

# File kyotocabinet.rb, line 208
def remove()
  # (native code)
end
seize() click to toggle source

Get a pair of the key and the value of the current record and remove it atomically.

  • @return a pair of the key and the value of the current record, or nil on failure.

  • @note If the cursor is invalidated, nil is returned. The cursor is moved to the next record implicitly.

# File kyotocabinet.rb, line 235
def seize()
  # (native code)
end
set_value(value, step = false) click to toggle source

Set the value of the current record.

  • @param value the value.

  • @param step true to move the cursor to the next record, or false for no move.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 202
def set_value(value, step = false)
  # (native code)
end
step() click to toggle source

Step the cursor to the next record.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 253
def step()
  # (native code)
end
step_back() click to toggle source

Step the cursor to the previous record.

  • @return true on success, or false on failure.

  • @note This method is dedicated to tree databases. Some database types, especially hash databases, may provide a dummy implementation.

# File kyotocabinet.rb, line 259
def step_back()
  # (native code)
end
to_s() click to toggle source

Get the string expression.

  • @return the string expression.

# File kyotocabinet.rb, line 274
def to_s()
  # (native code)
end

Generated with the Darkfish Rdoc Generator 2.

kyotocabinet-ruby-1.32/doc/KyotoCabinet/DB.html0000644000175000017500000025476011757456735020470 0ustar mikiomikio Class: KyotoCabinet::DB

KyotoCabinet::DB

Interface of database abstraction.

Constants

GCONCURRENT

generic mode: concurrent mode

GEXCEPTIONAL

generic mode: exceptional mode

MADD

merge mode: keep the existing value

MAPPEND

merge mode: append the new value

MREPLACE

merge mode: modify the existing record only

MSET

merge mode: overwrite the existing value

OAUTOSYNC

open mode: auto synchronization

OAUTOTRAN

open mode: auto transaction

OCREATE

open mode: writer creating

ONOLOCK

open mode: open without locking

ONOREPAIR

open mode: open without auto repair

OREADER

open mode: open as a reader

OTRUNCATE

open mode: writer truncating

OTRYLOCK

open mode: lock without blocking

OWRITER

open mode: open as a writer

Public Class Methods

new(opts = 0) click to toggle source

Create a database object.

  • @param opts the optional features by bitwise-or: DB::GEXCEPTIONAL for the exceptional mode, DB::GCONCURRENT for the concurrent mode.

  • @return the database object.

  • @note The exceptional mode means that fatal errors caused by methods are reported by exceptions raised. The concurrent mode means that database operations by multiple threads are performed concurrently without the giant VM lock. However, it has a side effect that such methods with call back of Ruby code as DB#accept, DB#accept_bulk, DB#iterate, DB#each, DB#each_key, DB#each_value, Cursor#accept are disabled.

# File kyotocabinet.rb, line 321
def initialize(opts = 0)
  # (native code)
end
process(path = "*", mode = DB::OWRITER | DB::OCREATE, opts = 0) click to toggle source

Process a database by the block parameter.

  • @param path the same to the one of the open method.

  • @param mode the same to the one of the open method.

  • @param opts the optional features by bitwise-or: DB::GCONCURRENT for the concurrent mode.

  • @block a block including operations for the database. The block receives the database object. The database is opened with the given parameters before the block and is closed implicitly after the block.

  • @return nil on success, or an error object on failure.

# File kyotocabinet.rb, line 670
def DB.process(path = "*", mode = DB::OWRITER | DB::OCREATE, opts = 0)
  # (native code)
end

Public Instance Methods

[](key) click to toggle source

An alias of DB#get.

# File kyotocabinet.rb, line 618
def [](key)
  # (native code)
end
[]=(key, value) click to toggle source

An alias of DB#store.

# File kyotocabinet.rb, line 622
def []=(key, value)
  # (native code)
end
accept(key, visitor = nil, writable = true) click to toggle source

Accept a visitor to a record.

  • @param key the key.

  • @param visitor a visitor object which implements the Visitor interface. If it is omitted, the block parameter is evaluated.

  • @param writable true for writable operation, or false for read-only operation.

  • @block If it is specified, the block is called as the visitor.

  • @return true on success, or false on failure.

  • @note The operation for each record is performed atomically and other threads accessing the same record are blocked. To avoid deadlock, any explicit database operation must not be performed in this method.

# File kyotocabinet.rb, line 349
def accept(key, visitor = nil, writable = true)
  # (native code)
end
accept_bulk(keys, visitor = nil, writable = true) click to toggle source

Accept a visitor to multiple records at once.

  • @param keys specifies an array of the keys.

  • @param visitor a visitor object which implements the Visitor interface, or a function object which receives the key and the value.

  • @param writable true for writable operation, or false for read-only operation.

  • @return true on success, or false on failure.

  • @note The operations for specified records are performed atomically and other threads accessing the same records are blocked. To avoid deadlock, any explicit database operation must not be performed in this method.

# File kyotocabinet.rb, line 358
def accept_bulk(keys, visitor = nil, writable = true)
  # (native code)
end
add(key, value) click to toggle source

Add a record.

  • @param key the key.

  • @param value the value.

  • @return true on success, or false on failure.

  • @note If no record corresponds to the key, a new record is created. If the corresponding record exists, the record is not modified and false is returned.

# File kyotocabinet.rb, line 383
def add(key, value)
  # (native code)
end
append(key, value) click to toggle source

Append the value of a record.

  • @param key the key.

  • @param value the value.

  • @return true on success, or false on failure.

  • @note If no record corresponds to the key, a new record is created. If the corresponding record exists, the given value is appended at the end of the existing value.

# File kyotocabinet.rb, line 399
def append(key, value)
  # (native code)
end
begin_transaction(hard = false) click to toggle source

Begin transaction.

  • @param hard true for physical synchronization with the device, or false for logical synchronization with the file system.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 505
def begin_transaction(hard = false)
  # (native code)
end
cas(key, oval, nval) click to toggle source

Perform compare-and-swap.

  • @param key the key.

  • @param oval the old value. nil means that no record corresponds.

  • @param nval the new value. nil means that the record is removed.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 425
def cas(key, oval, nval)
  # (native code)
end
check(key) click to toggle source

Check the existence of a record.

  • @param key the key.

  • @return the size of the value, or -1 on failure.

# File kyotocabinet.rb, line 444
def check(key)
  # (native code)
end
clear() click to toggle source

Remove all records.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 476
def clear()
  # (native code)
end
close() click to toggle source

Close the database file.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 339
def close()
  # (native code)
end
copy(dest) click to toggle source

Create a copy of the database file.

  • @param dest the path of the destination file.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 499
def copy(dest)
  # (native code)
end
count() click to toggle source

Get the number of records.

  • @return the number of records, or -1 on failure.

# File kyotocabinet.rb, line 535
def count()
  # (native code)
end
cursor() click to toggle source

Create a cursor object.

  • @return the return value is the created cursor object. Each cursor should be disabled with the Cursor#disable method when it is no longer in use.

# File kyotocabinet.rb, line 585
def cursor()
  # (native code)
end
cursor_process() click to toggle source

Process a cursor by the block parameter.

  • @block a block including operations for the cursor. The cursor is disabled implicitly after the block.

  • @return always nil.

# File kyotocabinet.rb, line 591
def cursor_process()
  # (native code)
end
delete(key, value) click to toggle source

An alias of DB#remove.

# File kyotocabinet.rb, line 630
def delete(key, value)
  # (native code)
end
dump_snapshot(dest) click to toggle source

Dump records into a snapshot file.

  • @param dest the name of the destination file.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 524
def dump_snapshot(dest)
  # (native code)
end
each() click to toggle source

Process each records with a iterator block.

  • @block the iterator to receive the key and the value of each record.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 649
def each()
  # (native code)
end
each_key() click to toggle source

Process the key of each record with a iterator block.

  • @block the iterator to receive the key of each record.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 655
def each_key()
  # (native code)
end
each_value() click to toggle source

Process the value of each record with a iterator block.

  • @block the iterator to receive the value of each record.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 661
def each_value()
  # (native code)
end
end_transaction(commit = true) click to toggle source

End transaction.

  • @param commit true to commit the transaction, or false to abort the transaction.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 511
def end_transaction(commit = true)
  # (native code)
end
error() click to toggle source

Get the last happened error.

  • @return the last happened error.

# File kyotocabinet.rb, line 326
def error()
  # (native code)
end
fetch(key, value) click to toggle source

An alias of DB#get.

# File kyotocabinet.rb, line 634
def fetch(key, value)
  # (native code)
end
get(key) click to toggle source

Retrieve the value of a record.

  • @param key the key.

  • @return the value of the corresponding record, or nil on failure.

# File kyotocabinet.rb, line 438
def get(key)
  # (native code)
end
get_bulk(keys, atomic = true) click to toggle source

Retrieve records at once.

  • @param keys an array of the keys of the records to retrieve.

  • @param atomic true to perform all operations atomically, or false for non-atomic operations.

  • @return a hash of retrieved records, or nil on failure.

# File kyotocabinet.rb, line 471
def get_bulk(keys, atomic = true)
  # (native code)
end
increment(key, num = 0, orig = 0) click to toggle source

Add a number to the numeric integer value of a record.

  • @param key the key.

  • @param num the additional number.

  • @param orig the origin number if no record corresponds to the key. If it is negative infinity and no record corresponds, this method fails. If it is positive infinity, the value is set as the additional number regardless of the current value.

  • @return the result value, or nil on failure.

  • @note The value is serialized as an 8-byte binary integer in big-endian order, not a decimal string. If existing value is not 8-byte, this method fails.

# File kyotocabinet.rb, line 408
def increment(key, num = 0, orig = 0)
  # (native code)
end
increment_double(key, num = 0, orig = 0) click to toggle source

Add a number to the numeric double value of a record.

  • @param key the key.

  • @param num the additional number.

  • @param orig the origin number if no record corresponds to the key. If it is negative infinity and no record corresponds, this method fails. If it is positive infinity, the value is set as the additional number regardless of the current value.

  • @return the result value, or nil on failure.

  • @note The value is serialized as an 16-byte binary fixed-point number in big-endian order, not a decimal string. If existing value is not 16-byte, this method fails.

# File kyotocabinet.rb, line 417
def increment_double(key, num = 0, orig = 0)
  # (native code)
end
inspect() click to toggle source

Get the inspection string.

  • @return the inspection string.

# File kyotocabinet.rb, line 614
def inspect()
  # (native code)
end
iterate(visitor, writable = true) click to toggle source

Iterate to accept a visitor for each record.

  • @param visitor a visitor object which implements the Visitor interface. If it is omitted, the block parameter is evaluated.

  • @param writable true for writable operation, or false for read-only operation.

  • @block If it is specified, the block is called as the visitor.

  • @return true on success, or false on failure.

  • @note The whole iteration is performed atomically and other threads are blocked. To avoid deadlock, any explicit database operation must not be performed in this method.

# File kyotocabinet.rb, line 367
def iterate(visitor, writable = true)
  # (native code)
end
length() click to toggle source

An alias of DB#count.

# File kyotocabinet.rb, line 643
def length()
  # (native code)
end
load_snapshot(src) click to toggle source

Load records from a snapshot file.

  • @param src the name of the source file.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 530
def load_snapshot(src)
  # (native code)
end
match_prefix(prefix, max = -1) click to toggle source

Get keys matching a prefix string.

  • @param prefix the prefix string.

  • @param max the maximum number to retrieve. If it is negative, no limit is specified.

  • @return an array of matching keys, or nil on failure.

# File kyotocabinet.rb, line 557
def match_prefix(prefix, max = -1)
  # (native code)
end
match_regex(regex, max = -1) click to toggle source

Get keys matching a regular expression string.

  • @param regex the regular expression string.

  • @param max the maximum number to retrieve. If it is negative, no limit is specified.

  • @return an array of matching keys, or nil on failure.

# File kyotocabinet.rb, line 564
def match_regex(regex, max = -1)
  # (native code)
end
match_similar(origin, range = 1, utf = false, max = -1) click to toggle source

Get keys similar to a string in terms of the levenshtein distance.

  • @param origin the origin string.

  • @param range the maximum distance of keys to adopt.

  • @param utf flag to treat keys as UTF-8 strings.

  • @param max the maximum number to retrieve. If it is negative, no limit is specified.

  • @return an array of matching keys, or nil on failure.

# File kyotocabinet.rb, line 573
def match_similar(origin, range = 1, utf = false, max = -1)
  # (native code)
end
merge(srcary, mode = DB::MSET) click to toggle source

Merge records from other databases.

  • @param srcary an array of the source detabase objects.

  • @param mode the merge mode. DB::MSET to overwrite the existing value, DB::MADD to keep the existing value, DB::MAPPEND to append the new value.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 580
def merge(srcary, mode = DB::MSET)
  # (native code)
end
occupy(writable = false, proc = nil) click to toggle source

Occupy database by locking and do something meanwhile.

  • @param writable true to use writer lock, or false to use reader lock.

  • @param proc a processor object which implements the FileProcessor interface. If it is nil, no processing is performed.

  • @return true on success, or false on failure.

  • @note The operation of the processor is performed atomically and other threads accessing the same record are blocked. To avoid deadlock, any explicit database operation must not be performed in this method.

# File kyotocabinet.rb, line 493
def occupy(writable = false, proc = nil)
  # (native code)
end
open(path = ":", mode = DB::OWRITER | DB::OCREATE) click to toggle source

Open a database file.

  • @param path the path of a database file. If it is "-", the database will be a prototype hash database. If it is "+", the database will be a prototype tree database. If it is ":", the database will be a stash database. If it is "*", the database will be a cache hash database. If it is "%", the database will be a cache tree database. If its suffix is ".kch", the database will be a file hash database. If its suffix is ".kct", the database will be a file tree database. If its suffix is ".kcd", the database will be a directory hash database. If its suffix is ".kcf", the database will be a directory tree database. If its suffix is ".kcx", the database will be a plain text database. Otherwise, this function fails. Tuning parameters can trail the name, separated by "#". Each parameter is composed of the name and the value, separated by "=". If the "type" parameter is specified, the database type is determined by the value in "-", "+", ":", "*", "%", "kch", "kct", "kcd", kcf", and "kcx". All database types support the logging parameters of "log", "logkinds", and "logpx". The prototype hash database and the prototype tree database do not support any other tuning parameter. The stash database supports "bnum". The cache hash database supports "opts", "bnum", "zcomp", "capcnt", "capsiz", and "zkey". The cache tree database supports all parameters of the cache hash database except for capacity limitation, and supports "psiz", "rcomp", "pccap" in addition. The file hash database supports "apow", "fpow", "opts", "bnum", "msiz", "dfunit", "zcomp", and "zkey". The file tree database supports all parameters of the file hash database and "psiz", "rcomp", "pccap" in addition. The directory hash database supports "opts", "zcomp", and "zkey". The directory tree database supports all parameters of the directory hash database and "psiz", "rcomp", "pccap" in addition. The plain text database does not support any other tuning parameter.

  • @param mode the connection mode. DB::OWRITER as a writer, DB::OREADER as a reader. The following may be added to the writer mode by bitwise-or: DB::OCREATE, which means it creates a new database if the file does not exist, DB::OTRUNCATE, which means it creates a new database regardless if the file exists, DB::OAUTOTRAN, which means each updating operation is performed in implicit transaction, DB::OAUTOSYNC, which means each updating operation is followed by implicit synchronization with the file system. The following may be added to both of the reader mode and the writer mode by bitwise-or: DB::ONOLOCK, which means it opens the database file without file locking, DB::OTRYLOCK, which means locking is performed without blocking, DB::ONOREPAIR, which means the database file is not repaired implicitly even if file destruction is detected.

  • @return true on success, or false on failure.

  • @note The tuning parameter "log" is for the original "tune_logger" and the value specifies the path of the log file, or "-" for the standard output, or "+" for the standard error. "logkinds" specifies kinds of logged messages and the value can be "debug", "info", "warn", or "error". "logpx" specifies the prefix of each log message. "opts" is for "tune_options" and the value can contain "s" for the small option, "l" for the linear option, and "c" for the compress option. "bnum" corresponds to "tune_bucket". "zcomp" is for "tune_compressor" and the value can be "zlib" for the ZLIB raw compressor, "def" for the ZLIB deflate compressor, "gz" for the ZLIB gzip compressor, "lzo" for the LZO compressor, "lzma" for the LZMA compressor, or "arc" for the Arcfour cipher. "zkey" specifies the cipher key of the compressor. "capcnt" is for "cap_count". "capsiz" is for "cap_size". "psiz" is for "tune_page". "rcomp" is for "tune_comparator" and the value can be "lex" for the lexical comparator, "dec" for the decimal comparator, "lexdesc" for the lexical descending comparator, or "decdesc" for the decimal descending comparator. "pccap" is for "tune_page_cache". "apow" is for "tune_alignment". "fpow" is for "tune_fbp". "msiz" is for "tune_map". "dfunit" is for "tune_defrag". Every opened database must be closed by the PolyDB::close method when it is no longer in use. It is not allowed for two or more database objects in the same process to keep their connections to the same database file at the same time.

# File kyotocabinet.rb, line 334
def open(path = ":", mode = DB::OWRITER | DB::OCREATE)
  # (native code)
end
path() click to toggle source

Get the path of the database file.

  • @return the path of the database file, or nil on failure.

# File kyotocabinet.rb, line 545
def path()
  # (native code)
end
remove(key) click to toggle source

Remove a record.

  • @param key the key.

  • @return true on success, or false on failure.

  • @note If no record corresponds to the key, false is returned.

# File kyotocabinet.rb, line 432
def remove(key)
  # (native code)
end
remove_bulk(keys, atomic = true) click to toggle source

Remove records at once.

  • @param keys an array of the keys of the records to remove.

  • @param atomic true to perform all operations atomically, or false for non-atomic operations.

  • @return the number of removed records, or -1 on failure.

# File kyotocabinet.rb, line 464
def remove_bulk(keys, atomic = true)
  # (native code)
end
replace(key, value) click to toggle source

Replace the value of a record.

  • @param key the key.

  • @param value the value.

  • @return true on success, or false on failure.

  • @note If no record corresponds to the key, no new record is created and false is returned. If the corresponding record exists, the value is modified.

# File kyotocabinet.rb, line 391
def replace(key, value)
  # (native code)
end
seize(key) click to toggle source

Retrieve the value of a record and remove it atomically.

  • @param key the key.

  • @return the value of the corresponding record, or nil on failure.

# File kyotocabinet.rb, line 450
def seize(key)
  # (native code)
end
set(key, value) click to toggle source

Set the value of a record.

  • @param key the key.

  • @param value the value.

  • @return true on success, or false on failure.

  • @note If no record corresponds to the key, a new record is created. If the corresponding record exists, the value is overwritten.

# File kyotocabinet.rb, line 375
def set(key, value)
  # (native code)
end
set_bulk(recs, atomic = true) click to toggle source

Store records at once.

  • @param recs a hash of the records to store.

  • @param atomic true to perform all operations atomically, or false for non-atomic operations.

  • @return the number of stored records, or -1 on failure.

# File kyotocabinet.rb, line 457
def set_bulk(recs, atomic = true)
  # (native code)
end
shift() click to toggle source

Remove the first record.

  • @return a pair of the key and the value of the removed record, or nil on failure.

# File kyotocabinet.rb, line 639
def shift()
  # (native code)
end
size() click to toggle source

Get the size of the database file.

  • @return the size of the database file in bytes, or -1 on failure.

# File kyotocabinet.rb, line 540
def size()
  # (native code)
end
status() click to toggle source

Get the miscellaneous status information.

  • @return a hash of the status information, or nil on failure.

# File kyotocabinet.rb, line 550
def status()
  # (native code)
end
store(key, value) click to toggle source

An alias of DB#store.

# File kyotocabinet.rb, line 626
def store(key, value)
  # (native code)
end
synchronize(hard = false, proc = nil) click to toggle source

Synchronize updated contents with the file and the device.

  • @param hard true for physical synchronization with the device, or false for logical synchronization with the file system.

  • @param proc a postprocessor object which implements the FileProcessor interface. If it is nil, no postprocessing is performed.

  • @block If it is specified, the block is called for postprocessing.

  • @return true on success, or false on failure.

  • @note The operation of the processor is performed atomically and other threads accessing the same record are blocked. To avoid deadlock, any explicit database operation must not be performed in this method.

# File kyotocabinet.rb, line 485
def synchronize(hard = false, proc = nil)
  # (native code)
end
to_s() click to toggle source

Get the string expression.

  • @return the string expression.

# File kyotocabinet.rb, line 609
def to_s()
  # (native code)
end
transaction(hard = false) click to toggle source

Perform entire transaction by the block parameter.

  • @param hard true for physical synchronization with the device, or false for logical synchronization with the file system.

  • @block a block including operations during transaction. If the block returns true, the transaction is committed. If the block returns false or an exception is thrown, the transaction is aborted.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 518
def transaction(hard = false)
  # (native code)
end
tune_encoding(enc) click to toggle source

Set the encoding of external strings.

  • @param enc the name of the encoding or its encoding object.

  • @note The default encoding of external strings is Encoding::ASCII_8BIT.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 604
def tune_encoding(enc)
  # (native code)
end
tune_exception_rule(codes) click to toggle source

Set the rule about throwing exception.

  • @param codes an array of error codes. If each method occurs an error corresponding to one of the specified codes, the error is thrown as an exception.

  • @return true on success, or false on failure.

# File kyotocabinet.rb, line 597
def tune_exception_rule(codes)
  # (native code)
end

Generated with the Darkfish Rdoc Generator 2.

kyotocabinet-ruby-1.32/doc/js/0000755000175000017500000000000011757456735015320 5ustar mikiomikiokyotocabinet-ruby-1.32/doc/js/darkfish.js0000644000175000017500000000616711757456735017463 0ustar mikiomikio/** * * Darkfish Page Functions * $Id: darkfish.js 53 2009-01-07 02:52:03Z deveiant $ * * Author: Michael Granger * */ /* Provide console simulation for firebug-less environments */ if (!("console" in window) || !("firebug" in console)) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}; }; /** * Unwrap the first element that matches the given @expr@ from the targets and return them. */ $.fn.unwrap = function( expr ) { return this.each( function() { $(this).parents( expr ).eq( 0 ).after( this ).remove(); }); }; function showSource( e ) { var target = e.target; var codeSections = $(target). parents('.method-detail'). find('.method-source-code'); $(target). parents('.method-detail'). find('.method-source-code'). slideToggle(); }; function hookSourceViews() { $('.method-description,.method-heading').click( showSource ); }; function toggleDebuggingSection() { $('.debugging-section').slideToggle(); }; function hookDebuggingToggle() { $('#debugging-toggle img').click( toggleDebuggingSection ); }; function hookQuickSearch() { $('.quicksearch-field').each( function() { var searchElems = $(this).parents('.section').find( 'li' ); var toggle = $(this).parents('.section').find('h3 .search-toggle'); // console.debug( "Toggle is: %o", toggle ); var qsbox = $(this).parents('form').get( 0 ); $(this).quicksearch( this, searchElems, { noSearchResultsIndicator: 'no-class-search-results', focusOnLoad: false }); $(toggle).click( function() { // console.debug( "Toggling qsbox: %o", qsbox ); $(qsbox).toggle(); }); }); }; function highlightTarget( anchor ) { console.debug( "Highlighting target '%s'.", anchor ); $("a[name=" + anchor + "]").each( function() { if ( !$(this).parent().parent().hasClass('target-section') ) { console.debug( "Wrapping the target-section" ); $('div.method-detail').unwrap( 'div.target-section' ); $(this).parent().wrap( '
' ); } else { console.debug( "Already wrapped." ); } }); }; function highlightLocationTarget() { console.debug( "Location hash: %s", window.location.hash ); if ( ! window.location.hash || window.location.hash.length == 0 ) return; var anchor = window.location.hash.substring(1); console.debug( "Found anchor: %s; matching %s", anchor, "a[name=" + anchor + "]" ); highlightTarget( anchor ); }; function highlightClickTarget( event ) { console.debug( "Highlighting click target for event %o", event.target ); try { var anchor = $(event.target).attr( 'href' ).substring(1); console.debug( "Found target anchor: %s", anchor ); highlightTarget( anchor ); } catch ( err ) { console.error( "Exception while highlighting: %o", err ); }; }; $(document).ready( function() { hookSourceViews(); hookDebuggingToggle(); hookQuickSearch(); highlightLocationTarget(); $('ul.link-list a').bind( "click", highlightClickTarget ); }); kyotocabinet-ruby-1.32/doc/js/jquery.js0000644000175000017500000015473411757456735017213 0ustar mikiomikio/* * jQuery 1.2.6 - New Wave Javascript * * Copyright (c) 2008 John Resig (jquery.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Date: 2008-09-25 09:50:52 -0700 (Thu, 25 Sep 2008) $ * $Rev: 38 $ */ (function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("",""]||!tags.indexOf("",""]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!tags.indexOf("",""]||(!tags.indexOf("",""]||!tags.indexOf("",""]||jQuery.browser.msie&&[1,"div
","
"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf(""&&tags.indexOf("=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&¬xml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&¬xml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&¬xml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set)elem[name]=value;return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return im[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("
").append(res.responseText.replace(//g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;ithis.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();kyotocabinet-ruby-1.32/doc/js/quicksearch.js0000644000175000017500000000504011757456735020157 0ustar mikiomikio/** * * JQuery QuickSearch - Hook up a form field to hide non-matching elements. * $Id: quicksearch.js 53 2009-01-07 02:52:03Z deveiant $ * * Author: Michael Granger * */ jQuery.fn.quicksearch = function( target, searchElems, options ) { // console.debug( "Quicksearch fn" ); var settings = { delay: 250, clearButton: false, highlightMatches: false, focusOnLoad: false, noSearchResultsIndicator: null }; if ( options ) $.extend( settings, options ); return jQuery(this).each( function() { // console.debug( "Creating a new quicksearch on %o for %o", this, searchElems ); new jQuery.quicksearch( this, searchElems, settings ); }); }; jQuery.quicksearch = function( searchBox, searchElems, settings ) { var timeout; var boxdiv = $(searchBox).parents('div').eq(0); function init() { setupKeyEventHandlers(); focusOnLoad(); }; function setupKeyEventHandlers() { // console.debug( "Hooking up the 'keypress' event to %o", searchBox ); $(searchBox). unbind( 'keyup' ). keyup( function(e) { return onSearchKey( e.keyCode ); }); $(searchBox). unbind( 'keypress' ). keypress( function(e) { switch( e.which ) { // Execute the search on Enter, Tab, or Newline case 9: case 13: case 10: clearTimeout( timeout ); e.preventDefault(); doQuickSearch(); break; // Allow backspace case 8: return true; break; // Only allow valid search characters default: return validQSChar( e.charCode ); } }); }; function focusOnLoad() { if ( !settings.focusOnLoad ) return false; $(searchBox).focus(); }; function onSearchKey ( code ) { clearTimeout( timeout ); // console.debug( "...scheduling search." ); timeout = setTimeout( doQuickSearch, settings.delay ); }; function validQSChar( code ) { var c = String.fromCharCode( code ); return ( (c == ':') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ); }; function doQuickSearch() { var searchText = searchBox.value; var pat = new RegExp( searchText, "im" ); var shownCount = 0; if ( settings.noSearchResultsIndicator ) { $('#' + settings.noSearchResultsIndicator).hide(); } // All elements start out hidden $(searchElems).each( function(index) { var str = $(this).text(); if ( pat.test(str) ) { shownCount += 1; $(this).fadeIn(); } else { $(this).hide(); } }); if ( shownCount == 0 && settings.noSearchResultsIndicator ) { $('#' + settings.noSearchResultsIndicator).slideDown(); } }; init(); }; kyotocabinet-ruby-1.32/doc/js/thickbox-compressed.js0000644000175000017500000001353211757456735021637 0ustar mikiomikio/* * Thickbox 3 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ var tb_pathToImage = "../images/loadingAnimation.gif"; eval(function(p,a,c,k,e,r){e=function(c){return(c35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('$(o).2S(9(){1u(\'a.18, 3n.18, 3i.18\');1w=1p 1t();1w.L=2H});9 1u(b){$(b).s(9(){6 t=X.Q||X.1v||M;6 a=X.u||X.23;6 g=X.1N||P;19(t,a,g);X.2E();H P})}9 19(d,f,g){3m{3(2t o.v.J.2i==="2g"){$("v","11").r({A:"28%",z:"28%"});$("11").r("22","2Z");3(o.1Y("1F")===M){$("v").q("<4 5=\'B\'><4 5=\'8\'>");$("#B").s(G)}}n{3(o.1Y("B")===M){$("v").q("<4 5=\'B\'><4 5=\'8\'>");$("#B").s(G)}}3(1K()){$("#B").1J("2B")}n{$("#B").1J("2z")}3(d===M){d=""}$("v").q("<4 5=\'K\'><1I L=\'"+1w.L+"\' />");$(\'#K\').2y();6 h;3(f.O("?")!==-1){h=f.3l(0,f.O("?"))}n{h=f}6 i=/\\.2s$|\\.2q$|\\.2m$|\\.2l$|\\.2k$/;6 j=h.1C().2h(i);3(j==\'.2s\'||j==\'.2q\'||j==\'.2m\'||j==\'.2l\'||j==\'.2k\'){1D="";1G="";14="";1z="";1x="";R="";1n="";1r=P;3(g){E=$("a[@1N="+g+"]").36();25(D=0;((D&1d;&1d;2T &2R;"}n{1D=E[D].Q;1G=E[D].u;14="<1e 5=\'1U\'>&1d;&1d;&2O; 2N"}}n{1r=1b;1n="1t "+(D+1)+" 2L "+(E.1c)}}}S=1p 1t();S.1g=9(){S.1g=M;6 a=2x();6 x=a[0]-1M;6 y=a[1]-1M;6 b=S.z;6 c=S.A;3(b>x){c=c*(x/b);b=x;3(c>y){b=b*(y/c);c=y}}n 3(c>y){b=b*(y/c);c=y;3(b>x){c=c*(x/b);b=x}}13=b+30;1a=c+2G;$("#8").q("<1I 5=\'2F\' L=\'"+f+"\' z=\'"+b+"\' A=\'"+c+"\' 23=\'"+d+"\'/>"+"<4 5=\'2D\'>"+d+"<4 5=\'2C\'>"+1n+14+R+"<4 5=\'2A\'>1l 1k 1j 1s");$("#Z").s(G);3(!(14==="")){9 12(){3($(o).N("s",12)){$(o).N("s",12)}$("#8").C();$("v").q("<4 5=\'8\'>");19(1D,1G,g);H P}$("#1U").s(12)}3(!(R==="")){9 1i(){$("#8").C();$("v").q("<4 5=\'8\'>");19(1z,1x,g);H P}$("#1X").s(1i)}o.1h=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}n 3(I==3k){3(!(R=="")){o.1h="";1i()}}n 3(I==3j){3(!(14=="")){o.1h="";12()}}};16();$("#K").C();$("#1L").s(G);$("#8").r({Y:"T"})};S.L=f}n{6 l=f.2r(/^[^\\?]+\\??/,\'\');6 m=2p(l);13=(m[\'z\']*1)+30||3h;1a=(m[\'A\']*1)+3g||3f;W=13-30;V=1a-3e;3(f.O(\'2j\')!=-1){1E=f.1B(\'3d\');$("#15").C();3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"<4 5=\'2e\'>1l 1k 1j 1s ")}n{$("#B").N();$("#8").q(" ")}}n{3($("#8").r("Y")!="T"){3(m[\'1A\']!="1b"){$("#8").q("<4 5=\'2f\'><4 5=\'1H\'>"+d+"<4 5=\'2e\'>1l 1k 1j 1s<4 5=\'F\' J=\'z:"+W+"p;A:"+V+"p\'>")}n{$("#B").N();$("#8").q("<4 5=\'F\' 3c=\'3b\' J=\'z:"+W+"p;A:"+V+"p;\'>")}}n{$("#F")[0].J.z=W+"p";$("#F")[0].J.A=V+"p";$("#F")[0].3a=0;$("#1H").11(d)}}$("#Z").s(G);3(f.O(\'37\')!=-1){$("#F").q($(\'#\'+m[\'26\']).1T());$("#8").24(9(){$(\'#\'+m[\'26\']).q($("#F").1T())});16();$("#K").C();$("#8").r({Y:"T"})}n 3(f.O(\'2j\')!=-1){16();3($.1q.35){$("#K").C();$("#8").r({Y:"T"})}}n{$("#F").34(f+="&1y="+(1p 33().32()),9(){16();$("#K").C();1u("#F a.18");$("#8").r({Y:"T"})})}}3(!m[\'1A\']){o.21=9(e){3(e==M){I=2w.2v}n{I=e.2u}3(I==27){G()}}}}31(e){}}9 1m(){$("#K").C();$("#8").r({Y:"T"})}9 G(){$("#2Y").N("s");$("#Z").N("s");$("#8").2X("2W",9(){$(\'#8,#B,#1F\').2V("24").N().C()});$("#K").C();3(2t o.v.J.2i=="2g"){$("v","11").r({A:"1Z",z:"1Z"});$("11").r("22","")}o.1h="";o.21="";H P}9 16(){$("#8").r({2U:\'-\'+20((13/2),10)+\'p\',z:13+\'p\'});3(!(1V.1q.2Q&&1V.1q.2P<7)){$("#8").r({38:\'-\'+20((1a/2),10)+\'p\'})}}9 2p(a){6 b={};3(!a){H b}6 c=a.1B(/[;&]/);25(6 i=0;i/dev/null`.chomp kcldflags = `kcutilmgr conf -l 2>/dev/null`.chomp kcldflags = kcldflags.gsub(/-l[\S]+/, "").strip kclibs = `kcutilmgr conf -l 2>/dev/null`.chomp kclibs = kclibs.gsub(/-L[\S]+/, "").strip kccflags = "-I/usr/local/include" if(kccflags.length < 1) kcldflags = "-L/usr/local/lib" if(kcldflags.length < 1) kclibs = "-lkyotocabinet -lz -lstdc++ -lrt -lpthread -lm -lc" if(kclibs.length < 1) Config::CONFIG["CPP"] = "g++ -E" $CFLAGS = "-I. #{kccflags} -Wall #{$CFLAGS} -O2" $LDFLAGS = "#{$LDFLAGS} -L. #{kcldflags}" $libs = "#{$libs} #{kclibs}" printf("setting variables ...\n") printf(" \$CFLAGS = %s\n", $CFLAGS) printf(" \$LDFLAGS = %s\n", $LDFLAGS) printf(" \$libs = %s\n", $libs) if have_header('kccommon.h') create_makefile('kyotocabinet') end