[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: jarun\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "set(CMAKE_POSITION_INDEPENDENT_CODE ON)\n\ncmake_minimum_required(VERSION 3.12)\n\nproject(dslib)\n\nfile(GLOB files CONFIGURE_DEPENDS include/*.h src/*.c)\nadd_library(ds SHARED ${files})\n\nfind_package(Threads REQUIRED)\ntarget_link_libraries(ds PUBLIC Threads::Threads)\n\ntarget_include_directories(ds\n    PUBLIC\n        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>\n        $<INSTALL_INTERFACE:include/ds>\n    )\n\nif (UNIX)\n    target_link_libraries(ds PRIVATE -Wl,-undefined,dynamic_lookup)\nendif()\n\nfile(GLOB files CONFIGURE_DEPENDS test/*.c )\nforeach(file IN LISTS files)\n    get_filename_component(test_name ${file} NAME_WE)\n\n    add_executable(${test_name} ${file})\n    target_link_libraries(${test_name} PRIVATE ds)\n\n    add_test(${test_name} ${test_name})\nendforeach()\n\ninclude(CTest)\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {name of author}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {project}  Copyright (C) {year}  {fullname}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n\n"
  },
  {
    "path": "Makefile",
    "content": "CC = gcc\nCFLAGS = -Wall -Wextra -Werror -O3 -fPIC $(INCLUDE)\n\nSRC = $(wildcard src/*.c)\nOBJS = $(SRC:%.c=%.o)\nINCLUDE = -Iinclude\nTARGET = libds.so.1.0\n\nBINDIR = ./bin\nHEADERDIR = /usr/include/dslib\nDESTDIR = /usr/lib\n\nall: $(TARGET)\n\n$(TARGET): $(OBJS)\n\tmkdir -p $(BINDIR)\n\t$(CC) $(CFLAGS) -shared -Wl,-soname,libds.so.1 -o $(BINDIR)/$(TARGET) $(OBJS)\n\tstrip $(BINDIR)/$(TARGET)\n\n.PHONY: test clean\ntest:\n\tcd test && $(MAKE)\n\nclean:\n\trm -f $(OBJS) $(BINDIR)/$(TARGET)\n\trm -rf $(BINDIR)\n\t# clean test files too\n\tcd test && $(MAKE) clean\n\ndistclean: clean\n\trm -f *~\n\ninstall: $(TARGET)\n\tinstall -m755 -d $(HEADERDIR)\n\tinstall -m644 -t $(HEADERDIR) include/*.h\n\tinstall -o root -m 644 $(BINDIR)/$(TARGET) $(DESTDIR)/\n\tln -sf $(DESTDIR)/$(TARGET) $(DESTDIR)/libds.so.1\n\tln -sf $(DESTDIR)/libds.so.1 $(DESTDIR)/libds.so\n\nuninstall:\n\trm -rf $(HEADERDIR)\n\trm -f $(DESTDIR)/libds.so $(DESTDIR)/libds.so.1 $(DESTDIR)/$(TARGET)\n"
  },
  {
    "path": "README.md",
    "content": "# dslib\n`dslib` is a library of cohesive data structures. The goal of `dslib` is to demonstrate how complex data structures (and related algorithms) can be developed by reusing simpler ones. In general, textbooks come with numerous unrelated examples, each relevant to a specific data structure. `dslib`, on the other hand, grows by building on the elementary data structures.\n\nThe core component is a circular doubly linked list. Library-internal data structures are dynamically (de)allocated.\n\nMost of the code conforms to the Linux kernel coding standards (verified against *checkpatch.pl*), other than a few unavoidable instances.\n\n`dslib` is an academic library. However, we'll be glad if someone finds any other application of it.\n\n<p align=\"center\">\n<a href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=RMLTQ76JSXJ4Q\"><img src=\"https://img.shields.io/badge/PayPal-donate-1eb0fc.svg\" alt=\"Donate via PayPal!\" /></a>\n</p>\n\n### Table of Contents\n- [Building blocks](#building-blocks)\n- [APIs](#apis)\n- [Thread-safety](#thread-safety)\n- [Compilation](#compilation)\n- [Testing](#testing)\n- [Developers](#developers)\n- [Contributions](#contributions)\n\n### Building blocks\n| DS | Description |\n| --- | --- |\n| dlist | Circular doubly linked list. Node has next, prev and data (`void *`, caller (de)allocates) pointers. |\n| queue | Builds on top of dlist. Each element is a dlist node pointing to the value inserted in the queue. |\n| stack | Builds on top of dlist. Each element is a dlist node pointing to the value pushed in the stack. |\n| tree | A binary search tree, stores integers. |\n| AVL | An AVL tree implementation, stores integers. |\n| BFS | Iterative Breadth-first search for tree and AVL implemented using the queue. |\n| DFS | Iterative Depth-first search for tree implemented using the stack. |\n\nThere are test cases for each DS. Though not very organized, they provide an insight into the usage of `dslib`.\n\n### APIs\nA complete list of APIs can be found in [apilist.txt](https://github.com/jarun/dslib/blob/master/apilist.txt). Most of the APIs are iterative.\nThe following 2 APIs are recursive and the iterative implementations are left as an exercise:\n\n```\nbool delete_tree_node(tree_pp head, int val);\nbool delete_avl_node(avl_pp head, int val);\n```\n\n### Thread-safety\nCurrently the Thread-Safe mode is implemented only for AVL. The lock functions are in common.h and common.c and it's easy to extend thread-safety in other structures.\n\n### Compilation\nThe following compilation steps are tested on Ubuntu 14.04.4 x86_64:\n\n    $ git clone https://github.com/jarun/dslib/\n    $ cd dslib\n    $ make\n\nTo install `dslib`, run:\n\n    $ sudo make install\n\nTo remove `dslib` from your system, run:\n\n    $ sudo make uninstall\n\nClean up (cleans test executables too):\n\n    $ make clean\n\n### Testing\nMake sure `dslib` is installed. To compile test cases under `test` subdirectory:\n\n    $ sudo make install\n    $ make test\n\nOnly informative logs are enabled. For DEBUG logs, set:\n\n    int current_log_level = DEBUG;\n\nin the source test file.\n\n### Developers\n- [Arun Prakash Jana](https://github.com/jarun) (Copyright © 2015)\n- [Ananya Jana](https://github.com/ananyajana)\n\n### Contributions\nContributions are welcome! We would love to see more data structures and APIs added to `dslib`.\n"
  },
  {
    "path": "apilist.txt",
    "content": "########################################\n1. Circular Doubly Linked List [dlist.h]\n########################################\n\nint add_head_dlist(dlist_pp head, dlist_p node);\nvoid *get_head_dlist(dlist_pp head);\nvoid *get_tail_dlist(dlist_pp head);\nint delete_head_dlist(dlist_pp head);\nint delete_tail_dlist(dlist_pp head);\nint destroy_dlist(dlist_pp head);\nint count_nodes_dlist(dlist_pp head);\n\n##################\n2. Queue [queue.h]\n##################\n\nqueue_p get_queue(void);\nbool enqueue(queue_p queue, void *val);\nvoid *dequeue(queue_p queue);\nbool isQueueEmpty(queue_p queue);\nbool destroy_queue(queue_p queue);\n\n##################\n3. Stack [stack.h]\n##################\n\nstack_p get_stack(void);\nbool push(stack_p stack, void *val);\nvoid *pop(stack_p stack);\nbool isStackEmpty(stack_p stack);\nbool destroy_stack(stack_p stack);\n\n##############################\n4. Binary Search Tree [tree.h]\n##############################\n\ntree_pp generate_tree(int *arr, int len);\ntree_pp init_tree(void);\nbool insert_tree_node(tree_pp head, int val);\nbool delete_tree_node(tree_pp head, int val);\nint destroy_tree(tree_pp head);\nint print_tree(tree_p root);\nint search_BFS(tree_pp root, int val, bool stop);\nint search_DFS(tree_pp root, int val, bool stop);\n\n###################\n5. AVL Tree [avl.h]\n###################\n\navl_pp generate_avl(int *arr, int len);\navl_pp init_avl(void);\nbool insert_avl_node(avl_pp head, int val);\nbool delete_avl_node(avl_pp head, int val);\nint destroy_avl(avl_pp head);\nint print_avl(avl_p root, avl_p parent);\nint search_BFS_avl(avl_pp root, int val, bool stop);\n"
  },
  {
    "path": "include/avl.h",
    "content": "/*\n * AVL Tree abstraction\n * Ref: https://en.wikipedia.org/wiki/AVL_tree\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"common.h\"\n\n#pragma once\n\ntypedef struct avl {\n\tint keyNode;\n\tint data;\n\tstruct avl *left;\n\tstruct avl *right;\n\tint height;\n} avl_t, *avl_p, **avl_pp;\n\n/* Generate AVL tree from an array of input values */\navl_pp generate_avl(int *arr, int len);\n\n/* Initialize an AVL tree */\navl_pp init_avl(void);\n\n/* Insert a node in AVL tree */\nbool insert_avl_node(avl_pp head, int key, int data);\n\n\n/* Delete a node from AVL tree */\nbool delete_avl_node(avl_pp head, int key);\n\n/* Destroy the tree */\nint destroy_avl(avl_pp head);\n// avl will be destroy isn't necessary sincronize it (is better not destroy)\n\n/* Print a tree in preorder */\nint print_avl(avl_p root, avl_p parent);\n\n/* Traverse tree in BFS to find a given value */\nint search_BFS_avl(avl_pp root, int key, bool stop);\n\n/*=======================================================*/\n/*         Library ThreadSafe APIs start here            */\n/*=======================================================*/\n\n//The struct is a generalization of avl_pp, to include for every tree one semaphore\ntypedef struct avlThSafe {\n\tavl_pp avlRoot;\n\tint semId;\n} avl_pp_S;\n\n/* Generate AVL tree from an array of input values */\navl_pp_S generate_avl_S(int *arr, int len);\n\n/* Initialize an AVL tree */\navl_pp_S init_avl_S(void);\n\n/* Insert a node in AVL tree */\nbool insert_avl_node_S(avl_pp_S head, int key, int data);\n\n/* Delete a node from AVL tree */\nbool delete_avl_node_S(avl_pp_S head, int key);\n\n/* Destroy the tree */\n/** [][] avl will be destroy isn't necessary sincronize it (is better not destroy) **/\n\n/* Print a tree in preorder, start by root */\nint print_avl_S(avl_pp_S root);\n\n/* Traverse tree in BFS to find a given value */\nint search_BFS_avl_S(avl_pp_S root, int key, bool stop);"
  },
  {
    "path": "include/common.h",
    "content": "/*\n * Common header file for dslib\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"log.h\"\n\n#pragma once\n\n#include <stdlib.h>\n#include <sys/types.h>\n#include <sys/ipc.h>\n#include <sys/sem.h>\n#include <errno.h>\n\n/* Introduce boolean type */\n#define TRUE 1\n#define FALSE !TRUE\n\n#define LEFT  0\n#define RIGHT 1\n\ntypedef unsigned char bool;\n\n/*=======================================================*/\n/*      Syncronize for ThreadSafe APIs start here        */\n/*=======================================================*/\n\nenum semName {wantWrite=0,readWorking=1,writeWorking=2};\n\nint semInit();\n\n/*#######################################*/\n/*   Lock/unlock for writers function    */\n/*#######################################*/\nint lockWriteSem(int semId);\n\nint unlockWriteSem(int semId);\n\n/*#######################################*/\n/*   Lock/unlock for readers function    */\n/*#######################################*/\nint lockReadSem(int semId);\n\nint unlockReadSem(int semId);\n\n//semInfo print\nvoid semInfo(int semId);\n\n\n/*\nThe scheme of synchronization is easy: (i use system 5)\nThere are 3 semaphore: wantWrite,readWorking and writeWorking (last like mutex, and the first two are counter in fact)\n\nREADER:\nIf more than one read-funx(like search) need to read data it  will be wait until wantWrite!=0.\nATOMICALLY it add at readWorking +1, to start only if no one write are current at working.\nAfter, ALL READER-funx can be work and finally decrease readWorking counter (this in concurrency).\n\nWRITER:\nto start it  add wantWrite +1, (to signal at new reader, it si necessary to waiting)\nafter the writers WAIT until all reader just at work finish.\nthen, writer-funx can lock writeWorking to write one at time (is a mutex),\nenter in critic section, and at the end unlock writeWorking.\nFinally decrement wantWrite -1, and finish.\n\n*/\n"
  },
  {
    "path": "include/dlist.h",
    "content": "/*\n * Circular Doubly Linked List abstraction\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"common.h\"\n\n#pragma once\n\n/* Circular Doubly Linked List ADT */\ntypedef struct dlist {\n\tvoid *data;\n\tstruct dlist *next;\n\tstruct dlist *prev;\n} dlist_t, *dlist_p, **dlist_pp;\n\n/* Add node at head of list */\nint add_head_dlist(dlist_pp head, dlist_p node);\n\n/* Get the head of list */\nvoid *get_head_dlist(dlist_pp head);\n\n/* Get the tail of list */\nvoid *get_tail_dlist(dlist_pp head);\n\n/* Delete the head of list */\nint delete_head_dlist(dlist_pp head);\n\n/* Delete the tail of list */\nint delete_tail_dlist(dlist_pp head);\n\n/* Clean up list */\nint destroy_dlist(dlist_pp head);\n\n/* Count total nodes in list */\nint count_nodes_dlist(dlist_pp head);\n"
  },
  {
    "path": "include/log.h",
    "content": "/*\n * A modular, level based log file implementation\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2014 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#pragma once\n\n#include <stdio.h>\n#include <stdarg.h>\n\n#define ERROR 0\n#define INFO 1\n#define DEBUG 2\n\n#define log(level, format, ...) \\\n\tdebug_log(__FILE__, __func__, __LINE__, \\\n\t\t\tlevel, format, ##__VA_ARGS__)\n\nvoid debug_log(const char *file,\n\t\tconst char *func,\n\t\tint line,\n\t\tint level,\n\t\tconst char *format,\n\t\t...) __attribute__((__format__(printf, 5, 6)));\n"
  },
  {
    "path": "include/queue.h",
    "content": "/*\n * Queue abstraction\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"dlist.h\"\n\n#pragma once\n\n/* Queue ADT using a circular doubly linked list */\ntypedef struct {\n\tdlist_pp head;\n} queue_t, *queue_p;\n\n/* Create a new Queue */\nqueue_p get_queue(void);\n\n/* Add a value to Queue */\nbool enqueue(queue_p queue, void *val);\n\n/* Remove a value from Queue */\nvoid *dequeue(queue_p queue);\n\n/* Check if the Queue is empty */\nbool isQueueEmpty(queue_p queue);\n\n/* Clean up Queue */\nbool destroy_queue(queue_p queue);\n"
  },
  {
    "path": "include/stack.h",
    "content": "/*\n * Stack abstraction\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"dlist.h\"\n\n#pragma once\n\n/* Stack ADT using a circular doubly linked list */\ntypedef struct {\n\tdlist_pp head;\n} stack_t, *stack_p;\n\n/* Create a new Stack */\nstack_p get_stack(void);\n\n/* Push a value to Stack */\nbool push(stack_p stack, void *val);\n\n/* Pop a value from Stack */\nvoid *pop(stack_p stack);\n\n/* Check if a stack is empty */\nbool isStackEmpty(stack_p stack);\n\n/* Clean up Stack */\nbool destroy_stack(stack_p stack);\n"
  },
  {
    "path": "include/tree.h",
    "content": "/*\n * Binary Search Tree abstraction\n *\n * Author: Ananya Jana <ananya.jana@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"common.h\"\n\n#pragma once\n\ntypedef struct tree {\n\tint data;\n\tstruct tree *left;\n\tstruct tree *right;\n} tree_t, *tree_p, **tree_pp;\n\n/* Generate tree from an array of input values */\ntree_pp generate_tree(int *arr, int len);\n\n/* Initalize a tree */\ntree_pp init_tree(void);\n\n/* Insert a node in tree */\nbool insert_tree_node(tree_pp head, int val);\n\n/* Delete a node from tree */\nbool delete_tree_node(tree_pp head, int val);\n\n/* Destroy the tree */\nint destroy_tree(tree_pp head);\n\n/* Print a tree in preorder */\nint print_tree(tree_p root);\n\n/* Traverse tree in BFS to find a given value */\nbool search_BFS(tree_pp root, int val, bool stop);\n\n/* Traverse tree in DFS to find a given value */\nbool search_DFS(tree_pp root, int val, bool stop);\n"
  },
  {
    "path": "src/avl.c",
    "content": "/*\n * AVL Tree implementation\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"stack.h\"\n#include \"queue.h\"\n#include \"avl.h\"\n\n/*\n * Struct to hold an AVL node and traversal\n * direction (left or right) to child node\n */\ntypedef struct {\n\tavl_p node;\n\tint direction;\n} nodedata, *nodedata_p;\n\n/*\n * Calculate the height of a node in AVL tree\n */\nint height(avl_p node)\n{\n\tint lh, rh;\n\n\tif (!node)\n\t\treturn 0;\n\n\tnode->left == NULL ? lh = 0 : (lh = 1 + node->left->height);\n\tnode->right == NULL ? rh = 0 : (rh = 1 + node->right->height);\n\n\treturn (lh >= rh ? lh : rh);\n}\n\n/*\n * Calculate balance factor of subtree\n */\nint BalanceFactor(avl_p node)\n{\n\tint lh, rh;\n\n\tif (!node)\n\t\treturn 0;\n\n\tnode->left == NULL ? lh = 0 : (lh = 1 + node->left->height);\n\tnode->right == NULL ? rh = 0 : (rh = 1 + node->right->height);\n\n\treturn (lh - rh);\n}\n\n/*\n * Rotate a node towards right\n */\navl_p RotateRight(avl_p node)\n{\n\tavl_p left_node = node->left;\n\n\tnode->left = left_node->right;\n\tleft_node->right = node;\n\n\tnode->height = height(node);\n\tleft_node->height = height(left_node);\n\n\treturn left_node;\n}\n\n/*\n * Rotate a node towards left\n */\navl_p RotateLeft(avl_p node)\n{\n\tavl_p right_node = node->right;\n\n\tnode->right = right_node->left;\n\tright_node->left = node;\n\n\tnode->height = height(node);\n\tright_node->height = height(right_node);\n\n\treturn right_node;\n}\n\n/*\n * Adjust a right right skewed subtree\n */\navl_p RightRight(avl_p node)\n{\n\treturn RotateLeft(node);\n}\n\n/*\n * Adjust a left left skewed subtree\n */\navl_p LeftLeft(avl_p node)\n{\n\treturn RotateRight(node);\n}\n\n/*\n * Adjust a left right skewed subtree\n */\navl_p LeftRight(avl_p node)\n{\n\tnode->left = RotateLeft(node->left);\n\treturn RotateRight(node);\n}\n\n/*\n * Adjust a right left skewed subtree\n */\navl_p RightLeft(avl_p node)\n{\n\tnode->right = RotateRight(node->right);\n\treturn RotateLeft(node);\n}\n\n/*\n * Rebalance subtree tmp based on balance factor & skew\n */\nbool rebalance(stack_p stack, avl_pp head, avl_p tmp, int data)\n{\n\tnodedata_p p = NULL;\n\tint direction;\n\tavl_p parent = NULL;\n\tbool modified = TRUE;\n\n\tif (BalanceFactor(tmp) == -2) { /* Right subtree longer */\n\t\tp = pop(stack);\n\t\tif (p) {\n\t\t\tparent = p->node;\n\t\t\tdirection = p->direction;\n\t\t}\n\n\t\tif (data >= tmp->right->keyNode) { /* Right-right skewed subtree */\n\t\t\tif (p)\n\t\t\t\tdirection == RIGHT\n\t\t\t\t?  (parent->right = RightRight(tmp))\n\t\t\t\t: (parent->left = RightRight(tmp));\n\t\t\telse /* If p is NULL, this is the topmost node, update *head */\n\t\t\t\t*head = RightRight(tmp);\n\t\t} else { /* Right-left skewed subtree */\n\t\t\tif (p)\n\t\t\t\tdirection == RIGHT\n\t\t\t\t? (parent->right = RightLeft(tmp))\n\t\t\t\t: (parent->left = RightLeft(tmp));\n\t\t\telse\n\t\t\t\t*head = RightLeft(tmp);\n\t\t}\n\t} else if (BalanceFactor(tmp) == 2) { /* Left subtree longer */\n\t\tp = pop(stack);\n\t\tif (p) {\n\t\t\tparent = p->node;\n\t\t\tdirection = p->direction;\n\t\t}\n\t\t/* If p is NULL, this is the topmost node, update *head */\n\n\t\tif (data < tmp->left->keyNode) { /* Left-left skewed subtree */\n\t\t\tif (p)\n\t\t\t\tdirection == RIGHT\n\t\t\t\t? (parent->right = LeftLeft(tmp))\n\t\t\t\t: (parent->left = LeftLeft(tmp));\n\t\t\telse\n\t\t\t\t*head = LeftLeft(tmp);\n\t\t} else { /* Left-right skewed subtree */\n\t\t\tif (p)\n\t\t\t\tdirection == RIGHT\n\t\t\t\t? (parent->right = LeftRight(tmp))\n\t\t\t\t: (parent->left = LeftRight(tmp));\n\t\t\telse\n\t\t\t\t*head = LeftRight(tmp);\n\t\t}\n\t} else\n\t\tmodified = FALSE;\n\n\tif (p)\n\t\tfree(p);\n\n\ttmp->height = height(tmp);\n\n\treturn modified;\n}\n\n/*\n * Delete all nodes of an AVL tree\n */\nint delete_avl_nodes(avl_p root)\n{\n\tint count = 0;\n\n\tif (!root) {\n\t\tlog(ERROR, \"root invalid.\\n\");\n\t\treturn 0;\n\t}\n\n\tif (root->left)\n\t\tcount += delete_avl_nodes(root->left);\n\n\tif (root->right)\n\t\tcount += delete_avl_nodes(root->right);\n\n\tfree(root);\n\troot = NULL;\n\n\treturn ++count;\n}\n\n\n\n/*=======================================================*/\n/*            Library exposed APIs start here            */\n/*=======================================================*/\n\n/*\n * Generate an AVL tree iteratively from an array of integers\n */\navl_pp generate_avl(int *arr, int len)\n{\n\n\tavl_pp head = NULL;\n\n\tif (!arr || !len) {\n\t\tlog(ERROR, \"Invalid array.\\n\");\n\t\treturn NULL;\n\t}\n\n\thead = init_avl();\n\tfor (int i = 0; i < len; i++) {\n\t\tif (insert_avl_node(head, i, arr[i]) == FALSE) {\n\t\t\tlog(ERROR, \"Insertion failed.\\n\");\n\t\t\tdestroy_avl(head);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\treturn head;\n}\n\n/*\n * Initialize an AVL tree with empty root node\n */\navl_pp init_avl(void)\n{\n\tavl_pp head = calloc(1, sizeof(avl_p));\n\t*head = NULL;\n\n\treturn head;\n}\n\n/*\n * Insert a new node into AVL tree\n */\nbool insert_avl_node(avl_pp head, int key, int data)\n{\n\tavl_p root = NULL;\n\tnodedata_p p = NULL;\n\tnodedata_p n = NULL;\n\tbool modified;\n\n\tif (!head) {\n\t\tlog(ERROR, \"Initialize AVL tree first\\n\");\n\t\treturn FALSE;\n\t}\n\n\troot = *head;\n\n\tif (!root) {\n\t\troot = (avl_p) calloc(1, sizeof(avl_t));\n\t\troot->keyNode = key;\n\t\troot->data = data;\n\n\t\t*head = root;\n\n\t\treturn TRUE;\n\t}\n\n\t/* Stack to rebalance each subtree bottom-up after insertion */\n\tstack_p stack = get_stack();\n\n\t//until current node isn't Null\n\twhile (root) {\n\t\t//if keyNod < of key to add, go left of tree\n\t\tif (key < root->keyNode) {\n\t\t\t//if left null, add node as left son\n\t\t\tif (!root->left) {\n\t\t\t\t/* Create an AVL node for new value */\n\t\t\t\troot->left = calloc(1, sizeof(avl_t));\n\t\t\t\troot->left->keyNode = key;\n\t\t\t\troot->left->data = data;\n\t\t\t\troot->height = height(root);\n\n\t\t\t\tmodified = FALSE;\n\n\t\t\t\t/* Unwind stack & rebalance nodes (only once) */\n\t\t\t\twhile ((p = pop(stack)) != NULL) {\n\t\t\t\t\t/* One rebalance for one insertion */\n\t\t\t\t\tif (!modified)\n\t\t\t\t\t\tmodified = rebalance(stack, head, p->node, key);\n\t\t\t\t\tfree(p);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t/* Push the parent node and traversal\n\t\t\t   direction in stack as we traverse down */\n\t\t\tn = malloc(sizeof(nodedata));\n\t\t\tn->node = root;\n\t\t\tn->direction = LEFT;\n\t\t\tpush(stack, n);\n\n\t\t\t/* Traverse further left */\n\t\t\troot = root->left;\n\t\t} else {    //key to add is >= then current key node\n\t\t\t//if right son null add son on it\n\t\t\tif (!root->right) {\n\t\t\t\troot->right = calloc(1, sizeof(avl_t));\n\t\t\t\troot->right->keyNode = key;\n\t\t\t\troot->right->data = data;\n\t\t\t\troot->height = height(root);\n\n\t\t\t\tmodified = FALSE;\n\n\t\t\t\twhile ((p = pop(stack)) != NULL) {\n\t\t\t\t\tif (!modified)\n\t\t\t\t\t\tmodified = rebalance(stack, head, p->node, key);\n\t\t\t\t\tfree(p);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tn = malloc(sizeof(nodedata));\n\t\t\tn->node = root;\n\t\t\tn->direction = RIGHT;\n\t\t\tpush(stack, n);\n\n\t\t\troot = root->right;\n\t\t}\n\t}\n\n\tdestroy_stack(stack);\n\n\treturn TRUE;\n}\n\n/*\n * Delete a node from AVL tree\n * Recursive method\n */\nbool delete_avl_node(avl_pp head, int key)\n{\n\tavl_p node;\n\tavl_p tmp;\n\n\tif (!head) {\n\t\tlog(ERROR, \"Initialize AVL tree first\\n\");\n\t\treturn FALSE;\n\t}\n\n\tnode = *head;\n\tif (!node) {\n\t\tlog(ERROR, \"No nodes to delete\\n\");\n\t\treturn FALSE;\n\t}\n\n\tif (key > node->keyNode) {\n\t\tif (!node->right)\n\t\t\treturn FALSE;\n\n\t\tif (delete_avl_node(&(node->right), key) == FALSE)\n\t\t\treturn FALSE;\n\n\t\tif (BalanceFactor(node) == 2) {\n\t\t\tif (BalanceFactor(node->left) >= 0)\n\t\t\t\tnode = LeftLeft(node);\n\t\t\telse\n\t\t\t\tnode = LeftRight(node);\n\t\t}\n\t} else if (key < node->keyNode) {\n\t\tif (!node->left)\n\t\t\treturn FALSE;\n\n\t\tif (delete_avl_node(&(node->left), key) == FALSE)\n\t\t\treturn FALSE;\n\n\t\tif (BalanceFactor(node) == -2) {\n\t\t\tif (BalanceFactor(node->right) <= 0)\n\t\t\t\tnode = RightRight(node);\n\t\t\telse\n\t\t\t\tnode = RightLeft(node);\n\t\t}\n\t} else { /* Match found */\n\t\tif (node->right) {  /* Delete the inorder successor */\n\t\t\ttmp = node->right;\n\t\t\twhile (tmp->left)\n\t\t\t\ttmp = tmp->left;\n\n\t\t\tnode->keyNode = tmp->keyNode;\n\t\t\tif (delete_avl_node(&(node->right), tmp->keyNode) == FALSE)\n\t\t\t\treturn FALSE;\n\n\t\t\tif (BalanceFactor(node) == 2) {\n\t\t\t\tif (BalanceFactor(node->left) >= 0)\n\t\t\t\t\tnode = LeftLeft(node);\n\t\t\t\telse\n\t\t\t\t\tnode = LeftRight(node);\n\t\t\t}\n\t\t} else {\n\t\t\t*head = node->left;\n\t\t\tfree(node);\n\t\t\treturn TRUE;\n\t\t}\n\t}\n\n\tnode->height = height(node);\n\t*head = node;\n\treturn TRUE;\n}\n\n/*\n * Destroy an AVL tree\n */\nint destroy_avl(avl_pp head)\n{\n\tint count = 0;\n\n\tif (!head) {\n\t\tlog(ERROR, \"head invalid.\\n\");\n\t\treturn -1;\n\t}\n\n\tcount = delete_avl_nodes(*head);\n\n\tfree(head);\n\thead = NULL;\n\n\treturn count;\n}\n\n/*\n * Print the values in an AVL tree in preorder\n */\nint print_avl(avl_p root, avl_p parent)\n{\n\tint count = 0;\n\n\tif (!root) {\n\t\tlog(ERROR, \"root invalid.\\n\");\n\t\treturn -1;\n\t}\n\n\t++count;\n\n\t/* Print key:data values in the node */\n\tlog(INFO, \"key:data=%6d:%d,  parent key=%6d\\n\", root->keyNode, root->data, parent->keyNode);\n\n\tif (root->left) {\n\t\tlog(INFO, \"LEFT.\\n\");\n\t\tcount += print_avl(root->left, root);\n\t}\n\n\tif (root->right) {\n\t\tlog(INFO, \"RIGHT.\\n\");\n\t\tcount += print_avl(root->right, root);\n\t}\n\n\treturn count;\n}\n\n/*\n * AVL Tree Breadth First Search implementation\n * Implements iterative search using a Queue\n * Checks for a match before adding a node to Queue\n *\n * PARAMS\n * ------\n * root: pointer to the root node pointer of an AVL tree\n * val : value to search\n * stop: TRUE: stop if Key is found and return val.\n *       FALSE: continue visiting of tree, print debug info and return the val of the last key.\n */\n\nint search_BFS_avl(avl_pp root, int key, bool stop)\n{\n\t//return -1 is error\n\t//return -2 is not Found\n\tavl_p node = NULL;\n\tqueue_p queue = NULL;\n\tint ret = -2;   //start with no found\n\n\tif (!root || !*root) {\n\t\tlog(ERROR, \"avl tree or root node is NULL!\\n\");\n\t\treturn -2;  //because avl is empty so key is not found\n\t}\n\n\t/* Check for a match in root node */\n\tnode = *root;\n\tif (node->keyNode == key) {\n\t\tif (!stop)\n\t\t\tlog(INFO, \"FOUND %d\\n\", key);\n\t\tif (stop)\n\t\t\tret = node->data;\n\t\telse\n\t\t\tret = node->data;\n\t}\n\tqueue = get_queue();\n\n\t/* Add root node to Queue */\n\tif (!enqueue(queue, *root)) {\n\t\tlog(ERROR, \"enqueue failed!\\n\");\n\t\tdestroy_queue(queue);\n\t\treturn -1;\n\t}\n\n\t/* Loop through all nodes in the Queue */\n\twhile ((node = dequeue(queue)) != NULL) {\n\t\tif (!stop)\n\t\t\tlog(INFO, \"tracking...\\n\");\n\t\t/* Process left child of node */\n\t\tif (node->left) {\n\t\t\tif (node->left->keyNode == key) {\n\t\t\t\tif (stop)\n\t\t\t\t\tret = node->left->data;\n\t\t\t\telse {\n\t\t\t\t\tlog(INFO, \"FOUND %d\\n\", key);\n\t\t\t\t\tret = node->right->data;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Add left child to Queue */\n\t\t\tif (!enqueue(queue, node->left)) {\n\t\t\t\tlog(ERROR, \"enqueue failed!\\n\");\n\t\t\t\tdestroy_queue(queue);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\n\t\t/* Process right child of node */\n\t\tif (node->right) {\n\t\t\tif (node->right->keyNode == key) {\n\t\t\t\tif (stop)\n\t\t\t\t\tret = node->right->data;\n\t\t\t\telse {\n\t\t\t\t\tlog(INFO, \"FOUND %d\\n\", key);\n\t\t\t\t\tret = node->left->data;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Add right child to Queue */\n\t\t\tif (!enqueue(queue, node->right)) {\n\t\t\t\tlog(ERROR, \"enqueue failed!\\n\");\n\t\t\t\tdestroy_queue(queue);\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Report if no match was found */\n\n\tdestroy_queue(queue);\n\n\treturn ret;\n}\n\n/*=======================================================*/\n/*         Library ThreadSafe APIs start here            */\n/*=======================================================*/\n\n/*\n * Generate an AVL tree iteratively from an array of integers\n */\navl_pp_S generate_avl_S(int *arr, int len)\n{\n\tint i = 0;\n\tavl_pp_S head;\n\n\tif (!arr || !len) {\n\t\tlog(ERROR, \"Invalid array.\\n\");\n\t\thead.avlRoot = NULL;\n\t\treturn head;\n\t}\n\n\thead = init_avl_S();\n\n\tfor (; i < len; i++) {\n\t\tif (insert_avl_node(head.avlRoot, i, arr[i]) == FALSE) {\n\t\t\tlog(ERROR, \"Insertion failed.\\n\");\n\t\t\tdestroy_avl(head.avlRoot);\n\t\t\thead.avlRoot = NULL;\n\t\t\treturn head;\n\t\t}\n\t}\n\n\treturn head;\n}\n\navl_pp_S init_avl_S(void)\n{\n\tavl_pp_S head;\n\n\thead.semId = semInit();\n\tif (head.semId == -1) {\n\t\tperror(\"Sem Setup failed\");\n\t\thead.avlRoot = NULL;\n\t\treturn head;\n\t}\n\n\thead.avlRoot = calloc(1, sizeof(avl_p));\n\t*head.avlRoot = NULL;\n\n\treturn head;\n}\n\nbool insert_avl_node_S(avl_pp_S head, int key, int data)\n{\n\tbool ret;\n\n\tlockWriteSem(head.semId);\n\tret = insert_avl_node(head.avlRoot, key, data);\n\tunlockWriteSem(head.semId);\n\treturn ret;\n}\n\nbool delete_avl_node_S(avl_pp_S head, int key)\n{\n\tbool ret;\n\n\tlockWriteSem(head.semId);\n\tret = delete_avl_node(head.avlRoot, key);\n\tunlockWriteSem(head.semId);\n\treturn ret;\n}\n\nint search_BFS_avl_S(avl_pp_S root, int key, bool stop)\n{\n\tint ret;\n\n\tlockReadSem(root.semId);\n\tret = search_BFS_avl(root.avlRoot, key, stop);\n\tunlockReadSem(root.semId);\n\treturn ret;\n}\n\nint print_avl_S(avl_pp_S root)\n{\n\tint ret;\n\n\tlockReadSem(root.semId);\n\tret = print_avl(*root.avlRoot, *root.avlRoot);\n\tunlockReadSem(root.semId);\n\treturn ret;\n}\n"
  },
  {
    "path": "src/common.c",
    "content": "//\n// Created by alfylinux on 21/10/18.\n//\n\n#include \"common.h\"\n\n\nint semInit()\n{\n\tint semId = semget(IPC_PRIVATE,3, IPC_CREAT | IPC_EXCL | 0666);\n\tif (semId == -1)\n\t{\n\t\tperror(\"Create Sem-s take error:\");\n\t\treturn -1;\n\t}\n\n\t//enum semName {wantWrite=0,readWorking=1,writeWorking=2}; number is Id of sem\n\tunsigned short semStartVal[3] = {0, 0, 1};\n\n\t//setup 3 semaphore in system5\n\tif (semctl(semId, 0, SETALL, semStartVal))\n\t{\n\t\tperror(\"set Sem take error:\");\n\t\treturn -1;\n\t}\n\n\tprintf(\"SEMAFORO Created\\n\");\n\tsemInfo(semId);\n\n\treturn semId;\n}\n\nint lockWriteSem(int semId)\n{\n\tstruct sembuf sem;\n\tsem.sem_flg = SEM_UNDO;\n\n\t//increase counter wantWrite\n\tsem.sem_num = wantWrite;\n\tsem.sem_op = +1;\n\tSEM_wantWrite:\n\tif (semop(semId, &sem, 1))\n\t{\n\t\tswitch (errno)\n\t\t{\n\t\t\tcase EINTR:\n\t\t\t\tgoto SEM_wantWrite;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"increase wantWrite semCount error:\");\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t//wait until =0 readerWork\n\tsem.sem_num = readWorking;\n\tsem.sem_op = 0;\n\n\tSEM_waitReaders:\n\tif (semop(semId, &sem, 1))\n\t{\n\t\tswitch (errno)\n\t\t{\n\t\t\tcase EINTR:\n\t\t\t\tgoto SEM_waitReaders;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"wait until 0 readWorking take error:\");\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t//wait noThread already work\n\tsem.sem_num = writeWorking;\n\tsem.sem_op = -1;\n\n\tSEM_writeWorking:\n\tif (semop(semId, &sem, 1))\n\t{\n\t\tswitch (errno)\n\t\t{\n\t\t\tcase EINTR:\n\t\t\t\tgoto SEM_writeWorking;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"lock writeWorking error:\");\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\n}\n\nint unlockWriteSem(int semId)\n{\n\tstruct sembuf sem;\n\tsem.sem_flg = SEM_UNDO;\n\n\t//signal finish writing work\n\tsem.sem_num = writeWorking;\n\tsem.sem_op = 1;\n\n\tSEM_writeWorking:\n\tif (semop(semId, &sem, 1))\n\t{\n\t\tswitch (errno)\n\t\t{\n\t\t\tcase EINTR:\n\t\t\t\tgoto SEM_writeWorking;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"unlock writeWorking error:\");\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t//reduce counter of wantWrite\n\tsem.sem_num = wantWrite;\n\tsem.sem_op = -1;\n\n\tSEM_wantWrite:\n\tif (semop(semId, &sem, 1))\n\t{\n\t\tswitch (errno)\n\t\t{\n\t\t\tcase EINTR:\n\t\t\t\tgoto SEM_wantWrite;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"decrease wantWrite semCount error:\");\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\n}\n\n\nint lockReadSem(int semId)\n{\n\tstruct sembuf sem[2];\n\tsem[0].sem_num = wantWrite;\n\tsem[0].sem_flg = SEM_UNDO;\n\tsem[1].sem_num = readWorking;\n\tsem[1].sem_flg = SEM_UNDO;\n\n\t//to be sure not concurrency problem, read Thread must be wait until no writes works, and instantly increase his counter\n\tsem[0].sem_op = 0;\n\tsem[1].sem_op = +1;\n\tSEM_wantWrite_readWorking:\n\tif (semop(semId, sem, 2))\n\t{\n\t\tswitch (errno)\n\t\t{\n\t\t\tcase EINTR:\n\t\t\t\tgoto SEM_wantWrite_readWorking;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"lockRead sem take error:\");\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint unlockReadSem(int semId)\n{\n\tstruct sembuf sem;\n\tsem.sem_flg = SEM_UNDO;\n\tsem.sem_num = readWorking;\n\tsem.sem_op = -1;\n\n\tSEM_readWorking:\n\tif (semop(semId, &sem, 1))\n\t{\n\t\tswitch (errno)\n\t\t{\n\t\t\tcase EINTR:\n\t\t\t\tgoto SEM_readWorking;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tperror(\"unlockRead sem take error:\");\n\t\t\t\treturn -1;\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn 0;\n}\n\nvoid semInfo(int semId)\n{\n\tunsigned short semInfo[3];\n\tsemctl(semId, 0, GETALL, semInfo);\n\t//enum semName {wantWrite=0,readWorking=1,writeWorking=2};\n\tprintf(\"\\nsem writeWorking=%d\\n\", semInfo[writeWorking]);\n\tprintf(\"sem readWorking=%d\\n\", semInfo[readWorking]);\n\tprintf(\"sem wantWrite=%d\\n\", semInfo[wantWrite]);\n}"
  },
  {
    "path": "src/dlist.c",
    "content": "/*\n * Circular Doubly Linked List implementation\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"dlist.h\"\n\n/*\n * Add a node to the head of dlist\n */\nint add_head_dlist(dlist_pp head, dlist_p node)\n{\n\tif (!node) {\n\t\tlog(ERROR, \"node is NULL!\\n\");\n\t\treturn -1;\n\t}\n\n\tif (!head) {\n\t\tlog(ERROR, \"head is NULL!\\n\");\n\t\treturn -1;\n\t}\n\n\tif (!*head) {\n\t\tnode->next = node;\n\t\tnode->prev = node;\n\t\t*head = node;\n\n\t\treturn 1;\n\t}\n\n\tnode->next = *head; /* Current head become head->next */\n\tnode->prev = (*head)->prev;\n\t(*head)->prev->next = node;\n\t(*head)->prev = node;\n\t*head = node;\n\n\treturn 1;\n}\n\n/*\n * Get the value in the head node of dlist\n * The node is not deleted\n */\nvoid *get_head_dlist(dlist_pp head)\n{\n\tif (!head || !*head) {\n\t\tlog(DEBUG, \"head or first node is NULL!\\n\");\n\t\treturn NULL;\n\t}\n\n\treturn (*head)->data;\n}\n\n/*\n * Get the value in the tail node of dlist\n * The node is not deleted\n */\nvoid *get_tail_dlist(dlist_pp head)\n{\n\tif (!head || !*head) {\n\t\tlog(DEBUG, \"head or first node is NULL!\\n\");\n\t\treturn NULL;\n\t}\n\n\treturn (*head)->prev->data;\n}\n\n/*\n * Delete the head node of dlist\n */\nint delete_head_dlist(dlist_pp head)\n{\n\tdlist_p tmp;\n\n\tif (!head || !*head) {\n\t\tlog(DEBUG, \"No nodes to delete!\\n\");\n\t\treturn -1;\n\t}\n\n\tif (*head == (*head)->next) {\n\t\tfree(*head);\n\t\t*head = NULL;\n\t\treturn 1;\n\t}\n\n\ttmp = *head;\n\t(*head)->data = NULL;\n\t(*head)->prev->next = (*head)->next;\n\t(*head)->next->prev = (*head)->prev;\n\t*head = (*head)->next; /* head->next becomes next head */\n\n\tfree(tmp);\n\n\treturn 1;\n}\n\n/*\n * Delete the tail node of dlist\n */\nint delete_tail_dlist(dlist_pp head)\n{\n\tdlist_p tmp;\n\n\tif (!head || !*head) {\n\t\tlog(DEBUG, \"head or first node is NULL!\\n\");\n\t\treturn -1;\n\t}\n\n\tif (*head == (*head)->next) {\n\t\tfree(*head);\n\t\t*head = NULL;\n\t\treturn 1;\n\t}\n\n\ttmp = (*head)->prev;\n\ttmp->data = NULL;\n\ttmp->prev->next = tmp->next; /* tail->prev becomes new tail */\n\ttmp->next->prev = tmp->prev;\n\n\tfree(tmp);\n\n\treturn 1;\n}\n\n/*\n * Deallocate all memory and destroy the dlist\n * Returns the number of nodes deleted\n */\nint destroy_dlist(dlist_pp head)\n{\n\tdlist_p tmp;\n\tint deleted = 0;\n\n\tif (!head) {\n\t\tlog(DEBUG, \"head is NULL.\\n\");\n\t\treturn -1;\n\t}\n\n\tif (!*head) {\n\t\tlog(DEBUG, \"No nodes to delete.\\n\");\n\t\treturn 0;\n\t}\n\n\t/* Set tail->next to NULL to end deletion loop */\n\t(*head)->prev->next = NULL;\n\n\twhile (*head) {\n\t\ttmp = *head;\n\t\t(*head)->data = NULL;\n\t\t(*head)->prev = NULL;\n\t\t*head = (*head)->next;\n\n\t\tfree(tmp);\n\t\tdeleted++;\n\t}\n\n\treturn deleted;\n}\n\n/*\n * Count the total number of nodes in the dlist\n */\nint count_nodes_dlist(dlist_pp head)\n{\n\tdlist_p tmp;\n\tint count = 0;\n\n\tif (!head || !*head) {\n\t\tlog(DEBUG, \"head or first node is NULL!\\n\");\n\t\treturn -1;\n\t}\n\n\ttmp = *head;\n\n\tdo {\n\t\tcount++;\n\t\ttmp = tmp->next;\n\t} while (tmp != *head);\n\n\treturn count;\n}\n"
  },
  {
    "path": "src/log.c",
    "content": "/*\n * A modular, level based log file implementation\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2014 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"log.h\"\n\nextern int current_log_level;\nchar *logarr[] = {\"ERROR\", \"INFO\", \"DEBUG\"};\n\nvoid debug_log(const char *file,\n\t\tconst char *func,\n\t\tint line,\n\t\tint level,\n\t\tconst char *format,\n\t\t...)\n{\n\tva_list ap;\n\n\tva_start(ap, format);\n\n\tif (level < 0 || level > DEBUG)\n\t\treturn;\n\n\tif (level <= current_log_level) {\n\t\tfprintf(stderr, \"[%s, %s(), ln %d] %s: \",\n\t\t\t\tfile, func, line, logarr[level]);\n\t\tvfprintf(stderr, format, ap);\n\t}\n\n\tva_end(ap);\n}\n"
  },
  {
    "path": "src/queue.c",
    "content": "/*\n * Queue implementation\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"queue.h\"\n\n/*\n * Create a new Queue\n * Alocate a head node\n */\nqueue_p get_queue(void)\n{\n\tqueue_p queue = calloc(1, sizeof(queue_t));\n\n\tqueue->head = calloc(1, sizeof(dlist_pp));\n\treturn queue;\n}\n\n/*\n * Add a value to Queue\n * Allocates a new dlist node and inserts value\n */\nbool enqueue(queue_p queue, void *val)\n{\n\tdlist_p nodeptr = calloc(1, sizeof(dlist_t));\n\n\tnodeptr->data = val;\n\n\treturn (add_head_dlist(queue->head, nodeptr) == 1); /* Last In */\n}\n\n/*\n * Remove the value at the front of the Queue\n * Deallocates the dlist node holding the value\n */\nvoid *dequeue(queue_p queue)\n{\n\tvoid *data = get_tail_dlist(queue->head); /* Last Out */\n\n\tif (delete_tail_dlist(queue->head) == -1)\n\t\tlog(DEBUG, \"head or first node is NULL!\\n\");\n\n\treturn data;\n}\n\n/*\n * Check if a Queue has any elements\n */\nbool isQueueEmpty(queue_p queue)\n{\n\tif (get_head_dlist(queue->head))\n\t\treturn TRUE;\n\n\treturn FALSE;\n}\n\n/*\n * Deallocate all dlist nodes\n * Destroy Queue\n */\nbool destroy_queue(queue_p queue)\n{\n\tif (destroy_dlist(queue->head) == -1)\n\t\treturn FALSE;\n\n\tfree(queue->head);\n\tfree(queue);\n\n\treturn TRUE;\n}\n"
  },
  {
    "path": "src/stack.c",
    "content": "/*\n * Stack implementation\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"stack.h\"\n\n/*\n * Create a new Stack\n * Alocate a head node\n */\nstack_p get_stack(void)\n{\n\tstack_p stack = calloc(1, sizeof(stack_t));\n\n\tstack->head = calloc(1, sizeof(dlist_pp));\n\treturn stack;\n}\n\n/*\n * Push a value to Stack\n * Allocates a new dlist node and inserts value\n */\nbool push(stack_p stack, void *val)\n{\n\tdlist_p nodeptr = calloc(1, sizeof(dlist_t));\n\n\tnodeptr->data = val;\n\n\treturn (add_head_dlist(stack->head, nodeptr) == 1); /* Last In */\n}\n\n/*\n * Pop a value from Stack\n * Deallocates the dlist node holding the value\n */\nvoid *pop(stack_p stack)\n{\n\tvoid *data = get_head_dlist(stack->head); /* First out */\n\n\tif (delete_head_dlist(stack->head) == -1)\n\t\tlog(DEBUG, \"head or first node is NULL!\\n\");\n\n\treturn data;\n}\n\n/*\n * Check if a stack has any elements\n */\nbool isStackEmpty(stack_p stack)\n{\n\tif (get_head_dlist(stack->head))\n\t\treturn TRUE;\n\n\treturn FALSE;\n}\n\n/*\n * Deallocate all dlist nodes\n * Destroy Stack\n */\nbool destroy_stack(stack_p stack)\n{\n\tif (destroy_dlist(stack->head) == -1)\n\t\treturn FALSE;\n\n\tfree(stack->head);\n\tfree(stack);\n\n\treturn TRUE;\n}\n"
  },
  {
    "path": "src/tree.c",
    "content": "/*\n * Iterative Binary Search Tree implementation\n *\n * Author: Ananya Jana <ananya.jana@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include \"queue.h\"\n#include \"stack.h\"\n#include \"tree.h\"\n\n/*\n * Delete all nodes of a tree\n */\nint delete_tree_nodes(tree_p root)\n{\n\tint count = 0;\n\n\tif (!root) {\n\t\tlog(ERROR, \"root invalid.\\n\");\n\t\treturn -1;\n\t}\n\n\tif (root->left)\n\t\tcount += delete_tree_nodes(root->left);\n\n\tif (root->right)\n\t\tcount += delete_tree_nodes(root->right);\n\n\tfree(root);\n\troot = NULL;\n\n\treturn ++count;\n}\n\n/*=======================================================*/\n/*            Library exposed APIs start here            */\n/*=======================================================*/\n\n/*\n * Generate a tree from an array of integers\n */\ntree_pp generate_tree(int *arr, int len)\n{\n\tint i = 0;\n\ttree_pp head = NULL;\n\n\tif (!arr || !len) {\n\t\tlog(ERROR, \"Invalid array.\\n\");\n\t\treturn NULL;\n\t}\n\n\thead = init_tree();\n\n\tfor (; i < len; i++) {\n\t\tif (insert_tree_node(head, arr[i]) == FALSE) {\n\t\t\tlog(ERROR, \"Insertion failed.\\n\");\n\t\t\tdestroy_tree(head);\n\t\t\treturn NULL;\n\t\t}\n\t}\n\n\treturn head;\n}\n\n/*\n * Initialize a tree with empty root node\n */\ntree_pp init_tree(void)\n{\n\ttree_pp head = calloc(1, sizeof(tree_p));\n\t*head = NULL;\n\n\treturn head;\n}\n\n/*\n * Insert a new node into tree\n */\nbool insert_tree_node(tree_pp head, int val)\n{\n\ttree_p root = NULL;\n\n\tif (!head) {\n\t\tlog(ERROR, \"Initialize tree first.\\n\");\n\t\treturn FALSE;\n\t}\n\n\troot = *head;\n\n\twhile (root) {\n\t\tif (val < root->data) {\n\t\t\tif (!root->left) {\n\t\t\t\troot->left = calloc(1, sizeof(tree_t));\n\t\t\t\troot = root->left;\n\t\t\t\troot->data = val;\n\t\t\t\treturn TRUE;\n\t\t\t}\n\n\t\t\troot = root->left;\n\t\t} else if (val > root->data) { /* Insert greater elements in right subtree */\n\t\t\tif (!root->right) {\n\t\t\t\troot->right = calloc(1, sizeof(tree_t));\n\t\t\t\troot = root->right;\n\t\t\t\troot->data = val;\n\t\t\t\treturn TRUE;\n\t\t\t}\n\n\t\t\troot = root->right;\n\t\t} else {\n\t\t\tlog(ERROR, \"BST must have unique values.\\n\");\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!*head) {\n\t\troot = (tree_p) calloc(1, sizeof(tree_t));\n\t\troot->data = val;\n\t\t*head = root;\n\n\t\treturn TRUE;\n\t}\n\n\treturn FALSE;\n}\n\n/*\n * Delete a node from tree\n */\nbool delete_tree_node(tree_pp head, int val)\n{\n\ttree_p root = NULL;\n\ttree_p prev = NULL;\n\tint direction;\n\n\tif (!head) {\n\t\tlog(ERROR, \"Initialize tree first.\\n\");\n\t\treturn FALSE;\n\t}\n\n\troot = *head;\n\n\twhile (root) {\n\t\tif (val < root->data) {\n\t\t\tif (!root->left)\n\t\t\t\tbreak;\n\n\t\t\tprev = root;\n\t\t\tdirection = LEFT;\n\t\t\troot = root->left;\n\t\t} else if (val > root->data) { /* Greater elements are in right subtree */\n\t\t\tif (!root->right)\n\t\t\t\tbreak;\n\n\t\t\tprev = root;\n\t\t\tdirection = RIGHT;\n\t\t\troot = root->right;\n\t\t} else { /* Match found */\n\t\t\tif (!root->left) {\n\t\t\t\tif (prev) {\n\t\t\t\t\tif (direction == LEFT)\n\t\t\t\t\t\tprev->left = root->right;\n\t\t\t\t\telse\n\t\t\t\t\t\tprev->right = root->right;\n\t\t\t\t} else /* This was the root node */\n\t\t\t\t\t*head = root->right;\n\n\t\t\t\tfree(root);\n\t\t\t\treturn TRUE;\n\t\t\t} else if (!root->right) {\n\t\t\t\tif (prev) {\n\t\t\t\t\tif (direction == LEFT)\n\t\t\t\t\t\tprev->left = root->left;\n\t\t\t\t\telse\n\t\t\t\t\t\tprev->right = root->left;\n\t\t\t\t} else /* This was the root node */\n\t\t\t\t\t*head = root->left;\n\n\t\t\t\tfree(root);\n\t\t\t\treturn TRUE;\n\t\t\t} else { /* Both subtrees have children */\n\t\t\t\t/* Delete inorder successor */\n\t\t\t\ttree_p min = root->right;\n\t\t\t\twhile (min->left)\n\t\t\t\t\tmin = min->left;\n\n\t\t\t\troot->data = min->data;\n\t\t\t\t/* Let's use some recursion here */\n\t\t\t\tdelete_tree_node(&(root->right), min->data);\n\n\t\t\t\treturn TRUE;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Fall through if root is NULL */\n\treturn FALSE;\n}\n\n/*\n * Destroy a tree\n */\nint destroy_tree(tree_pp head)\n{\n\tint count = 0;\n\n\tif (!head) {\n\t\tlog(ERROR, \"head invalid.\\n\");\n\t\treturn -1;\n\t}\n\n\tcount = delete_tree_nodes(*head);\n\n\tfree(head);\n\thead = NULL;\n\n\treturn count;\n}\n\n/*\n * Print the values in a tree in preorder\n */\nint print_tree(tree_p root)\n{\n\tint count = 0;\n\n\tif (!root) {\n\t\tlog(ERROR, \"root invalid.\\n\");\n\t\treturn -1;\n\t}\n\n\tlog(DEBUG, \"keyNode: %d.\\n\", root->data);\n\t++count;\n\n\tif (root->left)\n\t\tcount += print_tree(root->left);\n\tif (root->right)\n\t\tcount += print_tree(root->right);\n\n\treturn count;\n}\n\n/*\n * Tree Breadth First Search implementation\n * Implements iterative search using a Queue\n * Checks for a match before adding a node to Queue\n *\n * PARAMS\n * ------\n * root: pointer to the root node pointer of a tree\n * val : value to search\n * stop: stop if val is found\n */\nbool search_BFS(tree_pp root, int val, bool stop)\n{\n\ttree_p node = NULL;\n\tqueue_p queue = NULL;\n\tint ret = FALSE;\n\n\tif (!root || !*root) {\n\t\tlog(ERROR, \"tree or root node is NULL!\\n\");\n\t\treturn FALSE;\n\t}\n\n\t/* Check for a match in root node */\n\tnode = *root;\n\tif (node->data == val) {\n\t\tlog(INFO, \"FOUND %d\\n\", val);\n\n\t\tif (stop)\n\t\t\treturn TRUE;\n\t}\n\n\tqueue = get_queue();\n\n\t/* Add root node to Queue */\n\tif (!enqueue(queue, *root)) {\n\t\tlog(ERROR, \"enqueue failed!\\n\");\n\t\tdestroy_queue(queue);\n\t\treturn FALSE;\n\t}\n\n\t/* Loop through all nodes in the Queue */\n\twhile ((node = dequeue(queue)) != NULL) {\n\t\tlog(INFO, \"tracking...\\n\");\n\n\t\t/* Process left child of node */\n\t\tif (node->left) {\n\t\t\tif (node->left->data == val) {\n\t\t\t\tlog(INFO, \"FOUND %d\\n\", val);\n\t\t\t\tret = TRUE;\n\n\t\t\t\tif (stop)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Add left child to Queue */\n\t\t\tif (!enqueue(queue, node->left)) {\n\t\t\t\tlog(ERROR, \"enqueue failed!\\n\");\n\t\t\t\tdestroy_queue(queue);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\n\t\t/* Process right child of node */\n\t\tif (node->right) {\n\t\t\tif (node->right->data == val) {\n\t\t\t\tlog(INFO, \"FOUND %d\\n\", val);\n\t\t\t\tret = TRUE;\n\n\t\t\t\tif (stop)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t/* Add right child to Queue */\n\t\t\tif (!enqueue(queue, node->right)) {\n\t\t\t\tlog(ERROR, \"enqueue failed!\\n\");\n\t\t\t\tdestroy_queue(queue);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Report if no match was found */\n\tif (!ret)\n\t\tlog(INFO, \"NOT FOUND\\n\");\n\n\tdestroy_queue(queue);\n\n\treturn ret;\n}\n\n/*\n * Tree Depth First Search implementation\n * Implements iterative search using a Stack\n * Checks for a match before adding a node to Stack\n *\n * PARAMS\n * ------\n * root: pointer to the root node pointer of a tree\n * val : value to search\n * stop: stop if val is found\n */\nbool search_DFS(tree_pp root, int val, bool stop)\n{\n\tint ret = FALSE;\n\ttree_p node = NULL;\n\tstack_p stack = NULL;\n\n\tif (!root || !*root) {\n\t\tlog(ERROR, \"tree or root node is NULL.\\n\");\n\t\treturn FALSE;\n\t}\n\n\t/* Check for a match in root node */\n\tnode = *root;\n\tif (node->data == val) {\n\t\tlog(INFO, \"FOUND %d\\n\", val);\n\n\t\tif (stop)\n\t\t\treturn TRUE;\n\t}\n\n\tstack = get_stack();\n\n\t/* Add root node to Stack */\n\tif (!push(stack, *root)) {\n\t\tlog(ERROR, \"push failed!\\n\");\n\t\tdestroy_stack(stack);\n\t\treturn FALSE;\n\t}\n\n\t/* Process all valid nodes */\n\twhile (node) {\n\t\tlog(INFO, \"tracking...\\n\");\n\n\t\t/* Match and add complete\n\t\t   left subtree to Stack */\n\t\twhile (node->left) {\n\t\t\tif (node->left->data == val) {\n\t\t\t\tlog(INFO, \"FOUND %d\\n\", val);\n\t\t\t\tret = TRUE;\n\n\t\t\t\tif (stop) {\n\t\t\t\t\tnode = NULL;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t/* Add node to stack */\n\t\t\tif (!push(stack, node->left)) {\n\t\t\t\tlog(ERROR, \"push failed!\\n\");\n\t\t\t\tdestroy_stack(stack);\n\t\t\t\treturn FALSE;\n\t\t\t}\n\n\t\t\tnode = node->left;\n\t\t}\n\n\t\twhile ((node = pop(stack)) != NULL) {\n\t\t\t/* Process right child of node */\n\t\t\tif (node->right) {\n\t\t\t\tif (node->right->data == val) {\n\t\t\t\t\tlog(INFO, \"FOUND %d\\n\", val);\n\t\t\t\t\tret = TRUE;\n\n\t\t\t\t\tif (stop) {\n\t\t\t\t\t\tnode = NULL;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t/* Add right child to Stack */\n\t\t\t\tif (!push(stack, node->right)) {\n\t\t\t\t\tlog(ERROR, \"push failed!\\n\");\n\t\t\t\t\tdestroy_stack(stack);\n\t\t\t\t\treturn FALSE;\n\t\t\t\t}\n\n\t\t\t\tnode = node->right;\n\t\t\t\t/* Break inner loop if there's a right node */\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t/* Report if no match was found */\n\tif (!ret)\n\t\tlog(INFO, \"NOT FOUND\\n\");\n\n\tdestroy_stack(stack);\n\n\treturn ret;\n}\n"
  },
  {
    "path": "test/Makefile",
    "content": "CC = gcc\nCFLAGS = -Wall -Wextra -g -fsanitize=address,undefined $(INCLUDE)\n\n#INCLUDE = -I/usr/include/dslib\n#LIBS = -lds\n#SRCDIR =\n\nINCLUDE = -I../include\nLIBS =\nSRCDIR = ../src/*.c\n\nall:\n\t$(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_avl_1 test_avl_1.c $(LIBS)\n\t$(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_bst_1 test_bst_1.c $(LIBS)\n\t$(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_dlist_1 test_dlist_1.c $(LIBS)\n\t$(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_queue_1 test_queue_1.c $(LIBS)\n\t$(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o test_stack_1 test_stack_1.c $(LIBS)\n\t$(CC) $(CFLAGS) $(INCLUDE) $(SRCDIR) -o avl_Thread_Safe_Test avl_Thread_Safe_Test.c $(LIBS) -lpthread\n\n.PHONY: clean\nclean:\n\trm -f test_avl_1 test_bst_1 test_dlist_1 test_queue_1 test_stack_1 avl_Thread_Safe_Test\n"
  },
  {
    "path": "test/avl_Thread_Safe_Test.c",
    "content": "/*\n * Test cases for AVL-ThreadSafe tree\n *\n * Author: Emanuele Alfano <alfystar1701@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n/*\n * This demo works in posix, it create \"nSearch\" thread and him call forEver\n * \"search_BFS_avl_S\", with ctrl+c you send a lockWrite,\n * with ctrl+z you send unlockWrite\n *\n * The function must send in order:\n * 1° Lock-write\n * 2° Unlock-write\n *\n * Is also possible send different configuratio:\n * 1° Lock-write\n *      2° Lock-write\n *          3° Lock-write\n *          4° Unlock-write\n *      5° Unlock-write\n *  6° Unlock-write\n *  ...\n *\n * To end script type ctrl+\\ (sigKill)\n *\n *\n * Is important to see that, when first writeLock arrive, search thread just at work\n * finish his work and finaly the write lock arrive\n */\n\n#define nSearch 50\n\n#include <common.h>\n#include \"avl.h\"\n\n#include <signal.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <pthread.h>\n\nint current_log_level = DEBUG;\navl_pp_S head;\n\nint n_nodeInsert;\nint searchRange;\nint writePending;\n\nvoid *searchTh(void *info)\n{\n\tint id = *(int *)info;\n\tint keySearch;\n\tint found;\n\n\twhile (1) {\n\t\tkeySearch = (int) random() % searchRange;\n\n\t\tfound = search_BFS_avl_S(head, keySearch, TRUE);\n\n\t\tprintf(\"TH-Search %d Search key %d and ret %d\\n\", id, keySearch, found);\n\n\t\tusleep(1000000*random()%100);   //random wait between 1 and 100 ms\n\t}\n\tfree(info);\n\n\treturn NULL;\n}\n\nvoid lockWriteSem_sig(int sig)\n{\n\twritePending++;\n\tprintf(\"\\n\\t****sigINT receive sig = %d; n°writePending = %d\\n\\n\", sig, writePending);\n\tlockWriteSem(head.semId);\n\tprintf(\"\\n\\t####sigInt lock Write TAKE\\n\");\n}\n\nvoid unlockWriteSem_sig(int sig)\n{\n\t//note, if writePending = 0, this signal stay in wait until arrive one lockWriteSem_sig,\n\t//but the library wasn't design tu solve this!!! It work only if every Writer, on the Start lock the tree, and at the End unlock then.\n\tprintf(\"\\n\\t#(sigTSTP) receive sig = %d\\n\\n\", sig);\n\tunlockWriteSem(head.semId);\n\twritePending--;\n\tprintf(\"\\n\\t#(sigTSTP) unlock Write; n°writePending = %d\\n\", writePending);\n}\n\nint main(void)\n{\n\n\tsignal(SIGINT, lockWriteSem_sig);\n\tsignal(SIGTSTP, unlockWriteSem_sig);\n\thead = init_avl_S();\n\n\tn_nodeInsert = nSearch * 10;\n\tsearchRange = n_nodeInsert * 2;\n\n\n\tfor (int count = 0; count < n_nodeInsert; count++) {\n\t\tif (insert_avl_node_S(head, count, (int)random() % searchRange) == FALSE) {\n\t\t\tlog(ERROR, \"Insertion failed.\\n\");\n\t\t\tdestroy_avl(head.avlRoot);\n\t\t\treturn 0;\n\t\t}\n\t}\n\tprint_avl_S(head);\n\t//sleep(20);  //to give time to see tree print\n\n\tpthread_t tid;\n\n\tprintf(\"Start search Thread\\n\");\n\tfor (int count = 0; count < nSearch; count++) {\n\t\tint *i = malloc(sizeof(int));\n\t\t*i =  count;\n\t\tpthread_create(&tid, NULL, searchTh, i);\n\t}\n\twhile (1)\n\t\tpause();\n\treturn 0;\n}\n"
  },
  {
    "path": "test/test_avl_1.c",
    "content": "/*\n * Test cases for AVL tree\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <common.h>\n#include <avl.h>\n\nint current_log_level = INFO;\n\nint main(int argc, char **argv)\n{\n\tint count = 0;\n\n\tbool stop = FALSE;\n\n\tavl_pp head = init_avl();\n\tint arr[] = {30, 110, 10, 90, 120, 150, 70,\n\t\t140, 40, 130, 20, 50, 100, 80, 60};\n\t/* int arr[] = {10, 20, 30, 40, 50, 60, 70, 80,\n\t\t90, 100, 110, 120, 130, 140, 150}; */\n\tint len = sizeof(arr) / sizeof(arr[0]);\n\n\tfor (; count < len; ++count) {\n\t\tif (insert_avl_node(head, arr[count], 20) == FALSE) {\n\t\t\tlog(ERROR, \"Insertion failed.\\n\");\n\t\t\tdestroy_avl(head);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tif (argc == 2)\n\t\tsearch_BFS_avl(head, atoi(argv[1]), stop);\n\telse\n\t\tsearch_BFS_avl(head, 10, stop);\n\n\tcount = print_avl(*head, *head);\n\tlog(INFO, \"nodes printed: %d\\n\\n\", count);\n\n\tif (delete_avl_node(head, 110) == TRUE)\n\t\tlog(INFO, \"AVL node deleted\\n\\n\");\n\tcount = print_avl(*head, *head);\n\tlog(INFO, \"nodes printed: %d\\n\", count);\n\n\tcount = destroy_avl(head);\n\tlog(INFO, \"nodes deleted: %d\\n\", count);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "test/test_bst_1.c",
    "content": "/*\n * Test cases for BST\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <common.h>\n#include <tree.h>\n\nint current_log_level = INFO;\n\n/* Test BST */\nint main(int argc, char **argv)\n{\n\tint count = 0;\n\tbool stop = TRUE;\n\ttree_pp head = NULL;\n\tint arr[] = {10, 20, 30, 40, 50};\n\n\tlog(DEBUG, \"Calling generate_tree()\\n\");\n\thead = generate_tree(arr, sizeof(arr) / sizeof(arr[0]));\n\n\tif (argc == 2)\n\t\tsearch_BFS(head, atoi(argv[1]), stop);\n\telse\n\t\tsearch_BFS(head, 10, stop);\n\n\tcount = print_tree(*head);\n\tlog(INFO, \"nodes printed: %d\\n\", count);\n\n\tdelete_tree_node(head, 30);\n\tlog(INFO, \"\\n\\n\");\n\n\tcount = print_tree(*head);\n\tlog(INFO, \"nodes printed: %d\\n\", count);\n\n\tcount = destroy_tree(head);\n\tlog(INFO, \"nodes deleted: %d\\n\", count);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "test/test_dlist_1.c",
    "content": "/*\n * Test cases for dlist\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <common.h>\n#include <dlist.h>\n\nint current_log_level = INFO;\n\n/* Test dlist */\nint main(void)\n{\n\tint count = 5;\n\n\tdlist_p *head_pp = calloc(1, sizeof(dlist_p *));\n\n\twhile (count) {\n\t\tdlist_p node_p = calloc(1, sizeof(dlist_t));\n\n\t\tlog(DEBUG, \"node address %p\\n\", node_p);\n\t\tif (add_head_dlist(head_pp, node_p) == -1) {\n\t\t\tlog(ERROR, \"add_head_dlist failed!\\n\");\n\t\t\treturn -1;\n\t\t}\n\n\t\tlog(DEBUG, \"Node added\\n\");\n\n\t\tcount--;\n\t}\n\n\tlog(DEBUG, \"Total nodes1: %d\\n\", count_nodes_dlist(head_pp));\n\n\tif (delete_head_dlist(head_pp)) {\n\t\tlog(DEBUG, \"Total nodes after head delete: %d\\n\",\n\t\t\t\tcount_nodes_dlist(head_pp));\n\t} else {\n\t\tlog(ERROR, \"delete_head_dlist failed!\\n\");\n\t\treturn -1;\n\t}\n\n\tlog(DEBUG, \"Total nodes2: %d\\n\", count_nodes_dlist(head_pp));\n\n\tif (delete_tail_dlist(head_pp)) {\n\t\tlog(DEBUG, \"Total nodes after tail delete: %d\\n\",\n\t\t\t\tcount_nodes_dlist(head_pp));\n\t} else {\n\t\tlog(ERROR, \"delete_tail_dlist failed!\\n\");\n\t\treturn -1;\n\t}\n\n\tlog(DEBUG, \"Nodes destroyed: %d\\n\", destroy_dlist(head_pp));\n\tlog(DEBUG, \"Total nodes: %d\\n\", count_nodes_dlist(head_pp));\n\n\tfree(head_pp);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "test/test_queue_1.c",
    "content": "/*\n * Test cases for queue\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <common.h>\n#include <queue.h>\n\nint current_log_level = DEBUG;\n\n/* Test queue */\nint main(void)\n{\n\tint count = 5;\n\tint arr[5] = {0, 1, 2, 3, 4};\n\tint *val;\n\n\tqueue_p queue = get_queue();\n\n\twhile (count) {\n\t\tif (enqueue(queue, &arr[--count]) == FALSE) {\n\t\t\tlog(ERROR, \"enqueue failed!\\n\");\n\t\t\tdestroy_queue(queue);\n\t\t\treturn -1;\n\t\t}\n\n\t\tlog(DEBUG, \"enqueued: arr[%d] = %d\\n\", count, arr[count]);\n\t}\n\n\tcount = 5;\n\n\twhile (count) {\n\t\tval = dequeue(queue);\n\t\tif (val)\n\t\t\tlog(DEBUG, \"dequeued: arr[%d] = %d\\n\", --count, (int)*val);\n\t\telse\n\t\t\tlog(ERROR, \"dequeue failed!\\n\");\n\t}\n\n\tdestroy_queue(queue);\n\n\treturn 0;\n}\n"
  },
  {
    "path": "test/test_stack_1.c",
    "content": "/*\n * Test cases for stack\n *\n * Author: Arun Prakash Jana <engineerarun@gmail.com>\n * Copyright (C) 2015 by Arun Prakash Jana <engineerarun@gmail.com>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with dslib.  If not, see <http://www.gnu.org/licenses/>.\n */\n\n#include <common.h>\n#include <stack.h>\n\nint current_log_level = DEBUG;\n\n/* Test stack */\nint main(void)\n{\n\tint count = 5;\n\tint arr[5] = {0, 1, 2, 3, 4};\n\tint *val;\n\n\tstack_p stack = get_stack();\n\n\twhile (count) {\n\t\tif (push(stack, &arr[--count]) == FALSE) {\n\t\t\tlog(ERROR, \"push failed!\\n\");\n\t\t\tdestroy_stack(stack);\n\t\t\treturn -1;\n\t\t}\n\n\t\tlog(DEBUG, \"pushed: arr[%d] = %d\\n\", count, arr[count]);\n\t}\n\n\tcount = 5;\n\n\twhile (count) {\n\t\tval = pop(stack);\n\t\tif (val)\n\t\t\tlog(DEBUG, \"popped: arr[%d] = %d\\n\", --count, (int)*val);\n\t\telse\n\t\t\tlog(ERROR, \"pop failed!\\n\");\n\t}\n\n\tdestroy_stack(stack);\n\n\treturn 0;\n}\n"
  }
]