1
0
Fork 0
mirror of https://github.com/KingDuckZ/incredis synced 2024-11-23 00:33:46 +00:00

First commit

Import incredis straight from dindexer.
This commit is contained in:
King_DuckZ 2016-07-14 16:36:14 +01:00
commit 5d79a9101c
29 changed files with 3307 additions and 0 deletions

3
.gitmodules vendored Normal file
View file

@ -0,0 +1,3 @@
[submodule "lib/duckhandy"]
path = lib/duckhandy
url = ../duckhandy.git

77
CMakeLists.txt Normal file
View file

@ -0,0 +1,77 @@
cmake_minimum_required(VERSION 3.3 FATAL_ERROR)
project(incredis CXX)
list (APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules)
include(shared_git_project)
find_package(hiredis 0.11.0 REQUIRED)
find_package(CryptoPP 5.6)
find_package(libev 4.0 REQUIRED)
find_package(Boost 1.53.0 REQUIRED)
add_library(${PROJECT_NAME} SHARED
src/command.cpp
src/scan_iterator.cpp
src/reply.cpp
src/batch.cpp
src/script.cpp
src/script_manager.cpp
src/async_connection.cpp
src/incredis.cpp
src/incredis_batch.cpp
)
target_include_directories(${PROJECT_NAME} SYSTEM
PUBLIC ${Boost_INCLUDE_DIRS}
PRIVATE ${HIREDIS_INCLUDE_DIRS}
PUBLIC ${CMAKE_SOURCE_DIR}/lib/better-enums
PRIVATE ${LIBEV_INCLUDE_DIRS}
PRIVATE ${Boost_INCLUDE_DIRS}
)
target_include_directories(${PROJECT_NAME}
PUBLIC ${CMAKE_SOURCE_DIR}/include
PRIVATE ${CMAKE_CURRENT_BINARY_DIR}
)
target_link_libraries(${PROJECT_NAME}
PRIVATE ${HIREDIS_LIBRARIES}
PRIVATE ${LIBEV_LIBRARIES}
PRIVATE ${Boost_LIBRARIES}
)
configure_file(
src/incredisConfig.h.in
${CMAKE_CURRENT_BINARY_DIR}/incredisConfig.h
)
target_compile_definitions(${PROJECT_NAME}
PRIVATE EV_COMPAT3=0
)
if (CryptoPP_FOUND)
target_link_libraries(${PROJECT_NAME} PRIVATE ${CryptoPP_LIBRARIES})
target_include_directories(${PROJECT_NAME} SYSTEM PRIVATE ${CryptoPP_INCLUDE_DIRS})
set (has_cryptopp_lib ON)
else()
set (has_cryptopp_lib OFF)
endif()
install(TARGETS ${PROJECT_NAME}
LIBRARY DESTINATION lib
RUNTIME DESTINATION bin
ARCHIVE DESTINATION lib/static
)
target_compile_features(${PROJECT_NAME}
PUBLIC cxx_nullptr
PUBLIC cxx_range_for
PUBLIC cxx_lambdas
PUBLIC cxx_decltype_auto
PUBLIC cxx_defaulted_functions
PUBLIC cxx_deleted_functions
PUBLIC cxx_auto_type
PUBLIC cxx_decltype_incomplete_return_types
PUBLIC cxx_defaulted_move_initializers
PUBLIC cxx_noexcept
PUBLIC cxx_rvalue_references
)

674
COPYING Normal file
View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -0,0 +1,136 @@
# Module for locating the Crypto++ encryption library.
#
# Customizable variables:
# CryptoPP_ROOT_DIR
# This variable points to the CryptoPP root directory. On Windows the
# library location typically will have to be provided explicitly using the
# -D command-line option. The directory should include the include/cryptopp,
# lib and/or bin sub-directories.
#
# Read-only variables:
# CryptoPP_FOUND
# Indicates whether the library has been found.
#
# CryptoPP_INCLUDE_DIRS
# Points to the CryptoPP include directory.
#
# CryptoPP_LIBRARIES
# Points to the CryptoPP libraries that should be passed to
# target_link_libararies.
#
#
# Copyright (c) 2012 Sergiu Dotenco
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
INCLUDE (FindPackageHandleStandardArgs)
FIND_PATH (
CryptoPP_ROOT_DIR
NAMES cryptopp/cryptlib.h include/cryptopp/cryptlib.h
PATHS ENV CRYPTOPPROOT
DOC "CryptoPP root directory"
)
# Re-use the previous path:
FIND_PATH (
CRYPTOPP_INCLUDE_DIR
NAMES cryptopp/cryptlib.h
HINTS ${CryptoPP_ROOT_DIR}
PATH_SUFFIXES include
DOC "CryptoPP include directory"
)
FIND_LIBRARY (
CRYPTOPP_LIBRARY_DEBUG
NAMES cryptlibd cryptoppd
HINTS ${CryptoPP_ROOT_DIR}
PATH_SUFFIXES lib
DOC "CryptoPP debug library"
)
FIND_LIBRARY (
CRYPTOPP_LIBRARY_RELEASE
NAMES cryptlib cryptopp
HINTS ${CryptoPP_ROOT_DIR}
PATH_SUFFIXES lib
DOC "CryptoPP release library"
)
IF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE)
SET (
CRYPTOPP_LIBRARY
optimized ${CRYPTOPP_LIBRARY_RELEASE}
debug ${CRYPTOPP_LIBRARY_DEBUG} CACHE DOC "CryptoPP library"
)
ELSEIF (CRYPTOPP_LIBRARY_RELEASE)
SET (
CRYPTOPP_LIBRARY ${CRYPTOPP_LIBRARY_RELEASE} CACHE DOC
"CryptoPP library"
)
ENDIF (CRYPTOPP_LIBRARY_DEBUG AND CRYPTOPP_LIBRARY_RELEASE)
IF (CRYPTOPP_INCLUDE_DIR)
SET (_CRYPTOPP_VERSION_HEADER ${CRYPTOPP_INCLUDE_DIR}/cryptopp/config.h)
IF (EXISTS ${_CRYPTOPP_VERSION_HEADER})
FILE (
STRINGS ${_CRYPTOPP_VERSION_HEADER} _CRYPTOPP_VERSION_TMP REGEX
"^#define CRYPTOPP_VERSION[ \t]+[0-9]+$"
)
STRING (
REGEX REPLACE
"^#define CRYPTOPP_VERSION[ \t]+([0-9]+)" "\\1" _CRYPTOPP_VERSION_TMP
${_CRYPTOPP_VERSION_TMP}
)
STRING (
REGEX REPLACE "([0-9]+)[0-9][0-9]" "\\1" CRYPTOPP_VERSION_MAJOR
${_CRYPTOPP_VERSION_TMP}
)
STRING (
REGEX REPLACE "[0-9]([0-9])[0-9]" "\\1" CRYPTOPP_VERSION_MINOR
${_CRYPTOPP_VERSION_TMP}
)
STRING (
REGEX REPLACE "[0-9][0-9]([0-9])" "\\1" CRYPTOPP_VERSION_PATCH
${_CRYPTOPP_VERSION_TMP}
)
SET (CRYPTOPP_VERSION_COUNT 3)
SET (
CRYPTOPP_VERSION
${CRYPTOPP_VERSION_MAJOR}.${CRYPTOPP_VERSION_MINOR}.${CRYPTOPP_VERSION_PATCH}
)
ENDIF (EXISTS ${_CRYPTOPP_VERSION_HEADER})
ENDIF (CRYPTOPP_INCLUDE_DIR)
SET (CryptoPP_INCLUDE_DIRS ${CRYPTOPP_INCLUDE_DIR})
SET (CryptoPP_LIBRARIES ${CRYPTOPP_LIBRARY})
MARK_AS_ADVANCED (
CRYPTOPP_INCLUDE_DIR CRYPTOPP_LIBRARY CRYPTOPP_LIBRARY_DEBUG
CRYPTOPP_LIBRARY_RELEASE
)
FIND_PACKAGE_HANDLE_STANDARD_ARGS (
CryptoPP REQUIRED_VARS CryptoPP_ROOT_DIR
CRYPTOPP_INCLUDE_DIR CRYPTOPP_LIBRARY VERSION_VAR CRYPTOPP_VERSION
)

View file

