kyotocabinet-ruby-1.34/ 0000755 0001750 0001750 00000000000 13705221536 014121 5 ustar mikio mikio kyotocabinet-ruby-1.34/test.rb 0000755 0001750 0001750 00000003211 13365375620 015433 0 ustar mikio mikio #! /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 = RbConfig::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.34/COPYING 0000644 0001750 0001750 00000104513 11350435302 015150 0 ustar mikio mikio 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.34/MANIFEST 0000644 0001750 0001750 00000000205 11375735744 015263 0 ustar mikio mikio MANIFEST
extconf.rb
kyotocabinet.cc
kyotocabinet-doc.rb
kctest.rb
test.rb
makedoc.rb
makedist.sh
kyotocabinet.gemspec
COPYING
README
kyotocabinet-ruby-1.34/example/ 0000755 0001750 0001750 00000000000 11425314640 015550 5 ustar mikio mikio kyotocabinet-ruby-1.34/example/kcdbex2.rb 0000644 0001750 0001750 00000001634 11370205614 017422 0 ustar mikio mikio 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
kyotocabinet-ruby-1.34/example/kcdbex1.rb 0000644 0001750 0001750 00000001305 11370203455 017415 0 ustar mikio mikio 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
kyotocabinet-ruby-1.34/example/kcdbex3.rb 0000644 0001750 0001750 00000001664 11372731466 017441 0 ustar mikio mikio 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
}
}
kyotocabinet-ruby-1.34/example/memsize.rb 0000644 0001750 0001750 00000001423 11425314611 017544 0 ustar mikio mikio require '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.34/makedist.sh 0000755 0001750 0001750 00000000430 11360043166 016252 0 ustar mikio mikio #! /bin/sh
LANG=C
LC_ALL=C
PATH="$PATH:/usr/local/bin:$HOME/bin:.:.."
export LANG LC_ALL PATH
if [ -f Makefile ]
then
make distclean
fi
rm -rf casket casket* *~ *.tmp *.kcss *.gem hoge moge
name="${PWD##*/}"
cd ..
if [ -d "$name" ]
then
tar zcvf "$name.tar.gz" "$name"
fi
kyotocabinet-ruby-1.34/kctest.rb 0000755 0001750 0001750 00000072411 11750225361 015751 0 ustar mikio mikio #! /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.34/extconf.rb 0000644 0001750 0001750 00000001723 13365375447 016134 0 ustar mikio mikio require "mkmf"
File::unlink("Makefile") if (File::exist?("Makefile"))
dir_config('kyotocabinet')
home = ENV["HOME"]
ENV["PATH"] = ENV["PATH"] + ":/usr/local/bin:$home/bin:."
kccflags = `kcutilmgr conf -i 2>/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)
RbConfig::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
kyotocabinet-ruby-1.34/makedoc.rb 0000755 0001750 0001750 00000002330 11750224350 016045 0 ustar mikio mikio #! /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.34/README 0000644 0001750 0001750 00000001275 13705221265 015005 0 ustar mikio mikio ================================================================
Kyoto Cabinet: a straightforward implementation of DBM
Copyright (C) 2009-2010 Mikio Hirabayashi
================================================================
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 `mikio@dbmx.net'.
Thanks.
== END OF FILE ==
kyotocabinet-ruby-1.34/overview.rd 0000644 0001750 0001750 00000014550 13705221331 016314 0 ustar mikio mikio = 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 Mikio Hirabayashi
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.34/kyotocabinet.gemspec 0000644 0001750 0001750 00000001632 11757455777 020210 0 ustar mikio mikio require '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.34/kyotocabinet.cc 0000644 0001750 0001750 00000347524 13705217721 017143 0 ustar mikio mikio /*************************************************************************************************
* 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_
#include
#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_call_without_gvl(execute_impl, func, RUBY_UBF_IO, NULL);
#else
func->operate();
#endif
}
private:
static void* execute_impl(void* ptr) {
NativeFunction* func = (NativeFunction*)ptr;
func->operate();
return NULL;
}
};
/**
* 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];
memcpy(kbuf_, kbuf, ksiz);
kbuf_[ksiz] = '\0';
ksiz_ = ksiz;
vbuf_ = kbuf_ + ksiz + 1;
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.34/kyotocabinet-doc.rb 0000644 0001750 0001750 00000075634 11757456112 017730 0 ustar mikio mikio #--
# 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