@ -0,0 +1,55 @@
#Find libhiredis
#
# HIREDIS_INCLUDE_DIRS - where to find hiredis/hiredis.h
# HIREDIS_LIBRARIES - list of libraries when using libhiredis
# HIREDIS_FOUND - true if libhiredis found
# HIREDIS_VERSION_STRING - the version of the libhiredis found
#
find_path(HIREDIS_INCLUDE_DIR NAMES hiredis/hiredis.h)
find_library(HIREDIS_LIBRARY NAMES
hiredis
)
if(HIREDIS_INCLUDE_DIR)
if(EXISTS "${HIREDIS_INCLUDE_DIR}/hiredis/hiredis.h")
set(hiredis_ver_tmp_major 0)
set(hiredis_ver_tmp_minor 0)
set(hiredis_ver_tmp_patch 0)
file(STRINGS "${HIREDIS_INCLUDE_DIR}/hiredis/hiredis.h" hiredis_version_nums REGEX "^#define[\t ]+HIREDIS_(MAJOR|MINOR|PATCH)[\t ]+[0-9]+")
foreach(hiredis_version_def IN LISTS hiredis_version_nums)
if ("${hiredis_version_def}" MATCHES "HIREDIS_MAJOR")
string(REGEX REPLACE "^#define[\t ]+HIREDIS_MAJOR[\t ]+([0-9]+).*" "\\1" hiredis_ver_tmp_major "${hiredis_version_def}")
elseif ("${hiredis_version_def}" MATCHES "HIREDIS_MINOR")
string(REGEX REPLACE "^#define[\t ]+HIREDIS_MINOR[\t ]+([0-9]+).*" "\\1" hiredis_ver_tmp_minor "${hiredis_version_def}")
elseif ("${hiredis_version_def}" MATCHES "HIREDIS_PATCH")
string(REGEX REPLACE "^#define[\t ]+HIREDIS_PATCH[\t ]+([0-9]+).*" "\\1" hiredis_ver_tmp_patch "${hiredis_version_def}")
endif()
endforeach()
unset(hiredis_version_nums)
unset(hiredis_version_def)
set(HIREDIS_VERSION_STRING "${hiredis_ver_tmp_major}.${hiredis_ver_tmp_minor}.${hiredis_ver_tmp_patch}")
unset(hiredis_ver_tmp_major)
unset(hiredis_ver_tmp_minor)
unset(hiredis_ver_tmp_patch)
endif()
endif()
include(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(hiredis
REQUIRED_VARS HIREDIS_LIBRARY HIREDIS_INCLUDE_DIR
VERSION_VAR HIREDIS_VERSION_STRING
)
if(HIREDIS_FOUND)
set(HIREDIS_LIBRARIES ${HIREDIS_LIBRARY})
set(HIREDIS_INCLUDE_DIRS ${HIREDIS_INCLUDE_DIR})
endif()
mark_as_advanced(
HIREDIS_ROOT_DIR
HIREDIS_INCLUDE_DIR
HIREDIS_LIBRARY
)

View file

@ -0,0 +1,31 @@
# Try to find libev
# Once done, this will define
#
# LIBEV_FOUND - system has libev
# LIBEV_INCLUDE_DIRS - libev include directories
# LIBEV_LIBRARIES - libraries needed to use libev
if(LIBEV_INCLUDE_DIRS AND LIBEV_LIBRARIES)
set(LIBEV_FIND_QUIETLY TRUE)
else()
find_path(
LIBEV_INCLUDE_DIR
NAMES ev.h
HINTS ${LIBEV_ROOT_DIR}
PATH_SUFFIXES include)
find_library(
LIBEV_LIBRARY
NAME ev
HINTS ${LIBEV_ROOT_DIR}
PATH_SUFFIXES ${CMAKE_INSTALL_LIBDIR})
set(LIBEV_INCLUDE_DIRS ${LIBEV_INCLUDE_DIR})
set(LIBEV_LIBRARIES ${LIBEV_LIBRARY})
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(
libev DEFAULT_MSG LIBEV_LIBRARY LIBEV_INCLUDE_DIR)
mark_as_advanced(LIBEV_LIBRARY LIBEV_INCLUDE_DIR)
endif()

View file

@ -0,0 +1,85 @@
cmake_minimum_required(VERSION 2.8.12.2 FATAL_ERROR)
function (add_shared_git_project SUBMODULE_PATH)
if (IS_ABSOLUTE "${SUBMODULE_PATH}")
set(submod_path "${SUBMODULE_PATH}")
else()
set(submod_path "${CMAKE_CURRENT_SOURCE_DIR}/${SUBMODULE_PATH}")
endif()
if (NOT EXISTS "${submod_path}")
message(FATAL_ERROR "Path \"${submod_path}\" doesn't exist")
endif()
if (NOT IS_DIRECTORY "${submod_path}")
message(FATAL_ERROR "Path \"${submod_path}\" is not a valid directory")
endif()
if (NOT EXISTS "${submod_path}/.git")
message(FATAL_ERROR ".git not found in \"${submod_path}\". Not a git submodule?")
endif()
if (IS_DIRECTORY "${submod_path}/.git")
message(FATAL_ERROR "\"${submod_path}.git\" is a directory, not a file as expected. Not a git submodule?")
endif()
get_filename_component(proj_name_orig "${submod_path}" NAME)
if ("${proj_name_orig}" STREQUAL "")
message(FATAL_ERROR "Couldn't make up a name for given project in \"${submod_path}\"")
endif()
string(MAKE_C_IDENTIFIER "${submod_path}" proj_name_c_id)
string(TOUPPER ${proj_name_c_id} proj_name)
get_property(shared_projects_list GLOBAL PROPERTY SHARED_PROJECTS_LIST)
list(FIND shared_projects_list ${proj_name} found_index)
if (${found_index} GREATER -1)
#nothing to do, the variable is already set so the project must have been
#included already
return()
endif()
#Obtain the path to the working tree
# see http://stackoverflow.com/questions/27379818/git-possible-to-use-same-submodule-working-copy-by-multiple-projects
# git rev-parse --git-dir --show-toplevel
execute_process(
COMMAND git rev-parse --show-toplevel
WORKING_DIRECTORY "${submod_path}"
OUTPUT_VARIABLE matched_gitdir
OUTPUT_STRIP_TRAILING_WHITESPACE
)
#Make sure we got an absolute path
if (IS_ABSOLUTE "${matched_gitdir}")
set(reported_submodule_dir "${matched_gitdir}")
else()
file(RELATIVE_PATH reported_submodule_dir "${CMAKE_CURRENT_SOURCE_DIR}" "${submod_path}/${matched_gitdir}")
endif()
unset(matched_gitdir)
#Check if submodule is a subdirectory of the current source dir
file(RELATIVE_PATH reported_submodule_rel_path "${CMAKE_CURRENT_SOURCE_DIR}" "${reported_submodule_dir}")
string(LENGTH "${reported_submodule_rel_path}" rel_path_len)
if (${rel_path_len} GREATER 2)
string(SUBSTRING "${reported_submodule_rel_path}" 0 3 first_bit)
if ("../" STREQUAL "${first_bit}")
set(is_out_of_dirtree ON)
else()
set(is_out_of_dirtree OFF)
endif()
unset(first_bit)
else()
set(is_out_of_dirtree OFF)
endif()
unset(rel_path_len)
#Globally mark current submodule as handled
set_property(GLOBAL APPEND PROPERTY SHARED_PROJECTS_LIST ${proj_name})
set(shared_project_binary "${CMAKE_CURRENT_BINARY_DIR}/shared_projects/${proj_name_orig}")
if (is_out_of_dirtree)
#message(FATAL_ERROR "Would call add_subdirectory(\"${reported_submodule_dir}\" \"${shared_project_binary}\")")
add_subdirectory("${reported_submodule_dir}" "${shared_project_binary}" ${ARGN})
else()
#message(FATAL_ERROR "Would call add_subdirectory(\"${reported_submodule_rel_path}\")")
add_subdirectory("${reported_submodule_rel_path}" ${ARGN})
endif()
endfunction()

1
lib/duckhandy Submodule

@ -0,0 +1 @@
Subproject commit 0da25f9094c08ccb1312e502e020db6a68504d34

91
src/arg_to_bin_safe.hpp Normal file
View file

@ -0,0 +1,91 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef id9348909738B047B7B6912D73CB519039
#define id9348909738B047B7B6912D73CB519039
#include "duckhandy/compatibility.h"
#include <cstddef>
#include <boost/utility/string_ref.hpp>
#include <string>
namespace redis {
namespace implem {
template <typename T>
const char* arg_to_bin_safe_char ( const T& parArg );
template <typename T>
std::size_t arg_to_bin_safe_length ( const T& parArg ) a_pure;
template <typename T>
struct MakeCharInfo;
template<>
struct MakeCharInfo<std::string> {
MakeCharInfo ( const std::string& parData ) : m_string(parData) {}
const char* data ( void ) const { return m_string.data(); }
std::size_t size ( void ) const { return m_string.size(); }
private:
const std::string& m_string;
};
template<>
struct MakeCharInfo<boost::string_ref> {
MakeCharInfo ( const boost::string_ref& parData ) : m_data(parData.data()), m_size(parData.size()) {}
const char* data ( void ) const { return m_data; }
std::size_t size ( void ) const { return m_size; }
private:
const char* const m_data;
const std::size_t m_size;
};
template<>
struct MakeCharInfo<char> {
MakeCharInfo ( char parData ) : m_data(parData) {}
const char* data ( void ) const { return &m_data; }
std::size_t size ( void ) const { return 1; }
private:
const char m_data;
};
template <std::size_t N>
struct MakeCharInfo<char[N]> {
static_assert(N > 0, "Given input should have at least one character as it's assumed to be a null-terminated string");
MakeCharInfo ( const char (&parData)[N] ) : m_data(parData, N - 1) {}
const char* data ( void ) const { return m_data.data(); }
std::size_t size ( void ) const { return m_data.size(); }
private:
boost::string_ref m_data;
};
template <typename T>
inline const char* arg_to_bin_safe_char (const T& parArg) {
return MakeCharInfo<T>(parArg).data();
}
template <typename T>
inline std::size_t arg_to_bin_safe_length (const T& parArg) {
return MakeCharInfo<T>(parArg).size();
}
} //namespace implem
} //namespace redis
#endif

219
src/async_connection.cpp Normal file
View file

@ -0,0 +1,219 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "async_connection.hpp"
#include <hiredis/async.h>
#include <hiredis/adapters/libev.h>
#include <ev.h>
#include <thread>
#include <condition_variable>
#include <atomic>
#include <mutex>
#include <signal.h>
#include <cassert>
#include <sstream>
namespace redis {
namespace {
void async_callback (ev_loop* /*parLoop*/, ev_async* /*parObject*/, int /*parRevents*/) {
}
void async_halt_loop (ev_loop* parLoop, ev_async* /*parObject*/, int /*parRevents*/) {
ev_break(parLoop, EVBREAK_ALL);
}
void lock_mutex_libev (ev_loop* parLoop) noexcept {
std::mutex* mtx = static_cast<std::mutex*>(ev_userdata(parLoop));
assert(mtx);
try {
mtx->lock();
}
catch (const std::system_error&) {
assert(false);
}
}
void unlock_mutex_libev (ev_loop* parLoop) noexcept {
std::mutex* mtx = static_cast<std::mutex*>(ev_userdata(parLoop));
assert(mtx);
mtx->unlock();
}
} //unnamed namespace
struct AsyncConnection::LocalData {
LocalData() :
redis_poll_thread(),
connect_processed(false),
disconnect_processed(true)
{
}
ev_async watcher_wakeup;
ev_async watcher_halt;
std::thread redis_poll_thread;
std::mutex hiredis_mutex;
std::mutex libev_mutex;
std::condition_variable condition_connected;
std::condition_variable condition_disconnected;
std::string connect_err_msg;
std::atomic_bool connect_processed;
std::atomic_bool disconnect_processed;
};
void on_connect (const redisAsyncContext* parContext, int parStatus) {
assert(parContext and parContext->data);
AsyncConnection& self = *static_cast<AsyncConnection*>(parContext->data);
assert(parContext == self.m_conn.get());
assert(not self.m_local_data->connect_processed);
self.m_connection_lost = false;
self.m_connected = (parStatus == REDIS_OK);
self.m_local_data->connect_processed = true;
self.m_local_data->connect_err_msg = parContext->errstr;
self.m_local_data->condition_connected.notify_one();
}
void on_disconnect (const redisAsyncContext* parContext, int parStatus) {
assert(parContext and parContext->data);
AsyncConnection& self = *static_cast<AsyncConnection*>(parContext->data);
assert(self.m_connected);
assert(not self.m_local_data->disconnect_processed);
self.m_connection_lost = (REDIS_ERR == parStatus);
self.m_connected = false;
self.m_local_data->disconnect_processed = true;
self.m_local_data->connect_err_msg.clear();
self.m_local_data->condition_disconnected.notify_one();
};
AsyncConnection::AsyncConnection(std::string&& parAddress, uint16_t parPort) :
m_conn(nullptr, &redisAsyncDisconnect),
m_local_data(new LocalData()),
m_libev_loop_thread(ev_loop_new(EVFLAG_NOINOTIFY), &ev_loop_destroy),
m_address(std::move(parAddress)),
m_port(parPort),
m_connected(false),
m_connection_lost(false)
{
//Init libev stuff
{
signal(SIGPIPE, SIG_IGN);
//See: http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#THREAD_LOCKING_EXAMPLE
ev_async_init(&m_local_data->watcher_wakeup, &async_callback);
ev_async_start(m_libev_loop_thread.get(), &m_local_data->watcher_wakeup);
ev_async_init(&m_local_data->watcher_halt, &async_halt_loop);
ev_async_start(m_libev_loop_thread.get(), &m_local_data->watcher_halt);
ev_set_userdata(m_libev_loop_thread.get(), &m_local_data->libev_mutex);
ev_set_loop_release_cb(m_libev_loop_thread.get(), &unlock_mutex_libev, &lock_mutex_libev);
}
}
AsyncConnection::~AsyncConnection() noexcept {
this->disconnect();
this->wait_for_disconnect();
}
void AsyncConnection::connect() {
if (not m_conn) {
m_local_data->disconnect_processed = false;
RedisConnection conn(
(is_socket_connection() ?
redisAsyncConnectUnix(m_address.c_str())
:
redisAsyncConnect(m_address.c_str(), m_port)
),
&redisAsyncDisconnect
);
if (not conn) {
std::ostringstream oss;
oss << "Unable to connect to Redis server at " << m_address << ':' << m_port;
throw std::runtime_error(oss.str());
}
else {
conn->data = this;
}
if (REDIS_OK != redisLibevAttach(m_libev_loop_thread.get(), conn.get()))
throw std::runtime_error("Unable to set event loop");
if (REDIS_OK != redisAsyncSetConnectCallback(conn.get(), &on_connect))
throw std::runtime_error("Unable to set \"on_connect()\" callback");
if (REDIS_OK != redisAsyncSetDisconnectCallback(conn.get(), &on_disconnect))
throw std::runtime_error("Unable to set \"on_disconnect()\" callback");
std::swap(conn, m_conn);
m_local_data->redis_poll_thread = std::thread([this]() {
m_local_data->libev_mutex.lock();
ev_run(m_libev_loop_thread.get(), 0);
m_local_data->libev_mutex.unlock();
});
wakeup_event_thread();
}
}
void AsyncConnection::wait_for_connect() {
if (not m_local_data->connect_processed) {
std::unique_lock<std::mutex> lk(m_local_data->hiredis_mutex);
m_local_data->condition_connected.wait(lk, [this]() { return m_local_data->connect_processed.load(); });
assert(true == m_local_data->connect_processed);
}
}
void AsyncConnection::disconnect() {
if (not m_local_data->connect_processed)
return;
assert(m_local_data->redis_poll_thread.joinable());
m_local_data->connect_processed = false;
{
std::lock_guard<std::mutex> lock(m_local_data->libev_mutex);
assert(not ev_async_pending(&m_local_data->watcher_halt));
ev_async_send(m_libev_loop_thread.get(), &m_local_data->watcher_halt);
m_conn.reset();
}
m_local_data->redis_poll_thread.join();
}
void AsyncConnection::wait_for_disconnect() {
if (not m_local_data->disconnect_processed) {
std::unique_lock<std::mutex> lk(m_local_data->hiredis_mutex);
m_local_data->condition_disconnected.wait(lk, [this]() { return m_local_data->disconnect_processed.load(); });
assert(true == m_local_data->disconnect_processed);
}
}
bool AsyncConnection::is_connected() const {
const bool connected = m_conn and not m_conn->err and m_connected;
assert(not m_connection_lost or connected);
return connected;
}
boost::string_ref AsyncConnection::connection_error() const {
return m_local_data->connect_err_msg;
}
void AsyncConnection::wakeup_event_thread() {
std::lock_guard<std::mutex> lock(m_local_data->libev_mutex);
if (ev_async_pending(&m_local_data->watcher_wakeup) == false)
ev_async_send(m_libev_loop_thread.get(), &m_local_data->watcher_wakeup);
}
std::mutex& AsyncConnection::event_mutex() {
return m_local_data->libev_mutex;
}
bool AsyncConnection::is_socket_connection() const {
return not (m_port or m_address.empty());
}
} //namespace redis

74
src/async_connection.hpp Normal file
View file

@ -0,0 +1,74 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef id982A651A9BC34F6E9BA935A804B3A0A4
#define id982A651A9BC34F6E9BA935A804B3A0A4
#include <memory>
#include <string>
#include <cstdint>
#include <boost/utility/string_ref.hpp>
struct redisAsyncContext;
struct ev_loop;
namespace std {
class mutex;
} //namespace std
namespace redis {
class AsyncConnection {
friend void on_connect ( const redisAsyncContext*, int );
friend void on_disconnect ( const redisAsyncContext*, int );
public:
AsyncConnection ( std::string&& parAddress, uint16_t parPort );
~AsyncConnection ( void ) noexcept;
void connect ( void );
void wait_for_connect ( void );
void disconnect ( void );
void wait_for_disconnect ( void );
bool is_connected ( void ) const;
boost::string_ref connection_error ( void ) const;
void wakeup_event_thread ( void );
std::mutex& event_mutex ( void );
redisAsyncContext* connection ( void );
private:
using RedisConnection = std::unique_ptr<redisAsyncContext, void(*)(redisAsyncContext*)>;
using LibevLoop = std::unique_ptr<ev_loop, void(*)(ev_loop*)>;
bool is_socket_connection ( void ) const;
struct LocalData;
RedisConnection m_conn;
std::unique_ptr<LocalData> m_local_data;
LibevLoop m_libev_loop_thread;
std::string m_address;
uint16_t m_port;
volatile bool m_connected;
volatile bool m_connection_lost;
};
inline redisAsyncContext* AsyncConnection::connection() {
return m_conn.get();
}
} //namespace redis
#endif

229
src/batch.cpp Normal file
View file

@ -0,0 +1,229 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "batch.hpp"
#include "async_connection.hpp"
#include <hiredis/hiredis.h>
#include <hiredis/async.h>
#include <cassert>
#include <future>
#include <ciso646>
#include <boost/iterator/transform_iterator.hpp>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <sstream>
//#define VERBOSE_HIREDIS_COMM
#if defined(VERBOSE_HIREDIS_COMM)
# include <iostream>
#endif
namespace redis {
namespace {
const std::size_t g_max_redis_unanswered_commands = 1000;
struct HiredisCallbackData {
HiredisCallbackData ( std::atomic_size_t& parPendingFutures, std::condition_variable& parSendCmdCond ) :
promise(),
pending_futures(parPendingFutures),
send_command_condition(parSendCmdCond)
{
}
std::promise<Reply> promise;
std::atomic_size_t& pending_futures;
std::condition_variable& send_command_condition;
};
Reply make_redis_reply_type (redisReply* parReply) {
using boost::transform_iterator;
using PtrToReplyIterator = transform_iterator<Reply(*)(redisReply*), redisReply**>;
switch (parReply->type) {
case REDIS_REPLY_INTEGER:
return parReply->integer;
case REDIS_REPLY_STRING:
return std::string(parReply->str, parReply->len);
case REDIS_REPLY_ARRAY:
return std::vector<Reply>(
PtrToReplyIterator(parReply->element, &make_redis_reply_type),
PtrToReplyIterator(parReply->element + parReply->elements, &make_redis_reply_type)
);
case REDIS_REPLY_ERROR:
return ErrorString(parReply->str, parReply->len);
case REDIS_REPLY_STATUS:
return StatusString(parReply->str, parReply->len);
case REDIS_REPLY_NIL:
return nullptr;
default:
assert(false); //not reached
return Reply();
};
}
void hiredis_run_callback (redisAsyncContext*, void* parReply, void* parPrivData) {
assert(parPrivData);
auto* data = static_cast<HiredisCallbackData*>(parPrivData);
const auto old_count = data->pending_futures.fetch_add(-1);
assert(old_count > 0);
if (old_count == g_max_redis_unanswered_commands)
data->send_command_condition.notify_one();
if (parReply) {
auto reply = make_redis_reply_type(static_cast<redisReply*>(parReply));
data->promise.set_value(std::move(reply));
}
else {
assert(false); //Should this case also be managed?
}
delete data;
}
int array_throw_if_failed (int parErrCount, int parMaxReportedErrors, const std::vector<Reply>& parReplies, std::ostream& parStream) {
int err_count = 0;
for (const auto& rep : parReplies) {
if (rep.which() == RedisVariantType_Error) {
++err_count;
if (err_count + parErrCount <= parMaxReportedErrors)
parStream << '"' << get_error_string(rep).message() << "\" ";
}
else if (rep.which() == RedisVariantType_Array) {
err_count += array_throw_if_failed(err_count + parErrCount, parMaxReportedErrors, get_array(rep), parStream);
}
}
return err_count;
}
} //unnamed namespace
struct Batch::LocalData {
explicit LocalData ( std::atomic_size_t& parPendingFutures ) :
free_cmd_slot(),
futures_mutex(),
pending_futures(parPendingFutures)
{
}
std::condition_variable free_cmd_slot;
std::mutex futures_mutex;
std::atomic_size_t& pending_futures;
};
Batch::Batch (Batch&&) = default;
Batch::Batch (AsyncConnection* parConn, std::atomic_size_t& parPendingFutures) :
m_futures(),
m_replies(),
m_local_data(new LocalData(parPendingFutures)),
m_async_conn(parConn)
{
assert(m_async_conn);
assert(m_async_conn->connection());
}
Batch::~Batch() noexcept {
if (m_local_data)
this->reset();
}
void Batch::run_pvt (int parArgc, const char** parArgv, std::size_t* parLengths) {
assert(not replies_requested());
assert(parArgc >= 1);
assert(parArgv);
assert(parLengths); //This /could/ be null, but I don't see why it should
assert(m_local_data);
const auto pending_futures = m_local_data->pending_futures.fetch_add(1);
auto* data = new HiredisCallbackData(m_local_data->pending_futures, m_local_data->free_cmd_slot);
#if defined(VERBOSE_HIREDIS_COMM)
std::cout << "run_pvt(), " << pending_futures << " items pending... ";
#endif
if (pending_futures >= g_max_redis_unanswered_commands) {
#if defined(VERBOSE_HIREDIS_COMM)
std::cout << " waiting... ";
#endif
std::unique_lock<std::mutex> u_lock(m_local_data->futures_mutex);
m_local_data->free_cmd_slot.wait(u_lock, [this]() { return m_local_data->pending_futures < g_max_redis_unanswered_commands; });
}
#if defined(VERBOSE_HIREDIS_COMM)
std::cout << " emplace_back(future)... ";
#endif
m_futures.emplace_back(data->promise.get_future());
{
std::lock_guard<std::mutex> lock(m_async_conn->event_mutex());
const int command_added = redisAsyncCommandArgv(m_async_conn->connection(), &hiredis_run_callback, data, parArgc, parArgv, parLengths);
assert(REDIS_OK == command_added); // REDIS_ERR if error
static_cast<void>(command_added);
}
#if defined(VERBOSE_HIREDIS_COMM)
std::cout << "command sent to hiredis" << std::endl;
#endif
m_async_conn->wakeup_event_thread();
}
bool Batch::replies_requested() const {
return not m_replies.empty();
}
const std::vector<Reply>& Batch::replies() {
if (not replies_requested()) {
m_replies.reserve(m_futures.size());
for (auto& fut : m_futures) {
m_replies.emplace_back(fut.get());
}
auto empty_vec = std::move(m_futures);
}
return m_replies;
}
void Batch::throw_if_failed() {
std::ostringstream oss;
const int max_reported_errors = 3;
oss << "Error in reply: ";
const int err_count = array_throw_if_failed(0, max_reported_errors, replies(), oss);
if (err_count) {
oss << " (showing " << err_count << '/' << max_reported_errors << " errors on " << replies().size() << " total replies)";
throw std::runtime_error(oss.str());
}
}
void Batch::reset() noexcept {
try {
this->replies(); //force waiting for any pending jobs
}
catch (...) {
assert(false);
}
assert(m_local_data);
assert(0 == m_local_data->pending_futures);
m_futures.clear();
m_replies.clear();
}
RedisError::RedisError (const char* parMessage, std::size_t parLength) :
std::runtime_error(std::string(parMessage, parLength))
{
}
} //namespace redis

96
src/batch.hpp Normal file
View file

@ -0,0 +1,96 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef idD81C81D99196491A8C9B68DED8ADD260
#define idD81C81D99196491A8C9B68DED8ADD260
#include "reply.hpp"
#include "arg_to_bin_safe.hpp"
#include <vector>
#include <memory>
namespace std {
template <class R> class future;
template <class T> struct atomic;
} //namespace std
namespace redis {
class Command;
class AsyncConnection;
class Batch {
friend class Command;
public:
Batch ( Batch&& parOther );
Batch ( const Batch& ) = delete;
~Batch ( void ) noexcept;
const std::vector<Reply>& replies ( void );
bool replies_requested ( void ) const;
void throw_if_failed ( void );
template <typename... Args>
Batch& run ( const char* parCommand, Args&&... parArgs );
template <typename... Args>
Batch& operator() ( const char* parCommand, Args&&... parArgs );
void reset ( void ) noexcept;
private:
struct LocalData;
explicit Batch ( AsyncConnection* parConn, std::atomic<std::size_t>& parPendingFutures );
void run_pvt ( int parArgc, const char** parArgv, std::size_t* parLengths );
std::vector<std::future<Reply>> m_futures;
std::vector<Reply> m_replies;
std::unique_ptr<LocalData> m_local_data;
AsyncConnection* m_async_conn;
};
class RedisError : public std::runtime_error {
public:
RedisError ( const char* parMessage, std::size_t parLength );
};
template <typename... Args>
Batch& Batch::run (const char* parCommand, Args&&... parArgs) {
constexpr const std::size_t arg_count = sizeof...(Args) + 1;
using CharPointerArray = std::array<const char*, arg_count>;
using LengthArray = std::array<std::size_t, arg_count>;
using implem::arg_to_bin_safe_char;
using implem::arg_to_bin_safe_length;
using implem::MakeCharInfo;
using boost::string_ref;
this->run_pvt(
static_cast<int>(arg_count),
CharPointerArray{ (arg_to_bin_safe_char(string_ref(parCommand))), MakeCharInfo<typename std::remove_const<typename std::remove_reference<Args>::type>::type>(std::forward<Args>(parArgs)).data()... }.data(),
LengthArray{ arg_to_bin_safe_length(string_ref(parCommand)), arg_to_bin_safe_length(std::forward<Args>(parArgs))... }.data()
);
return *this;
}
template <typename... Args>
Batch& Batch::operator() (const char* parCommand, Args&&... parArgs) {
return this->run(parCommand, std::forward<Args>(parArgs)...);
}
} //namespace redis
#endif

92
src/command.cpp Normal file
View file

@ -0,0 +1,92 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.hpp"
#include "script_manager.hpp"
#include "async_connection.hpp"
#include <hiredis/hiredis.h>
#include <ciso646>
#include <cassert>
#include <algorithm>
#include <stdexcept>
#include <atomic>
//See docs directory for info about hiredis/libev with multithreading
namespace redis {
namespace {
} //unnamed namespace
struct Command::LocalData {
explicit LocalData (Command* parCommand, std::string&& parAddress, uint16_t parPort) :
async_connection(std::move(parAddress), parPort),
lua_scripts(parCommand),
pending_futures(0)
{
}
AsyncConnection async_connection;
ScriptManager lua_scripts;
std::atomic_size_t pending_futures;
};
Command::Command (std::string&& parAddress, uint16_t parPort) :
m_local_data(new LocalData(this, std::move(parAddress), parPort))
{
}
Command::Command (std::string&& parSocket) :
Command(std::move(parSocket), 0)
{
}
Command::~Command() noexcept = default;
void Command::connect() {
m_local_data->async_connection.connect();
}
void Command::wait_for_connect() {
m_local_data->async_connection.wait_for_connect();
}
void Command::disconnect() {
m_local_data->async_connection.disconnect();
}
void Command::wait_for_disconnect() {
m_local_data->async_connection.wait_for_disconnect();
}
bool Command::is_connected() const {
return m_local_data->async_connection.is_connected();
}
boost::string_ref Command::connection_error() const {
return m_local_data->async_connection.connection_error();
}
Batch Command::make_batch() {
assert(is_connected());
return Batch(&m_local_data->async_connection, m_local_data->pending_futures);
}
Script Command::make_script (const std::string &parScript) {
auto sha1 = m_local_data->lua_scripts.submit_lua_script(parScript);
return Script(sha1, m_local_data->lua_scripts);
}
} //namespace redis

84
src/command.hpp Normal file
View file

@ -0,0 +1,84 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef idD83EEBFC927840C6B9F32D61A1D1E582
#define idD83EEBFC927840C6B9F32D61A1D1E582
#include "reply.hpp"
#include "batch.hpp"
#include "script.hpp"
#include <array>
#include <string>
#include <cstdint>
#include <cstddef>
#include <cassert>
#include <vector>
#include <utility>
#include <boost/utility/string_ref.hpp>
#include <ciso646>
#include <stdexcept>
namespace redis {
class Command {
public:
Command ( std::string&& parAddress, uint16_t parPort );
explicit Command ( std::string&& parSocket );
~Command ( void ) noexcept;
void connect ( void );
void wait_for_connect ( void );
void disconnect ( void );
void wait_for_disconnect ( void );
bool is_connected ( void ) const;
boost::string_ref connection_error ( void ) const;
Batch make_batch ( void );
Script make_script ( const std::string& parScript );
template <typename... Args>
Reply run ( const char* parCommand, Args&&... parArgs );
private:
struct LocalData;
std::unique_ptr<LocalData> m_local_data;
};
template <typename... Args>
Reply Command::run (const char* parCommand, Args&&... parArgs) {
auto batch = make_batch();
batch.run(parCommand, std::forward<Args>(parArgs)...);
batch.throw_if_failed();
return batch.replies().front();
}
template <typename T>
struct StructAdapt;
template <typename AS, typename I>
inline AS range_as (const boost::iterator_range<I>& parRange) {
assert(not boost::empty(parRange));
AS retval;
const auto success = StructAdapt<AS>::decode(parRange, retval);
if (not success)
throw std::runtime_error("Error decoding range");
return retval;
};
} //namespace redis
#endif

137
src/incredis.cpp Normal file
View file

@ -0,0 +1,137 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "incredis.hpp"
#include "duckhandy/compatibility.h"
#include "duckhandy/lexical_cast.hpp"
#include <cassert>
#include <ciso646>
namespace redis {
namespace {
inline IncRedis::opt_string optional_string ( const Reply& parReply ) a_always_inline;
IncRedis::opt_string_list optional_string_list ( const Reply& parReply );
IncRedis::opt_string optional_string (const Reply& parReply) {
assert(parReply.which() == RedisVariantType_Nil or parReply.which() == RedisVariantType_String);
if (RedisVariantType_Nil == parReply.which())
return boost::none;
else
return get_string(parReply);
}
IncRedis::opt_string_list optional_string_list (const Reply& parReply) {
assert(parReply.which() == RedisVariantType_Nil or parReply.which() == RedisVariantType_Array);
if (RedisVariantType_Nil == parReply.which()) {
return boost::none;
}
else {
auto replies = get_array(parReply);
IncRedis::opt_string_list::value_type retval;
retval.reserve(replies.size());
for (const auto& rep : replies) {
retval.emplace_back(optional_string(rep));
}
return IncRedis::opt_string_list(std::move(retval));
}
}
} //unnamed namespace
IncRedis::IncRedis (std::string &&parAddress, uint16_t parPort) :
m_command(std::move(parAddress), parPort)
{
}
IncRedis::IncRedis (std::string&& parSocket) :
m_command(std::move(parSocket))
{
}
void IncRedis::connect() {
m_command.connect();
}
void IncRedis::wait_for_connect() {
m_command.wait_for_connect();
}
void IncRedis::disconnect() {
m_command.disconnect();
}
void IncRedis::wait_for_disconnect() {
m_command.wait_for_disconnect();
}
IncRedisBatch IncRedis::make_batch() {
return m_command.make_batch();
}
auto IncRedis::scan (boost::string_ref parPattern) -> scan_range {
return scan_range(scan_iterator(&m_command, false, parPattern), scan_iterator(&m_command, true));
}
auto IncRedis::hscan (boost::string_ref parKey, boost::string_ref parPattern) -> hscan_range {
return hscan_range(hscan_iterator(&m_command, parKey, false, parPattern), hscan_iterator(&m_command, parKey, true));
}
auto IncRedis::sscan (boost::string_ref parKey, boost::string_ref parPattern) -> sscan_range {
return sscan_range(sscan_iterator(&m_command, parKey, false, parPattern), sscan_iterator(&m_command, parKey, true));
}
auto IncRedis::zscan (boost::string_ref parKey, boost::string_ref parPattern) -> zscan_range {
return zscan_range(zscan_iterator(&m_command, parKey, false, parPattern), zscan_iterator(&m_command, parKey, true));
}
auto IncRedis::hget (boost::string_ref parKey, boost::string_ref parField) -> opt_string {
return optional_string(m_command.run("HGET", parKey, parField));
}
int IncRedis::hincrby (boost::string_ref parKey, boost::string_ref parField, int parInc) {
const auto inc = dhandy::lexical_cast<std::string>(parInc);
auto reply = m_command.run("HINCRBY", parKey, parField, inc);
return get_integer(reply);
}
auto IncRedis::srandmember (boost::string_ref parKey, int parCount) -> opt_string_list {
return optional_string_list(m_command.run("SRANDMEMBER", parKey, dhandy::lexical_cast<std::string>(parCount)));
}
auto IncRedis::srandmember (boost::string_ref parKey) -> opt_string {
return optional_string(m_command.run("SRANDMEMBER", parKey));
}
auto IncRedis::smembers (boost::string_ref parKey) -> opt_string_list {
return optional_string_list(m_command.run("SMEMBERS", parKey));
}
auto IncRedis::zrangebyscore (boost::string_ref parKey, double parMin, bool parMinIncl, double parMax, bool parMaxIncl, bool parWithScores) -> opt_string_list {
auto batch = make_batch();
batch.zrangebyscore(parKey, parMin, parMinIncl, parMax, parMaxIncl, parWithScores);
assert(batch.replies().size() == 1);
return optional_string_list(batch.replies().front());
}
bool IncRedis::script_flush() {
const auto ret = get<StatusString>(m_command.run("SCRIPT", "FLUSH"));
return ret.is_ok();
}
auto IncRedis::reply_to_string_list (const Reply& parReply) -> opt_string_list {
return optional_string_list(parReply);
}
} //namespace redis

98
src/incredis.hpp Normal file
View file

@ -0,0 +1,98 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef id7D338900114548A890B1EECE0C4D3C4C
#define id7D338900114548A890B1EECE0C4D3C4C
#include "command.hpp"
#include "incredis_batch.hpp"
#include "scan_iterator.hpp"
#include <boost/optional.hpp>
#include <string>
#include <boost/utility/string_ref.hpp>
#include <vector>
#include <boost/range/iterator_range_core.hpp>
#include <boost/range/empty.hpp>
#include <utility>
namespace redis {
class IncRedis {
public:
typedef ScanIterator<ScanSingleValues<std::string>> scan_iterator;
typedef boost::iterator_range<scan_iterator> scan_range;
typedef ScanIterator<ScanPairs<std::pair<std::string, std::string>, ScanCommands::HSCAN>> hscan_iterator;
typedef boost::iterator_range<hscan_iterator> hscan_range;
typedef ScanIterator<ScanSingleValuesInKey<std::string>> sscan_iterator;
typedef boost::iterator_range<sscan_iterator> sscan_range;
typedef ScanIterator<ScanPairs<std::pair<std::string, std::string>, ScanCommands::ZSCAN>> zscan_iterator;
typedef boost::iterator_range<zscan_iterator> zscan_range;
typedef boost::optional<std::string> opt_string;
typedef boost::optional<std::vector<opt_string>> opt_string_list;
IncRedis ( std::string&& parAddress, uint16_t parPort );
explicit IncRedis ( std::string&& parSocket );
~IncRedis ( void ) noexcept = default;
void connect ( void );
void wait_for_connect ( void );
void disconnect ( void );
void wait_for_disconnect ( void );
bool is_connected ( void ) const { return m_command.is_connected(); }
IncRedisBatch make_batch ( void );
Command& command ( void ) { return m_command; }
const Command& command ( void ) const { return m_command; }
//Scan
scan_range scan ( boost::string_ref parPattern=boost::string_ref() );
hscan_range hscan ( boost::string_ref parKey, boost::string_ref parPattern=boost::string_ref() );
sscan_range sscan ( boost::string_ref parKey, boost::string_ref parPattern=boost::string_ref() );
zscan_range zscan ( boost::string_ref parKey, boost::string_ref parPattern=boost::string_ref() );
//Hash
opt_string hget ( boost::string_ref parKey, boost::string_ref parField );
template <typename... Args>
opt_string_list hmget ( boost::string_ref parKey, Args&&... parArgs );
int hincrby ( boost::string_ref parKey, boost::string_ref parField, int parInc );
//Set
opt_string_list srandmember ( boost::string_ref parKey, int parCount );
opt_string srandmember ( boost::string_ref parKey );
opt_string_list smembers ( boost::string_ref parKey );
//Sorted set
opt_string_list zrangebyscore ( boost::string_ref parKey, double parMin, bool parMinIncl, double parMax, bool parMaxIncl, bool parWithScores );
//Script
bool script_flush ( void );
private:
static opt_string_list reply_to_string_list ( const Reply& parReply );
Command m_command;
};
template <typename... Args>
auto IncRedis::hmget (boost::string_ref parKey, Args&&... parArgs) -> opt_string_list {
static_assert(sizeof...(Args) > 0, "No fields specified");
return reply_to_string_list(m_command.run("HMGET", parKey, std::forward<Args>(parArgs)...));
}
} //namespace redis
#endif

27
src/incredisConfig.h.in Normal file
View file

@ -0,0 +1,27 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef id2F97AF7626CE45F08742867A2A737482
#define id2F97AF7626CE45F08742867A2A737482
#include "duckhandy/cmake_on_off.h"
#if CMAKE_@has_cryptopp_lib@
# define WITH_CRYPTOPP
#endif
#endif

92
src/incredis_batch.cpp Normal file
View file

@ -0,0 +1,92 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "incredis_batch.hpp"
#include "duckhandy/lexical_cast.hpp"
#include <sstream>
#include <utility>
#include <ciso646>
namespace redis {
namespace {
std::string make_boundary (double parValue, bool parExclude) {
std::ostringstream oss;
if (parExclude)
oss << '(';
oss << parValue;
return oss.str();
}
} //unnamed namespace
IncRedisBatch::IncRedisBatch (Batch&& parBatch) :
m_batch(std::move(parBatch))
{
}
void IncRedisBatch::reset() {
m_batch.reset();
}
void IncRedisBatch::throw_if_failed() {
m_batch.throw_if_failed();
}
IncRedisBatch& IncRedisBatch::select (int parIndex) {
m_batch.run("SELECT", dhandy::lexical_cast<std::string>(parIndex));
return *this;
}
IncRedisBatch& IncRedisBatch::client_setname (boost::string_ref parName) {
m_batch.run("CLIENT", "SETNAME", parName);
return *this;
}
IncRedisBatch& IncRedisBatch::hget (boost::string_ref parKey, boost::string_ref parField) {
m_batch.run("HGET", parKey, parField);
return *this;
}
IncRedisBatch& IncRedisBatch::hincrby (boost::string_ref parKey, boost::string_ref parField, int parInc) {
m_batch.run("HINCRBY", parKey, parField, dhandy::lexical_cast<std::string>(parInc));
return *this;
}
IncRedisBatch& IncRedisBatch::srandmember (boost::string_ref parKey, int parCount) {
m_batch.run("SRANDMEMBER", parKey, dhandy::lexical_cast<std::string>(parCount));
return *this;
}
IncRedisBatch& IncRedisBatch::srandmember (boost::string_ref parKey) {
m_batch.run("SRANDMEMBER", parKey);
return *this;
}
IncRedisBatch& IncRedisBatch::zrangebyscore (boost::string_ref parKey, double parMin, bool parMinIncl, double parMax, bool parMaxIncl, bool parWithScores) {
auto lower_bound = make_boundary(parMin, not parMinIncl);
auto upper_bound = make_boundary(parMax, not parMaxIncl);
if (parWithScores)
m_batch.run("ZRANGEBYSCORE", parKey, lower_bound, upper_bound, "WITHSCORES");
else
m_batch.run("ZRANGEBYSCORE", parKey, lower_bound, upper_bound);
return *this;
}
IncRedisBatch& IncRedisBatch::script_flush() {
m_batch.run("SCRIPT", "FLUSH");
return *this;
}
} //namespace redis

173
src/incredis_batch.hpp Normal file
View file

@ -0,0 +1,173 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef id3C772A92AB0E440DA84DAFD807BC962D
#define id3C772A92AB0E440DA84DAFD807BC962D
#include "batch.hpp"
#include "duckhandy/sequence_bt.hpp"
#include <boost/utility/string_ref.hpp>
#include <boost/lexical_cast.hpp>
#include <type_traits>
namespace redis {
class IncRedisBatch {
public:
enum ZADD_Mode {
ZADD_XX_UpdateOnly,
ZADD_NX_AlwaysAdd,
ZADD_None
};
IncRedisBatch ( void ) = delete;
IncRedisBatch ( IncRedisBatch&& ) = default;
IncRedisBatch ( const Batch& ) = delete;
IncRedisBatch ( Batch&& parBatch );
void reset ( void );
void throw_if_failed ( void );
const std::vector<Reply>& replies ( void ) { return m_batch.replies(); }
Batch& batch ( void ) { return m_batch; }
const Batch& batch ( void ) const { return m_batch; }
//Misc
IncRedisBatch& select ( int parIndex );
IncRedisBatch& client_setname ( boost::string_ref parName );
template <typename... Args>
IncRedisBatch& del ( Args&&... parArgs );
//Hash
IncRedisBatch& hget ( boost::string_ref parKey, boost::string_ref parField );
template <typename... Args>
IncRedisBatch& hmget ( boost::string_ref parKey, Args&&... parArgs );
template <typename... Args>
IncRedisBatch& hmset ( boost::string_ref parKey, Args&&... parArgs );
IncRedisBatch& hincrby ( boost::string_ref parKey, boost::string_ref parField, int parInc );
//Set
IncRedisBatch& srandmember ( boost::string_ref parKey, int parCount );
IncRedisBatch& srandmember ( boost::string_ref parKey );
template <typename... Args>
IncRedisBatch& sadd ( boost::string_ref parKey, Args&&... parArgs );
//Sorted set
template <typename... Args>
IncRedisBatch& zadd ( boost::string_ref parKey, ZADD_Mode parMode, bool parChange, Args&&... parArgs );
IncRedisBatch& zrangebyscore ( boost::string_ref parKey, double parMin, bool parMinIncl, double parMax, bool parMaxIncl, bool parWithScores );
//Script
IncRedisBatch& script_flush ( void );
private:
Batch m_batch;
};
namespace implem {
template <std::size_t... I, typename... Args>
void run_conv_floats_to_strings ( Batch& parBatch, dhandy::bt::index_seq<I...>, Args&&... parArgs );
} //namespace implem
template <typename... Args>
IncRedisBatch& IncRedisBatch::hmget (boost::string_ref parKey, Args&&... parArgs) {
static_assert(sizeof...(Args) > 0, "No fields specified");
m_batch.run("HMGET", parKey, std::forward<Args>(parArgs)...);
return *this;
}
template <typename... Args>
IncRedisBatch& IncRedisBatch::hmset (boost::string_ref parKey, Args&&... parArgs) {
static_assert(sizeof...(Args) >= 1, "No parameters specified");
static_assert(sizeof...(Args) % 2 == 0, "Uneven number of parameters received");
m_batch.run("HMSET", parKey, std::forward<Args>(parArgs)...);
return *this;
}
template <typename... Args>
IncRedisBatch& IncRedisBatch::sadd (boost::string_ref parKey, Args&&... parArgs) {
static_assert(sizeof...(Args) > 0, "No members specified");
m_batch.run("SADD", parKey, std::forward<Args>(parArgs)...);
return *this;
}
template <typename... Args>
IncRedisBatch& IncRedisBatch::del (Args&&... parArgs) {
static_assert(sizeof...(Args) > 0, "No keys specified");
m_batch.run("DEL", std::forward<Args>(parArgs)...);
return *this;
}
template <typename... Args>
IncRedisBatch& IncRedisBatch::zadd (boost::string_ref parKey, ZADD_Mode parMode, bool parChange, Args&&... parArgs) {
static_assert(sizeof...(Args) >= 1, "No score/value pairs specified");
static_assert(sizeof...(Args) % 2 == 0, "Uneven number of parameters received");
using dhandy::bt::index_range;
if (parChange) {
if (ZADD_None == parMode)
implem::run_conv_floats_to_strings(m_batch, index_range<0, sizeof...(Args)>(), "ZADD", parKey, "CH", std::forward<Args>(parArgs)...);
else if (ZADD_NX_AlwaysAdd == parMode)
implem::run_conv_floats_to_strings(m_batch, index_range<0, sizeof...(Args)>(), "ZADD", parKey, "NX", "CH", std::forward<Args>(parArgs)...);
else if (ZADD_XX_UpdateOnly == parMode)
implem::run_conv_floats_to_strings(m_batch, index_range<0, sizeof...(Args)>(), "ZADD", parKey, "XX", "CH", std::forward<Args>(parArgs)...);
}
else {
if (ZADD_None == parMode)
implem::run_conv_floats_to_strings(m_batch, index_range<0, sizeof...(Args)>(), "ZADD", parKey, std::forward<Args>(parArgs)...);
else if (ZADD_NX_AlwaysAdd == parMode)
implem::run_conv_floats_to_strings(m_batch, index_range<0, sizeof...(Args)>(), "ZADD", parKey, "NX", std::forward<Args>(parArgs)...);
else if (ZADD_XX_UpdateOnly == parMode)
implem::run_conv_floats_to_strings(m_batch, index_range<0, sizeof...(Args)>(), "ZADD", parKey, "XX", std::forward<Args>(parArgs)...);
}
return *this;
}
namespace implem {
template <std::size_t IGNORE_COUNT, std::size_t IDX, typename T, bool STRINGIZE=(IDX>=IGNORE_COUNT) && ((IDX-IGNORE_COUNT)%2)==0>
struct stringize_or_forward_impl {
typedef T type;
static T&& do_it ( T&& parT ) { return std::forward<T>(parT); }
};
template <std::size_t IGNORE_COUNT, std::size_t IDX, typename T>
struct stringize_or_forward_impl<IGNORE_COUNT, IDX, T, true> {
static_assert(std::is_floating_point<T>::value, "Scores must be given as floating point values");
typedef std::string type;
static std::string do_it ( T parT ) { return boost::lexical_cast<std::string>(parT); }
};
template <std::size_t IGNORE_COUNT, std::size_t IDX, typename T>
auto stringize_or_forward (T&& parValue) -> typename stringize_or_forward_impl<IGNORE_COUNT, IDX, T>::type {
return stringize_or_forward_impl<IGNORE_COUNT, IDX, T>::do_it(std::forward<T>(parValue));
}
template <std::size_t PreArgsCount, std::size_t... I, typename... Args>
void run_conv_floats_to_strings_impl (Batch& parBatch, dhandy::bt::index_seq<I...>, Args&&... parArgs) {
static_assert(sizeof...(I) == sizeof...(Args), "Wrong number of indices");
static_assert(PreArgsCount <= sizeof...(I), "Can't ignore more arguments than those that were received");
parBatch.run(stringize_or_forward<PreArgsCount, I>(std::forward<Args>(parArgs))...);
}
template <std::size_t... I, typename... Args>
void run_conv_floats_to_strings (Batch& parBatch, dhandy::bt::index_seq<I...>, Args&&... parArgs) {
static_assert(sizeof...(Args) >= sizeof...(I), "Unexpected count, there should be at least as many argument as there are indices");
constexpr const auto pre_args_count = sizeof...(Args) - sizeof...(I);
run_conv_floats_to_strings_impl<pre_args_count>(parBatch, dhandy::bt::index_range<0, sizeof...(Args)>(), std::forward<Args>(parArgs)...);
};
} //namespace implem
} //namespace redis
#endif

86
src/reply.cpp Normal file
View file

@ -0,0 +1,86 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "reply.hpp"
#include "duckhandy/lexical_cast.hpp"
#include <boost/variant/get.hpp>
namespace redis {
const long long& get_integer (const Reply& parReply) {
assert(RedisVariantType_Integer == parReply.which());
return boost::get<long long>(parReply);
}
const std::string& get_string (const Reply& parReply) {
static const std::string empty_str;
if (RedisVariantType_Nil == parReply.which())
return empty_str;
assert(RedisVariantType_String == parReply.which());
return boost::get<std::string>(parReply);
}
long long get_integer_autoconv_if_str (const Reply &parReply) {
using dhandy::lexical_cast;
const auto type = parReply.which();
switch (type) {
case RedisVariantType_Integer:
return get_integer(parReply);
case RedisVariantType_String:
return lexical_cast<long long>(get_string(parReply));
default:
assert(false);
return 0;
}
}
const std::vector<Reply>& get_array (const Reply& parReply) {
assert(RedisVariantType_Array == parReply.which());
return boost::get<std::vector<Reply>>(parReply);
}
const ErrorString& get_error_string (const Reply& parReply) {
assert(RedisVariantType_Error == parReply.which());
return boost::get<ErrorString>(parReply);
}
template <>
const std::string& get<std::string> (const Reply& parReply) {
return get_string(parReply);
}
template <>
const std::vector<Reply>& get<std::vector<Reply>> (const Reply& parReply) {
return get_array(parReply);
}
template <>
const long long& get<long long> (const Reply& parReply) {
return get_integer(parReply);
}
template <>
const ErrorString& get<ErrorString> (const Reply& parReply) {
return get_error_string(parReply);
}
template const std::string& get<std::string> ( const Reply& parReply );
template const std::vector<Reply>& get<std::vector<Reply>> ( const Reply& parReply );
template const long long& get<long long> ( const Reply& parReply );
template const ErrorString& get<ErrorString> ( const Reply& parReply );
} //namespace redis

92
src/reply.hpp Normal file
View file

@ -0,0 +1,92 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef id93FA96E3071745D9A1E45D4D29B9F7D0
#define id93FA96E3071745D9A1E45D4D29B9F7D0
#include <boost/variant/variant.hpp>
#include <string>
#include <vector>
namespace redis {
struct Reply;
class ErrorString {
public:
ErrorString ( const char* parCStr, std::size_t parLen ) :
m_msg(parCStr, parLen)
{ }
const std::string& message ( void ) const noexcept { return m_msg; }
private:
std::string m_msg;
};
class StatusString {
public:
StatusString ( const char* parCStr, std::size_t parLen ) :
m_msg(parCStr, parLen)
{ }
const std::string& message ( void ) const noexcept { return m_msg; }
bool is_ok ( void ) const { return "OK" == m_msg; }
private:
std::string m_msg;
};
namespace implem {
using RedisVariantType = boost::variant<
long long,
std::string,
std::vector<Reply>,
ErrorString,
StatusString,
std::nullptr_t
>;
} //namespace implem
enum RedisVariantTypes {
RedisVariantType_Integer = 0,
RedisVariantType_String,
RedisVariantType_Array,
RedisVariantType_Error,
RedisVariantType_Status,
RedisVariantType_Nil
};
struct Reply : implem::RedisVariantType {
using base_class = implem::RedisVariantType;
Reply ( void ) = default;
Reply ( long long parVal ) : base_class(parVal) {}
Reply ( std::string&& parVal ) : base_class(std::move(parVal)) {}
Reply ( std::vector<Reply>&& parVal ) : base_class(std::move(parVal)) {}
Reply ( ErrorString&& parVal ) : base_class(std::move(parVal)) {}
Reply ( StatusString&& parVal ) : base_class(std::move(parVal)) {}
Reply ( std::nullptr_t parVal ) : base_class(parVal) {}
~Reply ( void ) noexcept = default;
};
const long long& get_integer ( const Reply& parReply );
long long get_integer_autoconv_if_str ( const Reply& parReply );
const std::string& get_string ( const Reply& parReply );
const std::vector<Reply>& get_array ( const Reply& parReply );
const ErrorString& get_error_string ( const Reply& parReply );
template <typename T>
const T& get ( const Reply& parReply );
} //namespace redis
#endif

62
src/scan_iterator.cpp Normal file
View file

@ -0,0 +1,62 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "scan_iterator.hpp"
#include "duckhandy/lexical_cast.hpp"
#include "command.hpp"
#include <cassert>
#include <ciso646>
#include <string>
namespace redis {
namespace implem {
ScanIteratorBaseClass::ScanIteratorBaseClass (Command* parCommand) :
ScanIteratorBaseClass(parCommand, boost::string_ref())
{
}
ScanIteratorBaseClass::ScanIteratorBaseClass (Command* parCommand, boost::string_ref parMatchPattern) :
m_command(parCommand),
m_match_pattern(parMatchPattern)
{
assert(m_command);
assert(m_command->is_connected());
}
bool ScanIteratorBaseClass::is_connected() const {
return m_command and m_command->is_connected();
}
Reply ScanIteratorBaseClass::run (const char* parCommand, long long parScanContext, std::size_t parCount) {
const auto scan_context = dhandy::lexical_cast<std::string>(parScanContext);
const auto count_hint = dhandy::lexical_cast<std::string>(parCount);
if (m_match_pattern.empty())
return m_command->run(parCommand, scan_context, "COUNT", count_hint);
else
return m_command->run(parCommand, scan_context, "MATCH", m_match_pattern, "COUNT", count_hint);
}
Reply ScanIteratorBaseClass::run (const char* parCommand, const boost::string_ref& parParameter, long long parScanContext, std::size_t parCount) {
const auto scan_context = dhandy::lexical_cast<std::string>(parScanContext);
const auto count_hint = dhandy::lexical_cast<std::string>(parCount);
if (m_match_pattern.empty())
return m_command->run(parCommand, parParameter, scan_context, "COUNT", count_hint);
else
return m_command->run(parCommand, parParameter, scan_context, "MATCH", m_match_pattern, "COUNT", count_hint);
}
} //namespace implem
} //namespace redis

144
src/scan_iterator.hpp Normal file
View file

@ -0,0 +1,144 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef id774125B851514A26BD7C2AD1D804D732
#define id774125B851514A26BD7C2AD1D804D732
#include "reply.hpp"
#include "duckhandy/has_method.hpp"
#include "enum.h"
#include <boost/iterator/iterator_facade.hpp>
#include <type_traits>
#include <vector>
#include <cstddef>
#include <boost/utility/string_ref.hpp>
namespace redis {
template <typename ValueFetch>
class ScanIterator;
class Command;
namespace implem {
template <typename ValueFetch>
using ScanIteratorBaseIterator = boost::iterator_facade<ScanIterator<ValueFetch>, const typename ValueFetch::value_type, boost::forward_traversal_tag>;
class ScanIteratorBaseClass {
protected:
explicit ScanIteratorBaseClass ( Command* parCommand );
ScanIteratorBaseClass ( Command* parCommand, boost::string_ref parMatchPattern );
~ScanIteratorBaseClass ( void ) noexcept = default;
bool is_connected ( void ) const;
Reply run ( const char* parCommand, long long parScanContext, std::size_t parCount );
Reply run ( const char* parCommand, const boost::string_ref& parParameter, long long parScanContext, std::size_t parCount );
bool is_equal ( const ScanIteratorBaseClass& parOther ) const { return m_command == parOther.m_command; }
private:
Command* m_command;
boost::string_ref m_match_pattern;
};
} //namespace implem
BETTER_ENUM(ScanCommands, char,
SCAN, SSCAN, ZSCAN, HSCAN
);
template <typename ValueFetch>
class ScanIterator : private implem::ScanIteratorBaseClass, public implem::ScanIteratorBaseIterator<ValueFetch>, private ValueFetch {
friend class boost::iterator_core_access;
typedef implem::ScanIteratorBaseIterator<ValueFetch> base_iterator;
define_has_method(scan_target, ScanTarget);
public:
typedef typename base_iterator::difference_type difference_type;
typedef typename base_iterator::value_type value_type;
typedef typename base_iterator::pointer pointer;
typedef typename base_iterator::reference reference;
typedef typename base_iterator::iterator_category iterator_category;
template <typename Dummy=ValueFetch, typename=typename std::enable_if<not HasScanTargetMethod<Dummy>::value>::type>
ScanIterator ( Command* parCommand, bool parEnd, boost::string_ref parMatchPattern=boost::string_ref() );
template <typename Dummy=ValueFetch, typename=typename std::enable_if<HasScanTargetMethod<Dummy>::value>::type>
ScanIterator ( Command* parCommand, boost::string_ref parKey, bool parEnd, boost::string_ref parMatchPattern=boost::string_ref() );
private:
template <typename T>
Reply forward_scan_command ( typename std::enable_if<HasScanTargetMethod<T>::value, long long>::type parContext );
template <typename T>
Reply forward_scan_command ( typename std::enable_if<not HasScanTargetMethod<T>::value, long long>::type parContext );
bool is_end ( void ) const;
void increment ( void );
bool equal ( const ScanIterator& parOther ) const;
const value_type& dereference ( void ) const;
std::vector<value_type> m_reply;
long long m_scan_context;
std::size_t m_curr_index;
};
template <typename T>
struct ScanSingleValues {
typedef T value_type;
static constexpr const char* command ( void ) { return "SCAN"; }
static constexpr const std::size_t step = 1;
static constexpr const std::size_t work_count = 10;
static const T& make_value ( const Reply* parItem );
};
template <typename T>
struct ScanSingleValuesInKey {
typedef T value_type;
explicit ScanSingleValuesInKey ( boost::string_ref parScanTarget ) : m_scan_target(parScanTarget) {}
static constexpr const char* command ( void ) { return "SSCAN"; }
static constexpr const std::size_t step = 1;
static constexpr const std::size_t work_count = 10;
static const T& make_value ( const Reply* parItem );
boost::string_ref scan_target ( void ) const { return m_scan_target; }
private:
boost::string_ref m_scan_target;
};
template <typename P, char Command, typename A=decltype(P().first), typename B=decltype(P().second)>
struct ScanPairs {
static_assert(Command == ScanCommands::HSCAN or Command == ScanCommands::ZSCAN, "Invalid scan command chosen");
typedef P value_type;
explicit ScanPairs ( boost::string_ref parScanTarget ) : m_scan_target(parScanTarget) {}
static constexpr const char* command ( void ) { return ScanCommands::_from_integral(Command)._to_string(); }
static constexpr const std::size_t step = 2;
static constexpr const std::size_t work_count = 10;
static value_type make_value ( const Reply* parItem );
boost::string_ref scan_target ( void ) const { return m_scan_target; }
private:
boost::string_ref m_scan_target;
};
} //namespace redis
#include "scan_iterator.inl"
#endif

161
src/scan_iterator.inl Normal file
View file

@ -0,0 +1,161 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "command.hpp"
#include <cassert>
#include <ciso646>
namespace redis {
namespace implem {
} //namespace implem
template <typename ValueFetch>
template <typename Dummy, typename>
ScanIterator<ValueFetch>::ScanIterator (Command* parCommand, bool parEnd, boost::string_ref parMatchPattern) :
implem::ScanIteratorBaseClass(parCommand, parMatchPattern),
implem::ScanIteratorBaseIterator<ValueFetch>(),
ValueFetch(),
m_reply(),
m_scan_context(0),
m_curr_index(0)
{
if (not parEnd) {
m_curr_index = 1; //Some arbitrary value so is_end()==false
assert(not is_end());
this->increment();
}
else {
assert(is_end());
}
}
template <typename ValueFetch>
template <typename Dummy, typename>
ScanIterator<ValueFetch>::ScanIterator (Command* parCommand, boost::string_ref parKey, bool parEnd, boost::string_ref parMatchPattern) :
implem::ScanIteratorBaseClass(parCommand, parMatchPattern),
implem::ScanIteratorBaseIterator<ValueFetch>(),
ValueFetch(parKey),
m_reply(),
m_scan_context(0),
m_curr_index(0)
{
if (not parEnd) {
m_curr_index = 1; //Some arbitrary value so is_end()==false
assert(not is_end());
this->increment();
}
else {
assert(is_end());
}
}
template <typename ValueFetch>
bool ScanIterator<ValueFetch>::is_end() const {
return not m_curr_index and m_reply.empty() and not m_scan_context;
}
template <typename ValueFetch>
void ScanIterator<ValueFetch>::increment() {
assert(not is_end());
static_assert(ValueFetch::step > 0, "Can't have an increase step of 0");
if (m_curr_index + 1 < m_reply.size()) {
++m_curr_index;
}
else if (m_curr_index + 1 == m_reply.size() and not m_scan_context) {
m_reply.clear();
m_curr_index = 0;
}
else {
std::vector<Reply> array_reply;
long long new_context = m_scan_context;
do {
auto whole_reply = this->forward_scan_command<ValueFetch>(new_context);
array_reply = get_array(whole_reply);
assert(2 == array_reply.size());
assert(array_reply.size() % ValueFetch::step == 0);
new_context = get_integer_autoconv_if_str(array_reply[0]);
} while (new_context and get_array(array_reply[1]).empty());
const auto variant_array = get_array(array_reply[1]);
assert(variant_array.size() % ValueFetch::step == 0);
const std::size_t expected_reply_count = variant_array.size() / ValueFetch::step;
m_reply.clear();
m_reply.reserve(expected_reply_count);
for (std::size_t z = 0; z < variant_array.size(); z += ValueFetch::step) {
m_reply.push_back(ValueFetch::make_value(variant_array.data() + z));
}
assert(expected_reply_count == m_reply.size());
m_scan_context = new_context;
m_curr_index = 0;
}
}
template <typename ValueFetch>
bool ScanIterator<ValueFetch>::equal (const ScanIterator& parOther) const {
return
(&parOther == this) or
(is_end() and parOther.is_end()) or
(
not (is_end() or parOther.is_end()) and
implem::ScanIteratorBaseClass::is_equal(parOther) and
(m_scan_context == parOther.m_scan_context) and
(m_curr_index == parOther.m_curr_index) and
(m_reply.size() == parOther.m_reply.size())
);
}
template <typename ValueFetch>
auto ScanIterator<ValueFetch>::dereference() const -> const value_type& {
assert(not m_reply.empty());
assert(m_curr_index < m_reply.size());
return m_reply[m_curr_index];
}
template <typename ValueFetch>
template <typename T>
Reply ScanIterator<ValueFetch>::forward_scan_command (typename std::enable_if<HasScanTargetMethod<T>::value, long long>::type parContext) {
return implem::ScanIteratorBaseClass::run(T::command(), T::scan_target(), parContext, T::work_count);
}
template <typename ValueFetch>
template <typename T>
Reply ScanIterator<ValueFetch>::forward_scan_command (typename std::enable_if<not HasScanTargetMethod<T>::value, long long>::type parContext) {
return implem::ScanIteratorBaseClass::run(T::command(), parContext, T::work_count);
}
template <typename T>
auto ScanSingleValues<T>::make_value (const Reply* parItem) -> const value_type& {
assert(parItem);
return get<T>(*parItem);
}
template <typename T>
auto ScanSingleValuesInKey<T>::make_value (const Reply* parItem) -> const value_type& {
assert(parItem);
return get<T>(*parItem);
}
template <typename P, char Command, typename A, typename B>
auto ScanPairs<P, Command, A, B>::make_value (const Reply* parItem) -> value_type {
assert(parItem);
return value_type(get<A>(parItem[0]), get<B>(parItem[1]));
}
} //namespace redis

32
src/script.cpp Normal file
View file

@ -0,0 +1,32 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "script.hpp"
namespace redis {
Script::Script() :
m_sha1(),
m_manager(nullptr)
{
}
Script::Script (boost::string_ref parSha1, ScriptManager& parManager) :
m_sha1(parSha1),
m_manager(&parManager)
{
}
} //namespace redis

83
src/script.hpp Normal file
View file

@ -0,0 +1,83 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef id5B30CDA57F894CD6888093B64F9433DA
#define id5B30CDA57F894CD6888093B64F9433DA
#include "batch.hpp"
#include "duckhandy/lexical_cast.hpp"
#include "duckhandy/sequence_bt.hpp"
#include <boost/utility/string_ref.hpp>
#include <tuple>
#include <cassert>
#include <ciso646>
namespace redis {
class ScriptManager;
class Script {
public:
Script ( void );
Script ( Script&& ) = default;
Script ( boost::string_ref parSha1, ScriptManager& parManager );
~Script ( void ) noexcept = default;
template <typename... Keys, typename... Values>
void run ( Batch& parBatch, const std::tuple<Keys...>& parKeys, const std::tuple<Values...>& parValues );
Script& operator= ( Script&& ) = default;
private:
template <typename... Keys, typename... Values, std::size_t... KeyIndices, std::size_t... ValueIndices>
void run_with_indices ( Batch& parBatch, const std::tuple<Keys...>& parKeys, const std::tuple<Values...>& parValues, dhandy::bt::index_seq<KeyIndices...>, dhandy::bt::index_seq<ValueIndices...> );
boost::string_ref m_sha1;
ScriptManager* m_manager;
};
template <typename... Keys, typename... Values>
void Script::run (Batch& parBatch, const std::tuple<Keys...>& parKeys, const std::tuple<Values...>& parValues) {
this->run_with_indices(
parBatch,
parKeys,
parValues,
::dhandy::bt::index_range<0, sizeof...(Keys)>(),
::dhandy::bt::index_range<0, sizeof...(Values)>()
);
}
template <typename... Keys, typename... Values, std::size_t... KeyIndices, std::size_t... ValueIndices>
void Script::run_with_indices (Batch& parBatch, const std::tuple<Keys...>& parKeys, const std::tuple<Values...>& parValues, dhandy::bt::index_seq<KeyIndices...>, dhandy::bt::index_seq<ValueIndices...>) {
static_assert(sizeof...(Keys) == sizeof...(KeyIndices), "Wrong index count");
static_assert(sizeof...(Values) == sizeof...(ValueIndices), "Wrong value count");
static_assert(sizeof...(Keys) == std::tuple_size<std::tuple<Keys...>>::value, "Wrong key count");
static_assert(sizeof...(Values) == std::tuple_size<std::tuple<Values...>>::value, "Wrong value count");
assert(not m_sha1.empty());
assert(m_manager);
parBatch.run(
"EVALSHA",
m_sha1,
dhandy::lexical_cast<std::string>(sizeof...(Keys)),
std::get<KeyIndices>(parKeys)...,
std::get<ValueIndices>(parValues)...
);
}
} //namespace redis
#endif

111
src/script_manager.cpp Normal file
View file

@ -0,0 +1,111 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#include "script_manager.hpp"
#include "duckhandy/lexical_cast.hpp"
#include "command.hpp"
#include <cassert>
#if defined(MAKE_SHA1_WITH_CRYPTOPP)
# include <crypto++/sha.h>
#endif
namespace redis {
namespace {
#if defined(MAKE_SHA1_WITH_CRYPTOPP)
struct LuaScriptHash {
union {
struct {
uint64_t part_a, part_b;
uint32_t part_c;
};
uint8_t raw_bytes[20];
};
};
#endif
} //unnamed namespace
ScriptManager::ScriptManager (Command* parCommand) :
m_command(parCommand)
{
assert(m_command);
}
#if defined(MAKE_SHA1_WITH_CRYPTOPP)
boost::string_ref ScriptManager::add_lua_script_ifn (const std::string& parScript) {
assert(m_command->is_connected());
if (parScript.empty())
return boost::string_ref();
using dhandy::lexical_cast;
static_assert(20 == CryptoPP::SHA1::DIGESTSIZE, "Unexpected SHA1 digest size");
static_assert(sizeof(LuaScriptHash) >= CryptoPP::SHA1::DIGESTSIZE, "Wrong SHA1 struct size");
static_assert(Sha1Array().size() == CryptoPP::SHA1::DIGESTSIZE * 2, "Wrong array size");
LuaScriptHash digest;
CryptoPP::SHA1().CalculateDigest(digest.raw_bytes, reinterpret_cast<const uint8_t*>(parScript.data()), parScript.size());
//TODO: change when lexical_cast will support arrays
auto sha1_str_parta = lexical_cast<std::string, dhandy::tags::hexl>(__builtin_bswap64(digest.part_a));
auto sha1_str_partb = lexical_cast<std::string, dhandy::tags::hexl>(__builtin_bswap64(digest.part_b));
auto sha1_str_partc = lexical_cast<std::string, dhandy::tags::hexl>(__builtin_bswap32(digest.part_c));
const std::string sha1_str =
std::string(sizeof(digest.part_a) * 2 - sha1_str_parta.size(), '0') + sha1_str_parta +
std::string(sizeof(digest.part_b) * 2 - sha1_str_partb.size(), '0') + sha1_str_partb +
std::string(sizeof(digest.part_c) * 2 - sha1_str_partc.size(), '0') + sha1_str_partc
;
Sha1Array sha1_array;
assert(sha1_str.size() == sha1_array.size());
std::copy(sha1_str.begin(), sha1_str.end(), sha1_array.begin());
auto it_found = m_known_hashes.find(sha1_array);
const bool was_present = (m_known_hashes.end() != it_found);
if (was_present) {
return boost::string_ref(it_found->data(), it_found->size());
}
auto reply = m_command->run("SCRIPT", "LOAD", parScript);
assert(not was_present);
assert(get_string(reply) == sha1_str);
const auto it_inserted = m_known_hashes.insert(it_found, sha1_array);
(void)reply;
return boost::string_ref(it_inserted->data(), it_inserted->size());
}
#else
boost::string_ref ScriptManager::add_lua_script_ifn (const std::string& parScript) {
assert(m_command->is_connected());
auto it_found = m_known_scripts.find(parScript);
const bool was_present = (m_known_scripts.end() != it_found);
if (was_present) {
return boost::string_ref(it_found->second.data(), it_found->second.size());
}
auto reply = m_command->run("SCRIPT", "LOAD", parScript);
assert(not was_present);
const auto sha1_str = get_string(reply);
Sha1Array sha1_array;
std::copy(sha1_str.begin(), sha1_str.end(), sha1_array.begin());
auto it_inserted = m_known_scripts.insert(it_found, std::make_pair(parScript, sha1_array));
return boost::string_ref(it_inserted->second.data(), it_inserted->second.size());
}
#endif
} //namespace redis

62
src/script_manager.hpp Normal file
View file

@ -0,0 +1,62 @@
/* Copyright 2016, Michele Santullo
* This file is part of "incredis".
*
* "incredis" 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.
*
* "incredis" 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 "incredis". If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef id8E124FF76DF449CDB8FBA806F8EF4E78
#define id8E124FF76DF449CDB8FBA806F8EF4E78
#include "incredisConfig.h"
#if defined(WITH_CRYPTOPP)
# define MAKE_SHA1_WITH_CRYPTOPP
#endif
#include <boost/utility/string_ref.hpp>
#if defined(MAKE_SHA1_WITH_CRYPTOPP)
# include <set>
#else
# include <map>
#endif
#include <string>
#include <array>
#include <boost/utility/string_ref.hpp>
namespace redis {
class Command;
class ScriptManager {
public:
explicit ScriptManager ( Command* parCommand );
boost::string_ref submit_lua_script ( const std::string& parScript );
private:
using Sha1Array = std::array<char, 40>;
boost::string_ref add_lua_script_ifn ( const std::string& parScript );
Command* const m_command;
#if defined(MAKE_SHA1_WITH_CRYPTOPP)
std::set<Sha1Array> m_known_hashes;
#else
std::map<std::string, Sha1Array> m_known_scripts;
#endif
};
inline boost::string_ref ScriptManager::submit_lua_script (const std::string& parScript) {
return add_lua_script_ifn(parScript);
}
} //namespace redis
#endif