[
  {
    "path": ".gitignore",
    "content": "/build\n.ycm_extra_conf.py\n*.swp\nCMakeLists.txt.user\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "CMAKE_MINIMUM_REQUIRED(VERSION 2.8)\nproject(PlyCal)\n\n#cmake_policy(SET CMP0028 OLD)\nset(CMAKE_CXX_STANDARD 11)\nset(CMAKE_CXX_STANDARD_REQUIRED ON)\nset(CMAKE_CXX_EXTENSIONS OFF)\nadd_definitions(-std=c++11) # for qt creator\n\n# Optionally compiling part\noption(BUILD_PlyCal_GUI \"enables PlyCal viewer\" true)\noption(BUILD_PlyCal_TEST \"enables PlyCal test\" false)\n\n# default built type\nIF(NOT CMAKE_BUILD_TYPE)\n  \tset(CMAKE_BUILD_TYPE Release CACHE STRING \"Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel.\" FORCE)\nENDIF(NOT CMAKE_BUILD_TYPE)\n\ninclude_directories(\n\tthirdParty\n\tPlyCal\n\t)\n\n# The library prefix\nset(LIB_PREFIX plycal)\n# Include the subdirectories\nadd_subdirectory(PlyCal)\n\nif(BUILD_PlyCal_GUI)\n\tadd_subdirectory(PlyCal_qt)\nendif(BUILD_PlyCal_GUI)\n\nif(BUILD_PlyCal_TEST)\n\tadd_subdirectory(PlyCal_test)\nendif(BUILD_PlyCal_TEST)\n\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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    <program>  Copyright (C) <year>  <name of author>\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<https://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<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "PlyCal/CMakeLists.txt",
    "content": "if( CMAKE_BUILD_TYPE EQUAL \"Release\")\n\tadd_definitions( -DNODEBUG )\nendif(CMAKE_BUILD_TYPE EQUAL \"Release\")\n\nfile(GLOB LIB_SRC\n    \"*.cpp\"\n\t)\nfile(GLOB LIB_HEADER\n    \"*.h\"\n\t)\nfind_package(\n\tOpenCV\n\tREQUIRED\n\t)\nfind_package(\n\tPCL\n\tQUIET\n\tREQUIRED\n\t)\nfind_package(\n\tCeres\n\tREQUIRED\n\t)\nfind_package(\n\tBoost\n\tREQUIRED\n\tCOMPONENTS\n\tsystem\n\tthread\n\t)\nfind_package(\n\tEigen3\n\tREQUIRED\n\t)\n# Fix a compilation bug under ubuntu 16.04 (Xenial)\nlist(REMOVE_ITEM PCL_LIBRARIES \"vtkproj4\")\nadd_definitions(${PCL_DEFINITIONS})\n\ninclude_directories(\n\t${PCL_INCLUDE_DIRS}\n\t${Boost_INCLUDE_DIRS}\n\t${OpenCV_INCLUDE_DIRS}\n\t${Eigen_INCLUDE_DIRS}\n\t${CERES_INCLUDE_DIRS}\n\t)\nlink_directories(\n\t${PCL_LIBRARY_DIRS}\n\t${Boost_LIBRARY_DIRS}\n\t)\n\nset(\n\tEDLINE_SRC\n\t${PROJECT_SOURCE_DIR}/thirdParty/edlines/EDLineDetector.cpp\n\t)\n\n\nadd_library(\n\tplycal\n\tSHARED\n\t${LIB_SRC}\n\t${LIB_HEADER}\n\t${EDLINE_SRC}\n\t)\ntarget_link_libraries(\n\tplycal\n\t${OpenCV_LIBS}\n\t${Boost_LIBRARIES}\n\t${PCL_LIBRARIES}\n\t${CERES_LIBRARIES}\n\t)\nset_target_properties(\n\tplycal\n\tPROPERTIES\n\tOUTPUT_NAME\n\t${LIB_PREFIX}\n\t)\n"
  },
  {
    "path": "PlyCal/calibrator.cpp",
    "content": "/**\n  ******************************************************************************\n  * @file\tcalibrator.cpp\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-28\n  * @brief\tcalibrator.cpp\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Includes ------------------------------------------------------------------*/\n#include \"calibrator.h\"\n\n#include <fstream>\n#include <iostream>\n\n#include <pcl/registration/icp.h>\n#include <pcl/common/common.h>\n#include <pcl/common/io.h>\n\n#include <ceres/ceres.h>\n#include <ceres/rotation.h>\n\nusing namespace lqh;\n/* Private define ------------------------------------------------------------*/\n\n/* Private typedef -----------------------------------------------------------*/\nusing PCC = pcl::PointCloud<pcl::PointXYZRGB>;\nusing PCI = pcl::PointCloud<pcl::PointXYZI>;\n\nnamespace\n{\ntemplate <typename T>\nstatic void ProjectPoint2Image(const T* const q_ptr, const T* const t_ptr,\n\t\t\t\t\t\t\t   const Eigen::Matrix<T, 3, 3>& k,\n\t\t\t\t\t\t\t   const Eigen::Matrix<T, 3, Eigen::Dynamic>& p3,\n\t\t\t\t\t\t\t   Eigen::Matrix<T, 3, Eigen::Dynamic>& p2)\n{\n\tEigen::Map<const Eigen::Quaternion<T> > q(q_ptr);\n\tEigen::Map<const Eigen::Matrix<T, 1, 3> > t(t_ptr);\n\n\tp2 = (q.matrix()*p3);\n//    p2.colwise() += t;\n\tfor(uint32_t i=0; i<p2.cols(); i++)\n\t{\n\t\tp2.col(i) += t;\n\t\tp2.col(i) = p2.col(i)/p2(2,i);\n\t}\n\tp2 = k*p2;\n}\n\n/**\n * @brief Edge to edge error (point to line error)\n *        3D point P_i_j locates at 3D edge i, its index is j. 3D edge i has correspondense in\n *        image E_i(ax+by+c=0,a^2+b^2+c^2=1), project P_i_j into image with initial T(q,p) and\n *        get 2D point P'_i_j(u,v). If T(q,p) is correct or precise, P'_i_j should be on E_i.\n *        Thus, the error is the distance between P'_i_j and E_i\n */\nstruct Edge2EdgeError\n{\n\tconst Eigen::Matrix3d& K;       // camera matrix\n\tconst Eigen::Matrix3Xd& pts;    // 3d points\n\tconst Eigen::Vector3d& coef;    // 2d edge(line) coefficients\n\n\t/**\n\t * @brief Edge2EdgeError constructor\n\t *\n\t * @param k\t[in]: camera intrinsic parameter matrix K\n\t * @param ps[in]: 3D edge pints set, P_i_j(j=0,1,...n), it's 3xn matrix\n\t * @param cf[in]: 2D line coefficients (ax+by+c=0,a^2+b^2+c^2=1)\n\t */\n\tEdge2EdgeError(const Eigen::Matrix3d& k, const Eigen::Matrix3Xd& ps, const Eigen::Vector3d& cf):\n\t\tK(k), pts(ps), coef(cf) {}\n\n\n\t/**\n\t * @brief Ceres error compute function\n\t *\n\t * @tparam T\tdouble or Jet\n\t * @param q\t[in]: Quaternion (rotation)\n\t * @param p [in]: translation\n\t * @param residuals[out]: error\n\t *\n\t * @return true: indicate success\n\t */\n\ttemplate<typename T>\n\tbool operator()(const T* const q, const T* const p, T* residuals)const\n\t{\n\t\tEigen::Matrix<T, 3, Eigen::Dynamic> points;\n\t\tProjectPoint2Image<T>(q,p, K.cast<T>(), pts.cast<T>(), points);\n\n\t\tEigen::Matrix<T, Eigen::Dynamic, 1> tmp = (coef.transpose().cast<T>())*points;\n\t\tresiduals[0] = tmp.cwiseAbs().sum();\n\n\t\treturn true;\t// important\n\t}\n};\n\nstruct Point2PolygonError\n{\n\tconst Eigen::Matrix3d& K;\n\tconst Eigen::Matrix3Xd& pts;\n\tconst Eigen::Matrix3Xd& vertex;\n\tEigen::Matrix3Xd edge_normal;\n\n\tPoint2PolygonError(const Eigen::Matrix3d& k, const Eigen::Matrix3Xd& ps, const Eigen::Matrix3Xd& vx ):\n\t\tK(k), pts(ps), vertex(vx)\n\t{\n\t\tEigen::Vector3d center = vx.rowwise().mean();\n\t\tedge_normal.resize(3, vx.cols());\n\t\tedge_normal.row(2).setZero();\n\n\t\tfor(uint32_t i=0; i<vx.cols(); i++)\n\t\t{\n\t\t\tuint32_t next = (i == (vx.cols()-1)) ? 0 : i+1;\n\t\t\tEigen::Vector3d dir = vx.col(next) - vx.col(i);\n\t\t\tedge_normal(0, i) = -dir(1);\n\t\t\tedge_normal(1, i) = dir(0);\n\n\t\t\tif(edge_normal.col(i).dot(center - vx.col(i)) < 0 )\n\t\t\t{\n\t\t\t\tedge_normal.col(i) *= -1;\n\t\t\t}\n\t\t}\n\t}\n\n\ttemplate<typename T>\n\tbool operator()(const T* const q, const T* const t, T* residuals)const\n\t{\n\t\tusing Matrix3XT = Eigen::Matrix<T, 3, Eigen::Dynamic>;\n\n\t\tMatrix3XT vtx = vertex.cast<T>();\n\t\tMatrix3XT normals = edge_normal.cast<T>();\n\n\t\tMatrix3XT points;\n\t\tProjectPoint2Image<T>(q, t, K.cast<T>(), pts.cast<T>(), points);\n\n\t\tresiduals[0] = T(0);\n\t\tfor(uint32_t i=0; i<pts.cols(); i++)\n\t\t{\n\t\t\tbool flag = false;\n\t\t\tfor(uint32_t j=0; j<vertex.cols(); j++)\n\t\t\t{\n\t\t\t\tif( normals.col(j).dot(points.col(i) - vtx.col(j)) < T(0) )\n\t\t\t\t{\n\t\t\t\t\tflag = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// one point locates outside the polygon\n\t\t\tif(flag)\n\t\t\t{\n\t\t\t\tresiduals[0] += T(1);\n\t\t\t}\n\t\t}\n\n\t\treturn true;\t// important\n\t}\n\n\n};\n}\n\n\n/* Private variables ---------------------------------------------------------*/\n/* Private function prototypes -----------------------------------------------*/\n/* Private functions ---------------------------------------------------------*/\n\n/* Exported functions --------------------------------------------------------*/\n\n/**\n  * @brief\n  * @param\n  * @note\n  * @return None\n  */\nCalibrator::Calibrator(const nlohmann::json& js):\n\tis_valid_(false),\n\timg_width_(0),\n\timg_height_(0)\n{\n\tsize_ = js[\"size\"].get<uint32_t>();\n\tif(size_ < 3 )\n\t{\n\t\tstd::cerr << \"E: size must >= 3\\n \" << __FUNCTION__;\n\t\treturn;\n\t}\n\n\timgply_.reset( new ImagePolygon(js[\"img\"], size_) );\n\tpcply_.reset( new PointcloudPolygon(js[\"pc\"], size_) );\n\tpolygons_.clear();\n\tpolygons_v_.clear();\n\tpolygons_v_.reserve(10);\n\n\ttrack_error_threshold_ = js[\"track_error_threshold\"].get<double>();\n\n\tK_.setIdentity();\n\tT_.setIdentity();\n\n\tauto& k = js[\"cam\"][\"K\"];\n\tassert( k.size() == 3 );\n\tfor(uint8_t i=0; i<2; i++)\n\t{\n\t\tassert( k[i].size() == 3 );\n\t\tK_.row(i) << k[i][0], k[i][1], k[i][2];\n\t}\n\tK_.row(2) << 0,0,1;\n\n\tauto& t = js[\"tf\"];\n\tassert( t.size() == 4 );\n\tfor(uint8_t i=0; i<3; i++)\n\t{\n\t\tassert( t[i].size() == 4 );\n\t\tT_.row(i) << t[i][0], t[i][1], t[i][2], t[i][3];\n\t}\n\tT_.row(3) << 0,0,0,1;\n\n\tis_valid_ = true;\n}\n\nuint32_t Calibrator::Add(const cv::Mat& img, const PCI& pc,\n\t\t\t\t\t\t cv::Mat& img_out, pcl::PointCloud<pcl::PointXYZRGB>& pcc)\n{\n\tpolygons_.emplace_back(size_);\n\tauto& ply = polygons_.back();\n\tpolygons_v_.push_back(&ply);\n\n\tply.img = imgply_->Add(img,img_out);\n\tply.pc  = pcply_->Add(pc, pcc);\n\n\tif(ply.img != nullptr && ply.pc != nullptr)\n\t{\n\t\tMatchLines(ply);\n\t}\n\n//\tif( polygons_.size() == 1)\n//\t{\n//        MatchLines(ply);\n//\t}\n//\telse\n//\t{\n//\t\tauto it = std::prev(polygons_.end(),2);\n//        TrackLines(*it, ply);\n//\t}\n\n\t//return id\n\treturn polygons_v_.size()-1;\n}\n\nbool Calibrator::RefineImage(const cv::Mat& img,\n\t\t\t\t\t\t\t cv::Mat& img_out, const std::vector<cv::Point2d>& pts)\n{\n\tassert(pts.size() == size_);\n\n\tEigen::Matrix3Xd vtx(3, size_);\n\tvtx.row(2).setOnes();\n\n\tfor(uint8_t i=0; i<size_; i++)\n\t{\n\t\tvtx(0,i) = pts[i].x;\n\t\tvtx(1,i) = pts[i].y;\n\t}\n\n\tauto& ply = polygons_.back();\n\tply.img = imgply_->Init(img, img_out, vtx);\n\tif(ply.img == nullptr)\n\t{\n\t\treturn false;\n\t}\n\n\tif(ply.pc == nullptr)\n\t{\n\t\treturn true;\n\t}\n\t// both valid, match\n\tMatchLines(ply);\n//    if( polygons_.size() == 1)\n//    {\n//        MatchLines(ply);\n//    }\n//    else\n//    {\n//        auto it = std::prev(polygons_.end(),2);\n//        TrackLines(*it, ply);\n//    }\n\treturn true;\n}\n\nbool Calibrator::RefinePointcloud(const PCI& pc, PCC& pcc, const Eigen::Vector4d& param )\n{\n\tauto& ply = polygons_.back();\n\n\tpcply_->SetFilterParameters(param);\n\tply.pc = pcply_->Add(pc, pcc);\n\tif(ply.pc == nullptr)\n\t{\n\t\treturn false;\n\t}\n\n\tif(ply.img == nullptr)\n\t{\n\t\treturn true;\n\t}\n\n\t// both valid, match\n\tMatchLines(ply);\n//    if( polygons_.size() == 1)\n//    {\n//        MatchLines(ply);\n//    }\n//    else\n//    {\n//        auto it = std::prev(polygons_.end(),2);\n//        TrackLines(*it, ply);\n//    }\n\treturn true;\n}\n\n/**\n * @brief Calibrator::Remove\n * @todo: maybe we should use !!!skip\n * @param id\n * @return\n */\nbool Calibrator::Remove(uint32_t id)\n{\n\tif(id >= polygons_v_.size())\n\t{\n\t\treturn false;\n\t}\n\n\tpolygons_v_.erase(polygons_v_.begin()+id);\n\tauto it = polygons_.begin();\n\tstd::advance(it, id);\n\tpolygons_.erase(it);\n\treturn true;\n}\n\n// remove last one\nbool Calibrator::Remove()\n{\n\tif(polygons_.size() == 0)\n\t{\n\t\treturn false;\n\t}\n\n\tpolygons_.pop_back();\n\tpolygons_v_.pop_back();\n}\n\nbool Calibrator::Compute(Eigen::Matrix4d &tf)\n{\n\tif(polygons_.size() == 0)\n\t{\n\t\treturn false;\n\t}\n\n\tOptimize(tf);\n\n\tT_ = tf;\n\treturn true;\n}\n\n\nvoid  Calibrator::Optimize(Eigen::Matrix4d& tf)\n{\n\tEigen::Matrix3d rot = T_.topLeftCorner(3,3);\n\tEigen::Quaterniond q (rot);\n\tEigen::Vector3d p = T_.topRightCorner(3,1);\n\n\t//std::cout << \"Before \\nq:\\n\" << q.coeffs() << \"\\nt:\\n\" << p << std::endl;\n\n\tceres::Problem problem;\n\tceres::Solver::Summary summary;\n\tceres::Solver::Options options;\n\tceres::LossFunction* loss_function_edge (new ceres::SoftLOneLoss(1));\n\tceres::HuberLoss* loss_function_inlier (new ceres::HuberLoss(500));\n\tceres::LocalParameterization* quaternion_local_parameterization =\n\t\tnew ceres::EigenQuaternionParameterization;\n\n\tfor(const auto& ply : polygons_)\n\t{\n\t\t// add edge\n\t\tfor(uint32_t i=0; i<size_; i++)\n\t\t{\n\t\t\tif(ply.pc->edges[i].points.cols() == 0)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tceres::CostFunction* cost =\n\t\t\t\tnew ceres::AutoDiffCostFunction<Edge2EdgeError, 1,4,3>(\n\t\t\t\tnew Edge2EdgeError( K_, ply.pc->edges[i].points, ply.img->edges[ply.ids[i]].coef ));\n\n\t\t\tproblem.AddResidualBlock(cost, loss_function_edge,\n\t\t\t\t\t\t\t\t\t q.coeffs().data(), p.data() );\n\t\t}\n\t\t// add inlier points\n\t\tceres::CostFunction* cost = new ceres::AutoDiffCostFunction<Point2PolygonError,1,4,3>(\n\t\t\tnew Point2PolygonError(K_, ply.pc->inliers, ply.img->vertexs) );\n\t\tproblem.AddResidualBlock(cost, NULL, q.coeffs().data(), p.data());\n//        problem.AddResidualBlock(cost, loss_function_inlier, q.coeffs().data(), p.data());\n\t}\n\tproblem.SetParameterization(q.coeffs().data(), quaternion_local_parameterization);\n\t//options.linear_solver_type = ceres::DENSE_SCHUR;\n\toptions.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n\toptions.max_num_iterations = 5000;\n\t// or use all cpu cores\n\toptions.num_threads= boost::thread::hardware_concurrency() - 1;\n#if (CERES_VERSION_MAJOR < 2)\n\toptions.num_linear_solver_threads = options.num_threads;\n#endif\n\t//options.minimizer_progress_to_stdout = true;\n\n\tceres::Solve(options, &problem, &summary);\n\n\tstd::cout << summary.FullReport() << std::endl;\n\n\ttf = Eigen::Matrix4d::Identity();\n\ttf.topLeftCorner(3,3) = q.matrix();\n\ttf.topRightCorner(3,1) = p;\n\n\tstd::cout << \"T: \\n\" << tf << std::endl;\n}\n\n\nvoid Calibrator::TrackLines(const Polygon& ply_prev,  Polygon& ply) const\n{\n\t// image polygon keep orders, no futhur processing\n\n\t// tracking pointcloud edge\n//    using PC = pcl::PointCloud<pcl::PointXYZ>;\n//    auto Mat2PC = [](const Eigen::Matrix3Xd& mat, PC& pc)\n//    {\n//        pc.points.reserve(mat.cols());\n//        for(uint32_t i=0; i<mat.cols(); i++)\n//        {\n//            pc.points.emplace_back(mat(0,i), mat(1,i), mat(2,i));\n//        }\n//    };\n\n//    PC::Ptr pc_prev (new PC);\n//    PC::Ptr pc (new PC);\n//    PC pc_out;\n//    Mat2PC(ply_prev.pc->inliers, *pc_prev);\n//    Mat2PC(ply.pc->inliers, *pc);\n\n//    pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;\n//    icp.setInputSource(pc);\n//    icp.setInputTarget(pc_prev);\n//    icp.setMaximumIterations(200);\n//    icp.setTransformationEpsilon(1e-6);\n//    icp.setEuclideanFitnessEpsilon(1);\n\n//    icp.align(pc_out, Eigen::Matrix4d::Identity());\n//    Eigen::Matrix4d T = icp.getFinalTransformation();\n\n\n//    using PairUD = std::pair<uint32_t, double>;\n//    std::vector<PairUD> offsets(size_);\n\n//    for(uint32_t i=0; i<size_; i++)\n//    {\n//        offsets[i].first = i;\n//        offsets[i].second = 0;\n//        for(uint32_t j=0; j<size_; j++)\n//        {\n//            const auto& prev = ply_prev.pc->edges[(j+i)%size_];\n//            const auto& cur = ply.pc->edges[j];\n//            if(prev.coef.norm() < 0.1 || cur.points.cols() == 0)\n//            {\n//                continue;\n//            }\n//            for(uint32_t k=0; k<cur.points.cols(); k++)\n//            {\n//                offsets[i].second += prev.coef.cross(T*cur.points.col(k) - prev.p0).norm();\n//            }\n//        }\n//    }\n\n//    std::sort(offsets.begin(), offsets.end(), [](const PairUD& a, const PairUD& b)\n//    {\n//        return a.second < b.second;\n//    });\n\n//    uint32_t offset = offsets[0].first;\n//    for(uint32_t i=0; i<size_; i++)\n//    {\n//        ply.ids[i] = ply_prev.ids[(i+offset)%size_];\n//    }\n}\n\n/**\n * @brief match the 2/3d Polygon, since both polygon save edges\n * \t\t  as clock-wise, just find the offset is enough\n *\n * @param ply [in/out]\n */\nvoid Calibrator::MatchLines(Polygon& ply) const\n{\n\t// we find the offset based on the longest(most points) two edges\n\tstd::vector<uint32_t> ids(size_);\n\tfor(uint32_t i=0; i<size_; i++)\n\t{\n\t\tids[i] = i;\n\t}\n\n\t// decrease order\n\tstd::sort(ids.begin(), ids.end(), [&ply](uint32_t a, uint32_t b)\n\t{\n\t\treturn ply.pc->edges[a].points.cols() >\n\t\t\t   ply.pc->edges[b].points.cols();\n\t});\n\n\tconst auto& edge_0 = ply.pc->edges[ids[0]];\n\tconst auto& edge_1 = ply.pc->edges[ids[1]];\n\tint32_t gap = ids[1] - ids[0];\n\n\tusing PairUD = std::pair<uint32_t, double>;\n\tstd::vector<PairUD> offsets(size_);\n\n\tEigen::Matrix3d rot = T_.topLeftCorner(3,3);\n\tEigen::Vector3d trans = T_.topRightCorner(3,1);\n\n\tauto err_proj = [this, &rot, &trans](const ImagePolygon::Edge2D& img,\n\t\t\t\t\t\t\t\t\t\t const PointcloudPolygon::Edge3D& pc,\n\t\t\t\t\t\t\t\t\t\t double& err)\n\t{\n\t\tEigen::Vector2d dir_proj = (K_*(rot*pc.coef + trans)).head(2);\n\t\tdir_proj.normalize();\n\t\tEigen::Vector2d dir_img(img.coef(1), -img.coef(0));\n\t\tdir_img.normalize();\n\t\tdouble err_angle = std::acos(dir_proj.dot(dir_img))/MATH_PI*180;\n\n\n\t\tEigen::Matrix3Xd pt_proj = rot*pc.points;\n\t\tpt_proj.colwise() += trans;\n\t\tpt_proj = K_*pt_proj;\n\t\tfor(uint32_t i=0; i<pt_proj.cols(); i++)\n\t\t{\n\t\t\tpt_proj.col(i) = pt_proj.col(i)/pt_proj(2,i);\n\t\t}\n\t\tdouble err_dis = (img.coef.transpose()*pt_proj).cwiseAbs().sum();\n\n\t\terr += err_angle*err_dis;\n\t};\n\n\tfor(uint32_t i=0; i<size_; i++)\n\t{\n\t\toffsets[i].first = i;\n\t\toffsets[i].second = 0;\n\t\t// 3d edge_0 <----> 2d edge i\n\t\tuint32_t id1 = (static_cast<int32_t>(i)+gap) < 0 ? i+gap +size_ : (i+gap)%size_;\n\t\terr_proj(ply.img->edges[i], edge_0, offsets[i].second);\n\t\terr_proj(ply.img->edges[id1], edge_1, offsets[i].second);\n\t}\n\n\t// increase order, offsets[0] has smallest error\n\tstd::sort(offsets.begin(), offsets.end(), [](const PairUD& a, const PairUD&b)\n\t{\n\t\treturn a.second < b.second;\n\t});\n\n\t// ids[0] 3d edge <----> offsets[0].first 2d edge\n\tuint32_t id_img = offsets[0].first > ids[0] ? offsets[0].first - ids[0]:\n\t\t\t\t\t  offsets[0].first + size_ - ids[0];\n\n\tstd::cout << \"pc[0-4]: \";\n\tfor(uint32_t i=0; i<size_; i++)\n\t{\n\t\tply.ids[i] = (id_img+i)%size_;\n\n\t\tstd::cout << ply.ids[i] << \", \";\n\t}\n\tstd::cout << std::endl;\n\n\n}\n\n\n\n\nuint32_t Calibrator::SavePolygonData(const std::string& dir)\n{\n\tEigen::IOFormat csvfmt(Eigen::FullPrecision, Eigen::DontAlignCols, \", \", \"\\n\", \"\", \"\", \"\", \"\");\n\tuint32_t i = 0;\n\tfor(const auto& ply : polygons_)\n\t{\n\t\tstd::ofstream pc_inlier(dir+\"/pc_inlier_\"+std::to_string(i)+\".csv\");\n\t\tstd::ofstream pc_edge(dir+\"/pc_edge_\"+std::to_string(i)+\".csv\");\n\t\tstd::ofstream img_coef(dir+\"/img_coef_\"+std::to_string(i)+\".csv\");\n\t\tstd::ofstream img_vertex(dir+\"/img_vertex_\"+std::to_string(i)+\".csv\");\n\t\tif(!pc_inlier.good() || !pc_edge.good() ||\n\t\t\t\t!img_coef.good() || !img_vertex.good())\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\tpc_inlier << ply.pc->inliers.format(csvfmt);\n\t\tpc_inlier.close();\n\n\t\tuint32_t num = 0;\n\t\tfor(const auto& it: ply.pc->edges)\n\t\t{\n\t\t\tnum += it.points.cols();\n\t\t}\n\t\tEigen::Matrix4Xd edges(4, num);\n\t\tuint32_t id =0;\n\t\tfor(uint32_t j=0; j<ply.pc->edges.size(); j++)\n\t\t{\n\t\t\tconst auto& it = ply.pc->edges[j].points;\n\t\t\tif(it.cols() == 0)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tedges.block(0,id, 1, it.cols() ).setConstant(j);\n\t\t\tedges.block(1,id, 3, it.cols() ) = it;\n\t\t\tid += it.cols();\n\t\t}\n\t\tpc_edge << edges.format(csvfmt);\n\t\tpc_edge.close();\n\n\n\t\tEigen::Matrix3Xd coef(3, size_);\n\t\tfor(uint32_t j=0; j<ply.img->edges.size(); j++)\n\t\t{\n\t\t\tcoef.col(j) = ply.img->edges[ply.ids[j]].coef;\n\t\t}\n\t\timg_coef << coef.format(csvfmt);\n\t\timg_coef.close();\n\n\t\timg_vertex << ply.img->vertexs.format(csvfmt);\n\t\timg_vertex.close();\n\n\t\ti++;\n\t}\n\n}\n\n\n\n\nbool Calibrator::Project(pcl::PointCloud<pcl::PointXYZRGB>& pc, cv::Mat& img,\n\t\t\t\t\t\t const Eigen::Matrix4d& tf)\n{\n\tconst double resolution = 0.1;\n\tconst double depth_min = 1.0;\n\tconst double depth_gap = 10.0;\n\n\tif(img_width_ != img.cols || img_height_ != img.rows)\n\t{\n\t\timg_width_ = img.cols;\n\t\timg_height_ = img.rows;\n\t}\n//    Eigen::Vector4f pt_min, pt_max;\n//    pcl::getMinMax3D(pc, pt_min, pt_max);\n\n\n//    double depth_gap = std::sqrt(pt_max(0)*pt_max(0) + pt_max(1)+pt_max(1)) - depth_gap + 0.01;\n//    if(depth_gap > 5)\n//    {\n//        depth_gap = 5.0;\n//    }\n\tuint32_t  num = static_cast<uint32_t>(depth_gap/resolution);\n\tlqh::utils::color::rgbs colors = lqh::utils::color::get_rgbs(num);\n\n\tcv::Mat im;\n\timg.copyTo(im);\n\n\tfor(auto& p : pc.points)\n\t{\n\t\tEigen::Vector3d pt = K_*(tf*Eigen::Vector4d(p.x, p.y, p.z, 1)).topRows(3);\n\t\tif(pt(2) < 0.5)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tint32_t u = static_cast<int32_t>(pt(0)/pt(2));\n\t\tint32_t v = static_cast<int32_t>(pt(1)/pt(2));\n\n\t\tif(u < 0 || u >= img.cols || v<0 || v >= img.rows)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tcv::Vec3b color = im.at<cv::Vec3b>(cv::Point(u,v));\n\t\tp.r = color[2];\n\t\tp.g = color[1];\n\t\tp.b = color[0];\n\n\t\tdouble f = std::sqrt(p.x*p.x + p.y*p.y) - depth_min;\n\t\tuint32_t idx = static_cast<uint32_t>(f/resolution);\n\t\tif(idx >= num)\n\t\t{\n\t\t\tidx = num -1;\n\t\t}\n\t\tauto& c = colors[idx];\n\t\tcv::circle(img, cv::Point2d(u,v), 2, cv::Scalar(c[2], c[1], c[0]), -1);\n\t}\n}\n\n\nvoid Calibrator::SetTranformation(const Eigen::Matrix4d& tf)\n{\n\tT_ = tf;\n\n\t// check pointcloud filter\n\tif(img_height_ == 0 || img_width_ == 0)\n\t{\n\t\treturn;\n\t}\n\n\tEigen::Vector4d orig = pcply_->GetFilterParameters();\n\tauto getYaw = [this](double x, double y)->double\n\t{\n\t\tEigen::Vector4d v (0,0,0,1);\n\t\tv.head(3) = K_.inverse()*Eigen::Vector3d(x,y,1);\n\t\tv = T_.inverse()*v;\n\t\tdouble angle = std::atan2(v(1), v(0))/MATH_PI*180;\n\t\treturn angle <0? 360+angle : angle;\n\t};\n\tdouble angle0 = getYaw(0,0);\n\tdouble angle1 = getYaw(img_width_-1, img_height_-1);\n\n\tif(angle0 > angle1)\n\t{\n\t\tstd::swap(angle0, angle1);\n\t}\n\n\tif(angle1-angle0 <180)\n\t{\n\t\tif(orig(0)< angle0 || orig(0)>angle1 )\n\t\t{\n\t\t\torig(0) = angle0;\n\t\t}\n\t\tif(angle1 - orig(0) > orig(1))\n\t\t{\n\t\t\torig(1) = angle1 - orig(0);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif(orig(0)> angle0 && orig(0)<angle1 )\n\t\t{\n\t\t\torig(0) = angle1;\n\t\t}\n\t\tdouble gap = orig(0) >= angle1 ? 360-angle1+angle0 : angle0-orig(0);\n\t\tif(orig(1) > gap)\n\t\t{\n\t\t\torig(1) = gap;\n\t\t}\n\t}\n\tpcply_->SetFilterParameters(orig);\n}\n\n\n\n\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "PlyCal/calibrator.h",
    "content": "/**\n  ******************************************************************************\n  * @file\tcalibrator.h\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-28\n  * @brief\tcalibrator.h\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Define to prevent recursive inclusion -------------------------------------*/\n#ifndef __CALIBRATOR_H\n#define __CALIBRATOR_H\n\n/* Includes ------------------------------------------------------------------*/\n\n#include \"stdint.h\"\n#include <string>\n#include <memory>\n\n#include <Eigen/Dense>\n\n#include <opencv2/opencv.hpp>\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n\n#include \"image_polygon.h\"\n#include \"pointcloud_polygon.h\"\n\n#include \"json/json.hpp\"\n\n#include \"utils.h\"\n\n/* Exported macro ------------------------------------------------------------*/\n/* Exported types ------------------------------------------------------------*/\n\nnamespace lqh\n{\nclass Calibrator\n{\npublic:\n\texplicit Calibrator(const nlohmann::json& js);\n    uint32_t Add(const cv::Mat& img, const pcl::PointCloud<pcl::PointXYZI>& pc,\n                 cv::Mat& img_out, pcl::PointCloud<pcl::PointXYZRGB>& pcc);\n\n    bool RefineImage(const cv::Mat& img, cv::Mat& img_out, const std::vector<cv::Point2d>& pts);\n    bool RefinePointcloud(const pcl::PointCloud<pcl::PointXYZI>& pc,\n                          pcl::PointCloud<pcl::PointXYZRGB>& pcc,\n                          const Eigen::Vector4d& param );\n    uint32_t SavePolygonData(const std::string& dir);\n    void SetCameraK(const Eigen::Matrix3d& k)\n    {\n        K_ = k;\n    }\n    void SetTranformation(const Eigen::Matrix4d& tf);\n    bool Remove(uint32_t id);\n    bool Remove();\n    bool Compute(Eigen::Matrix4d& tf);\n    bool Compute()\n    {\n        return Compute(T_);\n    }\n    const Eigen::Matrix4d& GetTransformation()\n    {\n        return T_;\n    }\n\n    bool ImageGood(uint32_t id)\n    {\n        if(id >= polygons_v_.size())\n        {\n            return false;\n        }\n        return (polygons_v_[id]->img != nullptr);\n    }\n    bool PointcloudGood(uint32_t id)\n    {\n        if(id >= polygons_v_.size())\n        {\n            return false;\n        }\n        return (polygons_v_[id]->pc != nullptr);\n    }\n\n\tbool Good()\n\t{\n\t\treturn is_valid_;\n\t}\n\n    bool Project(pcl::PointCloud<pcl::PointXYZRGB>& pc, cv::Mat& img)\n    {\n        Project(pc, img, T_);\n    }\n    bool Project(pcl::PointCloud<pcl::PointXYZRGB>& pc, cv::Mat& img,\n                 const Eigen::Matrix4d& tf);\n\nprivate:\n\tstruct Polygon\n\t{\n\t\t/**\n\t\t * ids: corroesponences of 2d/3d Polygon\n\t\t * same edge: $i$th 3d edge  <---> ids[i] 2d edge\n         */\n\t\tstd::vector<uint32_t> ids;\n\t\tImagePolygon::Polygon2D::ConstPtr img;\n\t\tPointcloudPolygon::Polygon3D::ConstPtr pc;\n\n        Polygon(uint32_t size):img(nullptr), pc(nullptr)\n\t\t{\n\t\t\tids.resize(size);\n\t\t\tfor(uint32_t i=0; i<size; i++)\n\t\t\t{\n\t\t\t\tids[i] = i;\n\t\t\t}\n\t\t}\n\t};\n\n\tbool is_valid_;\n\tuint32_t size_;\n\tdouble track_error_threshold_;\n    uint32_t img_width_;\n    uint32_t img_height_;\n\tEigen::Matrix3d K_;\n\tEigen::Matrix4d T_;\n\tstd::unique_ptr<ImagePolygon> imgply_;\n\tstd::unique_ptr<PointcloudPolygon> pcply_;\n    std::vector<Polygon*> polygons_v_;\n\tstd::list<Polygon> polygons_;\n\n\tvoid TrackLines(const Polygon& ply_prev, Polygon& ply) const;\n\tvoid MatchLines(Polygon& ply) const;\n    void Optimize(Eigen::Matrix4d& tf);\n};\n}\n\n/* Exported constants --------------------------------------------------------*/\n/* Exported functions --------------------------------------------------------*/\n\n#endif /* !__CALIBRATOR_H */\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "PlyCal/image_polygon.cpp",
    "content": "/**\n  ******************************************************************************\n  * @file\timage_polygon.cpp\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-22\n  * @brief\timage_polygon.cpp\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Includes ------------------------------------------------------------------*/\n#include \"image_polygon.h\"\n\n#include <iostream>\n#include <cmath>\n\n#include \"utils.h\"\n\nusing namespace lqh;\n\n/* Private typedef -----------------------------------------------------------*/\n/* Private define ------------------------------------------------------------*/\n/* Private macro -------------------------------------------------------------*/\n/* Private variables ---------------------------------------------------------*/\n/* Private function prototypes -----------------------------------------------*/\n/* Private functions ---------------------------------------------------------*/\n/* Exported functions --------------------------------------------------------*/\n\n/**\n  * @brief\n  * @param\n  * @note\n  * @return None\n  */\nImagePolygon::ImagePolygon(const nlohmann::json& js, uint8_t size):\n\tsize_(size), polygon_(nullptr)\n{\n\t//!!! we don't set default\n\t// config line detector\n\tauto ed = js[\"edlines\"];\n\tEDLineParam para;\n\n\tpara.minLineLen = ed[\"minLineLen\"];\n\tpara.lineFitErrThreshold = ed[\"lineFitErrThreshold\"];\n\tpara.ksize = ed[\"ksize\"];\n\tpara.sigma = ed[\"sigma\"];\n\tpara.gradientThreshold = ed[\"gradientThreshold\"];\n\tpara.scanIntervals = ed[\"scanIntervals\"];\n\tpara.anchorThreshold = ed[\"anchorThreshold\"];\n\n\tdetector_.reset(new EDLineDetector(para));\n\n\tfeature_size_ = js[\"feature\"][\"size\"];\n\tfeature_offset_ = js[\"feature\"][\"offset\"];\n\tfeature_threshold_ = js[\"feature\"][\"threshold\"];\n\n\tmerge_distance_threshold_ = js[\"merge\"][\"distance_threshold\"];\n\tmerge_angle_threshold_ = js[\"merge\"][\"angle_threshold\"];\n\tmerge_endpoint_distance_threshold_ = js[\"merge\"][\"endpoint_distance_threshold\"];\n\n\tfilter_point_line_threshold_  = js[\"filter\"][\"point_line_threshold\"];\n\tfilter_line_angle_threshold_  = js[\"filter\"][\"line_angle_threshold\"];\n\tfilter_point_center_factor_    = js[\"filter\"][\"point_center_factor\"];\n\tif(filter_point_center_factor_ >1 || filter_point_center_factor_ <0)\n\t{\n\t\tstd::cout << \"W: point_dis_factor in (0,1)  get \" <<\n\t\t\t\t  filter_point_center_factor_ << \"\\n\";\n\t\tfilter_point_center_factor_ = 0.2;\n\t}\n\t// random\n\t// center to line distance\n\tfilter_point_center_max_ = 100;\n\tfilter_line_center_min_ = 50;\n\n\twidth_ = 0;\n\tlength_ = 0;\n\tangle_width_ = 0;\n\tangle_length_ = 0;\n\n\tEigen::Matrix3Xd pts(3,4);\n\tpts.row(2).setOnes();\n\tfor(uint8_t i=0; i<4; i++)\n\t{\n\t\tpts(0,i) = js[\"init\"][i][0].get<double>();\n\t\tpts(1,i) = js[\"init\"][i][1].get<double>();\n\t}\n\tpolygon_ = InitPolygon(pts);\n\n}\n\nImagePolygon::Polygon2D::Ptr ImagePolygon::InitPolygon(const Eigen::Matrix3Xd& pts)\n{\n\t// currently, only apply to rectangular\n\t// @TODO\n\tassert(pts.cols() == 4);\n\tassert(pts.cols() == size_ );\n\n\tusing PairUD = std::pair<uint32_t, double>;\n\t// sort the points(clock wise)\n\tEigen::Vector3d center = pts.rowwise().mean();\n\tcenter(2) = 1;\n\tstd::vector<PairUD> verts( size_ );\n\n\tfor(uint32_t i=0; i<size_; i++)\n\t{\n\t\tverts[i].first = i;\n\t\tverts[i].second = std::atan2(pts(1,i)-center(1), pts(0,i)-center(0)) + MATH_PI;\n\t}\n\tstd::sort(verts.begin(), verts.end(), [](PairUD& a, PairUD& b)\n\t{\n\t\treturn a.second < b.second;\n\t});\n\n\tPolygon2D::Ptr ply = std::make_shared<Polygon2D>(size_);\n\tply->center = center;\n\n\tauto EistimateCoef = [](const Eigen::Vector3d& p0,\n\t\t\t\t\t\t\tconst Eigen::Vector3d& p1,\n\t\t\t\t\t\t\tEigen::Vector3d& coef)\n\t{\n\t\tEigen::Vector3d dir = (p0-p1).normalized();\n\t\tEigen::Vector3d c = (p0+p1)/2;\n\n\t\tcoef(0) = -1*dir(1);\n\t\tcoef(1) = dir(0);\n\t\tcoef(2) = -1*(coef(0)*c(0) + coef(1)*c(1));\n\t};\n\n\tfor(uint32_t i=0; i<size_; i++)\n\t{\n\t\tuint32_t next = (i== size_-1) ? 0: i+1;\n\t\tply->vertexs.col(i) = pts.col(verts[i].first);\n\t\tEistimateCoef(pts.col(verts[i].first), pts.col(verts[next].first),\n\t\t\t\t\t  ply->edges[i].coef);\n\t\tply->edges[i].length = (pts.col(verts[i].first) - pts.col(verts[next].first)).norm();\n\t\tdouble dir = std::atan2(-ply->edges[i].coef(0), ply->edges[i].coef(1))/MATH_PI*180;\n\t\tply->edges[i].dir = (dir<0)?dir+180:dir;\n\t\t//ExtractLineFeature(img, pts.col(verts[i].first), pts.col(verts[next].first),\n\t\t//center, polygon_->edges[i].feature);\n\t}\n\n\tUpdateParameters(ply);\n\n\treturn ply;\n}\n\nImagePolygon::Polygon2D::ConstPtr ImagePolygon::Init(const cv::Mat& img,\n\t\tcv::Mat& img_out, const Eigen::Matrix3Xd& pts)\n{\n\tPolygon2D::Ptr ply = InitPolygon(pts);\n//    SaveMarkedImage(\"init.png\", img, ply);\n\treturn ExtractPolygon(img, img_out,ply);\n}\n\nImagePolygon::Polygon2D::ConstPtr ImagePolygon::Add(const cv::Mat& img, cv::Mat& img_out)\n{\n\tif(polygon_ == nullptr)\n\t{\n\t\tstd::cerr << \"E: init first\\n\";\n\t\treturn nullptr;\n\t}\n\treturn ExtractPolygon(img, img_out, polygon_);\n}\n\nImagePolygon::Polygon2D::ConstPtr ImagePolygon::ExtractPolygon(const cv::Mat& img,\n\t\tcv::Mat& img_out, Polygon2D::ConstPtr prev)\n{\n\t// we require color image\n\tassert(img.channels() == 3);\n\tstd::list<Line2D> lines;\n\tPolygon2D::Ptr ply;\n\n\tbool res = ExtractLines(img, lines);\n\tif(!res)\n\t{\n\t\tMarkImage(img_out, lines);\n\t\treturn nullptr;\n\t}\n//    SaveMarkedImage(\"ExtractLines.png\", img, lines);\n\n\tres &= FilterLines(lines, prev);\n\tif(!res)\n\t{\n\t\tMarkImage(img_out, lines);\n\t\treturn nullptr;\n\t}\n//    SaveMarkedImage(\"FilterLines.png\", img, lines);\n\n\tres &= MergeLines(lines);\n\tif(!res)\n\t{\n\t\tMarkImage(img_out, lines);\n\t\treturn nullptr;\n\t}\n//    SaveMarkedImage(\"EMergeLines.png\", img, lines);\n\n\tres &= FilterLinesByRectangule(lines, prev);\n\tif(!res)\n\t{\n\t\tMarkImage(img_out, lines);\n\t\treturn nullptr;\n\t}\n//    SaveMarkedImage(\"FilterLinesByRectangule.png\", img, lines);\n\n\tres &= SortLines(lines, prev, ply);\n\tif(res)\n\t{\n\t\tpolygon_ = ply;\n\t\tUpdateParameters();\n\t\tMarkImage(img_out, ply);\n\t\treturn ply;\n\t}\n\telse\n\t{\n\t\treturn nullptr;\n\t}\n}\n\nbool ImagePolygon::ExtractLines(const cv::Mat& img, std::list<Line2D>& ls)\n{\n\t//cv::Mat img_hsv;\n\t//cv::Mat imgs[3];\n\n\t//cv::cvtColor(img, img_hsv, cv::COLOR_BGR2HSV);\n\t//cv::split(img_hsv, imgs);\n\t//auto& img_h = imgs[2];\n\n\t//ls.clear();\n\n\n\t//// set circle\n\t//double x = polygon_->center(0);\n\t//double y = polygon_->center(1);\n\t//uint16_t r_max = static_cast<uint16_t>(filter_point_center_max_);\n\t//uint16_t r_min = static_cast<uint16_t>(filter_line_center_min_);\n\n\t//std::cout << \"cx: \" << x <<\" cy: \" << y\n\t//<< \"\\n r_max: \" << r_max << \"  r_min: \" << r_min << std::endl;\n\n\t////cv::Mat img_mask(img_h.rows, img_h.cols, CV_8U);\n\t////cv::circle(img_mask, cv::Point2d(x,y), r_max, cv::Scalar(255), -1);\n\t////cv::Mat img_roi;\n\t////img_h.copyTo(img_roi, img_mask);\n\n\n\t//double sum = 0;\n\t//uint8_t p_max = 0;\n\t//uint8_t p_min = 255;\n\n\t//for(uint16_t i=y-r_min; i<y+r_min; i++ )\n\t//{\n\t//for(uint16_t j=x-r_min; j<x+r_min; j++)\n\t//{\n\t//const auto& pixel = img_h.at<uint8_t>(i,j);\n\t//sum += pixel;\n\t//if( p_max < pixel)\n\t//{\n\t//p_max = pixel;\n\t//}\n\t//if(p_min > pixel)\n\t//{\n\t//p_min = pixel;\n\t//}\n\t//}\n\t//}\n\t//uint8_t average = static_cast<uint8_t>(sum/(4*r_min*r_min));\n\t//std::cout << \"average: \" << static_cast<int>(average)\n\t//<< \"  p_min: \" << static_cast<int>(p_min)\n\t//<< \" p_max: \" << static_cast<int>(p_max) << std::endl;\n\n\t//p_max += 4;\n\t//p_min -= 4;\n\n\t//for(uint16_t i=0; i<img.rows; i++)\n\t//{\n\t//for(uint16_t j=0; j<img.cols; j++)\n\t//{\n\t//double d = (i-y)*(i-y) + (j-x)*(j-x);\n\t//d = std::sqrt(d);\n\t//auto& pixel = img_h.at<uint8_t>(i,j);\n\n\t//if(d >= filter_point_center_max_)\n\t//{\n\t//pixel = 0;\n\t//}\n\t//else\n\t//{\n\t//if(pixel  > p_max)\n\t//{\n\t//pixel = 255 - (p_max - pixel);\n\t////pixel = 0;\n\t//}\n\t//else if(pixel < p_min)\n\t//{\n\t//pixel = 255 - (pixel-p_min);\n\t////pixel = 0;\n\t//}\n\t//else\n\t//{\n\t//pixel = 255;\n\t//}\n\t//}\n\t//}\n\t//}\n\n\t//cv::threshold(img_h, img_h,0,180,cv::THRESH_BINARY+cv::THRESH_OTSU);\n\t//img_h = img_h*255/180;\n\n\tcv::Mat img_h;\n\tcv::cvtColor(img, img_h, cv::COLOR_BGR2GRAY);\n//\tcv::imwrite(\"img_gray.png\", img_h);\n\n\tif(detector_->EDline(img_h) < 0 )\n\t{\n\t\tstd::cerr << \"E: EDline detector fail to detect lines in the image\\n\";\n\t\treturn false;\n\t}\n\n\tfor (uint16_t i =0; i<detector_->lineEquations_.size(); i++)\n\t{\n\t\tls.emplace_back();\n\t\tLine2D& last = ls.back();\n\n\t\t// ax+by+c=0  direction vector=(-b a)\n\t\tlast.dir = std::atan2(-detector_->lineEquations_[i][0],\n\t\t\t\t\t\t\t  detector_->lineEquations_[i][1])/MATH_PI*180;\n\n\t\tif(last.dir<0)\n\t\t{\n\t\t\tlast.dir += 180;\n\t\t}\n\n\t\tlast.p0  << detector_->lineEndpoints_[i][0],\n\t\t\t\t detector_->lineEndpoints_[i][1],\n\t\t\t\t 1;\n\t\tlast.p1 << detector_->lineEndpoints_[i][2],\n\t\t\t\tdetector_->lineEndpoints_[i][3],\n\t\t\t\t1;\n\t\tlast.coef << detector_->lineEquations_[i][0],\n\t\t\t\t  detector_->lineEquations_[i][1],\n\t\t\t\t  detector_->lineEquations_[i][2];\n\t\tlast.coef = last.coef/(last.coef.head(2).norm());\n\n\t\tlast.points.resize(2, detector_->lines_.sId[i+1]-detector_->lines_.sId[i]);\n\n\t\tuint16_t col_index = 0;\n\t\tfor(uint16_t j=detector_->lines_.sId[i]; j<detector_->lines_.sId[i+1]; j++)\n\t\t{\n\t\t\tlast.points.col(col_index++) << detector_->lines_.xCors[j],\n\t\t\t\t\t\t\tdetector_->lines_.yCors[j];\n\t\t}\n\t}\n\n\treturn true;\n}\n\n/**\n * filter criteria\n * 1. center to endpoint distances\n * 2. center to line distance\n * 3. endpoints to line distances\n * 4. line direction angle error\n */\nbool ImagePolygon::FilterLines(std::list<Line2D>& ls, Polygon2D::ConstPtr prev)\n{\n\tif(ls.size() < size_ )\n\t{\n\t\treturn false;\n\t}\n\tauto l = ls.begin();\n\twhile( l != ls.end() )\n\t{\n\t\tauto ln = l;\n\t\tl++;\n\t\tdouble center2point_0 = (prev->center - ln->p0).norm();\n\t\tdouble center2point_1 = (prev->center - ln->p1).norm();\n\t\tdouble center2line = std::abs(prev->center.dot(ln->coef));\n\n\t\tif( center2point_0 > filter_point_center_max_ ||\n\t\t\t\tcenter2point_1 > filter_point_center_max_ ||\n\t\t\t\tcenter2line < filter_line_center_min_  )\n\t\t{\n\t\t\tls.erase( ln );\n\t\t\tcontinue;\n\t\t}\n\n\t\tbool is_remove = true;\n\t\tfor(uint32_t i=0; i<size_; i++)\n\t\t{\n\t\t\tdouble d = std::abs(ln->p0.dot(prev->edges[i].coef));\n\t\t\td += std::abs(ln->p1.dot(prev->edges[i].coef));\n\t\t\tdouble angle = std::abs(ln->dir - prev->edges[i].dir);\n\t\t\tif(angle > 90)\n\t\t\t{\n\t\t\t\tangle = 180 - angle;\n\t\t\t}\n\t\t\tif(angle < filter_line_angle_threshold_ &&\n\t\t\t\t\td < filter_point_line_threshold_)\n\t\t\t{\n\t\t\t\tis_remove = false;\n\t\t\t}\n\t\t}\n\n\t\tif(is_remove )\n\t\t{\n\t\t\tls.erase( ln );\n\t\t}\n\t}\n\n\treturn ls.size() >= size_ ? true : false;\n}\n\n/**\n * @brief merge all paralle lines\n * @param ls\n * @return\n */\nbool ImagePolygon::MergeLines(std::list<Line2D>& ls)\n{\n\tif(ls.size() < size_)\n\t{\n\t\tstd::cerr << \"E: no enough line segments for \" << __FUNCTION__\n\t\t\t\t  << \"\\n   get \" << ls.size() << \" lines\\n\";\n\t\treturn false;\n\t}\n\n\tauto ln = ls.begin();\n\twhile(ln != ls.end())\n\t{\n\t\tbool flag = false;\n\t\tauto ln_nx = std::next(ln);\n\t\twhile(ln_nx != ls.end())\n\t\t{\n\t\t\t// distance error\n\t\t\tdouble d = std::abs(ln->p0.transpose()*ln_nx->coef);\n\t\t\td += std::abs(ln->p1.transpose()*ln_nx->coef);\n\t\t\td += std::abs(ln_nx->p0.transpose()*ln->coef);\n\t\t\td += std::abs(ln_nx->p1.transpose()*ln->coef);\n\n\t\t\tEigen::Vector4d e2e;\n\t\t\te2e(0) = (ln->p0 - ln_nx->p0).norm();\n\t\t\te2e(1) = (ln->p0 - ln_nx->p1).norm();\n\t\t\te2e(2) = (ln->p1 - ln_nx->p0).norm();\n\t\t\te2e(3) = (ln->p1 - ln_nx->p1).norm();\n\n\t\t\t// direction angle error\n\t\t\tdouble angle = std::abs(ln->dir - ln_nx->dir);\n\t\t\tif(angle > 90)\n\t\t\t{\n\t\t\t\tangle = 180 - angle;\n\t\t\t}\n\n\t\t\tif(angle < merge_angle_threshold_ &&\n\t\t\t\t\td < merge_distance_threshold_ &&\n\t\t\t\t\te2e.minCoeff() < merge_endpoint_distance_threshold_)\n\t\t\t{\n\t\t\t\t// merge two line segement\n\t\t\t\tflag = true;\n\n\t\t\t\t// find endpoints\n\t\t\t\tEigen::Matrix3Xd endpoint(3,4);\n\t\t\t\tendpoint.col(0) = ln->p0;\n\t\t\t\tendpoint.col(1) = ln->p1;\n\t\t\t\tendpoint.col(2) = ln_nx->p0;\n\t\t\t\tendpoint.col(3) = ln_nx->p1;\n\t\t\t\tuint32_t axis = 0; // x-axis\n\t\t\t\tif(std::abs(ln->dir - 90) < 10)\n\t\t\t\t{\n\t\t\t\t\taxis = 1; // y-axis\n\t\t\t\t}\n\n\t\t\t\tuint8_t id_max =0, id_min = 1;\n\t\t\t\tfor(uint8_t i=0; i<4; i++)\n\t\t\t\t{\n\t\t\t\t\tif(endpoint(axis, i) > endpoint(axis, id_max))\n\t\t\t\t\t{\n\t\t\t\t\t\tid_max = i;\n\t\t\t\t\t}\n\t\t\t\t\telse if (endpoint(axis, i) < endpoint(axis, id_min))\n\t\t\t\t\t{\n\t\t\t\t\t\tid_min = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tln->p0 = endpoint.col(id_min);\n\t\t\t\tln->p1 = endpoint.col(id_max);\n\n\t\t\t\tln->points.conservativeResize(Eigen::NoChange,\n\t\t\t\t\t\t\t\t\t\t\t  ln->points.cols()+ln_nx->points.cols());\n\t\t\t\tln->points.topRightCorner(2,ln_nx->points.cols()) = ln_nx->points;\n\n\t\t\t\t// erase node\n\t\t\t\tln_nx++;\n\t\t\t\tls.erase(std::prev(ln_nx));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tln_nx++;\n\t\t\t}\n\t\t}\n\n\t\tif(flag)\n\t\t{\n\t\t\tln->dir = -1;\n\t\t\tln->coef.setZero();\n\t\t}\n\n\t\tln++;\n\t}\n\n\n\tif(ls.size() < size_)\n\t{\n\t\tstd::cerr << \"E: no enough line segments after merging\\n\"\n\t\t\t\t  << \"   get \" << ls.size() << \" lines\\n\";\n\t\treturn false;\n\t}\n\n\t// re-fit lines\n\tfor(auto&ln : ls)\n\t{\n\t\tif(ln.dir >=0 )\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::vector<cv::Point2d> pts;\n\t\tpts.reserve(ln.points.cols());\n\t\tfor(uint32_t i=0; i<ln.points.cols(); i++)\n\t\t{\n\t\t\tpts.emplace_back(ln.points(0,i), ln.points(1,i));\n\t\t}\n\n\t\tstd::vector<double> coef(4, 0);\n\t\tcv::fitLine(pts, coef, cv::DIST_L1,0, 0.01, 0.01);\n\n\t\tln.coef(0) = coef[1];\n\t\tln.coef(1) = -coef[0];\n\t\tln.coef(2) = -1*(ln.coef(0)*coef[2] + ln.coef(1)*coef[3]);\n\t\tln.coef = ln.coef/(ln.coef.head(2).norm());\n\t\tln.dir = std::atan2(coef[1], coef[0])/MATH_PI*180;\n\t\tif(ln.dir < 0)\n\t\t{\n\t\t\tln.dir += 180;\n\t\t}\n\t}\n\n\treturn true;\n}\n\n//@TODO only apply to rectangular board\nbool ImagePolygon::FilterLinesByRectangule(std::list<Line2D>& ls, Polygon2D::ConstPtr prev)\n{\n\tassert(ls.size()>=4 );\n\tif(ls.size() < size_)\n\t{\n\t\tstd::cerr << \"E: no enough lines for \" << __FUNCTION__\n\t\t\t\t  << \"\\n get \" << ls.size() << \"lines \\n\";\n\t\treturn false;\n\t}\n\n\tstruct RectangleEdges\n\t{\n\t\tdouble error;\n\t\tuint32_t id0;\n\t\tuint32_t id1;\n\n\t\tRectangleEdges(double error_, uint32_t id0_, uint32_t id1_):\n\t\t\terror(error_), id0(id0_), id1(id1_) {}\n\t};\n\n\tstd::list<RectangleEdges> width;\n\tstd::list<RectangleEdges> length;\n\n\tuint32_t id0 = 0;\n\tfor(auto l=ls.cbegin(); l!=ls.cend(); l++)\n\t{\n\t\tuint32_t id1 = id0+1;\n\t\tEigen::Vector3d ep2c = prev->center - (l->p0 + l->p1)/2;\n\t\tfor(auto next=std::next(l); next!=ls.cend(); next++)\n\t\t{\n\t\t\tdouble err_angle = LineAngleError(l->dir, next->dir);\n\t\t\tif( err_angle < 10)\n\t\t\t{\n\t\t\t\t// parallel line\n\t\t\t\tdouble dis = std::abs(next->coef.dot(l->p0));\n\t\t\t\tdis += std::abs(next->coef.dot(l->p1));\n\t\t\t\tdis += std::abs(l->coef.dot(next->p0));\n\t\t\t\tdis += std::abs(l->coef.dot(next->p1));\n\t\t\t\tdis = dis/4;\n\n\t\t\t\tEigen::Vector3d c2c = (next->p0+next->p1)/2 - (l->p0 + l->p1)/2 ;\n\t\t\t\tc2c.normalize();\n\t\t\t\tdouble err_c2c = c2c.cross(ep2c).norm();\n\n\t\t\t\tdouble angle_width = LineAngleError(angle_width_,\n\t\t\t\t\t\t\t\t\t\t\t\t\tLineAngleAverage(l->dir,next->dir));\n\t\t\t\tdouble angle_length = LineAngleError(angle_length_,\n\t\t\t\t\t\t\t\t\t\t\t\t\t LineAngleAverage(l->dir, next->dir));\n\t\t\t\tif(angle_width > angle_length)\n\t\t\t\t{\n\t\t\t\t\tdouble dis_rate = std::abs(dis - width_)/width_;\n\t\t\t\t\tif(dis_rate < 0.15)\n\t\t\t\t\t{\n\t\t\t\t\t\tlength.emplace_back(dis_rate*err_angle*err_c2c, id0, id1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tdouble dis_rate = std::abs(dis - length_)/length_;\n\t\t\t\t\tif(dis_rate < 0.15)\n\t\t\t\t\t{\n\t\t\t\t\t\twidth.emplace_back(dis_rate*err_angle*err_c2c, id0, id1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tid1++;\n\t\t}\n\t\tid0++;\n\t}\n\n\tif(width.size()<1 || length.size() <1)\n\t{\n\t\tstd::cerr << \"E: FilterLinesByRectangule width: \" << width.size()\n\t\t\t\t  << \" length: \" << length.size() << std::endl;\n\t\treturn false;\n\t}\n\n\tauto RectangleEdgesSort = [](const RectangleEdges& a, const RectangleEdges& b)\n\t{\n\t\treturn a.error < b.error;\n\t};\n\n\tif(width.size() > 1)\n\t{\n\t\twidth.sort(RectangleEdgesSort);\n\t}\n\tif(length.size() > 1)\n\t{\n\t\tlength.sort(RectangleEdgesSort);\n\t}\n\n\tstd::set<uint32_t> edges;\n\tedges.insert(width.front().id0);\n\tedges.insert(width.front().id1);\n\tedges.insert(length.front().id0);\n\tedges.insert(length.front().id1);\n\n\tid0 = 0;\n\tauto ln = ls.begin();\n\twhile(ln != ls.end())\n\t{\n\t\tln++;\n\t\tif(edges.count(id0) == 0)\n\t\t{\n\t\t\tls.erase(std::prev(ln));\n\t\t}\n\t\tid0++;\n\t}\n\treturn true;\n}\n\nbool ImagePolygon::SortLines(std::list<Line2D>& ls, Polygon2D::ConstPtr prev, Polygon2D::Ptr& ply )\n{\n\tif(ls.size() != size_)\n\t{\n\t\tstd::cerr << \"E: too many/fewer line segments to sort\\n\"\n\t\t\t\t  << \"   get \" << ls.size() << \" lines\\n\";\n\t\treturn false;\n\t}\n\n\tusing PairUD = std::pair<uint32_t,double>;\n\tEigen::Vector3d center;\n\n\tfor(const auto& it:ls)\n\t{\n\t\tcenter += it.p0;\n\t\tcenter += it.p1;\n\t}\n\tcenter = center / (ls.size()*2);\n\n\tfor(auto& it:ls)\n\t{\n\t\tEigen::Vector3d mid = (it.p0 + it.p1)/2;\n\t\tit.dir = std::atan2(mid(1)-center(1), mid(0)-center(0)) + MATH_PI;\n\t}\n\tls.sort([](Line2D& a, Line2D& b)\n\t{\n\t\treturn a.dir < b.dir;\n\t});\n\n\n\t// find all vertexs\n\tstd::vector<Eigen::Vector3d>vertexs(size_);\n\t{\n\t\tauto l = ls.cbegin();\n\t\tfor(auto& it:vertexs)\n\t\t{\n\t\t\tEigen::Matrix2d A;\n\t\t\tEigen::Vector2d B;\n\n\t\t\tA.row(0) = l->coef.head(2);\n\t\t\tB(0) = -1*l->coef(2);\n\t\t\tif(l != ls.cbegin())\n\t\t\t{\n\t\t\t\tauto pre = std::prev(l);\n\t\t\t\tA.row(1) = pre->coef.head(2);\n\t\t\t\tB(1) = -1*pre->coef(2);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tA.row(1) = ls.back().coef.head(2);\n\t\t\t\tB(1) = -1*ls.back().coef(2);\n\t\t\t}\n\n\t\t\tit.head(2) = A.inverse()*B;\n\t\t\tit(2) = 1;\n\n\t\t\tl++;\n\t\t}\n\t}\n\n\t// find offset, index correspondence\n\tuint32_t id_cors = 0;\n\t{\n\t\tdouble error = INT_MAX;\n\t\tauto& l0 = ls.front();\n\t\tdouble dir = std::atan2(-l0.coef(0), l0.coef(1))/MATH_PI*180;\n\t\tif(dir < 0)\n\t\t{\n\t\t\tdir += 180;\n\t\t}\n\t\tfor(uint32_t i=0; i<size_; i++)\n\t\t{\n\t\t\tdouble err = std::abs(prev->edges[i].dir - dir)*2;\n\t\t\terr += std::abs(l0.p0.dot(prev->edges[i].coef));\n\t\t\terr += std::abs(l0.p1.dot(prev->edges[i].coef));\n\t\t\tif(err < error)\n\t\t\t{\n\t\t\t\tid_cors = i;\n\t\t\t}\n\t\t}\n\t}\n\n\tply = std::make_shared<Polygon2D>(size_);\n\tuint32_t id = 0;\n\tfor(const auto& it: ls)\n\t{\n\t\tuint32_t pindex = (id+id_cors)%size_;\n\n\t\tply->edges[pindex].coef = it.coef;\n\t\tdouble dir = std::atan2(-it.coef(0), it.coef(1))/MATH_PI*180;\n\t\tif(dir < 0)\n\t\t{\n\t\t\tdir += 180;\n\t\t}\n\t\tply->edges[pindex].dir = dir;\n\t\tEigen::Vector3d p01 = vertexs[id] - vertexs[(id+1)%size_];\n\t\tply->edges[pindex].length = p01.head(2).norm();\n\t\tply->vertexs.col(pindex) = vertexs[id];\n\n\t\tid++;\n\t}\n\n\treturn true;\n}\n\n\nvoid ImagePolygon::UpdateParameters()\n{\n\tUpdateParameters(polygon_);\n}\n\nvoid ImagePolygon::UpdateParameters(Polygon2D::Ptr ply)\n{\n\t// update threshold\n//\tEigen::Vector3d center;\n//\tcenter.setZero();\n\n//    for(auto& it: ply->vertexs)\n//\t{\n//\t\tcenter += it;\n//\t}\n//    center = center/size_;\n\n\tEigen::Vector3d center = ply->vertexs.rowwise().mean();\n\n\tply->center = center;\n\n\n\tEigen::VectorXd center2point(size_);\n\tEigen::VectorXd center2line(size_);\n\tfor(uint32_t i=0; i<size_; i++)\n\t{\n\t\tcenter2point(i) = (center - ply->vertexs.col(i)).norm();\n\t\tcenter2line(i) = std::abs( center.dot(ply->edges[i].coef) );\n\t}\n\tfilter_point_center_max_ = center2point.maxCoeff()*(1+filter_point_center_factor_);\n\tfilter_line_center_min_ = center2line.minCoeff()*(1-filter_point_center_factor_);\n\n\n\t//@TODO\n\tdouble dis0=0, dis1=0;\n\tdis0 += std::abs(ply->edges[2].coef.dot(ply->vertexs.col(0) ));\n\tdis0 += std::abs(ply->edges[2].coef.dot(ply->vertexs.col(1) ));\n\tdis0 += std::abs(ply->edges[0].coef.dot(ply->vertexs.col(2) ));\n\tdis0 += std::abs(ply->edges[0].coef.dot(ply->vertexs.col(3) ));\n\tdis0 = dis0 / 4;\n\tdouble angle1 = LineAngleAverage(ply->edges[2].dir, ply->edges[0].dir);\n\n\n\tdis1 += std::abs(ply->edges[1].coef.dot(ply->vertexs.col(0) ));\n\tdis1 += std::abs(ply->edges[1].coef.dot(ply->vertexs.col(3) ));\n\tdis1 += std::abs(ply->edges[3].coef.dot(ply->vertexs.col(1) ));\n\tdis1 += std::abs(ply->edges[3].coef.dot(ply->vertexs.col(2) ));\n\tdis1 = dis1 / 4;\n\tdouble angle0 = LineAngleAverage(ply->edges[1].dir, ply->edges[3].dir);\n\n\tif(dis0 < dis1)\n\t{\n\t\twidth_ = dis0;\n\t\tlength_ = dis1;\n\t\tangle_width_ = angle0;\n\t\tangle_length_ = angle1;\n\t}\n\telse\n\t{\n\t\twidth_ = dis1;\n\t\tlength_ = dis0;\n\t\tangle_width_ = angle1;\n\t\tangle_length_ = angle0;\n\t}\n\n\n\tstd::cout << \"width: \" << width_ << \" length: \" << length_\n\t\t\t  << \"\\n angle_width: \" << angle_width_\n\t\t\t  << \" angle_length: \" << angle_length_ << \"\\n\";\n\n}\n\n\ndouble ImagePolygon::LineAngleError(double l0, double l1)\n{\n\tdouble e = std::abs(l0 - l1);\n\tif(e >90)\n\t{\n\t\te = 180 - e;\n\t}\n\treturn e;\n}\n\n\ndouble ImagePolygon::LineAngleAverage(double l0, double l1)\n{\n\tdouble e = (l0+l1)/2;\n\tif(std::abs(l0 - l1) > 90)\n\t{\n\t\te = (l0+l1-180)/2;\n\t}\n\treturn e;\n}\n\nvoid ImagePolygon::MarkImage(cv::Mat &img, const std::list<Line2D> &ls)\n{\n\tutils::color::rgbs colors = utils::color::get_rgbs(ls.size());\n\tauto lines_it = ls.cbegin();\n\n\tfor (std::size_t i = 0; i < ls.size(); i++)\n\t{\n\t\tauto& it = *lines_it;\n\t\tcv::Scalar color(colors[i][0], colors[i][1], colors[i][2]);\n\t\tcv::Point2d p0(it.p0(0), it.p0(1));\n\t\tcv::Point2d p1(it.p1(0), it.p1(1));\n\n\t\tcv::line(img, p0, p1, color, 2 );\n\t\tcv::circle(img, p0, 5, color);\n\t\tcv::circle(img, p1, 4, color);\n\t\tcv::putText(img, std::to_string(i),(p0+p1)/2,\n\t\t\t\t\tcv::FONT_HERSHEY_SIMPLEX, 2, color, 2 );\n\t\tlines_it++;\n\t}\n\n\tif(polygon_ != nullptr)\n\t{\n\t\tconst auto& c = polygon_->center;\n\t\tcv::circle(img, cv::Point2d(c(0), c(1)), filter_line_center_min_,\n\t\t\t\t   cv::Scalar(0,0,255), 2);\n\t\tcv::circle(img, cv::Point2d(c(0), c(1)), filter_point_center_max_,\n\t\t\t\t   cv::Scalar(0,255,0), 2);\n\t}\n}\n\nvoid ImagePolygon::MarkImage(cv::Mat& img, Polygon2D::ConstPtr ply)\n{\n\tutils::color::rgbs colors = utils::color::get_rgbs( size_ );\n\tfor (uint32_t i = 0; i < size_; i++)\n\t{\n\t\tuint32_t next = (i== size_-1)?0:i+1;\n\t\tauto& it = ply->vertexs;\n\t\tauto& ln = ply->edges[i];\n\n\t\tcv::Scalar color(colors[i][2], colors[i][1], colors[i][0]);\n\t\tcv::Point2d p0( it(0,i), it(1,i) );\n\t\tcv::Point2d p1( it(0,next), it(1, next) );\n\t\t// draw id\n\t\tcv::putText(img, std::to_string(i),(p0+p1)/2,\n\t\t\t\t\tcv::FONT_HERSHEY_SIMPLEX, 2, color, 2 );\n\t\t// draw vertex\n\t\tif(i == 0)\n\t\t{\n\t\t\tcv::circle(img, p0, 8, color, 3);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcv::circle(img, p0, 5, color);\n\t\t}\n\n\t\t// draw line\n\t\tif( std::abs(ln.dir - 90 ) < 45)\n\t\t{\n\t\t\tp0.y = 0;\n\t\t\tp0.x = -1*ln.coef(2)/ln.coef(0);\n\t\t\tp1.y = img.rows;\n\t\t\tp1.x = -1*(ln.coef(2) + ln.coef(1)*p1.y)/ln.coef(0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tp0.x = 0;\n\t\t\tp0.y = -1*ln.coef(2)/ln.coef(1);\n\t\t\tp1.x = img.cols;\n\t\t\tp1.y = -1*(ln.coef(2) + ln.coef(0)*p1.x)/ln.coef(1);\n\t\t}\n\t\tcv::line(img, p0, p1, color, 1 );\n\t}\n}\n\n\nbool ImagePolygon::SaveMarkedImage(const std::string& fn,\n\t\t\t\t\t\t\t\t   const cv::Mat& img, const std::list<Line2D>&ls)\n{\n\tcv::Mat img_line;\n\n\tif(img.channels() == 1)\n\t{\n#if (CV_VERSION_MAJOR >= 4)\n\t\tcv::cvtColor(img, img_line, cv::COLOR_GRAY2BGR);\n#else\n\t\tcv::cvtColor(img, img_line, CV_GRAY2BGR);\n#endif\n\t}\n\telse\n\t{\n\t\timg_line = img.clone();\n\t}\n\n\tMarkImage(img_line, ls);\n\n\treturn cv::imwrite(fn, img_line);\n}\n\n\nbool ImagePolygon::SaveMarkedImage(const std::string& fn, const cv::Mat& img,\n\t\t\t\t\t\t\t\t   Polygon2D::ConstPtr ply)\n{\n\tcv::Mat img_line;\n\n\tif(img.channels() == 1)\n\t{\n#if (CV_VERSION_MAJOR >= 4)\n\t\tcv::cvtColor(img, img_line, cv::COLOR_GRAY2BGR);\n#else\n\t\tcv::cvtColor(img, img_line, CV_GRAY2BGR);\n#endif\n\n\t}\n\telse\n\t{\n\t\timg_line = img.clone();\n\t}\n\n\tMarkImage(img_line, ply);\n\n\treturn cv::imwrite(fn, img_line);\n\n}\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "PlyCal/image_polygon.h",
    "content": "/**\n  ******************************************************************************\n  * @file\timage_polygon.h\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-22\n  * @brief\timage_polygon.h\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Define to prevent recursive inclusion -------------------------------------*/\n#ifndef __IMAGE_POLYGON_H\n#define __IMAGE_POLYGON_H\n\n/* Includes ------------------------------------------------------------------*/\n\n#include <string>\n#include <vector>\n#include <memory>\n#include <stdint.h>\n\n#include <Eigen/Dense>\n\n#include \"json/json.hpp\"\n#include \"edlines/EDLineDetector.h\"\n\n/* Exported macro ------------------------------------------------------------*/\n/* Exported types ------------------------------------------------------------*/\n\nnamespace lqh\n{\nclass ImagePolygon\n{\npublic:\n\n\tusing LineFeature = Eigen::Matrix<uint8_t,3,Eigen::Dynamic>;\n\tstruct Edge2D\n\t{\n\t\tdouble dir;\n\t\tdouble length;\n\t\tEigen::Vector3d coef;\n\t\tLineFeature feature;\n\t};\n\n\tstruct Polygon2D\n\t{\n\t\tusing ConstPtr = std::shared_ptr<const Polygon2D>;\n\t\tusing Ptr = std::shared_ptr<Polygon2D>;\n\n        Eigen::Vector3d center;\n        Eigen::Matrix3Xd vertexs;\n\t\tstd::vector<Edge2D> edges;\n\n\t\tPolygon2D(uint32_t size)\n\t\t{\n\t\t\tcenter.setZero();\n            vertexs.resize(3, size);\n\t\t\tedges.resize(size);\n\t\t}\n\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\t};\n\n\texplicit ImagePolygon(const nlohmann::json& js, uint8_t size);\n    Polygon2D::ConstPtr Add(const cv::Mat& img, cv::Mat& img_out);\n    Polygon2D::ConstPtr Init(const cv::Mat& img, cv::Mat& img_out, const Eigen::Matrix3Xd& pts);\n    bool SaveMarkedImage(const std::string& fn, const cv::Mat& img,\n\t\t\t\t\t\t\t\tPolygon2D::ConstPtr pyg);\nprivate:\n\tstruct Line2D\n\t{\n\t\tdouble dir;\n\t\tEigen::Vector3d p0, p1;\n\t\tEigen::Vector3d coef;\n\t\tEigen::Matrix2Xi points;\n\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\t};\n\n\tconst uint32_t size_;\t// current implemention only support size_=4\n\tuint32_t feature_size_;\n\tuint32_t feature_offset_;\n\tdouble feature_threshold_;\n\n\tdouble merge_distance_threshold_;\n\tdouble merge_angle_threshold_;\n\tdouble merge_endpoint_distance_threshold_;\n\n\tdouble filter_point_line_threshold_;\n\tdouble filter_line_angle_threshold_;\n\tdouble filter_point_center_factor_;\n\tdouble filter_point_center_max_;\n\tdouble filter_line_center_min_;\n\n\t//@TODO only apply for rectangular board, size_ == 4\n\tdouble width_;\n\tdouble length_;\n\tdouble angle_width_;\n\tdouble angle_length_;\n\n\tstd::unique_ptr<EDLineDetector> detector_;\t// line detector\n\t// edge descripter\n\tPolygon2D::Ptr polygon_;\t// last polygon\n\n    Polygon2D::ConstPtr ExtractPolygon(const cv::Mat& img, cv::Mat& img_out,\n                                       Polygon2D::ConstPtr prev);\n    Polygon2D::Ptr InitPolygon(const Eigen::Matrix3Xd& pts);\n\tbool ExtractLines(const cv::Mat& img, std::list<Line2D>& ls);\n\tbool FilterLines(std::list<Line2D>& ls, Polygon2D::ConstPtr prev);\n\tbool MergeLines(std::list<Line2D>& ls);\n\tbool FilterLinesByRectangule(std::list<Line2D>& ls, Polygon2D::ConstPtr prev);\n    bool SortLines(std::list<Line2D>& ls, Polygon2D::ConstPtr prev, Polygon2D::Ptr& ply);\n\n    void UpdateParameters();\n    void UpdateParameters(Polygon2D::Ptr ply);\n\n\tdouble LineAngleError(double l0, double l1);\n\tdouble LineAngleAverage(double l0, double l1);\n\n    void MarkImage(cv::Mat& img_out, const std::list<Line2D>&ls);\n    void MarkImage(cv::Mat& img_out, Polygon2D::ConstPtr ply);\n\tbool SaveMarkedImage(const std::string& fn, const cv::Mat& img,\n\t\t\t\t\t\t const std::list<Line2D>&ls);\n};\n\n}\n\n/* Exported constants --------------------------------------------------------*/\n/* Exported functions --------------------------------------------------------*/\n\n#endif /* !__IMAGE_POLYGON_H */\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "PlyCal/pointcloud_polygon.cpp",
    "content": "/**\n  ******************************************************************************\n  * @file\tpointcloud_polygon.cpp\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-26\n  * @brief\tpointcloud_polygon.cpp\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Includes ------------------------------------------------------------------*/\n#include \"pointcloud_polygon.h\"\n\n#include <cmath>\n#include <map>\n#include <functional>\n\n#include <pcl/common/io.h>\n#include <pcl/common/common.h>\n#include <pcl/io/pcd_io.h>\n#include <pcl/sample_consensus/sac_model_plane.h>\n#include <pcl/sample_consensus/sac_model_line.h>\n#include <pcl/sample_consensus/model_types.h>\n#include <pcl/segmentation/sac_segmentation.h>\n\nusing namespace lqh;\n\n/* Private typedef -----------------------------------------------------------*/\n/* Private define ------------------------------------------------------------*/\n/* Private macro -------------------------------------------------------------*/\n//#define NODEBUG\n\n/* Private variables ---------------------------------------------------------*/\n/* Private function prototypes -----------------------------------------------*/\n/* Private functions ---------------------------------------------------------*/\n\n/* Exported functions --------------------------------------------------------*/\n\n/**\n  * @brief\n  * @param\n  * @note\n  * @return None\n  */\nPointcloudPolygon::PointcloudPolygon(const nlohmann::json& js, uint8_t size):\n\tsize_(size), polygon_(nullptr)\n{\n\tpc_angle_resolution_ = js[\"angle_resolution\"].get<double>();\n\tfilter_angle_start_ = js[\"filter\"][\"angle_start\"].get<double>();\n\tfilter_angle_size_ \t= js[\"filter\"][\"angle_size\"].get<double>();\n\tfilter_distance_  \t= js[\"filter\"][\"distance\"].get<double>();\n\tfilter_floor_gap_ \t= js[\"filter\"][\"floor_gap\"].get<double>();\n\tplane_point_num_min_ \t\t= js[\"plane\"][\"point_num_min\"].get<uint32_t>();\n\tplane_distance_threshold_ \t= js[\"plane\"][\"distance_threshold\"].get<double>();\n\tring_point_num_min_ = js[\"ring\"][\"point_num_min\"].get<uint32_t>();\n\tring_endpoint_num_  = js[\"ring\"][\"endpoint_num\"].get<uint32_t>();\n\tif(ring_endpoint_num_ > ring_point_num_min_)\n\t{\n\t\tstd::cout << \"W: ring:endpoint_num_min must <= ring:point_num_min\\n\"\n\t\t\t\t  << \"   set ring:endpoint_num = ring:point_num_min\\n\";\n\t\tring_endpoint_num_ = ring_point_num_min_;\n\t}\n\tedge_point_num_min_ = js[\"edge\"][\"point_num_min\"].get<uint32_t>();\n\tedge_distance_threshold_ = js[\"edge\"][\"distance_threshold\"].get<double>();\n}\n\n\nPointcloudPolygon::Polygon3D::ConstPtr PointcloudPolygon::Add(\n\tconst pcl::PointCloud<pcl::PointXYZI>& pc,\n\tpcl::PointCloud<pcl::PointXYZRGB>& pcc)\n{\n\tPolygon3D::Ptr ply = std::make_shared<Polygon3D>(size_);\n\tstd::vector<int> indices;\n\tif(pcc.size() != pc.size())\n\t{\n\t\tpcl::copyPointCloud(pc, pcc);\n\t}\n\tfor(auto& p : pcc.points)\n\t{\n\t\tp.rgba = 0xffffffff;\n\t}\n\n\n\tlqh::utils::color::rgbs colors = lqh::utils::color::get_rgbs(5);\n\n\tply->coef.setZero();\n\n\tSectorFilter(pc, indices);\n\tMarkPointcloud(pcc, colors[0], indices);\n\tif(indices.size() < plane_point_num_min_)\n\t{\n\t\treturn nullptr;\n\t}\n\n//\tSaveMarkedPointcloud(\"SectorFilter.pcd\", pc, indices);\n\n\tbool res = ExtractPlane(pc, indices, ply->coef);\n\tif(!res)\n\t{\n\t\treturn nullptr;\n\t}\n\tMarkPointcloud(pcc, colors[1], indices);\n//\tSaveMarkedPointcloud(\"ExtractPlane.pcd\", pc, indices);\n\tIndices edge_left, edge_right, inliers;\n\tExtractRings(pc, indices, inliers, edge_left, edge_right);\n\n\tMarkPointcloud(pcc, colors[2], inliers);\n\tMarkPointcloud(pcc, colors[3], edge_left);\n\tMarkPointcloud(pcc, colors[4], edge_right);\n\n//\tSaveMarkedPointcloud(\"inlier.pcd\", pc, inliers);\n//\tSaveMarkedPointcloud(\"edge_left.pcd\", pc, edge_left);\n//\tSaveMarkedPointcloud(\"edge_right.pcd\", pc, edge_right);\n\n\t// vertexs, line coefficient is not valid\n\tply->inliers.resize(3, inliers.size());\n\tfor(uint32_t i=0; i<inliers.size(); i++)\n\t{\n\t\tauto& p = pc.points[inliers[i]];\n\t\tply->inliers.col(i) << p.x, p.y, p.z;\n\t}\n\n\t//ExtractEdges(pc, edge_left, ply->edges[0], ply->edges[1]);\n\t//ExtractEdges(pc, edge_right, ply->edges[3], ply->edges[2]);\n\tExtractEdgesMems(pc, edge_left, ply->edges[0], ply->edges[1], true);\n\tExtractEdgesMems(pc, edge_right, ply->edges[3], ply->edges[2], false);\n\n\tpolygon_ = ply;\n//\tSaveMarkedPointcloud(\"Add.pcd\",pc, ply);\n\n\treturn ply;\n}\n\nvoid PointcloudPolygon::SetFilterParameters(const Eigen::Vector4d& p)\n{\n    if(p(0) >=0 && p(0) <=360)\n    {\n        filter_angle_start_ = p(0);\n    }\n    if(p(1) >0 && p(1) < 360)\n    {\n        filter_angle_size_  = p(1);\n    }\n    if(p(2) > 0)\n    {\n        filter_distance_    = p(2);\n    }\n    if(p(3) > -10)\n    {\n        filter_floor_gap_   = p(3);\n    }\n}\n\nvoid PointcloudPolygon::SectorFilter(const PCI& pc, Indices& indices)\n{\n\tindices.clear();\n\tindices.reserve(plane_point_num_min_*10);\n\n\tEigen::Vector4f min_pt, max_pt;\n\tpcl::getMinMax3D(pc, min_pt, max_pt);\n\n\tdouble z_threshold = min_pt(2)+ filter_floor_gap_;\n\n\tfor(uint32_t i=0; i<pc.points.size(); i++)\n\t{\n\t\tauto& p = pc.points[i];\n\t\tdouble theta = std::atan2(p.y, p.x)/MATH_PI*180;\n\t\tif(theta<0)\n\t\t{\n\t\t\ttheta += 360;\n\t\t}\n\t\tdouble dis = std::sqrt(p.y*p.y + p.x*p.x);\n\t\tdouble size = theta - filter_angle_start_;\n\t\tif(size < 0)\n\t\t{\n\t\t\tsize += 360;\n\t\t}\n\n\t\tif(p.z > z_threshold && dis < filter_distance_\n\t\t\t\t&& size < filter_angle_size_)\n\t\t{\n\t\t\tindices.push_back(i);\n\t\t}\n\t}\n}\n\nbool PointcloudPolygon::ExtractPlane(const PCI& pc, Indices& indices,\n\t\t\t\t\t\t\t\t\t Eigen::Vector4d& coef)\n{\n\tPCI::Ptr pc_ptr (new PCI);\n\tpcl::copyPointCloud(pc, *pc_ptr);\n\n\tpcl::IndicesPtr indices_ptr(new std::vector<int>);\n\tindices_ptr->resize(indices.size());\n\tstd::copy(indices.begin(), indices.end(), indices_ptr->begin());\n\n\tpcl::ModelCoefficients model_coef;\n\tpcl::PointIndices ids;\n\tpcl::SACSegmentation<pcl::PointXYZI> seg;\n\tseg.setOptimizeCoefficients (true);\n\tseg.setModelType (pcl::SACMODEL_PLANE);\n\tseg.setMethodType (pcl::SAC_RANSAC);\n\tseg.setDistanceThreshold (plane_distance_threshold_);\n\tseg.setInputCloud(pc_ptr);\n\tseg.setIndices(indices_ptr);\n\tseg.segment(ids, model_coef);\n\n\tif(ids.indices.size() > plane_point_num_min_ )\n\t{\n\t\tcoef << model_coef.values[0], model_coef.values[1],\n\t\t\t model_coef.values[2], model_coef.values[3];\n\t\tstd::swap(ids.indices, indices);\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\tstd::cerr << \"E: Fail to extract plane\" << std::endl;\n\t\treturn false;\n\t}\n}\n\nbool PointcloudPolygon::ExtractRings(const PCI& pc, const Indices& indices,\n\t\t\t\t\t\t\t\t\t Indices& inlier, Indices& left, Indices& right)\n{\n\tstruct Point\n\t{\n\t\tint8_t pitch;\n\t\tuint32_t id;\n\t\tdouble yaw;\n\n\t\tPoint(uint32_t pid, int8_t ppitch, double pyaw):\n\t\t\tpitch(ppitch),id(pid),yaw(pyaw) {}\n\t};\n\n\tif(indices.size() < plane_point_num_min_)\n\t{\n\t\tstd::cerr << \"E: no enough points to extract edge/inlier\\n\";\n\t\treturn false;\n\t}\n\n\n\tstd::map<int16_t, std::vector<Point>> pts;\n\tfor(auto it:indices)\n\t{\n\t\tauto& p = pc.points[it];\n\t\tdouble yaw = std::atan2(p.y, p.x);\n\t\tdouble pitch_d = std::atan(p.z/std::sqrt(p.y*p.y+p.x*p.x))/MATH_PI*180;\n\t\tint16_t pitch = std::round(pitch_d/pc_angle_resolution_);\n\n\t\tpts[pitch].emplace_back(it, pitch, yaw);\n\t}\n\n\tleft.reserve( pts.size()*ring_endpoint_num_ );\n\tright.reserve( pts.size()*ring_endpoint_num_ );\n\tinlier.reserve(indices.size() - pts.size()*ring_endpoint_num_*2);\n\n\tfor(auto& r: pts )\n\t{\n\t\tauto& ring = r.second;\n\n\n\t\t// every ring must have certain points\n\t\tif(ring.size() < ring_point_num_min_)\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\tstd::sort(ring.begin(), ring.end(),\n\t\t\t\t  [](const Point& a, const Point& b)\n\t\t{\n\t\t\treturn a.yaw < b.yaw;\n\t\t});\n\n\t\t// clean every ring with 3 sigma principle\n        // sample the center 1/3\n\t\tdouble mean = 0;\n\t\tdouble sigma = 0;\n        uint32_t num = ring.size()-1;\n        uint32_t num_3 = num/3;\n        std::vector<double> yaw_err(num);\n        for(uint32_t i=0; i<num; i++)\n\t\t{\n\t\t\tdouble tmp = ring[i+1].yaw - ring[i].yaw;\n            yaw_err[i]=tmp;\n            if(i >= num_3 && i<num_3*2)\n            {\n                mean += tmp;\n                sigma += tmp*tmp;\n            }\n\t\t}\n        mean = mean/(num_3);\n        sigma = std::sqrt((sigma- mean*mean)/num_3);\n\t\t// from center to both end \t\n\t\t// we don't check center point, we think it's valid\n        uint32_t center = num/2;\n        for(uint32_t i=center+1; i<num; i++)\n\t\t{\n\t\t\tif(std::abs(yaw_err[i]-mean) > 3*sigma)\n\t\t\t{\n\t\t\t\tring.erase(ring.begin()+i+1, ring.end());\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tfor(int32_t i=center-1; i>=0; i--)\n\t\t{\n\t\t\tif(std::abs(yaw_err[i]-mean) > 3*sigma)\n\t\t\t{\n                ring.erase(ring.begin(), ring.begin()+i+1);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\t// save endpoints: edges\n\n\t\tfor(uint32_t i=0; i<ring_endpoint_num_; i++)\n\t\t{\n\t\t\tuint32_t id_right = ring.size()-1-i;\n\t\t\tright.push_back(ring[i].id);\n\t\t\tleft.push_back(ring[id_right].id);\n\t\t}\n\t\t// save inside points: inlier\n\t\tif( ring.size() > 2*ring_endpoint_num_ )\n\t\t{\n\t\t\tfor(uint32_t i=ring_endpoint_num_;\n\t\t\t\t\ti<ring.size()-ring_endpoint_num_; i++)\n\t\t\t{\n\t\t\t\tinlier.push_back(ring[i].id);\n\t\t\t}\n\t\t}\n\t}\n\treturn true;\n}\n\nbool PointcloudPolygon::ExtractEdges(const PCI& pc, Indices& indices,\n\t\t\t\t\t\t\t\t\t Edge3D& edge0, Edge3D& edge1)\n{\n\tIndices ids;\n\tEigen::Vector3d coef, pt;\n\n\tFitLine(pc, indices, ids, coef, pt);\n\tstd::sort(ids.begin(), ids.end(), [&pc](const int a, const int b)\n\t{\n\t\treturn pc.points[a].z < pc.points[b].z;\n\t});\n\n\tauto AssembleEdge = [&pc](const Indices& indices, Edge3D& edge)\n\t{\n\t\tedge.points.resize(3, indices.size());\n\t\tfor(uint32_t i=0; i<indices.size(); i++)\n\t\t{\n\t\t\tauto& p = pc.points[indices[i]];\n\t\t\tedge.points.col(i) << p.x, p.y, p.z;\n\t\t}\n\t};\n\n\tauto Yaw = [](const pcl::PointXYZI& p)->double\n\t{\n\t\treturn std::atan2(p.y, p.x);\n\t};\n\n\t// only one line\n\tif(ids.size() == indices.size())\n\t{\n\t\tdouble yaw_b = Yaw(pc.points[ids.front()]);\n\t\tdouble yaw_t = Yaw(pc.points[ids.back()]);\n\t\tdouble yaw_bt = yaw_t-yaw_b;\n\t\tif(std::abs(yaw_bt) > MATH_PI)\n\t\t{\n\t\t\tyaw_bt = yaw_bt >MATH_PI ? 2*MATH_PI - yaw_bt : 2*MATH_PI+yaw_bt;\n\t\t}\n\n\t\tif(yaw_bt > 0)\n\t\t{\n\t\t\tedge0.coef = coef;\t\t\t// the line is first line\n\t\t\tedge0.p0 = pt;\n\t\t\tAssembleEdge(ids, edge0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tedge1.coef = coef;\n\t\t\tedge1.coef = pt;\n\t\t\tAssembleEdge(ids, edge1);\n\t\t}\n\t}\n\telse\n\t{\n\t\t// two lines\n\t\t// ids_another = indices - ids\n\t\tstd::vector<int> ids_another;\n\t\tstd::set_difference(\n\t\t\tindices.begin(), indices.end(),\n\t\t\tids.begin(), ids.end(),\n\t\t\tstd::back_inserter( ids_another )\n\t\t);\n\n\t\tdouble err_dis = 0;\n\t\tfor(uint32_t i=0; i<ring_endpoint_num_; i++)\n\t\t{\n\t\t\tauto& it = pc.points[indices[i]];\n\t\t\tEigen::Vector3d pt_i(it.x, it.y, it.z);\n\n\t\t\terr_dis += coef.cross(pt_i - pt).norm();\n\t\t}\n\t\terr_dis = err_dis/ring_endpoint_num_;\n\n\t\tif(err_dis > edge_distance_threshold_)\n\t\t{\n\t\t\t// fitline is the second line\n\t\t\tedge1.coef = coef;\n\t\t\tAssembleEdge(ids, edge1);\n\t\t\tAssembleEdge(ids_another, edge0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tedge0.coef = coef;\n\t\t\tAssembleEdge(ids, edge0);\n\t\t\tAssembleEdge(ids_another, edge1);\n\t\t}\n\t}\n\treturn true;\n}\n\nbool PointcloudPolygon::ExtractEdgesMems(const PCI& pc, Indices& indices,\n\t\tEdge3D& edge0, Edge3D& edge1, bool is_left)\n{\n\tIndices first, second;\n\tfirst.reserve(indices.size()/2);\n\n\t// left  find y-max,  right find y-min\n\tdouble y_m = pc.points[indices[0]].y;\n\tuint32_t id_sep = 0;\n\tif(is_left)\n\t{\n\t\tuint32_t i = 0;\n\t\tfor(auto id : indices)\n\t\t{\n\t\t\tif(pc.points[id].y >= y_m)\n\t\t\t{\n\t\t\t\ty_m = pc.points[id].y;\n\t\t\t\tid_sep = i;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n        if (id_sep == 0)\n        {\n            id_sep = indices.size()-1;\n        }\n\t}\n\telse\n\t{\n\t\tuint32_t i = 0;\n\t\tfor(auto id : indices)\n\t\t{\n\t\t\tif(pc.points[id].y < y_m)\n\t\t\t{\n\t\t\t\ty_m = pc.points[id].y;\n\t\t\t\tid_sep = i;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n        if(id_sep == indices.size()-1)\n        {\n            id_sep = 0;\n        }\n\t}\n\n\tfor(uint32_t i=0; i<=id_sep; i++)\n\t{\n\t\tfirst.push_back(indices[i]);\n\t}\n\tfor(uint32_t i=id_sep; i<indices.size(); i++)\n\t{\n\t\tsecond.push_back(indices[i]);\n\t}\n\n\n\tauto makeEdge = [&pc, this](Indices& indice, Edge3D& edge)\n\t{\n\t\tif(indice.size() > 3)\n\t\t{\n\t\t\tIndices inlier;\n\t\t\tFitLine(pc, indice, inlier, edge.coef, edge.p0);\n\t\t\tedge.points.resize(3, inlier.size());\n\t\t\tuint32_t i=0;\n\t\t\tfor(auto it: inlier)\n\t\t\t{\n\t\t\t\tedge.points(0,i)= pc.points[it].x;\n\t\t\t\tedge.points(1,i)= pc.points[it].y;\n\t\t\t\tedge.points(2,i)= pc.points[it].z;\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t};\n\n\tmakeEdge(first, edge0);\n\tmakeEdge(second, edge1);\n\n\treturn true;\n};\n\n\nvoid PointcloudPolygon::FitLine(const PCI& pc, const Indices& indices,\n\t\t\t\t\t\t\t\tIndices& inlier, Eigen::Vector3d& coef, Eigen::Vector3d& pt)\n{\n\tPCI::Ptr pc_ptr(new PCI);\n\tpc_ptr->points.reserve(indices.size());\n\n\tfor(auto it:indices)\n\t{\n\t\tpc_ptr->points.push_back( pc.points[it] );\n\t}\n\n\tpcl::ModelCoefficients model_coef;\n\tpcl::PointIndices ids;\n\n\tpcl::SACSegmentation<pcl::PointXYZI> seg;\n\tseg.setOptimizeCoefficients (true);\n\tseg.setModelType (pcl::SACMODEL_LINE);\n\tseg.setMethodType (pcl::SAC_RANSAC);\n\tseg.setDistanceThreshold (edge_distance_threshold_);\n\tseg.setInputCloud(pc_ptr);\n\tseg.segment(ids, model_coef);\n\n\tpt(0) \t= model_coef.values[0];\n\tpt(1) \t= model_coef.values[1];\n\tpt(2) \t= model_coef.values[2];\n\tcoef(0) = model_coef.values[3];\n\tcoef(1) = model_coef.values[4];\n\tcoef(2) = model_coef.values[5];\n\tcoef.normalize();\n\n\tinlier.reserve(ids.indices.size());\n\tfor(auto it:ids.indices)\n\t{\n\t\tinlier.push_back(indices[it]);\n\t}\n}\n\nbool PointcloudPolygon::SaveMarkedPointcloud(const std::string& fn, const PCI& pc,\n\t\tconst Indices& indices) const\n{\n\tpcl::PointCloud<pcl::PointXYZRGB> pcc;\n\tpcl::copyPointCloud(pc, pcc);\n\n\tfor(auto& it:pcc.points)\n\t{\n\t\tit.rgba = 0xffffffff;\n\t}\n\n\tfor(auto it: indices)\n\t{\n\t\tpcc.points[it].rgba = 0xffff0000;\n\t}\n\n\treturn pcl::io::savePCDFileBinary(fn, pcc);\n}\n\nbool PointcloudPolygon::SaveMarkedPointcloud(const std::string& fn,\n\t\tconst pcl::PointCloud<pcl::PointXYZI>& pc,\n\t\tPolygon3D::ConstPtr ply) const\n{\n\tpcl::PointCloud<pcl::PointXYZRGB> pcc;\n\tpcc.points.reserve(ply->inliers.cols() + ply->edges[0].points.cols()*\n\t\t\t\t\t   ply->edges.size());\n\n\tlqh::utils::color::rgbs colors = lqh::utils::color::get_rgbs(size_+1);\n\tpcl::PointXYZRGB p;\n\n\tfor(uint32_t i=0; i<size_; i++)\n\t{\n\t\tp.r = colors[i][0];\n\t\tp.g = colors[i][1];\n\t\tp.b = colors[i][2];\n\n\t\tauto& ps = ply->edges[i].points;\n\t\tfor(uint32_t j=0; j<ps.cols(); j++)\n\t\t{\n\t\t\tp.x = ps(0,j);\n\t\t\tp.y = ps(1,j);\n\t\t\tp.z = ps(2,j);\n\t\t\tpcc.push_back(p);\n\t\t}\n\t}\n\n\tp.r = colors.back()[0];\n\tp.g = colors.back()[1];\n\tp.b = colors.back()[2];\n\tfor(uint32_t i=0; i<ply->inliers.cols(); i++)\n\t{\n\t\tp.x = ply->inliers(0,i);\n\t\tp.y = ply->inliers(1,i);\n\t\tp.z = ply->inliers(2,i);\n\t\tpcc.push_back(p);\n\t}\n\n\treturn pcl::io::savePCDFileBinary(fn, pcc);\n}\n\nbool PointcloudPolygon::SaveEdgePoints(const std::string& fn_prefix)\n{\n\tEigen::IOFormat fmt(Eigen::FullPrecision, 0, \", \", \"\\n\", \"\", \"\", \"\", \"\");\n\tfor(uint8_t i=0; i<polygon_->edges.size(); i++)\n\t{\n\t\tstd::ofstream f(fn_prefix+std::to_string(i)+\".csv\");\n\n\t\tif( !f.good() )\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tf << polygon_->edges[i].points.transpose().format(fmt);\n\t\tf.close();\n\t}\n\n\treturn true;\n}\n\n\nvoid PointcloudPolygon::MarkPointcloud(pcl::PointCloud<pcl::PointXYZRGB>& pcc,\n\t\t\t\t\t\t\t\t\t   const lqh::utils::color::rgb& color,\n\t\t\t\t\t\t\t\t\t   const Indices& indices) const\n{\n\tfor(auto it : indices)\n\t{\n\t\tauto& p = pcc.points[it];\n\t\tp.r = color[0];\n\t\tp.g = color[1];\n\t\tp.b = color[2];\n\t}\n}\n\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "PlyCal/pointcloud_polygon.h",
    "content": "/**\n  ******************************************************************************\n  * @file\tpointcloud_polygon.h\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-26\n  * @brief\tpointcloud_polygon.h\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Define to prevent recursive inclusion -------------------------------------*/\n#ifndef __POINTCLOUD_POLYGON_H\n#define __POINTCLOUD_POLYGON_H\n\n/* Includes ------------------------------------------------------------------*/\n#include <string>\n\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n\n#include <Eigen/Dense>\n\n#include \"utils.h\"\n#include \"json/json.hpp\"\n\n/* Exported macro ------------------------------------------------------------*/\n/* Exported types ------------------------------------------------------------*/\nnamespace lqh\n{\nclass PointcloudPolygon\n{\npublic:\n\tstruct Edge3D\n\t{\n\t\t// @TODO\n\t\tEigen::Vector3d  p0;\t// maybe invalid\n\t\tEigen::Vector3d  coef; \t// maybe invalid\n\t\tEigen::Matrix3Xd points;\n\n\t\tEdge3D():p0(0,0,0),coef(0,0,0) {}\n\t};\n\tstruct Polygon3D\n\t{\n\t\tusing ConstPtr = std::shared_ptr<const Polygon3D>;\n\t\tusing Ptr = std::shared_ptr<Polygon3D>;\n\n\t\tEigen::Vector4d \tcoef;\n\t\tEigen::Matrix3Xd \tinliers;\n\t\tstd::vector<Eigen::Vector3d> vertexs;\t// maybe invalid\n\t\tstd::vector<Edge3D> edges;\n\n\t\tPolygon3D(uint32_t size)\n\t\t{\n\t\t\tvertexs.resize(size, Eigen::Vector3d::Zero());\n\t\t\tedges.resize(size);\n\t\t}\n\n\t\tEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\t};\n\n\texplicit PointcloudPolygon(const nlohmann::json& js, uint8_t size);\n    Polygon3D::ConstPtr Add(const pcl::PointCloud<pcl::PointXYZI>& pc,\n                            pcl::PointCloud<pcl::PointXYZRGB>& pcc);\n    void SetFilterParameters(const Eigen::Vector4d& p);\n    Eigen::Vector4d GetFilterParameters()\n    {\n        return Eigen::Vector4d(filter_angle_start_, filter_angle_size_,\n                               filter_distance_, filter_floor_gap_);\n    }\n\tbool SaveMarkedPointcloud(const std::string& fn,\n\t\t\t\t\t\t\t  const pcl::PointCloud<pcl::PointXYZI>& pc,\n\t\t\t\t\t\t\t  Polygon3D::ConstPtr ply) const;\n\tbool SaveEdgePoints(const std::string& fn_prefix);\nprivate:\n\tusing PCI = pcl::PointCloud<pcl::PointXYZI>;\n\tusing Indices = std::vector<int>;\n\n\tconst uint8_t \tsize_;\n\tdouble \t\tpc_angle_resolution_;\n\tdouble \t\tfilter_angle_start_;\n\tdouble \t\tfilter_angle_size_;\n\tdouble \t\tfilter_distance_;\n\tdouble \t\tfilter_floor_gap_;\n\tuint32_t \tplane_point_num_min_;\n\tdouble \t\tplane_distance_threshold_;\n\tuint32_t \tring_point_num_min_;\n\tuint32_t \tring_endpoint_num_;\n\tuint32_t \tedge_point_num_min_;\n\tdouble \t\tedge_distance_threshold_;\n\n\tPolygon3D::Ptr polygon_;\n\n\tvoid SectorFilter(const PCI& pc, Indices& indices);\n\tbool ExtractPlane(const PCI& pc, Indices& indices, Eigen::Vector4d& coef);\n\tPolygon3D::Ptr ExtractEdgeInlier(const PCI& pc, const Indices& indices);\n\tbool ExtractRings(const PCI& pc, const Indices& indices,\n\t\t\t\t\t  Indices& inlier, Indices& left, Indices& right);\n\tbool ExtractEdges(const PCI& pc, Indices& indices,\n\t\t\t\t\t  Edge3D& edge0, Edge3D& edge1);\n\tvoid FitLine(const PCI& pc, const Indices& indices,\n\t\t\t\t Indices& inlier, Eigen::Vector3d& coef, Eigen::Vector3d& pt);\n\n    void MarkPointcloud(pcl::PointCloud<pcl::PointXYZRGB>& pcc,\n                        const lqh::utils::color::rgb& color,\n                        const Indices& indices) const;\n\n\tbool SaveMarkedPointcloud(const std::string& fn, const PCI& pc,\n\t\t\t\t\t\t\t  const Indices& indices) const;\n\n\tbool ExtractEdgesMems(const PCI& pc, Indices& indices,\n\t\t\t\t\t\t  Edge3D& edge0, Edge3D& edge1, bool is_left);\n};\n\n}\n\n/* Exported constants --------------------------------------------------------*/\n/* Exported functions --------------------------------------------------------*/\n\n#endif /* !__POINTCLOUD_POLYGON_H */\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "PlyCal/utils.h",
    "content": "/*\n * utils.h\n * Copyright (C) 2016 Nick.Liao <simplelife_nick@hotmail.com>\n *\n * Distributed under terms of the MIT license.\n */\n\n#ifndef UTILS_H\n#define UTILS_H\n\n#include <stdint.h>\n#include <iostream>\n#include <string>\n#include <memory>\n#include <mutex>\n#include <condition_variable>\n#include <cmath>\n\n#include <boost/asio/io_service.hpp>\n#include <boost/bind.hpp>\n#include <boost/thread/thread.hpp>\n\n//#define LQH_DEBUG\n\n\nnamespace lqh\n{\n\nconst double MATH_PI = 3.1415926535897932384626433832;\n\nnamespace utils\n{\n\n/**\n * @brief\n * @note: used only in main thread\n */\nclass pm\n{\nprivate:\n\tboost::thread_group threadpool_;\n\tboost::asio::io_service service_;\n\tstd::unique_ptr<boost::asio::io_service::work> work_;\npublic:\n\t// type\n\tclass helper\n\t{\n\t\tfriend class pm;\n\tprivate:\n\t\tstd::mutex mtx_;\n\t\tstd::condition_variable cv_;\n\t\tuint32_t cnt_;\n\n\t\t// we don't want them to be called outside\n\t\tvoid increase()\n\t\t{\n\t\t\tstd::lock_guard<std::mutex> lg(mtx_);\n\t\t\tcnt_++;\n\t\t}\n\n\t\tvoid decrease()\n\t\t{\n\t\t\tstd::unique_lock<std::mutex> lg(mtx_);\n\t\t\tcnt_--;\n\n\t\t\tlg.unlock();\n\t\t\tcv_.notify_one();\n\t\t}\n\t\tvoid wait()\n\t\t{\n\t\t\tstd::unique_lock<std::mutex> ulk(mtx_);\n\t\t\twhile(cnt_)\n\t\t\t{\n\t\t\t\tcv_.wait(ulk, [this] {return !cnt_;} );\n\t\t\t\tcnt_ = 0;\n\t\t\t}\n\t\t}\n\tpublic:\n\t\thelper():cnt_(0) {};\n\t};\n\n\t// member function\n\n\tpm(uint32_t t_num=0):\n\t\twork_(new boost::asio::io_service::work(service_))\n\t{\n\n\t\tuint32_t hard_num = boost::thread::hardware_concurrency();\n\t\tt_num = t_num >0?t_num:(hard_num > 1? hard_num-1:1);\n\n\t\tfor(uint32_t i=0; i<hard_num; i++)\n\t\t{\n\t\t\tthreadpool_.create_thread(\n\t\t\t\tboost::bind(&boost::asio::io_service::run, &service_)\n\t\t\t);\n\t\t}\n\n#ifdef LQH_DEBUG\n\t\tstd::cout << \"Hardware support thread(s): \" << hard_num << std::endl\n\t\t\t\t  << \"PM start thread(s): \" << t_num << std::endl;\n#endif\n\n\t}\n\n\t~pm()\n\t{\n\t\twork_ = nullptr;\n\t\tthreadpool_.join_all();\n\t}\n\n\ttemplate <typename F>\n\tvoid post(helper& h, F f)\n\t{\n\t\tauto handler = [f, &h]()\n\t\t{\n\t\t\tf();\n\t\t\th.decrease();\n\t\t};\n\t\th.increase();\n\t\tservice_.post(handler);\n\t}\n\n\tvoid wait(helper& h)\n\t{\n\t\th.wait();\n\t}\n\n};\n\n\nclass color\n{\nprivate:\n\npublic:\n\tusing rgb = std::array<uint8_t,3>;\n\tusing rgbs = std::vector<rgb>;\n\tstatic rgb HSL2RGB(double H, double S, double L)\n\t{\n\t\trgb res{{0,0,0}};\n\n\t\tH = H<0 || H>360 ? 180:H;\n\t\tS = S<0 || S>1 ? 0.5:S;\n\t\tL = L<0 || L>1 ? 0.5:L;\n\n\n\t\tdouble C = (1-std::abs(2*L-1))*S;\n\t\tdouble X = C*(1-std::abs(std::fmod(H/60, 2) -1));\n\t\tdouble m = L - C/2;\n\n\t\tdouble RR, GG, BB;\n\n\t\tif(H <60)\n\t\t{\n\t\t\tRR = C;\n\t\t\tGG = X;\n\t\t\tBB = 0;\n\t\t}\n\t\telse if(H <120)\n\t\t{\n\t\t\tRR = X;\n\t\t\tGG = C;\n\t\t\tBB = 0;\n\t\t}\n\t\telse if(H <180)\n\t\t{\n\t\t\tRR = 0;\n\t\t\tGG = C;\n\t\t\tBB = X;\n\t\t}\n\t\telse if(H <240)\n\t\t{\n\t\t\tRR = 0;\n\t\t\tGG = X;\n\t\t\tBB = C;\n\t\t}\n\t\telse if(H <300)\n\t\t{\n\t\t\tRR = X;\n\t\t\tGG = 0;\n\t\t\tBB = C;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tRR = X;\n\t\t\tGG = 0;\n\t\t\tBB = C;\n\t\t}\n\n\t\tres[0] = static_cast<uint8_t>((RR+m)*255);\n\t\tres[1] = static_cast<uint8_t>((GG+m)*255);\n\t\tres[2] = static_cast<uint8_t>((BB+m)*255);\n\t\treturn res;\n\t};\n\tstatic rgbs get_rgbs(uint32_t n, double S=0.5, double L=0.5 )\n\t{\n\t\tn = !n ? 1:n;  // at least 1\n\t\trgbs res(n);\n\t\tdouble step = 360/n;\n\t\tdouble H = 0;\n\t\tfor(uint32_t i=0; i<n; i++, H+= step)\n\t\t{\n\t\t\tres[i] = HSL2RGB(H,S,L);\n\t\t}\n\n\t\treturn res;\n\t}\n\n};\n\n}\n}\n\n\n\n#endif /* !UTILS_H */\n"
  },
  {
    "path": "PlyCal_qt/CMakeLists.txt",
    "content": "set(CMAKE_INCLUDE_CURRENT_DIR ON)\n# Let CMake do the job for us\nset(CMAKE_AUTOMOC ON) # For meta object compiler\nset(CMAKE_AUTORCC ON) # Resource files\nset(CMAKE_AUTOUIC ON) # UI file\nadd_compile_options(-fPIC)\n\n\nfind_package(\n\tQt5\n\tREQUIRED\n\tCOMPONENTS\n\tCore\n\tGui\n\tWidgets\n\t)\n\nfind_package(\n\tVTK\n\tREQUIRED\n\t)\n\ninclude_directories(\n\t${VTK_INCLUDE_DIRS}\n\t${Qt5Widgets_INCLUDE_DIRS}\n\t)\n\nlink_directories(\n\t${VTK_LIBRARY_DIRS}\n\t)\n\nfile(GLOB UI_SRC\n    \"*.cpp\"\n)\n\nadd_executable(\n\t${PROJECT_NAME}-qt\n\t${UI_SRC}\n\t)\n\ntarget_link_libraries(\n\t${PROJECT_NAME}-qt\n\t${VTK_LIBRARIES}\n\t${LIB_PREFIX}\n\tQt5::Core\n\tQt5::Widgets\n\tQt5::Gui\n\t)\n\n"
  },
  {
    "path": "PlyCal_qt/cqtopencvviewergl.cpp",
    "content": "#include \"cqtopencvviewergl.h\"\n#include <QMouseEvent>\n#include <QDebug>\n\nCQtOpenCVViewerGl::CQtOpenCVViewerGl(QWidget *parent) :\n\tQOpenGLWidget(parent),\n\tis_pick_points_(false)\n{\n\tpoints_.reserve(4);\n\n\tmBgColor = QColor::fromRgb(150, 150, 150);\n}\n\nvoid CQtOpenCVViewerGl::initializeGL()\n{\n\tmakeCurrent();\n\tinitializeOpenGLFunctions();\n\n\tfloat r = ((float)mBgColor.darker().red())/255.0f;\n\tfloat g = ((float)mBgColor.darker().green())/255.0f;\n\tfloat b = ((float)mBgColor.darker().blue())/255.0f;\n\tglClearColor(r,g,b,1.0f);\n}\n\nvoid CQtOpenCVViewerGl::resizeGL(int width, int height)\n{\n\tmakeCurrent();\n\tglViewport(0, 0, (GLint)width, (GLint)height);\n\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglOrtho(0, width, -height, 0, 0, 1);\n\n\tglMatrixMode(GL_MODELVIEW);\n\n\trecalculatePosition();\n\n\temit imageSizeChanged(mRenderWidth, mRenderHeight);\n\n\tupdateScene();\n}\n\nvoid CQtOpenCVViewerGl::updateScene()\n{\n\tif (this->isVisible()) update();\n}\n\nvoid CQtOpenCVViewerGl::paintGL()\n{\n\tmakeCurrent();\n\n\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\trenderImage();\n}\n\nvoid CQtOpenCVViewerGl::renderImage()\n{\n\n\tdrawMutex.lock();\n\tmakeCurrent();\n\n\tglClear(GL_COLOR_BUFFER_BIT);\n\n\tif (!mRenderQtImg.isNull())\n\t{\n\t\tglLoadIdentity();\n\n\t\tglPushMatrix();\n\t\t{\n\t\t\tif (mResizedImg.width() <= 0)\n\t\t\t{\n\t\t\t\tif (mRenderWidth == mRenderQtImg.width() && mRenderHeight == mRenderQtImg.height())\n\t\t\t\t\tmResizedImg = mRenderQtImg;\n\t\t\t\telse\n\t\t\t\t\tmResizedImg = mRenderQtImg.scaled(QSize(mRenderWidth, mRenderHeight),\n\t\t\t\t\t\t\t\t\t\t\t\t\t  Qt::IgnoreAspectRatio,\n\t\t\t\t\t\t\t\t\t\t\t\t\t  Qt::SmoothTransformation);\n\t\t\t}\n\n\t\t\t// ---> Centering image in draw area\n\n\t\t\tglRasterPos2i(mRenderPosX, mRenderPosY);\n\n\t\t\tglPixelZoom(1, -1);\n\n\t\t\tglDrawPixels(mResizedImg.width(), mResizedImg.height(), GL_RGBA, GL_UNSIGNED_BYTE, mResizedImg.bits());\n\n\t\t}\n\t\tglPopMatrix();\n\n\t\t// end\n\t\tglFlush();\n\t}\n\n\tdrawMutex.unlock();\n}\n\nvoid CQtOpenCVViewerGl::recalculatePosition()\n{\n\tmImgRatio = (float)mOrigImage.cols/(float)mOrigImage.rows;\n\n\tmRenderWidth = this->size().width();\n\tmRenderHeight = floor(mRenderWidth / mImgRatio);\n\n\tif (mRenderHeight > this->size().height())\n\t{\n\t\tmRenderHeight = this->size().height();\n\t\tmRenderWidth = floor(mRenderHeight * mImgRatio);\n\t}\n\n\tmRenderPosX = floor((this->size().width() - mRenderWidth) / 2);\n\tmRenderPosY = -floor((this->size().height() - mRenderHeight) / 2);\n\n\tmResizedImg = QImage();\n}\n\nbool CQtOpenCVViewerGl::showImage(const cv::Mat& image, bool isInside)\n{\n\t// for pick poitns\n\tif(!isInside)\n\t{\n\t\timage.copyTo(img_);\n\t}\n\n\tdrawMutex.lock();\n\tif (image.channels() == 3)\n#if (CV_VERSION_MAJOR >= 4)\n\t\tcv::cvtColor(image, mOrigImage, cv::COLOR_BGR2RGBA);\n#else\n\t\tcvtColor(image, mOrigImage, CV_BGR2RGBA);\n#endif\n\telse if (image.channels() == 1)\n#if (CV_VERSION_MAJOR >= 4)\n\t\tcv::cvtColor(image, mOrigImage, cv::COLOR_GRAY2RGBA);\n#else\n\t\tcvtColor(image, mOrigImage, CV_GRAY2RGBA);\n#endif\n\n\telse if (image.channels() == 4)\n\t\tmOrigImage = image;\n\telse return false;\n\n\tmRenderQtImg = QImage((const unsigned char*)(mOrigImage.data),\n\t\t\t\t\t\t  mOrigImage.cols, mOrigImage.rows,\n\t\t\t\t\t\t  mOrigImage.step1(), QImage::Format_RGB32);\n\n\trecalculatePosition();\n\n\tupdateScene();\n\tdrawMutex.unlock();\n\treturn true;\n}\n\nvoid CQtOpenCVViewerGl::mousePressEvent(QMouseEvent *event)\n{\n\tif(!is_pick_points_ || event->button() != Qt::LeftButton)\n\t{\n\t\treturn;\n\t}\n\n\tint off_x = 0, off_y = 0;\n\tint img_x = 0, img_y = 0;\n\tif(width()/height() > mImgRatio )\n\t{\n\t\timg_y = height();\n\t\toff_y = 0;\n\t\timg_x = floor(height()*mImgRatio);\n\t\toff_x = floor((width() - img_x)/2);\n\t}\n\telse\n\t{\n\t\timg_x = width();\n\t\toff_x = 0;\n\t\timg_y = floor(width()/mImgRatio);\n\t\toff_y = floor((height() - img_y)/2);\n\t}\n\n\tdouble x = static_cast<double>(event->x() - off_x)/img_x*img_.cols;\n\tdouble y = static_cast<double>(event->y() - off_y)/img_y*img_.rows;\n\n\tpoints_.emplace_back(x,y);\n\tcv::Mat img;\n\timg_.copyTo(img);\n\tfor(const auto& p: points_)\n\t{\n\t\tcv::circle(img, p, 5, cv::Scalar(0,0,255),-1);\n\t}\n\tshowImage(img, true);\n}\n"
  },
  {
    "path": "PlyCal_qt/cqtopencvviewergl.h",
    "content": "#ifndef CQTOPENCVVIEWERGL_H\n#define CQTOPENCVVIEWERGL_H\n\n#include <QOpenGLWidget>\n#include <QOpenGLFunctions_2_0>\n#include <opencv2/opencv.hpp>\n#include <opencv2/core/core.hpp>\n\n#include <mutex>\n#include <memory>\n\nclass CQtOpenCVViewerGl : public QOpenGLWidget, protected QOpenGLFunctions_2_0\n{\n\tQ_OBJECT\npublic:\n\texplicit CQtOpenCVViewerGl(QWidget *parent = 0);\n    void startPickPoints()\n    {\n        is_pick_points_ = true;\n        points_.clear();\n    }\n    void stopPickPoints()\n    {\n        is_pick_points_ = false;\n        points_.clear();\n    }\n    void getPickpoints(std::vector<cv::Point2d>& pts)\n    {\n        pts.clear();\n        if(points_.size() >= 4)\n        {\n            pts = points_;\n        }\n        stopPickPoints();\n        return;\n    }\n\nsignals:\n\tvoid    imageSizeChanged( int outW, int outH ); /// Used to resize the image outside the widget\n\npublic slots:\n    bool    showImage(const cv::Mat& image, bool isInside = false);        /// Used to set the image to be viewed\n\nprotected:\n\tvoid \tinitializeGL(); /// OpenGL initialization\n\tvoid \tpaintGL(); /// OpenGL Rendering\n\tvoid \tresizeGL(int width, int height);        /// Widget Resize Event\n\n\tvoid        updateScene();\n\tvoid        renderImage();\n\n    // pick points\n    void    mousePressEvent(QMouseEvent* event);\n\nprivate:\n\tQImage      mRenderQtImg;           /// Qt image to be rendered\n\tQImage      mResizedImg;\n\tcv::Mat     mOrigImage;             /// original OpenCV image to be shown\n    QColor      mBgColor;               /// Background color\n    float       mImgRatio;             /// width/height = cols/rows ratio\n    int         mRenderWidth;\n    int         mRenderHeight;\n    int         mRenderPosX;\n    int         mRenderPosY;\n    std::mutex  drawMutex;\n\n    bool        is_pick_points_;\n    cv::Mat     img_;\n    std::vector<cv::Point2d> points_;\n\n\tvoid recalculatePosition();\n};\n\n#endif // CQTOPENCVVIEWERGL_H\n"
  },
  {
    "path": "PlyCal_qt/data_reader.cpp",
    "content": "/**\n  ******************************************************************************\n  * @file\tdata_reader.cpp\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-20\n  * @brief\tdata_reader.cpp\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Includes ------------------------------------------------------------------*/\n#include \"data_reader.h\"\n\n#include <QDebug>\n#include <QDir>\n#include <QFile>\n#include <QStringList>\n\n\n#include <string>\n\n#include <pcl/io/pcd_io.h>\n\n/* Private typedef -----------------------------------------------------------*/\n/* Private define ------------------------------------------------------------*/\n/* Private macro -------------------------------------------------------------*/\n/* Private variables ---------------------------------------------------------*/\n\nconst QString DataReader::kPointcloudFolderName (\"pointcloud\");\nconst QString DataReader::kImageFolderName(\"image_orig\");\nconst QString DataReader::kLaserscanFolderName(\"laser\");\nconst QString DataReader::kTransformFileNmae (\"tf.txt\");\n\n\n/* Private function prototypes -----------------------------------------------*/\n/* Private functions ---------------------------------------------------------*/\n/* Exported functions --------------------------------------------------------*/\n\nDataReader::DataReader(const QString& path):\n    dataset_root_(path),\n    image_extension_(\"jpeg\"),\n    is_valid_(false),\n    flag_kd_(0x00),\n    size_(0),\n    index_(0)\n{\n    size_ = getDataNum(path);\n    is_valid_ = size_>0 ? true:false;\n\n    K_ = cv::Mat(3, 3, CV_32FC1);\n    D_ = cv::Mat(5,1,CV_32FC1);\n}\n\n\nuint32_t DataReader::getDataNum(const QString &path)\n{\n\tQDir dir(path);\n\n\tif(!dir.exists())\n\t{\n\t\treturn false;\n\t}\n\n    QStringList items = dir.entryList(QDir::Dirs|QDir::Files|QDir::NoDotAndDotDot);\n\n    if(!items.contains(kPointcloudFolderName))\n    {\n        return 0;\n    }\n    if(!items.contains(kImageFolderName))\n    {\n        return 0;\n    }\n\n//    if(!items.contains(kLaserscanFolderName))\n//    {\n//        return 0;\n//    }\n//    if(!items.contains(kTransformFileNmae))\n//    {\n//        return 0;\n//    }\n\n    QStringList imgs = QDir(path + QDir::separator() + kImageFolderName)\n                       .entryList(QDir::Files|QDir::NoDotAndDotDot);\n    if(imgs.size() > 0)\n    {\n        QFileInfo fi(imgs[0]);\n        image_extension_ = fi.completeSuffix();\n    }\n\n    return imgs.count();\n}\n\n\n\npcl::PointCloud<pcl::PointXYZI>::Ptr DataReader::getPointcloud()\n{\n    QString fp = dataset_root_ + QDir::separator() + kPointcloudFolderName +\n                 QDir::separator() + QString(\"%1.pcd\").arg(index_);\n\n    pcl::PointCloud<pcl::PointXYZI>::Ptr pc(new pcl::PointCloud<pcl::PointXYZI>);\n    if(pcl::io::loadPCDFile(fp.toStdString(), *pc) == 1)\n    {\n        pc = nullptr;\n    }\n    return pc;\n}\n\n\n\nstd::shared_ptr<cv::Mat> DataReader::getImage()\n{\n    if(flag_kd_ &0x03 != 0x03)\n    {\n        // K, D not set\n        return nullptr;\n    }\n\n    QString fp = dataset_root_ + QDir::separator() + kImageFolderName +\n                 QDir::separator() + QString(\"%1.\").arg(index_) + image_extension_;\n\n    cv::Mat img_orig = cv::imread(fp.toStdString(), cv::IMREAD_COLOR);\n    if(img_orig.data == NULL)\n    {\n        std::cerr << \"Fail to read \" << fp.toStdString() << std::endl;\n        return nullptr;\n    }\n    std::shared_ptr<cv::Mat> img = std::make_shared<cv::Mat>();\n    cv::undistort(img_orig, *img, K_, D_);\n    return img;\n}\n\nbool DataReader::moveNext()\n{\n    if(index_ >= (size_-1))\n    {\n        return false;\n    }\n    index_++;\n    return true;\n}\n\nvoid DataReader::setCameraK(const Eigen::Matrix3d &k)\n{\n    K_ = cv::Mat(3,3,CV_32FC1);\n    for(uint8_t i=0; i<9; i++)\n    {\n        K_.ptr<float>(i/3)[i%3] = k(i/3,i%3);\n    }\n    flag_kd_ |= 0x01;\n}\n\nvoid DataReader::setCameraD(const Eigen::Matrix<double,5,1>& d)\n{\n    D_ = cv::Mat(5,1,CV_32FC1);\n\n    D_.ptr<float>(0)[0] = d(0);\n    D_.ptr<float>(1)[0] = d(1);\n    D_.ptr<float>(2)[0] = d(2);\n    D_.ptr<float>(3)[0] = d(3);\n    D_.ptr<float>(4)[0] = d(4);\n\n    flag_kd_ |= 0x02;\n}\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "PlyCal_qt/data_reader.h",
    "content": "/**\n  ******************************************************************************\n  * @file\tdata_reader.h\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-20\n  * @brief\tdata_reader.h\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Define to prevent recursive inclusion -------------------------------------*/\n#ifndef __DATA_READER_H\n#define __DATA_READER_H\n\n/* Includes ------------------------------------------------------------------*/\n#include <stdint.h>\n\n#include <QString>\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n\n#include <opencv2/opencv.hpp>\n\n/* Exported macro ------------------------------------------------------------*/\n/* Exported types ------------------------------------------------------------*/\nclass DataReader\n{\npublic:\n    DataReader(const QString& path);\n    bool isValid()\n    {\n        return is_valid_;\n    }\n    pcl::PointCloud<pcl::PointXYZI>::Ptr getPointcloud();\n    std::shared_ptr<cv::Mat> getImage();\n    bool moveNext();\n    uint32_t getDatasetSize()\n    {\n        return size_;\n    }\n    uint32_t getCurrentId()\n    {\n        return index_;\n    }\n    void setCameraK(const Eigen::Matrix3d& k);\n    void setCameraD(const Eigen::Matrix<double,5,1>& d);\n\nprivate:\n    static const QString kPointcloudFolderName;\n    static const QString kImageFolderName;\n    static const QString kLaserscanFolderName;\n    static const QString kTransformFileNmae;\n\n    QString dataset_root_;\n    QString image_extension_;\t\n    bool is_valid_;\n    uint8_t flag_kd_;\n\tuint32_t index_;\n\tuint32_t size_;\n    cv::Mat K_;\n    cv::Mat D_;\n\n    uint32_t getDataNum(const QString& path);\n};\n\n/* Exported constants --------------------------------------------------------*/\n/* Exported functions --------------------------------------------------------*/\n\n#endif /* !__DATA_READER_H */\n\n/*****************************END OF FILE**************************************/\n\n"
  },
  {
    "path": "PlyCal_qt/imageviewer.cpp",
    "content": "#include \"imageviewer.h\"\n#include \"ui_imageviewer.h\"\n\n#include <QMenu>\n#include <QFileDialog>\n#include <QMessageBox>\n#include <QDebug>\n\nImageViewer::ImageViewer(QWidget *parent) :\n    QMainWindow(parent),\n    ui(new Ui::ImageViewer),\n    img_(nullptr)\n{\n    ui->setupUi(this);\n\n    setWindowFlags(Qt::Window\n                   | Qt::WindowMinimizeButtonHint\n                   | Qt::WindowMaximizeButtonHint);\n}\n\nImageViewer::~ImageViewer()\n{\n    delete ui;\n}\n\n\n/**\n * @brief show image in standlone window\n * @param img\n */\nvoid ImageViewer::showImage(std::shared_ptr<cv::Mat> img)\n{\n    ui->image_widget->showImage(*img);\n    img_ = img;\n}\n\nvoid ImageViewer::startPickPoints()\n{\n    ui->image_widget->startPickPoints();\n}\n\nvoid ImageViewer::quitPickPoints()\n{\n    ui->image_widget->stopPickPoints();\n}\n\nvoid ImageViewer::getPickPoitns(std::vector<cv::Point2d>& pts)\n{\n    ui->image_widget->getPickpoints(pts);\n}\n\nvoid ImageViewer::contextMenuEvent(QContextMenuEvent *event)\n{\n    if(img_ == nullptr)\n    {\n        return;\n    }\n    QMenu menu(this);\n    menu.addAction(ui->actionSave_Image);\n    menu.exec(event->globalPos());\n}\n\n\nvoid ImageViewer::on_actionSave_Image_triggered()\n{\n    QString fn = QFileDialog::getSaveFileName(this,\n                 tr(\"Save Image\"),\n                 \"\",\n                 tr(\"Image(*.png)\"));\n    qDebug() << fn;\n    if(fn.isEmpty())\n    {\n        return;\n    }\n    if(!cv::imwrite(fn.toStdString(), *img_))\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Fail to save image\"));\n    }\n}\n\n"
  },
  {
    "path": "PlyCal_qt/imageviewer.h",
    "content": "#ifndef IMAGEVIEWER_H\n#define IMAGEVIEWER_H\n\n#include <QMainWindow>\n#include <QContextMenuEvent>\n\n#include <memory>\n\n#include <opencv2/opencv.hpp>\n\nnamespace Ui {\nclass ImageViewer;\n}\n\nclass ImageViewer : public QMainWindow\n{\n    Q_OBJECT\n\npublic:\n    explicit ImageViewer(QWidget *parent = 0);\n    ~ImageViewer();\n\n    void startPickPoints();\n    void quitPickPoints();\n    void getPickPoitns(std::vector<cv::Point2d>& pts);\n\npublic slots:\n    void showImage(std::shared_ptr<cv::Mat> img);\n\nprotected:\n    void contextMenuEvent(QContextMenuEvent *event) override;\n\nprivate slots:\n    void on_actionSave_Image_triggered();\n\nprivate:\n    Ui::ImageViewer *ui;\n    std::shared_ptr<cv::Mat> img_;\n};\n\n#endif // IMAGEVIEWER_H\n"
  },
  {
    "path": "PlyCal_qt/imageviewer.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>ImageViewer</class>\n <widget class=\"QMainWindow\" name=\"ImageViewer\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>800</width>\n    <height>600</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Image Viewer</string>\n  </property>\n  <widget class=\"QWidget\" name=\"centralwidget\">\n   <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n    <property name=\"spacing\">\n     <number>0</number>\n    </property>\n    <property name=\"leftMargin\">\n     <number>0</number>\n    </property>\n    <property name=\"topMargin\">\n     <number>0</number>\n    </property>\n    <property name=\"rightMargin\">\n     <number>0</number>\n    </property>\n    <property name=\"bottomMargin\">\n     <number>0</number>\n    </property>\n    <item>\n     <widget class=\"CQtOpenCVViewerGl\" name=\"image_widget\" native=\"true\"/>\n    </item>\n   </layout>\n  </widget>\n  <action name=\"actionSave_Image\">\n   <property name=\"text\">\n    <string>Save Image</string>\n   </property>\n   <property name=\"toolTip\">\n    <string>save this image</string>\n   </property>\n  </action>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>CQtOpenCVViewerGl</class>\n   <extends>QWidget</extends>\n   <header>cqtopencvviewergl.h</header>\n   <container>1</container>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "PlyCal_qt/main.cpp",
    "content": "#include \"mainwindow.h\"\n#include <QApplication>\n\nint main(int argc, char *argv[])\n{\n    QApplication a(argc, argv);\n    MainWindow w;\n    w.show();\n\n    return a.exec();\n}\n"
  },
  {
    "path": "PlyCal_qt/mainwindow.cpp",
    "content": "#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include <QAction>\n#include <QDebug>\n#include <QFileDialog>\n#include <QDir>\n#include <QMessageBox>\n#include <QCloseEvent>\n#include <QThread>\n#include <QInputDialog>\n#include <QLineEdit>\n#include <QDateTime>\n#include <QTimer>\n\n#include <string>\n#include <fstream>\n\n\nMainWindow::MainWindow(QWidget *parent) :\n    QMainWindow(parent),\n    ui(new Ui::MainWindow),\n    sid_(INT_MAX),\n    is_calibrated_(false),\n    data_reader_(nullptr),\n    img_(nullptr), pc_(nullptr)\n{\n    ui->setupUi(this);\n\n    config_path_ = QFileDialog::getOpenFileName(this,\n                   tr(\"Open File\"),\n                   \".\",\n                   tr(\"Config JSON Files(*.json)\"));\n\n    if(config_path_.isEmpty())\n    {\n        QTimer::singleShot(0,this, &QApplication::quit);\n        return;\n    }\n\n    std::ifstream f(config_path_.toStdString());\n    if(!f.good())\n    {\n        f.close();\n        QTimer::singleShot(0,this, &QApplication::quit);\n        return;\n    }\n\n    try\n    {\n        f >> js_;\n    }\n    catch(nlohmann::json::parse_error& e)\n    {\n        std::cerr << e.what();\n        f.close();\n        QTimer::singleShot(0,this, &QApplication::quit);\n        return;\n    }\n    calibrator_.reset(new lqh::Calibrator(js_));\n\n\n    auto& flt = js_[\"pc\"][\"filter\"];\n    ui->angle_start_slide->setValue(static_cast<int>(flt[\"angle_start\"]));\n    ui->angle_size_slide->setValue(static_cast<int>(flt[\"angle_size\"]));\n    ui->distance_slide->setValue(static_cast<int>(10*flt[\"distance\"].get<double>()) );\n    ui->floor_gap_slide->setValue(static_cast<int>(10*flt[\"floor_gap\"].get<double>()) );\n\n    img_viewer_.reset(new ImageViewer);\n    img_viewer_->show();\n    pc_viewer_.reset(new PointcloudViewer);\n    pc_viewer_->show();\n\n    connect(ui->angle_start_slide, &QSlider::valueChanged, this, &MainWindow::processSlider);\n    connect(ui->angle_size_slide, &QSlider::valueChanged, this, &MainWindow::processSlider);\n    connect(ui->distance_slide, &QSlider::valueChanged, this, &MainWindow::processSlider);\n    connect(ui->floor_gap_slide, &QSlider::valueChanged, this, &MainWindow::processSlider);\n}\n\nMainWindow::~MainWindow()\n{\n    delete ui;\n}\n\nvoid MainWindow::closeEvent(QCloseEvent * event)\n{\n    if(img_viewer_)\n    {\n        img_viewer_->close();\n        img_viewer_.release();\n    }\n    if(pc_viewer_)\n    {\n        pc_viewer_->close();\n        img_viewer_.release();\n    }\n\n    event->accept();\n}\n\nvoid MainWindow::on_actionSet_K_triggered()\n{\n    bool ok = false;\n    QString last;\n    auto& K = js_[\"cam\"][\"K\"];\n    for(uint8_t i=0; i<9; i++)\n    {\n        last.append(QString(\"%1 \").arg(K[i/3][i%3].get<double>()));\n    }\n    QString ks = QInputDialog::getText(this,\n                                       tr(\"Camera matrix, K\"),\n                                       tr(\"K\"),\n                                       QLineEdit::Normal,\n                                       last,\n                                       &ok);\n    if(!ok)\n    {\n        return;\n    }\n    if(!ks.isEmpty())\n    {\n        ks.replace(QChar('\\n'), QChar(' '));\n        QStringList ns = ks.simplified().split(\" \");\n        if(ns.size() == 9)\n        {\n            Eigen::Matrix3d CK;\n            for(uint8_t i=0; i<9; i++)\n            {\n                CK(i/3,i%3) = ns[i].toDouble();\n                K[i/3][i%3] = CK(i/3,i%3);\n            }\n            if(data_reader_ != nullptr)\n            {\n                data_reader_->setCameraK(CK);\n            }\n            calibrator_->SetCameraK(CK);\n            return;\n        }\n    }\n    QMessageBox::warning(this, tr(\"Error\"), tr(\"Invalid parameters\"));\n}\n\nvoid MainWindow::on_actionSet_D_triggered()\n{\n    bool ok = false;\n    auto& D = js_[\"cam\"][\"D\"];\n    QString last = QString(\"%1 %2 %3 %4 %5\")\n                   .arg(D[0].get<double>())\n                   .arg(D[1].get<double>())\n                   .arg(D[2].get<double>())\n                   .arg(D[3].get<double>())\n                   .arg(D[4].get<double>());\n\n    QString ks = QInputDialog::getText(this,\n                                       tr(\"Distortion Parameters\"),\n                                       tr(\"D\"),\n                                       QLineEdit::Normal,\n                                       last,\n                                       &ok);\n    if(!ok)\n    {\n        return;\n    }\n    if(!ks.isEmpty())\n    {\n        Eigen::Matrix<double,5,1> CD;\n        ks.replace(QChar('\\n'), QChar(' '));\n        QStringList ns = ks.split(\" \");\n        if(ns.size() == 5)\n        {\n            for(uint8_t i=0; i<5; i++)\n            {\n                CD(i) = ns[i].toDouble();\n                D[i] = CD(i);\n            }\n            if(data_reader_ != nullptr)\n            {\n                data_reader_->setCameraD(CD);\n            }\n            return;\n        }\n    }\n    QMessageBox::warning(this, tr(\"Error\"), tr(\"Invalid parameters\"));\n}\n\nvoid MainWindow::on_actionOpen_Dataset_triggered()\n{\n    QString dir = QFileDialog::getExistingDirectory(this, tr(\"Open Directory\"),\n                  QDir::homePath(),\n                  QFileDialog::ShowDirsOnly);\n    if(!dir.isEmpty())\n    {\n        data_reader_.reset(new DataReader(dir));\n        if(!data_reader_->isValid())\n        {\n            data_reader_ = nullptr;\n            QMessageBox::warning(this, tr(\"Warn\"), tr(\"The directory is invalid\"));\n            return;\n        }\n        Eigen::Matrix3d K;\n        Eigen::Matrix<double,5,1> D;\n        auto& JK = js_[\"cam\"][\"K\"];\n        auto& JD = js_[\"cam\"][\"D\"];\n        for(uint8_t i=0; i<9; i++)\n        {\n            K(i/3,i%3) = JK[i/3][i%3];\n            if(i<5)\n            {\n                D(i) = JD[i];\n            }\n        }\n        data_reader_->setCameraK(K);\n        data_reader_->setCameraD(D);\n        data_root_ = dir;\n        ui->total_data_num->setText(QString::number(data_reader_->getDatasetSize()));\n\n        showTFWindow();\n\n//        on_next_pose_clicked();\n    }\n}\n\nvoid MainWindow::on_next_pose_clicked()\n{\n    if(is_calibrated_)\n    {\n        //after calibration\n        if(sid_ < sensor_data_.size()-1)\n        {\n            sid_++;\n        }\n        else\n        {\n            if(data_reader_->moveNext())\n            {\n                sensor_data_.emplace_back(data_reader_->getCurrentId());\n                auto& last = sensor_data_.back();\n                last.img = data_reader_->getImage();\n                last.pc = data_reader_->getPointcloud();\n                if(!last.img )\n                {\n                    sensor_data_.pop_back();\n                    QMessageBox::warning(this, tr(\"Error\"), tr(\"Fail to read image\"));\n                    return;\n                }\n                if(!last.pc)\n                {\n                    sensor_data_.pop_back();\n                    QMessageBox::warning(this, tr(\"Error\"), tr(\"Fail to read pointcloud\"));\n                    return;\n                }\n                last.pid = INT_MAX; // invalid\n                sid_ = sensor_data_.size()-1;\n            }\n            else\n            {\n                // last one and fail to read more, so do noting\n                return;\n            }\n        }\n        showCalibrateResult();\n    }\n    else\n    {\n        // before calibration\n        processData();\n    }\n}\n\nvoid MainWindow::on_quick_next_pose_clicked()\n{\n    if(is_calibrated_)\n    {\n        // previous\n        if (sid_ >0)\n        {\n            sid_--;\n        }\n        showCalibrateResult();\n    }\n    else\n    {\n        // quick next\n        setEnabledAll(false);\n        setCursor(Qt::WaitCursor);\n\n        bool res = processData();\n\n        while(res)\n        {\n            res = processData();\n            QCoreApplication::processEvents(QEventLoop::AllEvents);\n//            QThread::msleep(5);\n        }\n\n        setCursor(Qt::ArrowCursor);\n        setEnabledAll(true);\n    }\n}\n\nvoid MainWindow::on_delete_pose_clicked()\n{\n    if(sensor_data_.size() > 0 )\n    {\n        sensor_data_.back().img_good = false;\n        sensor_data_.back().pc_good = false;\n        calibrator_->Remove();\n    }\n    processData(false);\n}\n\nvoid MainWindow::on_calibrate_clicked()\n{\n    if(sensor_data_.size() < 1)\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"No enough data to do calibration, at lease 3\"));\n        return;\n    }\n\n    setEnabledAll(false);\n    setCursor(Qt::WaitCursor);\n//    calibrator_->SavePolygonData(std::string(\"/home/nick/tmp\"));\n\n    bool res = calibrator_->Compute();\n\n    setCursor(Qt::ArrowCursor);\n    setEnabledAll(true);\n\n    if(!res)\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Fail to calibrate\"));\n        return;\n    }\n\n    is_calibrated_ = true;\n    ui->quick_next_pose->setText(tr(\"Previous\"));\n    showCalibrateResult();\n    pc_viewer_->showCoordinateSystem(Eigen::Affine3f(calibrator_->GetTransformation().inverse().cast<float>()), 1, 0.5);\n\n    auto T =  calibrator_->GetTransformation();\n    auto& tf = js_[\"tf\"];\n    tf.clear();\n    for(uint8_t i=0; i<4; i++)\n    {\n        tf.push_back(std::vector<double> {T(i,0), T(i,1), T(i,2), T(i,3)});\n    }\n}\n\nvoid MainWindow::on_pick_points_start_clicked()\n{\n    img_viewer_->startPickPoints();\n}\n\nvoid MainWindow::on_pick_points_quit_clicked()\n{\n    img_viewer_->quitPickPoints();\n}\n\nvoid MainWindow::on_pick_points_end_clicked()\n{\n    std::vector<cv::Point2d> pts;\n    img_viewer_->getPickPoitns(pts);\n\n    if(pts.size() != js_[\"size\"])\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Must choose \")\n                             + QString::number(js_[\"size\"].get<int>())\n                             +tr(\" points\"));\n        return;\n    }\n    auto& img_i = js_[\"img\"][\"init\"];\n    img_i.clear();\n    for(int i=0; i<js_[\"size\"].get<int>(); i++)\n    {\n        img_i.push_back(std::vector<double> {pts[i].x, pts[i].y});\n    }\n\n    auto& last = sensor_data_.back();\n    if( calibrator_->RefineImage(*last.img, *last.img_marked, pts) )\n    {\n        last.img_good = true;\n    }\n\n    img_viewer_->showImage(last.img_marked);\n\n    updateLabels();\n}\n\n\nvoid MainWindow::updateLabels()\n{\n    if(sensor_data_.size() > 0)\n    {\n        ui->current_data_id->setText(QString::number(sid_));\n\n        uint32_t num  = sensor_data_.size();\n        if(!sensor_data_.back().good())\n        {\n            num -= 1;\n        }\n        ui->processed_data_num->setText(QString::number(num));\n    }\n    else\n    {\n        ui->current_data_id->setText(\"Null\");\n        ui->processed_data_num->setText(\"0\");\n    }\n}\n\n\nbool MainWindow::processData(bool is_check)\n{\n    if(data_reader_ == nullptr)\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Open dataset first\"));\n        return false;\n    }\n\n    if( is_check && sensor_data_.size()>0 && !sensor_data_.back().good() )\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Current data is not good, adjust or delete\"));\n        return false;\n    }\n\n    if(sensor_data_.size() > 0 && !data_reader_->moveNext())\n    {\n        return false;\n    }\n\n    sensor_data_.emplace_back(data_reader_->getCurrentId());\n    sid_ = sensor_data_.size()-1;\n    auto& last = sensor_data_.back();\n    last.img = data_reader_->getImage();\n    if(!last.img )\n    {\n        sensor_data_.pop_back();\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Fail to read image\"));\n        return false;\n    }\n\n    last.pc = data_reader_->getPointcloud();\n    if(!last.pc)\n    {\n        sensor_data_.pop_back();\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Fail to read pointcloud\"));\n        return false;\n    }\n\n    last.img_marked = std::make_shared<cv::Mat>();\n    last.img->copyTo(*last.img_marked);\n    last.pc_marked.reset(new pcl::PointCloud<pcl::PointXYZRGB>);\n    last.pid = calibrator_->Add(*last.img, *last.pc, *last.img_marked, *last.pc_marked);\n    if(calibrator_->ImageGood(last.pid))\n    {\n        last.img_good = true;\n    }\n    if(calibrator_->PointcloudGood(last.pid))\n    {\n        last.pc_good = true;\n    }\n\n    img_viewer_->showImage(last.img_marked);\n    pc_viewer_->showPointcloud(last.pc_marked);\n\n    sid_ = sensor_data_.size()-1;\n    updateLabels();\n\n    return true;\n}\n\n\nvoid MainWindow::setEnabledAll(bool status)\n{\n    QList<QPushButton*> btns = ui->centralWidget->findChildren<QPushButton*>();\n    for(auto& it : btns)\n    {\n        it->setEnabled(status);\n    }\n\n    QList<QSlider*> sliders = ui->pointcloud_group->findChildren<QSlider*>();\n    for(auto& it : sliders)\n    {\n        it->setEnabled(status);\n    }\n}\n\n\nvoid MainWindow::showCalibrateResult()\n{\n    auto& sd = sensor_data_[sid_];\n\n    if(sd.img_proj == nullptr || sd.pc_proj == nullptr)\n    {\n        sd.img_proj.reset(new cv::Mat);\n        sd.img->copyTo(*sd.img_proj);\n        sd.pc_proj.reset(new pcl::PointCloud<pcl::PointXYZRGB>);\n        pcl::copyPointCloud(*sd.pc, *sd.pc_proj);\n        for(auto& p: sd.pc_proj->points)\n        {\n            p.rgba = 0xffffffff;\n        }\n        calibrator_->Project(*sd.pc_proj, *sd.img_proj);\n    }\n\n    img_viewer_->showImage(sd.img_proj);\n    pc_viewer_->showPointcloud(sd.pc_proj);\n\n    updateLabels();\n}\n\nvoid MainWindow::on_actionSave_Result_triggered()\n{\n    if(!is_calibrated_)\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Not calibrate yet\"));\n        return;\n    }\n\n    QString fp = data_root_ + QDir::separator()\n                 + \"calibration_\" + QDateTime::currentDateTime().toString(\"yyyy-M-d-h-m-s\")\n                 +\".json\";\n    std::ofstream f(fp.toStdString());\n    if(!f.good())\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Fail to open file \")+fp);\n        return;\n    }\n\n    const Eigen::Matrix4d& tf = calibrator_->GetTransformation();\n    nlohmann::json js;\n    for(uint8_t i=0; i<4; i++)\n    {\n        js[\"T\"].push_back({tf(i,0), tf(i,1), tf(i,2), tf(i,3)});\n    }\n    js[\"K\"] = js_[\"cam\"][\"K\"];\n    js[\"D\"] = js_[\"cam\"][\"D\"];\n\n    f << js.dump(4);\n    f.close();\n\n    QMessageBox::information(this, tr(\"Success\"), tr(\"Save calibration result to \")+fp);\n}\n\nvoid MainWindow::processSlider()\n{\n    Eigen::Vector4d param;\n    param(0) = ui->angle_start_slide->value();\n    param(1) = ui->angle_size_slide->value();\n    param(2) = ui->distance_slide->value()/10.0;\n    param(3) = ui->floor_gap_slide->value()/10.0;\n\n    ui->angle_start_text->setText( QString::number(param(0)) );\n    ui->angle_size_text->setText( QString::number(param(1)) );\n    ui->distance_text->setText( QString::number(param(2)) );\n    ui->floor_gap_text->setText( QString::number(param(3)) );\n\n    if(sensor_data_.size() == 0 || calibrator_ == nullptr)\n    {\n        return;\n    }\n    auto& filter = js_[\"pc\"][\"filter\"];\n    filter[\"angle_start\"] = param(0);\n    filter[\"angle_size\"] = param(1);\n    filter[\"distance\"] = param(2);\n    filter[\"floor_gap\"] = param(3);\n    auto& sd = sensor_data_.back();\n    calibrator_->RefinePointcloud(*sd.pc, *sd.pc_marked, param);\n    if(calibrator_->PointcloudGood(sd.pid))\n    {\n        sd.pc_good = true;\n    }\n\n    pc_viewer_->showPointcloud(sd.pc_marked);\n}\n\n\nvoid MainWindow::on_actionSave_Config_triggered()\n{\n    std::ofstream f(config_path_.toStdString());\n    if(!f.good())\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Fail to open config file\"));\n        return;\n    }\n    f << js_.dump(4);\n    f.close();\n}\n\n\nvoid MainWindow::updateWithTransformation(Eigen::Matrix4d tf)\n{\n    std::shared_ptr<cv::Mat> img_mark = std::make_shared<cv::Mat>();\n    img_->copyTo(*img_mark);\n    pcl::PointCloud<pcl::PointXYZRGB>::Ptr pcc (new pcl::PointCloud<pcl::PointXYZRGB>);\n    pcl::copyPointCloud(*pc_, *pcc);\n    for(auto& p : pcc->points)\n    {\n        p.rgba = 0xffffffff;\n    }\n\n//    calibrator_->SetTranformation(tf_);\n    calibrator_->SetTranformation(tf);\n    calibrator_->Project(*pcc, *img_mark);\n\n    img_viewer_->showImage(img_mark);\n    pc_viewer_->showPointcloud(pcc);\n}\n\n\nvoid MainWindow::tfwindowClose()\n{\n    this->move(tfwindow_->pos());\n    this->show();\n    tfwindow_.reset(nullptr);\n\n    on_next_pose_clicked();\n}\n\nvoid MainWindow::showTFWindow()\n{\n    img_ = data_reader_->getImage();\n    pc_ = data_reader_->getPointcloud();\n    if(img_ == nullptr || pc_ == nullptr )\n    {\n        QMessageBox::warning(this, tr(\"Error\"), tr(\"Fail to read image or pointcloud\"));\n        data_reader_.reset(nullptr);\n        return;\n    }\n    pcl::PointCloud<pcl::PointXYZRGB>::Ptr pcc (new pcl::PointCloud<pcl::PointXYZRGB>);\n    pcl::copyPointCloud(*pc_, *pcc);\n    for(auto& p : pcc->points)\n    {\n        p.rgba = 0xffffffff;\n    }\n    std::shared_ptr<cv::Mat> img_mark = std::make_shared<cv::Mat>();\n    img_->copyTo(*img_mark);\n\n    tfwindow_.reset(new TFwindow(calibrator_->GetTransformation()));\n    connect(tfwindow_.get(), &TFwindow::newTransformation, this, &MainWindow::updateWithTransformation);\n    connect(tfwindow_.get(), &TFwindow::tfwindowClose, this, &MainWindow::tfwindowClose);\n\n\n\n    calibrator_->Project(*pcc, *img_mark);\n    img_viewer_->showImage(img_mark);\n    pc_viewer_->showPointcloud(pcc);\n\n    tfwindow_->move(this->pos());\n    tfwindow_->show();\n    this->hide();\n}\n"
  },
  {
    "path": "PlyCal_qt/mainwindow.h",
    "content": "#ifndef MAINWINDOW_H\n#define MAINWINDOW_H\n\n#include <QMainWindow>\n#include <memory>\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n\n#include \"tfwindow.h\"\n#include \"pointcloudviewer.h\"\n#include \"imageviewer.h\"\n\n#include \"json/json.hpp\"\n#include \"calibrator.h\"\n#include \"data_reader.h\"\n\nnamespace Ui\n{\nclass MainWindow;\n}\n\nclass MainWindow : public QMainWindow\n{\n    Q_OBJECT\n\npublic:\n    explicit MainWindow(QWidget *parent = 0);\n    ~MainWindow();\n\npublic slots:\n    void updateWithTransformation(Eigen::Matrix4d tf);\n    void tfwindowClose();\n\nprotected:\n    void closeEvent(QCloseEvent *);\nprivate:\n    struct SensorData\n    {\n        bool img_good;\n        bool pc_good;\n        uint32_t id;\n        uint32_t pid;\n        std::shared_ptr<cv::Mat> img;\n        pcl::PointCloud<pcl::PointXYZI>::Ptr pc;\n        std::shared_ptr<cv::Mat> img_marked;\n        pcl::PointCloud<pcl::PointXYZRGB>::Ptr pc_marked;\n        std::shared_ptr<cv::Mat> img_proj;\n        pcl::PointCloud<pcl::PointXYZRGB>::Ptr pc_proj;\n\n        SensorData(uint32_t index):img_good(false), pc_good(false),\n            id(index),\n            img(nullptr), pc(nullptr),\n            img_marked(nullptr), pc_marked(nullptr),\n            img_proj(nullptr), pc_proj(nullptr){}\n        bool good()\n        {\n            return (img_good && pc_good);\n        }\n    };\n\n    Ui::MainWindow *ui;\n\n    QString config_path_;\n    nlohmann::json js_;\n\n    bool is_calibrated_;\n    uint32_t sid_;\n    QString data_root_;\n\n    std::shared_ptr<cv::Mat> img_;\n    pcl::PointCloud<pcl::PointXYZI>::Ptr pc_;\n\n    std::unique_ptr<DataReader> data_reader_;\n    std::unique_ptr<PointcloudViewer> pc_viewer_;\n    std::unique_ptr<ImageViewer> img_viewer_;\n    std::unique_ptr<TFwindow> tfwindow_;\n    std::unique_ptr<lqh::Calibrator> calibrator_;\n    std::vector<SensorData> sensor_data_;\n\n    void updateLabels();\n    bool processData(bool is_check = true);\n    void setEnabledAll(bool status);\n    void showCalibrateResult();\n    void showTFWindow();\n\nprivate slots:\n    void on_actionSet_K_triggered();\n    void on_actionSet_D_triggered();\n    void on_actionOpen_Dataset_triggered();\n\n    void on_next_pose_clicked();\n    void on_quick_next_pose_clicked();\n    void on_delete_pose_clicked();\n    void on_calibrate_clicked();\n\n    void on_pick_points_start_clicked();\n    void on_pick_points_end_clicked();\n    void on_pick_points_quit_clicked();\n    void on_actionSave_Result_triggered();\n\n    void processSlider();\n    void on_actionSave_Config_triggered();\n};\n\n#endif // MAINWINDOW_H\n"
  },
  {
    "path": "PlyCal_qt/mainwindow.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>MainWindow</class>\n <widget class=\"QMainWindow\" name=\"MainWindow\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>641</width>\n    <height>521</height>\n   </rect>\n  </property>\n  <property name=\"minimumSize\">\n   <size>\n    <width>600</width>\n    <height>500</height>\n   </size>\n  </property>\n  <property name=\"windowTitle\">\n   <string>Multi-Sensor Extrinsic Calibration</string>\n  </property>\n  <property name=\"styleSheet\">\n   <string notr=\"true\"/>\n  </property>\n  <widget class=\"QWidget\" name=\"centralWidget\">\n   <property name=\"styleSheet\">\n    <string notr=\"true\">QSlider{\n\toutline: none;\n    border:none;\n}\nQPushButton{     \n\t outline: none;\n\t border: 2px solid #8f8f91;\n     border-radius: 20px;\n     background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n                                       stop: 0 #f6f7fa, stop: 1 #dadbde); \n}     \nQPushButton::pressed{     \n\tbackground-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,\n                                       stop: 0 #dadbde, stop: 1 #f6f7fa);  \n}     \nQPushButton::disabled{     \n\tborder: none;\n}     \nQPushButton:flat {\n     border: none;  /* no border for a flat push button */\n }\nQPushButton:default {\n     border-color: navy; /* make the default button prominent */\n }\n\n#centralWidget\n{\t\n\tbackground-color: rgb(255, 255, 255);\n}</string>\n   </property>\n   <layout class=\"QVBoxLayout\" name=\"verticalLayout\" stretch=\"1,6,2\">\n    <item>\n     <layout class=\"QHBoxLayout\" name=\"horizontalLayout\">\n      <property name=\"topMargin\">\n       <number>6</number>\n      </property>\n      <property name=\"bottomMargin\">\n       <number>6</number>\n      </property>\n      <item>\n       <widget class=\"QLabel\" name=\"label\">\n        <property name=\"text\">\n         <string>Current Data ID</string>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"current_data_id\">\n        <property name=\"font\">\n         <font>\n          <pointsize>16</pointsize>\n          <weight>75</weight>\n          <bold>true</bold>\n         </font>\n        </property>\n        <property name=\"styleSheet\">\n         <string notr=\"true\">QLabel{\n\tcolor: rgb(115, 210, 22);\n\tbackground-color: #ccc;\n}</string>\n        </property>\n        <property name=\"text\">\n         <string>0</string>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"label_2\">\n        <property name=\"text\">\n         <string>Processed Data Num</string>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"processed_data_num\">\n        <property name=\"font\">\n         <font>\n          <pointsize>16</pointsize>\n          <weight>75</weight>\n          <bold>true</bold>\n         </font>\n        </property>\n        <property name=\"styleSheet\">\n         <string notr=\"true\">QLabel{\n\tcolor: rgb(115, 210, 22);\n\tbackground-color: #ccc;\n}</string>\n        </property>\n        <property name=\"text\">\n         <string>0</string>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"label_9\">\n        <property name=\"text\">\n         <string>Total Data Num</string>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QLabel\" name=\"total_data_num\">\n        <property name=\"font\">\n         <font>\n          <pointsize>16</pointsize>\n          <weight>75</weight>\n          <bold>true</bold>\n         </font>\n        </property>\n        <property name=\"styleSheet\">\n         <string notr=\"true\">QLabel{\ncolor: rgb(239, 41, 41);\n\tbackground-color: #ccc;\n}</string>\n        </property>\n        <property name=\"text\">\n         <string>0</string>\n        </property>\n        <property name=\"alignment\">\n         <set>Qt::AlignCenter</set>\n        </property>\n       </widget>\n      </item>\n     </layout>\n    </item>\n    <item>\n     <layout class=\"QVBoxLayout\" name=\"verticalLayout_2\" stretch=\"2,3\">\n      <property name=\"spacing\">\n       <number>10</number>\n      </property>\n      <property name=\"sizeConstraint\">\n       <enum>QLayout::SetDefaultConstraint</enum>\n      </property>\n      <property name=\"topMargin\">\n       <number>10</number>\n      </property>\n      <property name=\"bottomMargin\">\n       <number>10</number>\n      </property>\n      <item>\n       <widget class=\"QGroupBox\" name=\"image_group\">\n        <property name=\"title\">\n         <string>Image Control</string>\n        </property>\n        <layout class=\"QHBoxLayout\" name=\"horizontalLayout_2\">\n         <property name=\"spacing\">\n          <number>40</number>\n         </property>\n         <property name=\"leftMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"topMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"rightMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"bottomMargin\">\n          <number>10</number>\n         </property>\n         <item>\n          <widget class=\"QPushButton\" name=\"pick_points_start\">\n           <property name=\"enabled\">\n            <bool>true</bool>\n           </property>\n           <property name=\"sizePolicy\">\n            <sizepolicy hsizetype=\"Minimum\" vsizetype=\"Expanding\">\n             <horstretch>0</horstretch>\n             <verstretch>0</verstretch>\n            </sizepolicy>\n           </property>\n           <property name=\"text\">\n            <string>Start Selection</string>\n           </property>\n          </widget>\n         </item>\n         <item>\n          <widget class=\"QPushButton\" name=\"pick_points_quit\">\n           <property name=\"enabled\">\n            <bool>true</bool>\n           </property>\n           <property name=\"sizePolicy\">\n            <sizepolicy hsizetype=\"Minimum\" vsizetype=\"Expanding\">\n             <horstretch>0</horstretch>\n             <verstretch>0</verstretch>\n            </sizepolicy>\n           </property>\n           <property name=\"text\">\n            <string>Quit Selection</string>\n           </property>\n          </widget>\n         </item>\n         <item>\n          <widget class=\"QPushButton\" name=\"pick_points_end\">\n           <property name=\"enabled\">\n            <bool>true</bool>\n           </property>\n           <property name=\"sizePolicy\">\n            <sizepolicy hsizetype=\"Minimum\" vsizetype=\"Expanding\">\n             <horstretch>0</horstretch>\n             <verstretch>0</verstretch>\n            </sizepolicy>\n           </property>\n           <property name=\"text\">\n            <string>Finish Selection</string>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QGroupBox\" name=\"pointcloud_group\">\n        <property name=\"title\">\n         <string>PointCloud Control</string>\n        </property>\n        <layout class=\"QGridLayout\" name=\"gridLayout\" rowstretch=\"1,1,1,0\" columnstretch=\"1,0,8,0\">\n         <property name=\"leftMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"rightMargin\">\n          <number>10</number>\n         </property>\n         <property name=\"spacing\">\n          <number>0</number>\n         </property>\n         <item row=\"0\" column=\"0\">\n          <widget class=\"QLabel\" name=\"label_3\">\n           <property name=\"sizePolicy\">\n            <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Expanding\">\n             <horstretch>0</horstretch>\n             <verstretch>0</verstretch>\n            </sizepolicy>\n           </property>\n           <property name=\"minimumSize\">\n            <size>\n             <width>100</width>\n             <height>0</height>\n            </size>\n           </property>\n           <property name=\"maximumSize\">\n            <size>\n             <width>100</width>\n             <height>16777215</height>\n            </size>\n           </property>\n           <property name=\"text\">\n            <string>Angle Start</string>\n           </property>\n           <property name=\"alignment\">\n            <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>\n           </property>\n          </widget>\n         </item>\n         <item row=\"2\" column=\"0\">\n          <widget class=\"QLabel\" name=\"label_5\">\n           <property name=\"sizePolicy\">\n            <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Expanding\">\n             <horstretch>0</horstretch>\n             <verstretch>0</verstretch>\n            </sizepolicy>\n           </property>\n           <property name=\"minimumSize\">\n            <size>\n             <width>100</width>\n             <height>0</height>\n            </size>\n           </property>\n           <property name=\"maximumSize\">\n            <size>\n             <width>100</width>\n             <height>16777215</height>\n            </size>\n           </property>\n           <property name=\"text\">\n            <string>Distance</string>\n           </property>\n           <property name=\"alignment\">\n            <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>\n           </property>\n          </widget>\n         </item>\n         <item row=\"1\" column=\"2\">\n          <widget class=\"QSlider\" name=\"angle_size_slide\">\n           <property name=\"minimumSize\">\n            <size>\n             <width>0</width>\n             <height>30</height>\n            </size>\n           </property>\n           <property name=\"maximum\">\n            <number>360</number>\n           </property>\n           <property name=\"orientation\">\n            <enum>Qt::Horizontal</enum>\n           </property>\n          </widget>\n         </item>\n         <item row=\"2\" column=\"2\">\n          <widget class=\"QSlider\" name=\"distance_slide\">\n           <property name=\"minimumSize\">\n            <size>\n             <width>0</width>\n             <height>30</height>\n            </size>\n           </property>\n           <property name=\"maximum\">\n            <number>100</number>\n           </property>\n           <property name=\"orientation\">\n            <enum>Qt::Horizontal</enum>\n           </property>\n          </widget>\n         </item>\n         <item row=\"0\" column=\"2\">\n          <widget class=\"QSlider\" name=\"angle_start_slide\">\n           <property name=\"minimumSize\">\n            <size>\n             <width>0</width>\n             <height>30</height>\n            </size>\n           </property>\n           <property name=\"maximum\">\n            <number>360</number>\n           </property>\n           <property name=\"orientation\">\n            <enum>Qt::Horizontal</enum>\n           </property>\n          </widget>\n         </item>\n         <item row=\"1\" column=\"0\">\n          <widget class=\"QLabel\" name=\"label_4\">\n           <property name=\"sizePolicy\">\n            <sizepolicy hsizetype=\"Preferred\" vsizetype=\"Expanding\">\n             <horstretch>0</horstretch>\n             <verstretch>0</verstretch>\n            </sizepolicy>\n           </property>\n           <property name=\"minimumSize\">\n            <size>\n             <width>100</width>\n             <height>0</height>\n            </size>\n           </property>\n           <property name=\"maximumSize\">\n            <size>\n             <width>100</width>\n             <height>16777215</height>\n            </size>\n           </property>\n           <property name=\"text\">\n            <string>Angle Size</string>\n           </property>\n           <property name=\"alignment\">\n            <set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>\n           </property>\n          </widget>\n         </item>\n         <item row=\"0\" column=\"3\">\n          <widget class=\"QLabel\" name=\"angle_start_text\">\n           <property name=\"minimumSize\">\n            <size>\n             <width>35</width>\n             <height>0</height>\n            </size>\n           </property>\n           <property name=\"maximumSize\">\n            <size>\n             <width>40</width>\n             <height>16777215</height>\n            </size>\n           </property>\n           <property name=\"text\">\n            <string>000</string>\n           </property>\n           <property name=\"alignment\">\n            <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>\n           </property>\n          </widget>\n         </item>\n         <item row=\"1\" column=\"3\">\n          <widget class=\"QLabel\" name=\"angle_size_text\">\n           <property name=\"minimumSize\">\n            <size>\n             <width>35</width>\n             <height>0</height>\n            </size>\n           </property>\n           <property name=\"maximumSize\">\n            <size>\n             <width>40</width>\n             <height>16777215</height>\n            </size>\n           </property>\n           <property name=\"text\">\n            <string>000</string>\n           </property>\n           <property name=\"alignment\">\n            <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>\n           </property>\n          </widget>\n         </item>\n         <item row=\"2\" column=\"3\">\n          <widget class=\"QLabel\" name=\"distance_text\">\n           <property name=\"minimumSize\">\n            <size>\n             <width>35</width>\n             <height>0</height>\n            </size>\n           </property>\n           <property name=\"maximumSize\">\n            <size>\n             <width>40</width>\n             <height>16777215</height>\n            </size>\n           </property>\n           <property name=\"text\">\n            <string>00.0</string>\n           </property>\n           <property name=\"alignment\">\n            <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>\n           </property>\n          </widget>\n         </item>\n         <item row=\"3\" column=\"0\">\n          <widget class=\"QLabel\" name=\"label_6\">\n           <property name=\"text\">\n            <string>Floor Gap</string>\n           </property>\n          </widget>\n         </item>\n         <item row=\"3\" column=\"2\">\n          <widget class=\"QSlider\" name=\"floor_gap_slide\">\n           <property name=\"maximum\">\n            <number>100</number>\n           </property>\n           <property name=\"orientation\">\n            <enum>Qt::Horizontal</enum>\n           </property>\n          </widget>\n         </item>\n         <item row=\"3\" column=\"3\">\n          <widget class=\"QLabel\" name=\"floor_gap_text\">\n           <property name=\"text\">\n            <string>0.0</string>\n           </property>\n           <property name=\"alignment\">\n            <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>\n           </property>\n          </widget>\n         </item>\n        </layout>\n       </widget>\n      </item>\n     </layout>\n    </item>\n    <item>\n     <layout class=\"QHBoxLayout\" name=\"horizontalLayout_3\">\n      <property name=\"spacing\">\n       <number>40</number>\n      </property>\n      <property name=\"leftMargin\">\n       <number>10</number>\n      </property>\n      <property name=\"topMargin\">\n       <number>10</number>\n      </property>\n      <property name=\"rightMargin\">\n       <number>10</number>\n      </property>\n      <property name=\"bottomMargin\">\n       <number>10</number>\n      </property>\n      <item>\n       <widget class=\"QPushButton\" name=\"next_pose\">\n        <property name=\"enabled\">\n         <bool>true</bool>\n        </property>\n        <property name=\"sizePolicy\">\n         <sizepolicy hsizetype=\"Minimum\" vsizetype=\"Expanding\">\n          <horstretch>0</horstretch>\n          <verstretch>0</verstretch>\n         </sizepolicy>\n        </property>\n        <property name=\"text\">\n         <string>Next Pose</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QPushButton\" name=\"quick_next_pose\">\n        <property name=\"sizePolicy\">\n         <sizepolicy hsizetype=\"Minimum\" vsizetype=\"Expanding\">\n          <horstretch>0</horstretch>\n          <verstretch>0</verstretch>\n         </sizepolicy>\n        </property>\n        <property name=\"text\">\n         <string>Quick Next</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QPushButton\" name=\"delete_pose\">\n        <property name=\"enabled\">\n         <bool>true</bool>\n        </property>\n        <property name=\"sizePolicy\">\n         <sizepolicy hsizetype=\"Minimum\" vsizetype=\"Expanding\">\n          <horstretch>0</horstretch>\n          <verstretch>0</verstretch>\n         </sizepolicy>\n        </property>\n        <property name=\"text\">\n         <string>Delete Pose</string>\n        </property>\n       </widget>\n      </item>\n      <item>\n       <widget class=\"QPushButton\" name=\"calibrate\">\n        <property name=\"enabled\">\n         <bool>true</bool>\n        </property>\n        <property name=\"sizePolicy\">\n         <sizepolicy hsizetype=\"Minimum\" vsizetype=\"Expanding\">\n          <horstretch>0</horstretch>\n          <verstretch>0</verstretch>\n         </sizepolicy>\n        </property>\n        <property name=\"minimumSize\">\n         <size>\n          <width>0</width>\n          <height>0</height>\n         </size>\n        </property>\n        <property name=\"text\">\n         <string>Calibrate</string>\n        </property>\n       </widget>\n      </item>\n     </layout>\n    </item>\n   </layout>\n  </widget>\n  <widget class=\"QToolBar\" name=\"toolBar\">\n   <property name=\"windowTitle\">\n    <string>toolBar</string>\n   </property>\n   <property name=\"styleSheet\">\n    <string notr=\"true\"/>\n   </property>\n   <attribute name=\"toolBarArea\">\n    <enum>TopToolBarArea</enum>\n   </attribute>\n   <attribute name=\"toolBarBreak\">\n    <bool>false</bool>\n   </attribute>\n   <addaction name=\"actionSave_Config\"/>\n   <addaction name=\"actionSave_Result\"/>\n   <addaction name=\"actionSet_K\"/>\n   <addaction name=\"actionSet_D\"/>\n   <addaction name=\"actionOpen_Dataset\"/>\n  </widget>\n  <action name=\"actionSave_Config\">\n   <property name=\"text\">\n    <string>Save Config</string>\n   </property>\n   <property name=\"toolTip\">\n    <string>save result and config to files</string>\n   </property>\n   <property name=\"shortcut\">\n    <string>Ctrl+S</string>\n   </property>\n  </action>\n  <action name=\"actionSet_K\">\n   <property name=\"text\">\n    <string>Set K</string>\n   </property>\n   <property name=\"toolTip\">\n    <string>set camera matrix</string>\n   </property>\n  </action>\n  <action name=\"actionSet_D\">\n   <property name=\"text\">\n    <string>Set D</string>\n   </property>\n   <property name=\"toolTip\">\n    <string>set distortion coefficients</string>\n   </property>\n  </action>\n  <action name=\"actionOpen_Dataset\">\n   <property name=\"text\">\n    <string>Open Dataset</string>\n   </property>\n   <property name=\"toolTip\">\n    <string>choose dataset directory</string>\n   </property>\n  </action>\n  <action name=\"actionSave_Result\">\n   <property name=\"text\">\n    <string>Save Result</string>\n   </property>\n   <property name=\"toolTip\">\n    <string>Save calibration result</string>\n   </property>\n  </action>\n </widget>\n <layoutdefault spacing=\"6\" margin=\"11\"/>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "PlyCal_qt/pointcloudviewer.cpp",
    "content": "#include \"pointcloudviewer.h\"\n#include \"ui_pointcloudviewer.h\"\n\n#include <QMenu>\n#include <QDebug>\n\n\nPointcloudViewer::PointcloudViewer(QWidget *parent) :\n    QMainWindow(parent),\n    ui(new Ui::PointcloudViewer)\n{\n    ui->setupUi(this);\n    setWindowFlags(Qt::Window\n                   | Qt::WindowMinimizeButtonHint\n                   | Qt::WindowMaximizeButtonHint);\n\n    viewer_ = std::unique_ptr<pcl::visualization::PCLVisualizer>(\n                  new pcl::visualization::PCLVisualizer(\"viewer\", false));\n    ui->qvtkWidget->SetRenderWindow(viewer_->getRenderWindow());\n    viewer_->setupInteractor(ui->qvtkWidget->GetInteractor(), ui->qvtkWidget->GetRenderWindow());\n    ui->qvtkWidget->update();\n\n    viewer_->resetCamera();\n    showCoordinateSystem(Eigen::Affine3f::Identity(), 0, 2);\n}\n\nPointcloudViewer::~PointcloudViewer()\n{\n    delete ui;\n}\n\n\n/**\n * @brief show(add/update) pointcloud in the viewer\n * @param [in] pc xyzrgb pointcloud pointer\n * @param [in] index pointcloud id\n */\nvoid PointcloudViewer::showPointcloud(pcl::PointCloud<pcl::PointXYZRGB>::Ptr pc, int index)\n{\n    std::string pc_name = std::string(\"cloud_\")+std::to_string(index);\n    if(cloud_names_.count(index))\n    {\n        // update\n        viewer_->updatePointCloud(pc, pc_name);\n    }\n    else\n    {\n        //add\n        cloud_names_.insert(index);\n        viewer_->addPointCloud(pc, pc_name);\n    }\n    ui->qvtkWidget->update();\n}\n\n\n/**\n * @brief show coordinate in the viewer\n * @param [in] tf    the coordinate transformation\n * @param [in] index the coordinate id\n * @param [in] scale the scale, default 1.0\n */\nvoid PointcloudViewer::showCoordinateSystem(const Eigen::Affine3f& tf, int index, double scale)\n{\n    std::string frame_name = std::string(\"frame_\") + std::to_string(index);\n    if(frame_names_.count(index))\n    {\n        viewer_->updateCoordinateSystemPose(frame_name, tf);\n    }\n    else\n    {\n        frame_names_.insert(index);\n        viewer_->addCoordinateSystem(scale, tf, frame_name);\n    }\n}\n\n\nvoid PointcloudViewer::contextMenuEvent(QContextMenuEvent *event)\n{\n    qDebug() << \"right click\";\n    QMenu menu(this);\n    menu.addAction(ui->actionSave_PointCloud);\n    menu.exec(event->globalPos());\n}\n\nvoid PointcloudViewer::on_actionSave_PointCloud_triggered()\n{\n    qDebug() << \"right click\";\n}\n"
  },
  {
    "path": "PlyCal_qt/pointcloudviewer.h",
    "content": "#ifndef POINTCLOUDVIEWER_H\n#define POINTCLOUDVIEWER_H\n\n#include <QMainWindow>\n#include <QContextMenuEvent>\n\n#include <set>\n\n#include <pcl/point_cloud.h>\n#include <pcl/point_types.h>\n#include <pcl/visualization/pcl_visualizer.h>\n\n#include <vtkRenderWindow.h>\n\nnamespace Ui {\nclass PointcloudViewer;\n}\n\nclass PointcloudViewer : public QMainWindow\n{\n    Q_OBJECT\n\npublic:\n    explicit PointcloudViewer(QWidget *parent = 0);\n    ~PointcloudViewer();\n\npublic slots:\n    void showPointcloud(pcl::PointCloud<pcl::PointXYZRGB>::Ptr pc, int index = 0);\n    void showCoordinateSystem(const Eigen::Affine3f& tf, int index, double scale=1.0);\n\nprotected:\n    void contextMenuEvent(QContextMenuEvent *event) override;\n\nprivate slots:\n    void on_actionSave_PointCloud_triggered();\n\nprivate:\n    Ui::PointcloudViewer *ui;\n    std::unique_ptr<pcl::visualization::PCLVisualizer> viewer_;\n    std::set<int> cloud_names_;\n    std::set<int> frame_names_;\n};\n\n#endif // POINTCLOUDVIEWER_H\n"
  },
  {
    "path": "PlyCal_qt/pointcloudviewer.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>PointcloudViewer</class>\n <widget class=\"QMainWindow\" name=\"PointcloudViewer\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>800</width>\n    <height>600</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>PointCloud Viewer</string>\n  </property>\n  <widget class=\"QWidget\" name=\"centralwidget\">\n   <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n    <property name=\"spacing\">\n     <number>0</number>\n    </property>\n    <property name=\"leftMargin\">\n     <number>0</number>\n    </property>\n    <property name=\"topMargin\">\n     <number>0</number>\n    </property>\n    <property name=\"rightMargin\">\n     <number>0</number>\n    </property>\n    <property name=\"bottomMargin\">\n     <number>0</number>\n    </property>\n    <item>\n     <widget class=\"QVTKWidget\" name=\"qvtkWidget\"/>\n    </item>\n   </layout>\n  </widget>\n  <action name=\"actionSave_PointCloud\">\n   <property name=\"text\">\n    <string>Save PointCloud</string>\n   </property>\n   <property name=\"toolTip\">\n    <string>save this pointcloud</string>\n   </property>\n  </action>\n </widget>\n <customwidgets>\n  <customwidget>\n   <class>QVTKWidget</class>\n   <extends>QWidget</extends>\n   <header>QVTKWidget.h</header>\n  </customwidget>\n </customwidgets>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "PlyCal_qt/tfwindow.cpp",
    "content": "#include \"tfwindow.h\"\n#include \"ui_tfwindow.h\"\n\n#include <Eigen/Geometry>\n\nstatic const double PI(3.141592653589793238462);\n\nTFwindow::TFwindow(const Eigen::Matrix4d& tf, QWidget *parent) :\n    QMainWindow(parent),\n    ui(new Ui::TFwindow)\n{\n    ui->setupUi(this);\n\n\tauto setWidget = [](double data, QSlider* sld, QLabel* lb)\n\t{\n\t\tint32_t val = static_cast<int32_t>(std::round(data*500+500));\n\t\tif (val <0 )\n\t\t{\n\t\t\tval = 0;\n\t\t}\n\t\tif(val > 1000)\n\t\t{\n\t\t\tval = 1000;\n\t\t}\n\t\tsld->setValue(val);\n        lb->setText(QString(\"%1\").arg((val-500.0)/500.0, 6, 'f',3,' '));\n\t};\n\n\tsetWidget(tf(0,3), ui->tx_slide, ui->tx_text);\n\tsetWidget(tf(1,3), ui->ty_slide, ui->ty_text);\n\tsetWidget(tf(2,3), ui->tz_slide, ui->tz_text);\n\n\t// xyz - euler\n\tEigen::Matrix3d rotation = tf.topLeftCorner(3,3);\n\t// [0:pi]x[-pi:pi]x[-pi:pi]\n\tEigen::Vector3d angle = rotation.eulerAngles(0, 1, 2)/PI*180;\n\tEigen::Vector3i r = angle.cast<int>();\n\n\tuint16_t v = r(0) <0 ? 0 : (r(0)>180? 180: r(0));\n\tui->rx_slide->setValue( v );\n\tui->rx_text->setText( QString::number(v) );\n\n\tv = r(1) < -180 ? 0 : (r(1) > 180 ? 360 : r(1) +180);\n\tui->ry_slide->setValue( v );\n\tui->ry_text->setText( QString::number(r(1)) );\n\n\tv = r(2) < -180 ? 0 : (r(2) > 180 ? 360 : r(2) +180);\n    ui->rz_slide->setValue( v );\n    ui->rz_text->setText( QString::number(r(2)) );\n\n\n    connect(ui->rx_slide, &QSlider::valueChanged, this, &TFwindow::process);\n    connect(ui->ry_slide, &QSlider::valueChanged, this, &TFwindow::process);\n    connect(ui->rz_slide, &QSlider::valueChanged, this, &TFwindow::process);\n    connect(ui->tx_slide, &QSlider::valueChanged, this, &TFwindow::process);\n    connect(ui->ty_slide, &QSlider::valueChanged, this, &TFwindow::process);\n    connect(ui->tz_slide, &QSlider::valueChanged, this, &TFwindow::process);\n}\n\nTFwindow::~TFwindow()\n{\n    delete ui;\n}\n\nvoid TFwindow::process()\n{\n    Eigen::Matrix4d tf;\n    tf.setIdentity();\n    tf(0,3) = (ui->tx_slide->value() - 500)/500.0;\n    ui->tx_text->setText(QString::number(tf(0,3)));\n    tf(1,3) = (ui->ty_slide->value() - 500)/500.0;\n    ui->ty_text->setText(QString::number(tf(1,3)));\n    tf(2,3) = (ui->tz_slide->value() - 500)/500.0;\n    ui->tz_text->setText(QString::number(tf(2,3)));\n\n    ui->rx_text->setText(QString::number(ui->rx_slide->value()));\n    double rx = ui->rx_slide->value()/180.0*PI;\n    ui->ry_text->setText(QString::number(ui->ry_slide->value()-180));\n    double ry = (ui->ry_slide->value()-180.0)/180.0*PI;\n    ui->rz_text->setText(QString::number(ui->rz_slide->value()-180));\n    double rz = (ui->rz_slide->value()-180.0)/180.0*PI;\n\n    Eigen::Quaterniond ag =  Eigen::AngleAxisd(rx,  Eigen::Vector3d::UnitX())\n                             *  Eigen::AngleAxisd(ry,  Eigen::Vector3d::UnitY())\n                             *  Eigen::AngleAxisd(rz,  Eigen::Vector3d::UnitZ());\n    tf.topLeftCorner(3,3) = ag.matrix();\n    tf.row(3) << 0,0,0,1;\n\n    emit newTransformation(tf);\n}\n\n\nvoid TFwindow::closeEvent(QCloseEvent *event)\n{\n    emit tfwindowClose();\n    event->accept();\n}\n"
  },
  {
    "path": "PlyCal_qt/tfwindow.h",
    "content": "#ifndef TFWINDIOW_H\n#define TFWINDIOW_H\n\n#include <QMainWindow>\n#include <QCloseEvent>\n\n#include <Eigen/Dense>\n\nnamespace Ui {\nclass TFwindow;\n}\n\nclass TFwindow : public QMainWindow\n{\n    Q_OBJECT\n\npublic:\n    explicit TFwindow(const Eigen::Matrix4d& tf, QWidget *parent = 0);\n    ~TFwindow();\n\nsignals:\n    void newTransformation(Eigen::Matrix4d tf);\n//    void newTransformation();\n    void tfwindowClose();\n\nprotected:\n    void closeEvent(QCloseEvent *event) override;\n\nprivate:\n    Ui::TFwindow *ui;\n\nprivate slots:\n\tvoid process();\n\n};\n\n#endif // TFWINDIOW_H\n"
  },
  {
    "path": "PlyCal_qt/tfwindow.ui",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<ui version=\"4.0\">\n <class>TFwindow</class>\n <widget class=\"QMainWindow\" name=\"TFwindow\">\n  <property name=\"geometry\">\n   <rect>\n    <x>0</x>\n    <y>0</y>\n    <width>796</width>\n    <height>399</height>\n   </rect>\n  </property>\n  <property name=\"windowTitle\">\n   <string>MainWindow</string>\n  </property>\n  <widget class=\"QWidget\" name=\"centralwidget\">\n   <layout class=\"QVBoxLayout\" name=\"verticalLayout\">\n    <item>\n     <widget class=\"QGroupBox\" name=\"groupBox\">\n      <property name=\"title\">\n       <string>Rotation</string>\n      </property>\n      <layout class=\"QGridLayout\" name=\"gridLayout\">\n       <item row=\"0\" column=\"0\">\n        <widget class=\"QLabel\" name=\"label\">\n         <property name=\"text\">\n          <string>X</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"0\" column=\"1\">\n        <widget class=\"QSlider\" name=\"rx_slide\">\n         <property name=\"maximum\">\n          <number>180</number>\n         </property>\n         <property name=\"orientation\">\n          <enum>Qt::Horizontal</enum>\n         </property>\n        </widget>\n       </item>\n       <item row=\"0\" column=\"2\">\n        <widget class=\"QLabel\" name=\"rx_text\">\n         <property name=\"text\">\n          <string>000</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"1\" column=\"0\">\n        <widget class=\"QLabel\" name=\"label_3\">\n         <property name=\"text\">\n          <string>Y</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"1\" column=\"1\">\n        <widget class=\"QSlider\" name=\"ry_slide\">\n         <property name=\"maximum\">\n          <number>360</number>\n         </property>\n         <property name=\"orientation\">\n          <enum>Qt::Horizontal</enum>\n         </property>\n        </widget>\n       </item>\n       <item row=\"1\" column=\"2\">\n        <widget class=\"QLabel\" name=\"ry_text\">\n         <property name=\"text\">\n          <string>000</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"2\" column=\"0\">\n        <widget class=\"QLabel\" name=\"label_5\">\n         <property name=\"text\">\n          <string>Z</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"2\" column=\"1\">\n        <widget class=\"QSlider\" name=\"rz_slide\">\n         <property name=\"maximum\">\n          <number>360</number>\n         </property>\n         <property name=\"orientation\">\n          <enum>Qt::Horizontal</enum>\n         </property>\n        </widget>\n       </item>\n       <item row=\"2\" column=\"2\">\n        <widget class=\"QLabel\" name=\"rz_text\">\n         <property name=\"text\">\n          <string>000</string>\n         </property>\n        </widget>\n       </item>\n      </layout>\n     </widget>\n    </item>\n    <item>\n     <widget class=\"QGroupBox\" name=\"groupBox_2\">\n      <property name=\"title\">\n       <string>Translation</string>\n      </property>\n      <layout class=\"QGridLayout\" name=\"gridLayout_2\">\n       <item row=\"0\" column=\"0\">\n        <widget class=\"QLabel\" name=\"label_7\">\n         <property name=\"text\">\n          <string>X</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"0\" column=\"1\">\n        <widget class=\"QSlider\" name=\"tx_slide\">\n         <property name=\"maximum\">\n          <number>1000</number>\n         </property>\n         <property name=\"orientation\">\n          <enum>Qt::Horizontal</enum>\n         </property>\n        </widget>\n       </item>\n       <item row=\"0\" column=\"2\">\n        <widget class=\"QLabel\" name=\"tx_text\">\n         <property name=\"text\">\n          <string>000</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"1\" column=\"0\">\n        <widget class=\"QLabel\" name=\"label_9\">\n         <property name=\"text\">\n          <string>Y</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"1\" column=\"1\">\n        <widget class=\"QSlider\" name=\"ty_slide\">\n         <property name=\"maximum\">\n          <number>1000</number>\n         </property>\n         <property name=\"orientation\">\n          <enum>Qt::Horizontal</enum>\n         </property>\n        </widget>\n       </item>\n       <item row=\"1\" column=\"2\">\n        <widget class=\"QLabel\" name=\"ty_text\">\n         <property name=\"text\">\n          <string>000</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"2\" column=\"0\">\n        <widget class=\"QLabel\" name=\"label_11\">\n         <property name=\"text\">\n          <string>Z</string>\n         </property>\n        </widget>\n       </item>\n       <item row=\"2\" column=\"1\">\n        <widget class=\"QSlider\" name=\"tz_slide\">\n         <property name=\"maximum\">\n          <number>1000</number>\n         </property>\n         <property name=\"orientation\">\n          <enum>Qt::Horizontal</enum>\n         </property>\n        </widget>\n       </item>\n       <item row=\"2\" column=\"2\">\n        <widget class=\"QLabel\" name=\"tz_text\">\n         <property name=\"text\">\n          <string>000</string>\n         </property>\n        </widget>\n       </item>\n      </layout>\n     </widget>\n    </item>\n   </layout>\n  </widget>\n </widget>\n <resources/>\n <connections/>\n</ui>\n"
  },
  {
    "path": "PlyCal_test/CMakeLists.txt",
    "content": "if( CMAKE_BUILD_TYPE EQUAL \"Release\")\n\tadd_definitions( -DNODEBUG )\nendif(CMAKE_BUILD_TYPE EQUAL \"Release\")\n\n\nadd_executable(\n\ttest_image_polygon\n\ttest_image_polygon.cpp\n\t)\ntarget_link_libraries(\n\ttest_image_polygon\n\tplycal\n\t)\n\nadd_executable(\n\ttest_image_polygons\n\ttest_image_polygons.cpp\n\t)\ntarget_link_libraries(\n\ttest_image_polygons\n\tplycal\n\t)\n\nadd_executable(\n\ttest_pointcloud_polygon\n\ttest_pointcloud_polygon.cpp\n\t)\ntarget_link_libraries(\n\ttest_pointcloud_polygon\n\tplycal\n\t)\n\n\n"
  },
  {
    "path": "PlyCal_test/test_image_polygon.cpp",
    "content": "/**\n  ******************************************************************************\n  * @file\ttest_imagepolygon.cpp\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-25\n  * @brief\ttest_imagepolygon.cpp\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Includes ------------------------------------------------------------------*/\n#include \"image_polygon.h\"\n\n#include <iostream>\n#include <fstream>\n\n#include <Eigen/Dense>\n\n/* Private typedef -----------------------------------------------------------*/\n/* Private define ------------------------------------------------------------*/\n/* Private macro -------------------------------------------------------------*/\n/* Private variables ---------------------------------------------------------*/\n/* Private function prototypes -----------------------------------------------*/\n/* Private functions ---------------------------------------------------------*/\n\n/* Exported functions --------------------------------------------------------*/\n\n/**\n  * @brief\n  * @param\n  * @note\n  * @return None\n  */\nint main(int argc, char** argv)\n{\n\tstd::string config_path, img_path;\n\n\tif(argc >= 3)\n\t{\n\t\tconfig_path = std::string(argv[1]);\n\t\timg_path = std::string(argv[2]);\n\t}\n\telse\n\t{\n\t\tstd::cerr << \"Usage: \" << argv[0] << \" config_path image_path\"\n\t\t\t\t  << std::endl;\n\t\treturn 1;\n\t}\n\n\n\tstd::cout << \"----------------------------------------\"<< std::endl\n\t\t\t  << \"config path: \" << config_path << std::endl\n\t\t\t  << \"image  path: \" << img_path << std::endl\n\t\t\t  << \"----------------------------------------\" << std::endl;\n\n\t// parse config file\n\tstd::ifstream f (config_path);\n\tif ( !f.good() )\n\t{\n\t\tstd::cerr << \"[ERROR]\\tconfig file doesn't exist\" << std::endl;\n\t\treturn 2;\n\t}\n\n\tstd::string content{ std::istreambuf_iterator<char>(f),\n\t\t\t\t\t\t std::istreambuf_iterator<char>()  };\n\tf.close();\n\n\tauto js= nlohmann::json::parse(content);\n\tauto& corners = js[\"img\"][\"init\"];\n\tEigen::Matrix3Xd points;\n\tpoints.resize(3,4);\n\tpoints.row(2).setOnes();\n\n\tfor(uint8_t i=0; i<4; i++)\n\t{\n\t\tpoints(0,i) = corners[i][0].get<double>();\n\t\tpoints(1,i) = corners[i][1].get<double>();\n\t}\n\n    cv::Mat img = cv::imread(img_path, cv::IMREAD_COLOR);\n\tcv::Mat img_out;\n\n\tlqh::ImagePolygon cvx(js[\"img\"], 4);\n\tcvx.Init(img, img_out, points);\n\tlqh::ImagePolygon::Polygon2D::ConstPtr ply = cvx.Add(img, img_out);\n\tcvx.SaveMarkedImage(\"ExtractPolygon.jpg\", img, ply);\n\n\tstd::cout << \"-----------------END----------------\\n\";\n\n\treturn 0;\n}\n\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "PlyCal_test/test_image_polygons.cpp",
    "content": "/**\n  ******************************************************************************\n  * @file\ttest_image_polygons.cpp\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2018-01-02\n  * @brief\ttest_image_polygons.cpp\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2018 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Includes ------------------------------------------------------------------*/\n#include \"image_polygon.h\"\n\n#include <fstream>\n\n#include <Eigen/Dense>\n\n\n/* Private typedef -----------------------------------------------------------*/\n/* Private define ------------------------------------------------------------*/\n/* Private macro -------------------------------------------------------------*/\n/* Private variables ---------------------------------------------------------*/\n/* Private function prototypes -----------------------------------------------*/\n/* Private functions ---------------------------------------------------------*/\n\n/* Exported functions --------------------------------------------------------*/\n\n/**\n  * @brief\n  * @param\n  * @note\n  * @return None\n  */\nint main(int argc, char** argv)\n{\n\tstd::string config_path, img_root_path;\n\tuint32_t num = 0;\n\n\tif(argc >= 4)\n\t{\n\t\tconfig_path = std::string(argv[1]);\n\t\timg_root_path = std::string(argv[2]);\n\t\tnum = std::stoi(std::string(argv[3]));\n\t}\n\telse\n\t{\n\t\tstd::cerr << \"Usage: \" << argv[0] << \" config_path image_root_path image_num\"\n\t\t\t\t  << std::endl;\n\t\treturn 1;\n\t}\n\n\n\tstd::cout << \"\\n----------------------------------------\"\n\t\t\t  << \"\\nconfig path: \" << config_path\n\t\t\t  << \"\\nimage  path: \" << img_root_path\n\t\t\t  << \"\\nimage   num: \" << num\n\t\t\t  << \"\\n----------------------------------------\" << std::endl;\n\n\t// parse config file\n\tstd::ifstream f (config_path);\n\tif ( !f.good() )\n\t{\n\t\tstd::cerr << \"[ERROR]\\tconfig file doesn't exist\" << std::endl;\n\t\treturn 2;\n\t}\n\n\tstd::string content{ std::istreambuf_iterator<char>(f),\n\t\t\t\t\t\t std::istreambuf_iterator<char>()  };\n\tf.close();\n\n\tauto js= nlohmann::json::parse(content);\n\tauto& corners = js[\"img\"][\"init\"];\n\tEigen::Matrix3Xd points;\n\tpoints.resize(3,4);\n\tpoints.row(2).setOnes();\n\n\tfor(uint8_t i=0; i<4; i++)\n\t{\n\t\tpoints(0,i) = corners[i][0].get<double>();\n\t\tpoints(1,i) = corners[i][1].get<double>();\n\t}\n\n\tstd::string img_path = img_root_path + \"/0.jpeg\";\n\n\tcv::Mat img = cv::imread(img_path, cv::IMREAD_COLOR);\n\tcv::Mat img_out;\n\n\tlqh::ImagePolygon cvx(js[\"img\"], 4);\n\tcvx.Init(img, img_out, points);\n\n\n\tfor(uint32_t i=0; i<num; i++)\n\t{\n\t\tstd::cout << \"Process: \" << i << \"\\n\";\n\t\timg_path = img_root_path + \"/\" + std::to_string(i) + \".jpeg\";\n\t\tstd::string fn_out =  std::to_string(i) + \".png\";\n\n\t\tcv::Mat img = cv::imread(img_path, cv::IMREAD_COLOR);\n\t\tlqh::ImagePolygon::Polygon2D::ConstPtr ply = cvx.Add(img, img_out);\n\t\tif(ply != nullptr)\n\t\t{\n\t\t\tcvx.SaveMarkedImage(fn_out, img, ply);\n\t\t\tstd::cout << \"-------------OK\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"-------------Fail\\n\";\n\t\t}\n\t}\n\n\tstd::cout << \"-----------------END----------------\\n\";\n\n\treturn 0;\n}\n\n\n\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "PlyCal_test/test_pointcloud_polygon.cpp",
    "content": "/**\n  ******************************************************************************\n  * @file\ttest_pointcloud_polygon.cpp\n  * @author\tNick.Liao\n  * @version V1.0.0\n  * @date\t2017-12-26\n  * @brief\ttest_pointcloud_polygon.cpp\n  ******************************************************************************\n  * @attention\n  *\n  * Copyright (C) 2017 Nick.Liao <simplelife_nick@hotmail.com>\n  * Distributed under terms of the MIT license.\n  ******************************************************************************\n  */\n\n/* Includes ------------------------------------------------------------------*/\n#include <string>\n#include <iostream>\n#include <fstream>\n\n\n#include <pcl/point_types.h>\n#include <pcl/point_cloud.h>\n#include <pcl/io/pcd_io.h>\n\n#include \"json/json.hpp\"\n#include \"pointcloud_polygon.h\"\n\n/* Private typedef -----------------------------------------------------------*/\n/* Private define ------------------------------------------------------------*/\n/* Private macro -------------------------------------------------------------*/\n/* Private variables ---------------------------------------------------------*/\n/* Private function prototypes -----------------------------------------------*/\n/* Private functions ---------------------------------------------------------*/\n\n/* Exported functions --------------------------------------------------------*/\n\n/**\n  * @brief\n  * @param\n  * @note\n  * @return None\n  */\nint main(int argc, char** argv)\n{\n\tstd::string config_path, pc_path;\n\tstd::string edge_prefix;\n\n\tif(argc >= 3)\n\t{\n\t\tconfig_path = std::string(argv[1]);\n\t\tpc_path = std::string(argv[2]);\n\t\tedge_prefix = std::string(argv[3]);\n\t}\n\telse\n\t{\n\t\tstd::cerr << \"Usage: \" << argv[0] << \" config_path pointlcoud_path\"\n\t\t\t\t  << std::endl;\n\t\treturn 1;\n\t}\n\n\n\tstd::cout << \"----------------------------------------\"<< std::endl\n\t\t\t  << \"config      path: \" << config_path << std::endl\n\t\t\t  << \"pointcloud  path: \" << pc_path << std::endl\n\t\t\t  << \"----------------------------------------\" << std::endl;\n\n\t// parse config file\n\tstd::ifstream f (config_path);\n\tif ( !f.good() )\n\t{\n\t\tstd::cerr << \"[ERROR]\\tconfig file doesn't exist\" << std::endl;\n\t\treturn 2;\n\t}\n\n\tstd::string content{ std::istreambuf_iterator<char>(f),\n\t\t\t\t\t\t std::istreambuf_iterator<char>()  };\n\tf.close();\n\n\tauto js= nlohmann::json::parse(content);\n\tpcl::PointCloud<pcl::PointXYZI> pc;\n\tpcl::PointCloud<pcl::PointXYZRGB> pcc;\n\tif(pcl::io::loadPCDFile(pc_path, pc) == -1)\n\t{\n\t\tstd::cerr << \"[ERROR]\\tfail to read pointcoud\" << std::endl;\n\t\treturn 3;\n\t}\n\n\tlqh::PointcloudPolygon pp(js[\"pc\"], 4);\n\tpp.Add(pc, pcc);\n\tpp.SaveEdgePoints(edge_prefix);\n\n\tstd::cout << \"-----------------END----------------\\n\";\n\n\treturn 0;\n}\n\n\n\n/*****************************END OF FILE**************************************/\n"
  },
  {
    "path": "README.md",
    "content": "# Extrinsic Calibration of the camera and LiDAR via polygon plane\nThis project includes the extrinsic calibration library and gui tool for calibrating the extrinsic parameter(6-DoF rigid-body transformation) between the camera and LiDAR. This method needs convex polygon plane as calibration object and the camera intrinsic parameter(K, D) are needed (if images are not undistorted).  \n\n*note: current implemention only support rectangular plane*\n\n## Dependency list\n- [pcl](http://pointclouds.org/) \n- [ceres](http://ceres-solver.org/)\n- Eigen 3\n- VTK\n- Qt 5 (system)\n\n## Build\nwe test on `Ubuntu 16.04`, if you already install ros kinect and then you only need to compile and install ceres-solver. \n```sh\n$ mkdir build& cd build\n$ cmake .. \t\t\t\t\t\t\t# build library and QT GUI\n$ cmake -DBUILD_PlyCal_TEST=True ..\t#build test tools(only for debug usage)\n$ make\n```\n\n\n## Test\nWe have tested the current qt-based tool with RSLidar-16, RSlidar-32, Rslidar-mems by rectangular plane. And we provide test data and config file under `./data`directory which was collected with RSLidar-16 and usb webcam.\n\n## Usage  \n[中文使用说明](./doc/README.md)  \n\nBefore using the gui tool:\n1. Calibrate camera and put intrinsic parameter `D, K` at config file or set by gui.  \n2. Collect synced image(png,jpg,jpeg) and pointcloud (pcd), put them into `some_place/image_orig` and  `some_place/pointcloud` directory, respectively. Name the file like `0.jpg, 1.jpg, ..., n.jpg`.  \n![Demo](./doc/demo.gif) \n\n\n## Reference  \nFor the method you can read the paper:  \n```\n@INPROCEEDINGS{8665256, \nauthor={Q. {Liao} and Z. {Chen} and Y. {Liu} and Z. {Wang} and M. {Liu}}, \nbooktitle={2018 IEEE International Conference on Robotics and Biomimetics (ROBIO)}, \ntitle={Extrinsic Calibration of Lidar and Camera with Polygon}, \nyear={2018}, \nvolume={}, \nnumber={}, \npages={200-205}, \nkeywords={calibration;cameras;feature extraction;image fusion;image sensors;micromechanical devices;optical radar;sensor fusion;stereo image processing;heterogeneous exteroceptive sensors;heterogeneous sensory systems;multisensor information;polygon board;t6/32-beam Lidar;extrinsic calibration;MEMS-Lidar;point-cloud;laser range finder;2D feature space;3D feature space;Calibration;Cameras;Laser radar;Three-dimensional displays;Sensors;Image edge detection;Two dimensional displays}, \ndoi={10.1109/ROBIO.2018.8665256}, \nISSN={}, \nmonth={Dec},}\n```"
  },
  {
    "path": "data/config.json",
    "content": "{\n    \"cam\": {\n        \"D\": [\n            -0.343338393354793,\n            0.0806974339575093,\n            -0.000525540233605921,\n            0.00260712954510535,\n            0.0\n        ],\n        \"K\": [\n            [\n                1085.87150849092,\n                0.0,\n                967.618455232044\n            ],\n            [\n                0.0,\n                1085.71794017434,\n                512.798695326787\n            ],\n            [\n                0.0,\n                0.0,\n                1.0\n            ]\n        ]\n    },\n    \"img\": {\n        \"edlines\": {\n            \"anchorThreshold\": 10,\n            \"gradientThreshold\": 80,\n            \"ksize\": 3,\n            \"lineFitErrThreshold\": 2,\n            \"minLineLen\": 30,\n            \"scanIntervals\": 1,\n            \"sigma\": 1\n        },\n        \"feature\": {\n            \"offset\": 3,\n            \"size\": 8,\n            \"threshold\": 0.8\n        },\n        \"filter\": {\n            \"line_angle_threshold\": 8,\n            \"point_center_factor\": 0.4,\n            \"point_line_threshold\": 80\n        },\n        \"init\": [\n            [\n                1200.8,\n                273.6\n            ],\n            [\n                1509.6,\n                420.0\n            ],\n            [\n                1589.6,\n                775.2\n            ],\n            [\n                888.0,\n                645.6\n            ]\n        ],\n        \"merge\": {\n            \"angle_threshold\": 2,\n            \"distance_threshold\": 35,\n            \"endpoint_distance_threshold\": 80\n        }\n    },\n    \"pc\": {\n        \"angle_resolution\": 1.5,\n        \"edge\": {\n            \"distance_threshold\": 0.05,\n            \"point_num_min\": 5\n        },\n        \"filter\": {\n            \"angle_size\": 73.0,\n            \"angle_start\": 327.0,\n            \"distance\": 5.3,\n            \"floor_gap\": 1.2\n        },\n        \"plane\": {\n            \"distance_threshold\": 0.06,\n            \"point_num_min\": 20\n        },\n        \"ring\": {\n            \"endpoint_num\": 2,\n            \"point_num_min\": 7\n        }\n    },\n    \"size\": 4,\n    \"tf\": [\n        [\n            -0.0587731866433256,\n            -0.997313988353226,\n            0.0437095088827632,\n            0.0584119503362388\n        ],\n        [\n            0.0680705634344673,\n            -0.0476870940689982,\n            -0.996540184565063,\n            -0.104226321432097\n        ],\n        [\n            0.995947845484644,\n            -0.0555945113679224,\n            0.0706904475884742,\n            0.0\n        ],\n        [\n            0.0,\n            0.0,\n            0.0,\n            1.0\n        ]\n    ],\n    \"track_error_threshold\": 30\n}"
  },
  {
    "path": "doc/README.md",
    "content": "# PlyCal\n> LIAO Qinghai  2019.2.25\n\n[for English Version click here](#english-version)\n\n\n本程序只实现了利用四边形板校准，暂未实现利用任意polygon的校准。  \n\n## 准备  \n如example文件夹所示，使用本软件需要一个config.json文件和图像、点云对应的文件。  \nconfig.json：参考example/config.json，正常只需要修改其中相机的K、D。此文件路径无要求  \ndataset：dataset指example下的`image_orig`和`pointcloud`，这两个文件夹名称不可以更改且必须在同一文件夹下。`image_orig`内需要有N(N>=4)张未反畸变的图片，`pointcloud`中有N份对应的pcd点云文件，二者应该时间上已经对应同步。  \n\n## 操作  \n1. 打卡config文件。在终端启动./PlyCal-qt后会直接进入config.json文件的选择。 \n2. 打开dataset。如下图为主界面，点击`Open Dataset`选择保护`image_orig`和`pointcloud`的文件夹。主界面会显示总的数据帧数。  \n![main](./main.png)\n\n3. 手动调整初值。打开dataset后主界面会隐藏，出现如下的调整初值的界面和一个显示点云的窗口、一个显示图像的窗口（此时点云会投影到图像、图像颜色也会投影到点云）。再下图的界面中手工条件rotation、translation且观察图像界面中的点云深度投影，OK是关掉下界面即可。\n![init](./init.png)\n4. 手动条件polygon。返回主界面后，目前还不能第一次在点云和图像中都直接检测出四边形。对于图像，可以先点击`Start Selection`，然后鼠标在图片窗口中点击目标四边形的四个角点，完成后点击`Finish Selection`，正常检测结果如下图。对于点云，使用`Pointcloud Control`下的四个sliderbar来切割点云，缩小检测的范围，正常结果如下。\n\n![img](./img.jpg)\n![pc](./pc.png)\n\n5. 检测。第一帧手动调整结束后，可以使用`Next Pose`来一帧一帧的处理下一帧，或者使用`Quick`快速处理，当数据检测结果不好时可以回到步骤4手动调整或者`Delete`\n6. 校准。点击`Calibrate`调用校准优化，结果在终端有打印，也可以点击`Save Result`。config文件此时也可以保存（会覆写之前的config）。\n\n# English Version\n(Translated with AI): \nThis program only implements calibration with quadrilateral plates, not with any polygon for the moment.\n\n## Intend\nAs shown in the example folder, to use this software you need a config.json file and the corresponding files for the image and point cloud.\nconfig.json: refer to example/config.json, normally you only need to change the K and D of the camera in it, there is no requirement for the path of this file.\ndataset: dataset refers to image_orig and pointcloud under example, the name of these two folders can not be changed and must be in the same folder. image_orig needs to have N (N>=4) undistorted images in it, and there are N corresponding pcd pointcloud files in pointcloud, the two should be synchronised in time. be synchronised in time.\n\n## Manipulate\n1. Punch the config file. In the terminal launching . /PlyCal-qt will take you directly to the config.json file selection.\n\n2. Open dataset. as shown below for the main interface, click Open Dataset to select the folder protecting image_orig and pointcloud. The main interface will show the total number of data frames.\n![main](./main.png)\n\n3. Adjust the initial value manually. After opening dataset, the main interface will be hidden, and the following interface for adjusting the initial value will appear, together with a window for displaying the point cloud and a window for displaying the image (at this time, the point cloud will be projected to the image, and the image colour will also be projected to the point cloud). In the following interface, manually set the conditions of rotation and translation and observe the depth projection of the point cloud in the image interface, and then close the following interface.\n![init](./init.png)\n\n4. After returning to the main interface, it is not yet possible to detect the quadrilateral directly in both point cloud and image for the first time (for now?). For the image, you can click Start Selection first, then click the four corner points of the target quadrilateral in the image window, and then click Finish Selection when you are done, the normal detection result is as below. For point cloud, use the four sliderbar under Pointcloud Control to cut the point cloud and narrow the detection range, the normal results are as follows.\n\n![img](./img.jpg)\n![pc](./pc.png)\n\n5. Detection. After the first frame is manually adjusted, you can use Next Pose to process the next frame one by one, or use Quick Quick Processing, when the data detection result is not good you can go back to step 4 to manually adjust or Delete.\n6. Calibrate. Click Calibrate to call calibration optimisation, the result will be printed in the terminal, you can also click Save Result. config file can also be saved at this time (will overwrite the previous config).\n"
  },
  {
    "path": "thirdParty/edlines/EDLineDetector.cpp",
    "content": "/*IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\n By downloading, copying, installing or using the software you agree to this license.\n If you do not agree to this license, do not download, install,\n copy or use the software.\n\n\n                          License Agreement\n               For Open Source Computer Vision Library\n\nCopyright (C) 2011-2012, Lilian Zhang, all rights reserved.\nCopyright (C) 2013, Manuele Tamburrano, Stefano Fabri, all rights reserved.\nThird party copyrights are property of their respective owners.\n\nTo extract edge and lines, this library implements the EDLines Algorithm and the Edge Drawing detector:\nhttp://www.sciencedirect.com/science/article/pii/S0167865511001772\nhttp://www.sciencedirect.com/science/article/pii/S1047320312000831\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n  * Redistributions of source code must retain the above copyright notice,\n    this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright notice,\n    this list of conditions and the following disclaimer in the documentation\n    and/or other materials provided with the distribution.\n\n  * The name of the copyright holders may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\nThis software is provided by the copyright holders and contributors \"as is\" and\nany express or implied warranties, including, but not limited to, the implied\nwarranties of merchantability and fitness for a particular purpose are disclaimed.\nIn no event shall the Intel Corporation or contributors be liable for any direct,\nindirect, incidental, special, exemplary, or consequential damages\n(including, but not limited to, procurement of substitute goods or services;\nloss of use, data, or profits; or business interruption) however caused\nand on any theory of liability, whether in contract, strict liability,\nor tort (including negligence or otherwise) arising in any way out of\nthe use of this software, even if advised of the possibility of such damage.\n*/\n\n\n#include \"EDLineDetector.h\"\n\n#include <fstream>\n\n//#define DEBUG_EDLINE\n\n#ifdef DEBUG_EDLINE\n\t#include <sys/stat.h>\n\t#include <sys/types.h>\n\t#include <ctime>\n\t#include <sys/errno.h>\n\n\tstatic std::string DEBUG_FOLDER;\n#endif\n\n#define Horizontal  255//if |dx|<|dy|;\n#define Vertical    0//if |dy|<=|dx|;\n#define UpDir       1\n#define RightDir    2\n#define DownDir     3\n#define LeftDir     4\n#define TryTime     6\n#define SkipEdgePoint 2\n\n\n\nusing namespace std;\n\nvoid writeMat(cv::Mat m, string name, int n)\n{\n\tstd::stringstream ss;\n\tstring s;\n\tss << n;\n\tss >> s;\n\tstring fileNameConf = name + s;\n\tcv::FileStorage fsConf(fileNameConf, cv::FileStorage::WRITE);\n\tfsConf << \"m\" << m;\n\tfsConf.release();\n}\n\n\n/**\n * @brief writeImage save cv::Mat to image(special for 32CV_32F data type)\n *\n * @param img  image to save\n * @param name image name\n */\nvoid writeImage(cv::Mat img, std::string name)\n{\n\tif(img.depth() == CV_32F)\n\t{\n\t\tdouble minVal, maxVal, alpha, beta;\n\t\tcv::minMaxLoc(img, &minVal, &maxVal);\n\t\tif(minVal >= maxVal)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\talpha = UINT16_MAX/(maxVal-minVal);\n\t\tbeta = -minVal*alpha;\n\t\tcv::Mat img8;\n\t\timg.convertTo(img8, CV_16UC1, alpha, beta);\n\t\tcv::imwrite(name, img8);\n\t}\n\telse\n\t{\n\t\tcv::imwrite(name, img);\n\t}\n}\n\n\nEDLineDetector::EDLineDetector()\n{\n\t//  cout<<\"Call EDLineDetector constructor function\"<<endl;\n\t//set parameters for line segment detection\n\tksize_ = 5;\n\tsigma_ = 1.0;\n\tgradienThreshold_ = 80; // ***** ORIGINAL WAS 25\n\tanchorThreshold_  = 2;//8\n\tscanIntervals_    = 2;//2\n\tminLineLen_       = 15;\n\tlineFitErrThreshold_ = 1.4;\n\tInitEDLine_();\n}\n\nEDLineDetector::EDLineDetector(EDLineParam param)\n{\n\t//set parameters for line segment detection\n\tksize_ = param.ksize;\n\tsigma_ = param.sigma;\n\tgradienThreshold_ = param.gradientThreshold;\n\tanchorThreshold_  = param.anchorThreshold;\n\tscanIntervals_    = param.scanIntervals;\n\tminLineLen_       = param.minLineLen;\n\tlineFitErrThreshold_ = param.lineFitErrThreshold;\n\n\tInitEDLine_();\n}\n\nvoid EDLineDetector::InitEDLine_()\n{\n\n#ifdef DEBUG_EDLINE_LOG\n\tfs.open(\"edline_log.yml\", cv::FileStorage::WRITE);\n#endif\n\n\tbValidate_           = true;\n\tATA = cv::Mat_<int>(2, 2);\n\tATV = cv::Mat_<int>(1, 2);\n\ttempMatLineFit = cv::Mat_<int>(2, 2);\n\ttempVecLineFit = cv::Mat_<int>(1, 2);\n\tfitMatT = cv::Mat_<int>(2, minLineLen_);\n\tfitVec = cv::Mat_<int>(1, minLineLen_);\n\n\tfor (int i = 0; i < minLineLen_; i++)\n\t{\n\t\tfitMatT[1][i] = 1;\n\t}\n\n\tdxImg_.create( 1, 1, CV_32FC1 );\n\tdyImg_.create( 1, 1, CV_32FC1 );\n\tgImgWO_.create( 1, 1, CV_32FC1 );\n\tpFirstPartEdgeX_ = NULL;\n\tpFirstPartEdgeY_ = NULL;\n\tpFirstPartEdgeS_ = NULL;\n\tpSecondPartEdgeX_ = NULL;\n\tpSecondPartEdgeY_ = NULL;\n\tpSecondPartEdgeS_ = NULL;\n\tpAnchorX_ = NULL;\n\tpAnchorY_ = NULL;\n}\n\nEDLineDetector::~EDLineDetector()\n{\n\tif (pFirstPartEdgeX_ != NULL)\n\t{\n\t\tdelete [] pFirstPartEdgeX_;\n\t\tdelete [] pFirstPartEdgeY_;\n\t\tdelete [] pSecondPartEdgeX_;\n\t\tdelete [] pSecondPartEdgeY_;\n\t\tdelete [] pAnchorX_;\n\t\tdelete [] pAnchorY_;\n\t}\n\n\tif (pFirstPartEdgeS_ != NULL)\n\t{\n\t\tdelete [] pFirstPartEdgeS_;\n\t\tdelete [] pSecondPartEdgeS_;\n\t}\n\n\n}\n\nint EDLineDetector::EdgeDrawing(cv::Mat const &image, EdgeChains &edgeChains, bool smoothed )\n{\n\timageWidth = image.cols;\n\timageHeight = image.rows;\n\tunsigned int pixelNum = imageWidth * imageHeight;\n\n\tcv::Mat cImage = image.clone();\n\n\tif (!smoothed) //input image hasn't been smoothed.\n\t{\n\t\tcv::GaussianBlur(image, cImage, cv::Size(ksize_, ksize_), sigma_);\n\t}\n\n\t//Is this useful? Doesn't seem to have references\n\t//else{\n//\t\tunsigned char *pImage = image.GetImageData();\n//\t\tmemcpy(cvImage->data.ptr, pImage, pixelNum*sizeof(unsigned char));\n//\t}\n\n\tunsigned int edgePixelArraySize = pixelNum / 5;\n\tunsigned int maxNumOfEdge = edgePixelArraySize / 20;\n\t//compute dx, dy images\n\t//\n\tif (gImg_.cols != imageWidth || gImg_.rows != imageHeight)\n\t{\n\t\tif (pFirstPartEdgeX_ != NULL)\n\t\t{\n\t\t\tdelete [] pFirstPartEdgeX_;\n\t\t\tdelete [] pFirstPartEdgeY_;\n\t\t\tdelete [] pSecondPartEdgeX_;\n\t\t\tdelete [] pSecondPartEdgeY_;\n\t\t\tdelete [] pFirstPartEdgeS_;\n\t\t\tdelete [] pSecondPartEdgeS_;\n\t\t\tdelete [] pAnchorX_;\n\t\t\tdelete [] pAnchorY_;\n\t\t}\n\n\t\tdxImg_.create(imageHeight, imageWidth, CV_32FC1);\n\t\tdyImg_.create(imageHeight, imageWidth, CV_32FC1 );\n\t\tgImgWO_.create(imageHeight, imageWidth, CV_32FC1 );\n\t\tgImg_.create(imageHeight, imageWidth, CV_32FC1 );\n\t\tdirImg_.create(imageHeight, imageWidth, CV_8UC1 );\n\t\tedgeImage_.create(imageHeight, imageWidth, CV_8UC1 );\n\n\t\tpFirstPartEdgeX_ = new unsigned int[edgePixelArraySize];\n\t\tpFirstPartEdgeY_ = new unsigned int[edgePixelArraySize];\n\t\tpSecondPartEdgeX_ = new unsigned int[edgePixelArraySize];\n\t\tpSecondPartEdgeY_ = new unsigned int[edgePixelArraySize];\n\t\tpFirstPartEdgeS_ = new unsigned int[maxNumOfEdge];\n\t\tpSecondPartEdgeS_ = new unsigned int[maxNumOfEdge];\n\t\tpAnchorX_ = new unsigned int[edgePixelArraySize];\n\t\tpAnchorY_ = new unsigned int[edgePixelArraySize];\n\t}\n\n\tcv::Sobel( cImage, dxImg_, CV_32FC1, 1, 0, 3);\n\tcv::Sobel( cImage, dyImg_, CV_32FC1, 0, 1, 3);\n\n\t//compute gradient and direction images\n\n\tcv::Mat sumDxDy;\n\tdouble t = (double)cv::getTickCount();\n\n\tcv::Mat dxABS_m = cv::abs(dxImg_);\n\tcv::Mat dyABS_m = cv::abs(dyImg_);\n\tcv::add(dyABS_m, dxABS_m, sumDxDy);\n\tcv::threshold(sumDxDy, gImg_, gradienThreshold_ + 1, 0, cv::THRESH_TOZERO);\n\tgImg_ = gImg_ / 4;\n\tgImgWO_ = sumDxDy / 4;\n\tcv::compare(dxABS_m, dyABS_m, dirImg_, cv::CMP_LT);\n\n\n//\tcv::imwrite(\"sumDxDy.png\", sumDxDy);\n\n#ifdef DEBUG_EDLINE\n\tDEBUG_FOLDER = std::string(\"./\") + std::to_string(std::time(0));\n\tint status = mkdir(DEBUG_FOLDER.c_str(), 0777);\n\tif(!status)\n\t{\n//        cv::imshow(\"dxImg_\", dxImg_);\n//        cv::imshow(\"dyImg_\", dyImg_);\n//        cv::waitKey();\n\t\twriteImage(dxImg_, DEBUG_FOLDER+\"/dxImg.png\");\n\t\twriteImage(dyImg_, DEBUG_FOLDER+\"/dyImg.png\");\n\t\twriteImage(gImg_, DEBUG_FOLDER+\"/gImg.png\");\n\t\twriteImage(dirImg_, DEBUG_FOLDER+\"/dirImg.png\");\n\t}\n\telse\n\t{\n\t\tDEBUG_FOLDER.clear();\n\t\tstd::cerr << \"Fail to create folder: \" << DEBUG_FOLDER << std::endl\n\t\t\t\t  << \"Error No: \" << errno << std::endl\n\t\t\t\t  << strerror(errno) << std::endl;\n\t}\n#endif\n\n\tt = ((double)cv::getTickCount() - t) / cv::getTickFrequency();\n\t//std::cout << \"FOR ABS: \" << t << \"s\" << std::endl;\n\n\t//short *pdxImg = dxImg_.ptr<short>();\n\t//short *pdyImg = dyImg_.ptr<short>();\n\n\tfloat *pgImg  = gImg_.ptr<float>();\n\tfloat gValue1, gValue2, gValue3;\n\n\tunsigned char *pdirImg = dirImg_.ptr();\n\n\t//extract the anchors in the gradient image, store into a vector\n\tmemset(pAnchorX_,  0, edgePixelArraySize * sizeof(unsigned int)); //initialization\n\tmemset(pAnchorY_,  0, edgePixelArraySize * sizeof(unsigned int));\n\tunsigned int anchorsSize = 0;\n\tunsigned int indexInArray;\n\n\tfor (unsigned int w = 1; w < imageWidth - 1; w = w + scanIntervals_)\n\t{\n\t\tfor (unsigned int h = 1; h < imageHeight - 1; h = h + scanIntervals_)\n\t\t{\n\t\t\tindexInArray = h * imageWidth + w;\n\t\t\t//gValue1 = pdirImg[indexInArray];\n\t\t\tif (pdirImg[indexInArray] == Horizontal) //if the direction of pixel is horizontal, then compare with up and down\n\t\t\t{\n\t\t\t\t//gValue2 = pgImg[indexInArray];\n\t\t\t\tif (pgImg[indexInArray] >= pgImg[indexInArray - imageWidth] + anchorThreshold_\n\t\t\t\t\t\t&& pgImg[indexInArray] >= pgImg[indexInArray + imageWidth] + anchorThreshold_) // (w,h) is accepted as an anchor\n\t\t\t\t{\n\t\t\t\t\tpAnchorX_[anchorsSize]   = w;\n\t\t\t\t\tpAnchorY_[anchorsSize++] = h;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse  // if(pdirImg[indexInArray]==Vertical){//it is vertical edge, should be compared with left and right\n\t\t\t{\n\t\t\t\t//gValue2 = pgImg[indexInArray];\n\t\t\t\tif (pgImg[indexInArray] >= pgImg[indexInArray - 1] + anchorThreshold_\n\t\t\t\t\t\t&& pgImg[indexInArray] >= pgImg[indexInArray + 1] + anchorThreshold_) // (w,h) is accepted as an anchor\n\t\t\t\t{\n\t\t\t\t\tpAnchorX_[anchorsSize]   = w;\n\t\t\t\t\tpAnchorY_[anchorsSize++] = h;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (anchorsSize > edgePixelArraySize)\n\t{\n\t\tcout << \"anchor size is larger than its maximal size. anchorsSize=\" << anchorsSize\n\t\t\t << \", maximal size = \" << edgePixelArraySize << endl;\n\t\treturn -1;\n\t}\n\n#ifdef DEBUG_EDLINE\n\tcout << \"Anchor point detection, anchors.size=\" << anchorsSize << endl;\n#endif\n\t//link the anchors by smart routing\n\tedgeImage_.setTo(0);\n\tunsigned char *pEdgeImg = edgeImage_.data;\n\tmemset(pFirstPartEdgeX_,  0, edgePixelArraySize * sizeof(unsigned int)); //initialization\n\tmemset(pFirstPartEdgeY_,  0, edgePixelArraySize * sizeof(unsigned int));\n\tmemset(pSecondPartEdgeX_, 0, edgePixelArraySize * sizeof(unsigned int));\n\tmemset(pSecondPartEdgeY_, 0, edgePixelArraySize * sizeof(unsigned int));\n\tmemset(pFirstPartEdgeS_,  0, maxNumOfEdge * sizeof(unsigned int));\n\tmemset(pSecondPartEdgeS_, 0, maxNumOfEdge * sizeof(unsigned int));\n\tunsigned int offsetPFirst = 0, offsetPSecond = 0;\n\tunsigned int offsetPS = 0;\n\n\tunsigned int x, y;\n\tunsigned int lastX, lastY;\n\tunsigned char lastDirection;//up = 1, right = 2, down = 3, left = 4;\n\tunsigned char shouldGoDirection;//up = 1, right = 2, down = 3, left = 4;\n\tint edgeLenFirst, edgeLenSecond;\n\tfor (unsigned int i = 0; i < anchorsSize; i++)\n\t{\n\t\tx = pAnchorX_[i];\n\t\ty = pAnchorY_[i];\n\t\tindexInArray = y * imageWidth + x;\n\t\tif (pEdgeImg[indexInArray]) //if anchor i is already been an edge pixel.\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\t/*The walk stops under 3 conditions:\n\t\t * 1. We move out of the edge areas, i.e., the thresholded gradient value\n\t\t *    of the current pixel is 0.\n\t\t * 2. The current direction of the edge changes, i.e., from horizontal\n\t\t *    to vertical or vice versa.?? (This is turned out not correct. From the online edge draw demo\n\t\t *    we can figure out that authors don't implement this rule either because their extracted edge\n\t\t *    chain could be a circle which means pixel directions would definitely be different\n\t\t *    in somewhere on the chain.)\n\t\t * 3. We encounter a previously detected edge pixel. */\n\t\tpFirstPartEdgeS_[offsetPS] = offsetPFirst;\n\t\tif (pdirImg[indexInArray] == Horizontal) //if the direction of this pixel is horizontal, then go left and right.\n\t\t{\n\t\t\t//fist go right, pixel direction may be different during linking.\n\t\t\tlastDirection = RightDir;\n\t\t\twhile (pgImg[indexInArray] > 0 && !pEdgeImg[indexInArray])\n\t\t\t{\n\t\t\t\tpEdgeImg[indexInArray] = 1;        // Mark this pixel as an edge pixel\n\t\t\t\tpFirstPartEdgeX_[offsetPFirst] = x;\n\t\t\t\tpFirstPartEdgeY_[offsetPFirst++] = y;\n\t\t\t\tshouldGoDirection = 0;//unknown\n\t\t\t\tif (pdirImg[indexInArray] == Horizontal) //should go left or right\n\t\t\t\t{\n\t\t\t\t\tif (lastDirection == UpDir || lastDirection == DownDir) //change the pixel direction now\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x > lastX) //should go right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = RightDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //should go left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = LeftDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastX = x;\n\t\t\t\t\tlastY = y;\n\t\t\t\t\tif (lastDirection == RightDir || shouldGoDirection == RightDir) //go right\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == imageWidth - 1 || y == 0 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the right and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray + 1];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth + 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = RightDir;\n\t\t\t\t\t}\n\t\t\t\t\telse if (lastDirection == LeftDir || shouldGoDirection == LeftDir) //go left\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || y == 0 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the left and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth - 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray - 1];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = LeftDir;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse  //should go up or down.\n\t\t\t\t{\n\t\t\t\t\tif (lastDirection == RightDir || lastDirection == LeftDir) //change the pixel direction now\n\t\t\t\t\t{\n\t\t\t\t\t\tif (y > lastY) //should go down\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = DownDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //should go up\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = UpDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastX = x;\n\t\t\t\t\tlastY = y;\n\t\t\t\t\tif (lastDirection == DownDir || shouldGoDirection == DownDir) //go down\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || x == imageWidth - 1 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the down and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray + imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray + imageWidth];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //down-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-down\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = DownDir;\n\t\t\t\t\t}\n\t\t\t\t\telse if (lastDirection == UpDir || shouldGoDirection == UpDir) //go up\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || x == imageWidth - 1 || y == 0) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the up and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray - imageWidth];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray - imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //up-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-up\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = UpDir;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tindexInArray = y * imageWidth + x;\n\t\t\t}//end while go right\n\t\t\t//then go left, pixel direction may be different during linking.\n\t\t\tx = pAnchorX_[i];\n\t\t\ty = pAnchorY_[i];\n\t\t\tindexInArray = y * imageWidth + x;\n\t\t\tpEdgeImg[indexInArray] = 0;//mark the anchor point be a non-edge pixel and\n\t\t\tlastDirection = LeftDir;\n\t\t\tpSecondPartEdgeS_[offsetPS] = offsetPSecond;\n\t\t\twhile (pgImg[indexInArray] > 0 && !pEdgeImg[indexInArray])\n\t\t\t{\n\t\t\t\tpEdgeImg[indexInArray] = 1;        // Mark this pixel as an edge pixel\n\t\t\t\tpSecondPartEdgeX_[offsetPSecond] = x;\n\t\t\t\tpSecondPartEdgeY_[offsetPSecond++] = y;\n\t\t\t\tshouldGoDirection = 0;//unknown\n\t\t\t\tif (pdirImg[indexInArray] == Horizontal) //should go left or right\n\t\t\t\t{\n\t\t\t\t\tif (lastDirection == UpDir || lastDirection == DownDir) //change the pixel direction now\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x > lastX) //should go right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = RightDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //should go left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = LeftDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastX = x;\n\t\t\t\t\tlastY = y;\n\t\t\t\t\tif (lastDirection == RightDir || shouldGoDirection == RightDir) //go right\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == imageWidth - 1 || y == 0 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the right and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray + 1];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth + 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = RightDir;\n\t\t\t\t\t}\n\t\t\t\t\telse   if (lastDirection == LeftDir || shouldGoDirection == LeftDir) //go left\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || y == 0 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the left and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth - 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray - 1];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = LeftDir;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse  //should go up or down.\n\t\t\t\t{\n\t\t\t\t\tif (lastDirection == RightDir || lastDirection == LeftDir) //change the pixel direction now\n\t\t\t\t\t{\n\t\t\t\t\t\tif (y > lastY) //should go down\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = DownDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //should go up\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = UpDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastX = x;\n\t\t\t\t\tlastY = y;\n\t\t\t\t\tif (lastDirection == DownDir || shouldGoDirection == DownDir) //go down\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || x == imageWidth - 1 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the down and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray + imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray + imageWidth];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //down-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-down\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = DownDir;\n\t\t\t\t\t}\n\t\t\t\t\telse   if (lastDirection == UpDir || shouldGoDirection == UpDir) //go up\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || x == imageWidth - 1 || y == 0) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the up and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray - imageWidth];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray - imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //up-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-up\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = UpDir;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tindexInArray = y * imageWidth + x;\n\t\t\t}//end while go left\n\t\t\t//end anchor is Horizontal\n\t\t}\n\t\telse  //the direction of this pixel is vertical, go up and down\n\t\t{\n\t\t\t//fist go down, pixel direction may be different during linking.\n\t\t\tlastDirection = DownDir;\n\t\t\twhile (pgImg[indexInArray] > 0 && !pEdgeImg[indexInArray])\n\t\t\t{\n\t\t\t\tpEdgeImg[indexInArray] = 1;        // Mark this pixel as an edge pixel\n\t\t\t\tpFirstPartEdgeX_[offsetPFirst] = x;\n\t\t\t\tpFirstPartEdgeY_[offsetPFirst++] = y;\n\t\t\t\tshouldGoDirection = 0;//unknown\n\t\t\t\tif (pdirImg[indexInArray] == Horizontal) //should go left or right\n\t\t\t\t{\n\t\t\t\t\tif (lastDirection == UpDir || lastDirection == DownDir) //change the pixel direction now\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x > lastX) //should go right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = RightDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //should go left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = LeftDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastX = x;\n\t\t\t\t\tlastY = y;\n\t\t\t\t\tif (lastDirection == RightDir || shouldGoDirection == RightDir) //go right\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == imageWidth - 1 || y == 0 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the right and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray + 1];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth + 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = RightDir;\n\t\t\t\t\t}\n\t\t\t\t\telse   if (lastDirection == LeftDir || shouldGoDirection == LeftDir) //go left\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || y == 0 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the left and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth - 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray - 1];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = LeftDir;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse  //should go up or down.\n\t\t\t\t{\n\t\t\t\t\tif (lastDirection == RightDir || lastDirection == LeftDir) //change the pixel direction now\n\t\t\t\t\t{\n\t\t\t\t\t\tif (y > lastY) //should go down\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = DownDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //should go up\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = UpDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastX = x;\n\t\t\t\t\tlastY = y;\n\t\t\t\t\tif (lastDirection == DownDir || shouldGoDirection == DownDir) //go down\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || x == imageWidth - 1 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the down and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray + imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray + imageWidth];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //down-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-down\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = DownDir;\n\t\t\t\t\t}\n\t\t\t\t\telse   if (lastDirection == UpDir || shouldGoDirection == UpDir) //go up\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || x == imageWidth - 1 || y == 0) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the up and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray - imageWidth];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray - imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //up-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-up\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = UpDir;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tindexInArray = y * imageWidth + x;\n\t\t\t}//end while go down\n\t\t\t//then go up, pixel direction may be different during linking.\n\t\t\tlastDirection = UpDir;\n\t\t\tx = pAnchorX_[i];\n\t\t\ty = pAnchorY_[i];\n\t\t\tindexInArray = y * imageWidth + x;\n\t\t\tpEdgeImg[indexInArray] = 0;//mark the anchor point be a non-edge pixel and\n\t\t\tpSecondPartEdgeS_[offsetPS] = offsetPSecond;\n\t\t\twhile (pgImg[indexInArray] > 0 && !pEdgeImg[indexInArray])\n\t\t\t{\n\t\t\t\tpEdgeImg[indexInArray] = 1;        // Mark this pixel as an edge pixel\n\t\t\t\tpSecondPartEdgeX_[offsetPSecond] = x;\n\t\t\t\tpSecondPartEdgeY_[offsetPSecond++] = y;\n\t\t\t\tshouldGoDirection = 0;//unknown\n\t\t\t\tif (pdirImg[indexInArray] == Horizontal) //should go left or right\n\t\t\t\t{\n\t\t\t\t\tif (lastDirection == UpDir || lastDirection == DownDir) //change the pixel direction now\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x > lastX) //should go right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = RightDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //should go left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = LeftDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastX = x;\n\t\t\t\t\tlastY = y;\n\t\t\t\t\tif (lastDirection == RightDir || shouldGoDirection == RightDir) //go right\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == imageWidth - 1 || y == 0 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the right and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray + 1];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth + 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = RightDir;\n\t\t\t\t\t}\n\t\t\t\t\telse   if (lastDirection == LeftDir || shouldGoDirection == LeftDir) //go left\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || y == 0 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the left and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth - 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray - 1];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = LeftDir;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse  //should go up or down.\n\t\t\t\t{\n\t\t\t\t\tif (lastDirection == RightDir || lastDirection == LeftDir) //change the pixel direction now\n\t\t\t\t\t{\n\t\t\t\t\t\tif (y > lastY) //should go down\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = DownDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //should go up\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tshouldGoDirection = UpDir;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastX = x;\n\t\t\t\t\tlastY = y;\n\t\t\t\t\tif (lastDirection == DownDir || shouldGoDirection == DownDir) //go down\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || x == imageWidth - 1 || y == imageHeight - 1) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the down and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray + imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray + imageWidth];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray + imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //down-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //down-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-down\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ty = y + 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = DownDir;\n\t\t\t\t\t}\n\t\t\t\t\telse   if (lastDirection == UpDir || shouldGoDirection == UpDir) //go up\n\t\t\t\t\t{\n\t\t\t\t\t\tif (x == 0 || x == imageWidth - 1 || y == 0) //reach the image border\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Look at 3 neighbors to the up and pick the one with the max. gradient value\n\t\t\t\t\t\tgValue1 = pgImg[indexInArray - imageWidth + 1];\n\t\t\t\t\t\tgValue2 = pgImg[indexInArray - imageWidth];\n\t\t\t\t\t\tgValue3 = pgImg[indexInArray - imageWidth - 1];\n\t\t\t\t\t\tif (gValue1 >= gValue2 && gValue1 >= gValue3) //up-right\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x + 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if (gValue3 >= gValue2 && gValue3 >= gValue1) //up-left\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tx = x - 1;\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //straight-up\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ty = y - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlastDirection = UpDir;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tindexInArray = y * imageWidth + x;\n\t\t\t}//end while go up\n\t\t}//end anchor is Vertical\n\t\t//only keep the edge chains whose length is larger than the minLineLen_;\n\t\tedgeLenFirst = offsetPFirst - pFirstPartEdgeS_[offsetPS];\n\t\tedgeLenSecond = offsetPSecond - pSecondPartEdgeS_[offsetPS];\n\t\tif (edgeLenFirst + edgeLenSecond < minLineLen_ + 1) //short edge, drop it\n\t\t{\n\t\t\toffsetPFirst = pFirstPartEdgeS_[offsetPS];\n\t\t\toffsetPSecond = pSecondPartEdgeS_[offsetPS];\n\t\t}\n\t\telse\n\t\t{\n\t\t\toffsetPS++;\n\t\t}\n\t}\n\t//store the last index\n\tpFirstPartEdgeS_[offsetPS]  = offsetPFirst;\n\tpSecondPartEdgeS_[offsetPS] = offsetPSecond;\n\tif (offsetPS > maxNumOfEdge)\n\t{\n\t\tcout << \"Edge drawing Error: The total number of edges is larger than MaxNumOfEdge, \"\n\t\t\t \"numofedge = \" << offsetPS << \", MaxNumOfEdge=\" << maxNumOfEdge << endl;\n\t\treturn -1;\n\t}\n\tif (offsetPFirst > edgePixelArraySize || offsetPSecond > edgePixelArraySize)\n\t{\n\t\tcout << \"Edge drawing Error: The total number of edge pixels is larger than MaxNumOfEdgePixels, \"\n\t\t\t \"numofedgePixel1 = \" << offsetPFirst << \",  numofedgePixel2 = \" << offsetPSecond <<\n\t\t\t \", MaxNumOfEdgePixel=\" << edgePixelArraySize << endl;\n\t\treturn -1;\n\t}\n\n\t/*now all the edge information are stored in pFirstPartEdgeX_, pFirstPartEdgeY_,\n\t *pFirstPartEdgeS_,  pSecondPartEdgeX_, pSecondPartEdgeY_, pSecondPartEdgeS_;\n\t *we should reorganize them into edgeChains for easily using.   */\n\t//unsigned int tempID;\n\tlong  int tempID;\n\tedgeChains.xCors.resize(offsetPFirst + offsetPSecond);\n\tedgeChains.yCors.resize(offsetPFirst + offsetPSecond);\n\tedgeChains.sId.resize(offsetPS + 1);\n\tunsigned int *pxCors = edgeChains.xCors.data();\n\tunsigned int *pyCors = edgeChains.yCors.data();\n\tunsigned int *psId   = edgeChains.sId.data();\n\toffsetPFirst = 0;\n\toffsetPSecond = 0;\n\tunsigned int indexInCors = 0;\n\tunsigned int numOfEdges = 0;\n\tfor (unsigned int edgeId = 0; edgeId < offsetPS; edgeId++)\n\t{\n\t\t//step1, put the first and second parts edge coordinates together from edge start to edge end\n\t\tpsId[numOfEdges++] = indexInCors;\n\t\tindexInArray = pFirstPartEdgeS_[edgeId];\n\t\toffsetPFirst = pFirstPartEdgeS_[edgeId + 1];\n\t\tfor (tempID = offsetPFirst - 1; tempID >= indexInArray; tempID--) //add first part edge\n\t\t{\n\t\t\tpxCors[indexInCors]   = pFirstPartEdgeX_[tempID];\n\t\t\tpyCors[indexInCors++] = pFirstPartEdgeY_[tempID];\n\t\t}\n\t\tindexInArray = pSecondPartEdgeS_[edgeId];\n\t\toffsetPSecond = pSecondPartEdgeS_[edgeId + 1];\n\t\tfor (tempID = indexInArray + 1; tempID < offsetPSecond; tempID++) //add second part edge\n\t\t{\n\t\t\tpxCors[indexInCors]  = pSecondPartEdgeX_[tempID];\n\t\t\tpyCors[indexInCors++] = pSecondPartEdgeY_[tempID];\n\t\t}\n\t}\n\tpsId[numOfEdges] = indexInCors;//the end index of the last edge\n\tedgeChains.numOfEdges = numOfEdges;\n\n#ifdef DEBUG_EDLINE\n\tif(!DEBUG_FOLDER.empty())\n\t{\n\t\tstd::string edge_folder = DEBUG_FOLDER+\"/edge/\";\n\t\tint status = mkdir(edge_folder.c_str(), 0777);\n\n\t\tif(!status)\n\t\t{\n\t\t\t/*Show the extracted edge cvImage in color. Each chain is in different color.*/\n\t\t\tcout << \"Edge Drawing, numofedge = \" << numOfEdges << endl;\n\t\t\tcv::Mat tmp, singleImg;\n\t\t\tcv::cvtColor(dirImg_, tmp, CV_GRAY2BGR);\n\t\t\tcv::cvtColor(dirImg_, singleImg, CV_GRAY2BGR);\n\t\t\tcv::Vec3b rColor;\n\t\t\tint lowest = 100, highest = 255;\n\t\t\tint range = (highest - lowest) + 1;\n\n\t\t\tsrand((unsigned)time(0));\n\n\t\t\tfor (unsigned int i = 0; i < edgeChains.numOfEdges; i++)\n\t\t\t{\n\t\t\t\tcv::Mat foo = singleImg.clone();\n\t\t\t\tstd::ofstream f(edge_folder+std::to_string(i)+\".txt\");\n\n\t\t\t\trColor.val[0] = lowest + int(rand() % range);\n\t\t\t\trColor.val[1] = lowest + int(rand() % range);\n\t\t\t\trColor.val[2] = lowest + int(rand() % range);\n\n\t\t\t\tfor (indexInCors = psId[i]; indexInCors < psId[i + 1]; indexInCors++)\n\t\t\t\t{\n\t\t\t\t\ttmp.at<cv::Vec3b>(pyCors[indexInCors], pxCors[indexInCors])\t= rColor;\n\t\t\t\t\tfoo.at<cv::Vec3b>(pyCors[indexInCors], pxCors[indexInCors])\t= cv::Vec3b{0x00,0x00,0xff};\n\t\t\t\t\tf << pyCors[indexInCors] << \" , \" << pxCors[indexInCors] << std::endl;\n\t\t\t\t}\n\n\t\t\t\tcv::imwrite(edge_folder+std::to_string(i)+\".png\",foo);\n\t\t\t\tf.close();\n\t\t\t}\n\t\t\tcv::imwrite(DEBUG_FOLDER+\"/edges.png\", tmp);\n\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"Fail to create edge folder: \" << edge_folder << std::endl\n\t\t\t\t\t  << \"Error No: \" << errno << std::endl\n\t\t\t\t\t  << strerror(errno) << std::endl;\n\t\t}\n\n\t}\n#endif\n\n\treturn 1;\n}\n\n\nint EDLineDetector::EDline(cv::Mat const &image, LineChains &lines, bool smoothed)\n{\n\n\t//first, call EdgeDrawing function to extract edges\n\tEdgeChains edges;\n\tif ( EdgeDrawing(image, edges, smoothed) < 0 )\n\t{\n\t\tcout << \"Line Detection not finished\" << endl;\n\t\treturn -1;\n\t}\n\n\t//  bValidate_ =false;\n\n\t//detect lines\n\tunsigned int linePixelID = edges.sId[edges.numOfEdges];\n\tlines.xCors.resize(linePixelID);\n\tlines.yCors.resize(linePixelID);\n\tlines.sId.resize(5 * edges.numOfEdges);\n\n\tunsigned int *pEdgeXCors = edges.xCors.data();\n\tunsigned int *pEdgeYCors = edges.yCors.data();\n\tunsigned int *pEdgeSID   = edges.sId.data();\n\tunsigned int *pLineXCors = lines.xCors.data();\n\tunsigned int *pLineYCors = lines.yCors.data();\n\tunsigned int *pLineSID   = lines.sId.data();\n\tunsigned char *pdirImg = dirImg_.data;\n\tunsigned int numOfLines = 0;\n\tunsigned int offsetInEdgeArrayS, offsetInEdgeArrayE, newOffsetS;//start index and end index\n\tunsigned int offsetInLineArray = 0;\n\tfloat direction;//line direction\n\tdouble lineFitErr;//the line fit error;\n\tstd::array<double, 2> lineEquation;\n\n\tlogNT_ = 2.0 * ( log10( (double) imageWidth ) + log10( (double) imageHeight ) );\n\tlineEquations_.clear();\n\tlineEndpoints_.clear();\n\tlineDirection_.clear();\n\n\tfor (unsigned int edgeID = 0; edgeID < edges.numOfEdges; edgeID++)\n\t{\n\t\toffsetInEdgeArrayS = pEdgeSID[edgeID];\n\t\toffsetInEdgeArrayE = pEdgeSID[edgeID + 1];\n\n\t\t//extract line segments from an edge, may find more than one segments\n\t\twhile (offsetInEdgeArrayE > offsetInEdgeArrayS + minLineLen_)\n\t\t{\n\t\t\t//find an initial line segment\n\t\t\twhile (offsetInEdgeArrayE > offsetInEdgeArrayS + minLineLen_)\n\t\t\t{\n\t\t\t\tlineFitErr = LeastSquaresLineFit_(pEdgeXCors, pEdgeYCors,\n\t\t\t\t\t\t\t\t\t\t\t\t  offsetInEdgeArrayS, lineEquation);\n\t\t\t\tif ( lineFitErr <= lineFitErrThreshold_ )\n\t\t\t\t{\n\t\t\t\t\tbreak; //ok, an initial line segment detected\n\t\t\t\t}\n\t\t\t\t//skip the first two pixel in the chain and try with the remaining pixels\n\t\t\t\toffsetInEdgeArrayS += SkipEdgePoint;\n\t\t\t}\n\t\t\t// exit if no initial line is detected\n\t\t\tif (lineFitErr > lineFitErrThreshold_)\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// An initial line segment is detected. Try to extend this line segment\n\t\t\tpLineSID[numOfLines] = offsetInLineArray;\n\t\t\t// for a line ax+by+c=0, coef1 = 1/sqrt(a^2+b^2);\n\t\t\tdouble coef1;\n\t\t\t// for a line ax+by+c=0 and a point(xi, yi),\n\t\t\t// pointToLineDis = coef1*|a*xi+b*yi+c|\n\t\t\tdouble pointToLineDis;\n\t\t\tbool bExtended = true;\n\t\t\tbool bFirstTry = true;\n\t\t\t//to against noise, we accept a few outlier of a line.\n\t\t\tint numOfOutlier;\n\t\t\tint tryTimes = 0;\n\n\t\t\t//y=ax+b, i.e. ax-y+b=0\n\t\t\tif ( pdirImg[pEdgeYCors[offsetInEdgeArrayS]*imageWidth + pEdgeXCors[offsetInEdgeArrayS]]\n\t\t\t\t\t== Horizontal )\n\t\t\t{\n\t\t\t\twhile (bExtended)\n\t\t\t\t{\n\t\t\t\t\ttryTimes++;\n\t\t\t\t\tif (bFirstTry)\n\t\t\t\t\t{\n\t\t\t\t\t\tbFirstTry = false;\n\t\t\t\t\t\t//First add the initial line segment to the line array\n\t\t\t\t\t\tfor (int i = 0; i < minLineLen_; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpLineXCors[offsetInLineArray]   = pEdgeXCors[offsetInEdgeArrayS];\n\t\t\t\t\t\t\tpLineYCors[offsetInLineArray++] = pEdgeYCors[offsetInEdgeArrayS++];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse  //after each try, line is extended, line equation should be re-estimated\n\t\t\t\t\t{\n\t\t\t\t\t\t//adjust the line equation\n\t\t\t\t\t\tlineFitErr = LeastSquaresLineFit_(pLineXCors, pLineYCors, pLineSID[numOfLines],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  newOffsetS, offsetInLineArray, lineEquation);\n\t\t\t\t\t}\n\n\t\t\t\t\tcoef1 = 1 / sqrt( lineEquation[0]*lineEquation[0] + 1);\n\t\t\t\t\tnumOfOutlier = 0;\n\t\t\t\t\tnewOffsetS = offsetInLineArray;\n\n\t\t\t\t\twhile (offsetInEdgeArrayE > offsetInEdgeArrayS)\n\t\t\t\t\t{\n\t\t\t\t\t\tpointToLineDis = fabs(lineEquation[0] * pEdgeXCors[offsetInEdgeArrayS] -\n\t\t\t\t\t\t\t\t\t\t\t  pEdgeYCors[offsetInEdgeArrayS] + lineEquation[1]) * coef1;\n\t\t\t\t\t\tpLineXCors[offsetInLineArray] = pEdgeXCors[offsetInEdgeArrayS];\n\t\t\t\t\t\tpLineYCors[offsetInLineArray++] = pEdgeYCors[offsetInEdgeArrayS++];\n\t\t\t\t\t\tif (pointToLineDis > lineFitErrThreshold_)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnumOfOutlier++;\n\t\t\t\t\t\t\tif (numOfOutlier > 3) break;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //we count number of connective outliers.\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnumOfOutlier = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//pop back the last few outliers from lines and return them to edge chain\n\t\t\t\t\toffsetInLineArray  -= numOfOutlier;\n\t\t\t\t\toffsetInEdgeArrayS -= numOfOutlier;\n\n\t\t\t\t\t//some new pixels are added to the line\n//\t\t\t\t\tif (offsetInLineArray - newOffsetS > 0 && tryTimes < TryTime)\n//\t\t\t\t\t{\n//\t\t\t\t\t}\n//\t\t\t\t\telse\n\t\t\t\t\tif (offsetInLineArray <= newOffsetS || tryTimes >= TryTime)\n\t\t\t\t\t{\n\t\t\t\t\t\tbExtended = false;//no new pixels are added.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//the line equation coefficients,for line w1x+w2y+w3 =0, we normalize it to make w1^2+w2^2 = 1.\n\t\t\t\tstd::array<double, 3> lineEqu {{lineEquation[0]*coef1, -1 * coef1, lineEquation[1]*coef1}};\n\t\t\t\t//check the line\n\t\t\t\tif ( LineValidation_(pLineXCors, pLineYCors, pLineSID[numOfLines],\n\t\t\t\t\t\t\t\t\t offsetInLineArray, lineEqu, direction) )\n\t\t\t\t{\n\t\t\t\t\t//store the line equation coefficients\n\t\t\t\t\tlineEquations_.push_back(lineEqu);\n\t\t\t\t\t/*At last, compute the line endpoints and store them.\n\t\t\t\t\t *we project the first and last pixels in the pixelChain onto the best fit line\n\t\t\t\t\t *to get the line endpoints.\n\t\t\t\t\t *xp= (w2^2*x0-w1*w2*y0-w3*w1)/(w1^2+w2^2)\n\t\t\t\t\t *yp= (w1^2*y0-w1*w2*x0-w3*w2)/(w1^2+w2^2)  */\n\t\t\t\t\tstd::array<float, 4> lineEndP;//line endpoints\n\t\t\t\t\tdouble a1 = lineEqu[1] * lineEqu[1];\n\t\t\t\t\tdouble a2 = lineEqu[0] * lineEqu[0];\n\t\t\t\t\tdouble a3 = lineEqu[0] * lineEqu[1];\n\t\t\t\t\tdouble a4 = lineEqu[2] * lineEqu[0];\n\t\t\t\t\tdouble a5 = lineEqu[2] * lineEqu[1];\n\t\t\t\t\tunsigned int Px = pLineXCors[pLineSID[numOfLines] ];//first pixel\n\t\t\t\t\tunsigned int Py = pLineYCors[pLineSID[numOfLines] ];\n\t\t\t\t\tlineEndP[0] = a1 * Px - a3 * Py - a4; //x\n\t\t\t\t\tlineEndP[1] = a2 * Py - a3 * Px - a5; //y\n\t\t\t\t\tPx = pLineXCors[offsetInLineArray - 1 ]; //last pixel\n\t\t\t\t\tPy = pLineYCors[offsetInLineArray - 1 ];\n\t\t\t\t\tlineEndP[2] = a1 * Px - a3 * Py - a4; //x\n\t\t\t\t\tlineEndP[3] = a2 * Py - a3 * Px - a5; //y\n\t\t\t\t\tlineEndpoints_.push_back(lineEndP);\n\t\t\t\t\tlineDirection_.push_back(direction);\n\t\t\t\t\tnumOfLines++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\toffsetInLineArray = pLineSID[numOfLines];// line was not accepted, the offset is set back\n\t\t\t\t}\n\t\t\t}\n\t\t\telse  //x=ay+b, i.e. x-ay-b=0\n\t\t\t{\n\t\t\t\twhile (bExtended)\n\t\t\t\t{\n\t\t\t\t\ttryTimes++;\n\t\t\t\t\tif (bFirstTry)\n\t\t\t\t\t{\n\t\t\t\t\t\tbFirstTry = false;\n\t\t\t\t\t\tfor (int i = 0; i < minLineLen_; i++) //First add the initial line segment to the line array\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpLineXCors[offsetInLineArray]   = pEdgeXCors[offsetInEdgeArrayS];\n\t\t\t\t\t\t\tpLineYCors[offsetInLineArray++] = pEdgeYCors[offsetInEdgeArrayS++];\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse  //after each try, line is extended, line equation should be re-estimated\n\t\t\t\t\t{\n\t\t\t\t\t\t//adjust the line equation\n\t\t\t\t\t\tlineFitErr = LeastSquaresLineFit_(pLineXCors, pLineYCors, pLineSID[numOfLines],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  newOffsetS, offsetInLineArray, lineEquation);\n\t\t\t\t\t}\n\t\t\t\t\tcoef1 = 1 / sqrt(1 + lineEquation[0] * lineEquation[0]);\n\t\t\t\t\tnumOfOutlier = 0;\n\t\t\t\t\tnewOffsetS = offsetInLineArray;\n\t\t\t\t\twhile (offsetInEdgeArrayE > offsetInEdgeArrayS)\n\t\t\t\t\t{\n\t\t\t\t\t\tpointToLineDis = fabs(pEdgeXCors[offsetInEdgeArrayS] -\n\t\t\t\t\t\t\t\t\t\t\t  lineEquation[0] * pEdgeYCors[offsetInEdgeArrayS] - lineEquation[1]) * coef1;\n\t\t\t\t\t\tpLineXCors[offsetInLineArray] = pEdgeXCors[offsetInEdgeArrayS];\n\t\t\t\t\t\tpLineYCors[offsetInLineArray++] = pEdgeYCors[offsetInEdgeArrayS++];\n\t\t\t\t\t\tif (pointToLineDis > lineFitErrThreshold_)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnumOfOutlier++;\n\t\t\t\t\t\t\tif (numOfOutlier > 3) break;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse  //we count number of connective outliers.\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tnumOfOutlier = 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t//pop back the last few outliers from lines and return them to edge chain\n\t\t\t\t\toffsetInLineArray  -= numOfOutlier;\n\t\t\t\t\toffsetInEdgeArrayS -= numOfOutlier;\n\t\t\t\t\tif (offsetInLineArray - newOffsetS > 0 && tryTimes < TryTime) //some new pixels are added to the line\n\t\t\t\t\t{\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tbExtended = false;//no new pixels are added.\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//the line equation coefficients,for line w1x+w2y+w3 =0, we normalize it to make w1^2+w2^2 = 1.\n\t\t\t\tstd::array<double, 3> lineEqu {1 * coef1, -lineEquation[0]*coef1, -lineEquation[1]*coef1};\n\t\t\t\tif (LineValidation_(pLineXCors, pLineYCors, pLineSID[numOfLines], offsetInLineArray, lineEqu, direction)) //check the line\n\t\t\t\t{\n\t\t\t\t\t//store the line equation coefficients\n\t\t\t\t\tlineEquations_.push_back(lineEqu);\n\t\t\t\t\t/*At last, compute the line endpoints and store them.\n\t\t\t\t\t *we project the first and last pixels in the pixelChain onto the best fit line\n\t\t\t\t\t *to get the line endpoints.\n\t\t\t\t\t *xp= (w2^2*x0-w1*w2*y0-w3*w1)/(w1^2+w2^2)\n\t\t\t\t\t *yp= (w1^2*y0-w1*w2*x0-w3*w2)/(w1^2+w2^2)  */\n\t\t\t\t\tstd::array<float, 4> lineEndP;//line endpoints\n\t\t\t\t\tdouble a1 = lineEqu[1] * lineEqu[1];\n\t\t\t\t\tdouble a2 = lineEqu[0] * lineEqu[0];\n\t\t\t\t\tdouble a3 = lineEqu[0] * lineEqu[1];\n\t\t\t\t\tdouble a4 = lineEqu[2] * lineEqu[0];\n\t\t\t\t\tdouble a5 = lineEqu[2] * lineEqu[1];\n\t\t\t\t\tunsigned int Px = pLineXCors[pLineSID[numOfLines] ];//first pixel\n\t\t\t\t\tunsigned int Py = pLineYCors[pLineSID[numOfLines] ];\n\t\t\t\t\tlineEndP[0] = a1 * Px - a3 * Py - a4; //x\n\t\t\t\t\tlineEndP[1] = a2 * Py - a3 * Px - a5; //y\n\t\t\t\t\tPx = pLineXCors[offsetInLineArray - 1 ]; //last pixel\n\t\t\t\t\tPy = pLineYCors[offsetInLineArray - 1 ];\n\t\t\t\t\tlineEndP[2] = a1 * Px - a3 * Py - a4; //x\n\t\t\t\t\tlineEndP[3] = a2 * Py - a3 * Px - a5; //y\n\t\t\t\t\tlineEndpoints_.push_back(lineEndP);\n\t\t\t\t\tlineDirection_.push_back(direction);\n\t\t\t\t\tnumOfLines++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\toffsetInLineArray = pLineSID[numOfLines];// line was not accepted, the offset is set back\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Extract line segments from the remaining pixel; Current chain has been shortened already.\n\t\t}\n\t}//end for(unsigned int edgeID=0; edgeID<edges.numOfEdges; edgeID++)\n\n\tpLineSID[numOfLines] = offsetInLineArray;\n\tlines.numOfLines = numOfLines;\n\n#ifdef DEBUG_EDLINE\n\tif(!DEBUG_FOLDER.empty())\n\t{\n\t\tstd::string line_folder = DEBUG_FOLDER+\"/line/\";\n\t\tint status = mkdir(line_folder.c_str(), 0777);\n\n\t\tif(!status)\n\t\t{\n\t\t\t/*Show the extracted lines in color. Each line is in different color.*/\n\t\t\tcout << \"Line Drawing, numofLines = \" << numOfLines << endl;\n\n\t\t\tcv::Mat img_all, img_single;\n\t\t\tcv::convertScaleAbs(image, img_all, double(UINT8_MAX)/UINT16_MAX);\n\t\t\tcv::cvtColor(img_all, img_all, CV_GRAY2BGR);\n\t\t\timg_single = img_all.clone();\n\t\t\tcv::Vec3b rColor;\n\t\t\tint lowest = 100, highest = 255;\n\t\t\tint range = (highest - lowest) + 1;\n\n\t\t\tsrand((unsigned)time(0));\n\n\t\t\tfor (unsigned int i = 0; i < lines.numOfLines; i++)\n\t\t\t{\n\t\t\t\tcv::Mat foo = img_single.clone();\n\t\t\t\tstd::ofstream f(line_folder+std::to_string(i)+\".txt\");\n\n\t\t\t\trColor.val[0] = lowest + int(rand() % range);\n\t\t\t\trColor.val[1] = lowest + int(rand() % range);\n\t\t\t\trColor.val[2] = lowest + int(rand() % range);\n\n\t\t\t\tfor(offsetInLineArray = pLineSID[i]; offsetInLineArray<pLineSID[i+1]; offsetInLineArray++)\n\t\t\t\t{\n\t\t\t\t\timg_all.at<cv::Vec3b>(pLineYCors[offsetInLineArray], pLineXCors[offsetInLineArray])\t= rColor;\n\t\t\t\t\tfoo.at<cv::Vec3b>(pLineYCors[offsetInLineArray], pLineXCors[offsetInLineArray])\t= cv::Vec3b{0x00,0x00,0xff};\n\t\t\t\t\tf << pLineYCors[offsetInLineArray] << \" , \" << pLineXCors[offsetInLineArray] << std::endl;\n\t\t\t\t}\n\n\t\t\t\tcv::imwrite(line_folder+std::to_string(i)+\".png\",foo);\n\t\t\t\tf.close();\n\t\t\t}\n\t\t\tcv::imwrite(DEBUG_FOLDER+\"/lines.png\", img_all);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cerr << \"Fail to create line folder: \" << line_folder << std::endl\n\t\t\t\t\t  << \"Error No: \" << errno << std::endl\n\t\t\t\t\t  << strerror(errno) << std::endl;\n\t\t}\n\n\t}\n\n#endif\n\treturn 1;\n}\n\nint EDLineDetector::EDline(cv::Mat const &image, bool smoothed)\n{\n\tif ( EDline(image, lines_, smoothed) < 0 )\n\t{\n\t\treturn -1;\n\t}\n\n\tlineSalience_.clear();\n\tlineSalience_.resize(lines_.numOfLines);\n\tunsigned char *pgImg  = gImgWO_.ptr();\n\tunsigned int indexInLineArray;\n\tunsigned int *pXCor = lines_.xCors.data();\n\tunsigned int *pYCor = lines_.yCors.data();\n\tunsigned int *pSID  = lines_.sId.data();\n\tfor (unsigned int i = 0; i < lineSalience_.size(); i++)\n\t{\n\t\tint salience = 0;\n\t\tfor (indexInLineArray = pSID[i]; indexInLineArray < pSID[i + 1]; indexInLineArray++)\n\t\t{\n\t\t\tsalience += pgImg[pYCor[indexInLineArray] * imageWidth + pXCor[indexInLineArray] ];\n\t\t}\n\t\tlineSalience_[i] = (float) salience;\n\t}\n\treturn 1;\n}\n\n\ndouble EDLineDetector::LeastSquaresLineFit_(  unsigned int *xCors,   unsigned int *yCors,\n\t\tunsigned int offsetS, std::array<double, 2> &lineEquation)\n{\n\tif (lineEquation.size() != 2)\n\t{\n\t\tstd::cout << \"SHOULD NOT BE != 2\" << std::endl;\n\t\tCV_Assert(false);\n\t}\n\n\tfloat * pMatT;\n\tfloat * pATA;\n\tdouble fitError = 0;\n\tdouble coef;\n\tunsigned char *pdirImg = dirImg_.data;\n\tunsigned int offset = offsetS;\n\t/*If the first pixel in this chain is horizontal,\n\t *then we try to find a horizontal line, y=ax+b;*/\n\tif ( pdirImg[ yCors[offsetS]*imageWidth + xCors[offsetS] ] == Horizontal )\n\t{\n\t\t/*Build the system,and solve it using least square regression: mat * [a,b]^T = vec\n\t\t * [x0,1]         [y0]\n\t\t * [x1,1] [a]     [y1]\n\t\t *    .   [b]  =   .\n\t\t * [xn,1]         [yn]*/\n\t\tpMatT = fitMatT.ptr<float>(); //fitMatT = [x0, x1, ... xn; 1,1,...,1];\n\t\tfor (int i = 0; i < minLineLen_; i++)\n\t\t{\n\t\t\t//*(pMatT+minLineLen_) = 1; //the value are not changed;\n\t\t\t*(pMatT++)   = xCors[offsetS];\n\t\t\tfitVec[0][i] = yCors[offsetS++];\n\t\t}\n\t\tATA = fitMatT * fitMatT.t();\n\t\tATV = fitMatT * fitVec.t();\n\t\t/* [a,b]^T = Inv(mat^T * mat) * mat^T * vec */\n\t\tpATA = ATA.ptr<float>();\n\t\tcoef = 1.0 / (double(pATA[0]) * double(pATA[3]) - double(pATA[1]) * double(pATA[2]));\n\t\t// lineEquation = svd.Invert(ATA) * matT * vec;\n\t\tlineEquation[0] = coef * ( double(pATA[3]) * double(ATV[0][0]) - double(pATA[1]) * double(ATV[0][1]));\n\t\tlineEquation[1] = coef * ( double(pATA[0]) * double(ATV[0][1]) - double(pATA[2]) * double(ATV[0][0]));\n\t\t/*compute line fit error */\n\t\tfor (int i = 0; i < minLineLen_; i++)\n\t\t{\n\t\t\tcoef = double(yCors[offset]) - double(xCors[offset++]) * lineEquation[0] - lineEquation[1];\n\t\t\tfitError += coef * coef;\n\t\t}\n\t\treturn sqrt(fitError);\n\t}\n\t/*If the first pixel in this chain is vertical,\n\t *then we try to find a vertical line, x=ay+b;*/\n//\tif (pdirImg[yCors[offsetS]*imageWidth + xCors[offsetS]] == Vertical)\n\telse\n\t{\n\t\t/*Build the system,and solve it using least square regression: mat * [a,b]^T = vec\n\t\t * [y0,1]         [x0]\n\t\t * [y1,1] [a]     [x1]\n\t\t *    .   [b]  =   .\n\t\t * [yn,1]         [xn]*/\n\t\tpMatT = fitMatT.ptr<float>();//fitMatT = [y0, y1, ... yn; 1,1,...,1];\n\t\tfor (int i = 0; i < minLineLen_; i++)\n\t\t{\n\t\t\t//*(pMatT+minLineLen_) = 1;//the value are not changed;\n\t\t\t*(pMatT++)           = yCors[offsetS];\n\t\t\tfitVec[0][i]          = xCors[offsetS++];\n\t\t}\n\t\tATA = fitMatT * (fitMatT.t());\n\t\tATV = fitMatT * fitVec.t();\n\t\t/* [a,b]^T = Inv(mat^T * mat) * mat^T * vec */\n\t\tpATA = ATA.ptr<float>();\n\t\tcoef = 1.0 / (double(pATA[0]) * double(pATA[3]) - double(pATA[1]) * double(pATA[2]));\n\t\t//      lineEquation = svd.Invert(ATA) * matT * vec;\n\t\tlineEquation[0] = coef * ( double(pATA[3]) * double(ATV[0][0]) - double(pATA[1]) * double(ATV[0][1]));\n\t\tlineEquation[1] = coef * ( double(pATA[0]) * double(ATV[0][1]) - double(pATA[2]) * double(ATV[0][0]));\n\t\t/*compute line fit error */\n\t\tfor (int i = 0; i < minLineLen_; i++)\n\t\t{\n\t\t\tcoef = double(xCors[offset]) - double(yCors[offset++]) * lineEquation[0] - lineEquation[1];\n\t\t\tfitError += coef * coef;\n\t\t}\n\t\treturn sqrt(fitError);\n\t}\n\treturn 0;\n}\n\ndouble EDLineDetector::LeastSquaresLineFit_(  unsigned int *xCors,   unsigned int *yCors,\n\t\tunsigned int offsetS, unsigned int newOffsetS,\n\t\tunsigned int offsetE,   std::array<double, 2> &lineEquation)\n{\n\tint length = offsetE - offsetS;\n\tint newLength = offsetE - newOffsetS;\n\tif (length <= 0 || newLength <= 0)\n\t{\n\t\tcout << \"EDLineDetector::LeastSquaresLineFit_ Error:\"\n\t\t\t \" the expected line index is wrong...offsetE = \"\n\t\t\t << offsetE << \", offsetS=\" << offsetS << \", newOffsetS=\" << newOffsetS << endl;\n\t\treturn -1;\n\t}\n\tif (lineEquation.size() != 2)\n\t{\n\t\tstd::cout << \"SHOULD NOT BE != 2\" << std::endl;\n\t\tCV_Assert(false);\n\t}\n\tcv::Mat_<float>  matT(2, newLength);\n\tcv::Mat_<float>  vec(newLength, 1);\n\tfloat * pMatT;\n\tfloat * pATA;\n\t//  double fitError = 0;\n\tdouble coef;\n\tunsigned char *pdirImg = dirImg_.data;\n\t/*If the first pixel in this chain is horizontal,\n\t *then we try to find a horizontal line, y=ax+b;*/\n\tif (pdirImg[yCors[offsetS]*imageWidth + xCors[offsetS] ] == Horizontal)\n\t{\n\t\t/*Build the new system,and solve it using least square regression: mat * [a,b]^T = vec\n\t\t * [x0',1]         [y0']\n\t\t * [x1',1] [a]     [y1']\n\t\t *    .    [b]  =   .\n\t\t * [xn',1]         [yn']*/\n\t\tpMatT = matT.ptr<float>();//matT = [x0', x1', ... xn'; 1,1,...,1]\n\t\tfor (int i = 0; i < newLength; i++)\n\t\t{\n\t\t\t*(pMatT + newLength) = 1;\n\t\t\t*(pMatT++)         = xCors[newOffsetS];\n\t\t\tvec[0][i]          = yCors[newOffsetS++];\n\t\t}\n\t\t/* [a,b]^T = Inv(ATA + mat^T * mat) * (ATV + mat^T * vec) */\n\t\ttempMatLineFit = matT * matT.t();\n\t\ttempVecLineFit = matT * vec;\n\t\tATA = ATA + tempMatLineFit;\n\t\tATV = ATV + tempVecLineFit;\n\t\tpATA = ATA.ptr<float>();\n\t\tcoef = 1.0 / (double(pATA[0]) * double(pATA[3]) - double(pATA[1]) * double(pATA[2]));\n\t\tlineEquation[0] = coef * ( double(pATA[3]) * double(ATV[0][0]) - double(pATA[1]) * double(ATV[0][1]));\n\t\tlineEquation[1] = coef * ( double(pATA[0]) * double(ATV[0][1]) - double(pATA[2]) * double(ATV[0][0]));\n\t\t/*compute line fit error */\n\t\t//      for(int i=0; i<length; i++){\n\t\t//          coef = double(yCors[offsetS]) - double(xCors[offsetS++]) * lineEquation[0] - lineEquation[1];\n\t\t//          fitError += coef*coef;\n\t\t//      }\n\t\treturn 0;\n\t}\n\t/*If the first pixel in this chain is vertical,\n\t *then we try to find a vertical line, x=ay+b;*/\n\tif (pdirImg[yCors[offsetS]*imageWidth + xCors[offsetS] ] == Vertical)\n\t{\n\t\t/*Build the system,and solve it using least square regression: mat * [a,b]^T = vec\n\t\t * [y0',1]         [x0']\n\t\t * [y1',1] [a]     [x1']\n\t\t *    .    [b]  =   .\n\t\t * [yn',1]         [xn']*/\n//\t\tpMatT = matT.GetData();//matT = [y0', y1', ... yn'; 1,1,...,1]\n\t\tpMatT = matT.ptr<float>();//matT = [y0', y1', ... yn'; 1,1,...,1]\n\t\tfor (int i = 0; i < newLength; i++)\n\t\t{\n\t\t\t*(pMatT + newLength) = 1;\n\t\t\t*(pMatT++)         = yCors[newOffsetS];\n\t\t\tvec[0][i]             = xCors[newOffsetS++];\n\t\t}\n\t\t/* [a,b]^T = Inv(ATA + mat^T * mat) * (ATV + mat^T * vec) */\n//\t\tmatT.MultiplyWithTransposeOf(matT, tempMatLineFit);\n\t\ttempMatLineFit = matT * matT.t();\n\t\ttempVecLineFit = matT * vec;\n\t\tATA = ATA + tempMatLineFit;\n\t\tATV = ATV + tempVecLineFit;\n//\t\tpATA = ATA.GetData();\n\t\tpATA = ATA.ptr<float>();\n\t\tcoef = 1.0 / (double(pATA[0]) * double(pATA[3]) - double(pATA[1]) * double(pATA[2]));\n\t\tlineEquation[0] = coef * ( double(pATA[3]) * double(ATV[0][0]) - double(pATA[1]) * double(ATV[0][1]));\n\t\tlineEquation[1] = coef * ( double(pATA[0]) * double(ATV[0][1]) - double(pATA[2]) * double(ATV[0][0]));\n\t\t/*compute line fit error */\n\t\t//      for(int i=0; i<length; i++){\n\t\t//          coef = double(xCors[offsetS]) - double(yCors[offsetS++]) * lineEquation[0] - lineEquation[1];\n\t\t//          fitError += coef*coef;\n\t\t//      }\n\t}\n\treturn 0;\n}\n\nbool EDLineDetector::LineValidation_(  unsigned int *xCors,   unsigned int *yCors,\n\t\t\t\t\t\t\t\t\t   unsigned int offsetS, unsigned int offsetE,\n\t\t\t\t\t\t\t\t\t   std::array<double, 3> &lineEquation, float &direction)\n{\n\tif (bValidate_)\n\t{\n\t\tint n = offsetE - offsetS;\n\t\t/*first compute the direction of line, make sure that the dark side always be the\n\t\t *left side of a line.*/\n\t\tint meanGradientX = 0, meanGradientY = 0;\n\t\tfloat *pdxImg = dxImg_.ptr<float>();\n\t\tfloat *pdyImg = dyImg_.ptr<float>();\n\t\tdouble dx, dy;\n\t\tstd::vector<double> pointDirection;\n\t\tint index;\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tindex = yCors[offsetS] * imageWidth + xCors[offsetS++];\n\t\t\tmeanGradientX += pdxImg[index];\n\t\t\tmeanGradientY += pdyImg[index];\n\t\t\tdx = (double) pdxImg[index];\n\t\t\tdy = (double) pdyImg[index];\n\t\t\tpointDirection.push_back(atan2(-dx, dy));\n\t\t}\n\t\tdx = fabs(lineEquation[1]);\n\t\tdy = fabs(lineEquation[0]);\n\t\tif (meanGradientX == 0 && meanGradientY == 0) //not possible, if happens, it must be a wrong line,\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif (meanGradientX > 0 && meanGradientY >= 0) //first quadrant, and positive direction of X axis.\n\t\t{\n\t\t\tdirection = atan2(-dy, dx); //line direction is in fourth quadrant\n\t\t}\n\t\tif (meanGradientX <= 0 && meanGradientY > 0) //second quadrant, and positive direction of Y axis.\n\t\t{\n\t\t\tdirection  = atan2(dy, dx); //line direction is in first quadrant\n\t\t}\n\t\tif (meanGradientX < 0 && meanGradientY <= 0) //third quadrant, and negative direction of X axis.\n\t\t{\n\t\t\tdirection = atan2(dy, -dx); //line direction is in second quadrant\n\t\t}\n\t\tif (meanGradientX >= 0 && meanGradientY < 0) //fourth quadrant, and negative direction of Y axis.\n\t\t{\n\t\t\tdirection = atan2(-dy, -dx); //line direction is in third quadrant\n\t\t}\n\t\t/*then check whether the line is on the border of the image. We don't keep the border line.*/\n\t\tif (fabs(direction) < 0.15 || M_PI - fabs(direction) < 0.15) //Horizontal line\n\t\t{\n\t\t\tif (fabs(lineEquation[2]) < 10 || fabs(imageHeight - fabs(lineEquation[2])) < 10) //upper border or lower border\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (fabs(fabs(direction) - M_PI * 0.5) < 0.15) //Vertical line\n\t\t{\n\t\t\tif (fabs(lineEquation[2]) < 10 || fabs(imageWidth - fabs(lineEquation[2])) < 10) //left border or right border\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t//count the aligned points on the line which have the same direction as the line.\n\t\tdouble disDirection;\n\t\tint k = 0;\n\t\tfor (int i = 0; i < n; i++)\n\t\t{\n\t\t\tdisDirection = fabs(direction - pointDirection[i]);\n\t\t\tif (fabs(2 * M_PI - disDirection) < 0.392699 || disDirection < 0.392699) //same direction, pi/8 = 0.392699081698724\n\t\t\t{\n\t\t\t\tk++;\n\t\t\t}\n\t\t}\n\t\t//now compute NFA(Number of False Alarms)\n\t\tdouble ret = nfa(n, k, 0.125, logNT_);\n\n\t\treturn (ret > 0); //0 corresponds to 1 mean false alarm\n\t}\n\telse\n\t{\n\t\treturn true;\n\t}\n}\n"
  },
  {
    "path": "thirdParty/edlines/EDLineDetector.h",
    "content": "/*IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.\n\n By downloading, copying, installing or using the software you agree to this license.\n If you do not agree to this license, do not download, install,\n copy or use the software.\n\n\n                          License Agreement\n               For Open Source Computer Vision Library\n\nCopyright (C) 2011-2012, Lilian Zhang, all rights reserved.\nCopyright (C) 2013, Manuele Tamburrano, Stefano Fabri, all rights reserved.\nThird party copyrights are property of their respective owners.\n\nTo extract edge and lines, this library implements the EDLines Algorithm and the Edge Drawing detector:\nhttp://www.sciencedirect.com/science/article/pii/S0167865511001772\nhttp://www.sciencedirect.com/science/article/pii/S1047320312000831\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n  * Redistributions of source code must retain the above copyright notice,\n    this list of conditions and the following disclaimer.\n\n  * Redistributions in binary form must reproduce the above copyright notice,\n    this list of conditions and the following disclaimer in the documentation\n    and/or other materials provided with the distribution.\n\n  * The name of the copyright holders may not be used to endorse or promote products\n    derived from this software without specific prior written permission.\n\nThis software is provided by the copyright holders and contributors \"as is\" and\nany express or implied warranties, including, but not limited to, the implied\nwarranties of merchantability and fitness for a particular purpose are disclaimed.\nIn no event shall the Intel Corporation or contributors be liable for any direct,\nindirect, incidental, special, exemplary, or consequential damages\n(including, but not limited to, procurement of substitute goods or services;\nloss of use, data, or profits; or business interruption) however caused\nand on any theory of liability, whether in contract, strict liability,\nor tort (including negligence or otherwise) arising in any way out of\nthe use of this software, even if advised of the possibility of such damage.\n*/\n\n#ifndef EDLINEDETECTOR_HH_\n#define EDLINEDETECTOR_HH_\n\n#include <vector>\n#include <iostream>\n#include <list>\n#include <opencv2/core/core.hpp>\n#include <opencv2/features2d/features2d.hpp>\n#include <opencv2/imgproc/imgproc.hpp>\n#include <opencv2/highgui/highgui.hpp>\n//#include \"opencv2/core/utility.hpp\"\n#include <array>\n\n\nstruct Pixel\n{\n\tunsigned int x; //X coordinate\n\tunsigned int y; //Y coordinate\n};\nstruct EdgeChains\n{\n\tstd::vector<unsigned int> xCors;//all the x coordinates of edge points\n\tstd::vector<unsigned int> yCors;//all the y coordinates of edge points\n\tstd::vector<unsigned int> sId;  //the start index of each edge in the coordinate arrays\n\tunsigned int numOfEdges;        //the number of edges whose length are larger than minLineLen; numOfEdges < sId.size;\n};\nstruct LineChains\n{\n\tstd::vector<unsigned int> xCors;//all the x coordinates of line points\n\tstd::vector<unsigned int> yCors;//all the y coordinates of line points\n\tstd::vector<unsigned int> sId;  //the start index of each line in the coordinate arrays\n\tunsigned int numOfLines;        //the number of lines whose length are larger than minLineLen; numOfLines < sId.size;\n};\n\ntypedef  std::list<Pixel> PixelChain;//each edge is a pixel chain\n\n\nstruct EDLineParam\n{\n\tint \tksize;\n\tfloat \tsigma;\n\tfloat \tgradientThreshold;\n\tfloat \tanchorThreshold;\n\tint \tscanIntervals;\n\tint \tminLineLen;\n\tdouble \tlineFitErrThreshold;\n};\n\n#define RELATIVE_ERROR_FACTOR   100.0\n#define M_LN10   2.30258509299404568402\n#define log_gamma(x)    ((x)>15.0?log_gamma_windschitl(x):log_gamma_lanczos(x))\n\n/* This class is used to detect lines from input image.\n * First, edges are extracted from input image following the method presented in Cihan Topal and\n * Cuneyt Akinlar's paper:\"Edge Drawing: A Heuristic Approach to Robust Real-Time Edge Detection\", 2010.\n * Then, lines are extracted from the edge image following the method presented in Cuneyt Akinlar and\n * Cihan Topal's paper:\"EDLines: A real-time line segment detector with a false detection control\", 2011\n * PS: The linking step of edge detection has a little bit difference with the Edge drawing algorithm\n *     described in the paper. The edge chain doesn't stop when the pixel direction is changed.\n */\nclass EDLineDetector\n{\npublic:\n\tEDLineDetector();\n\tEDLineDetector(EDLineParam param);\n\t~EDLineDetector();\n\n\t/*extract edges from image\n\t *image:    In, gray image;\n\t *edges:    Out, store the edges, each edge is a pixel chain\n\t *smoothed: In, flag to mark whether the image has already been smoothed by Gaussian filter.\n\t *return -1: error happen\n\t */\n\tint EdgeDrawing(cv::Mat const &image, EdgeChains &edgeChains, bool smoothed = false);\n\t/*extract lines from image\n\t *image:    In, gray image;\n\t *lines:    Out, store the extracted lines,\n\t *smoothed: In, flag to mark whether the image has already been smoothed by Gaussian filter.\n\t *return -1: error happen\n\t */\n\tint EDline(cv::Mat const &image, LineChains &lines, bool smoothed = false);\n\t/*extract line from image, and store them*/\n\tint EDline(cv::Mat const &image, bool smoothed = false);\n\n\tcv::Mat dxImg_;//store the dxImg;\n\tcv::Mat dyImg_;//store the dyImg;\n\tcv::Mat gImgWO_;//store the gradient image without threshold;\n\tLineChains lines_; //store the detected line chains;\n\t//store the line Equation coefficients, vec3=[w1,w2,w3] for line w1*x + w2*y + w3=0;\n\tstd::vector<std::array<double, 3> > lineEquations_;\n\t//store the line endpoints, [x1,y1,x2,y3]\n\tstd::vector<std::array<float, 4> > lineEndpoints_;\n\t//store the line direction\n\tstd::vector<float>  lineDirection_;\n\t//store the line ::salience, which is the summation of gradients of pixels on line\n\tstd::vector<float>  lineSalience_;\n\tunsigned int imageWidth;\n\tunsigned int imageHeight;\n\nprivate:\n\tvoid InitEDLine_();\n\t/*For an input edge chain, find the best fit line, the default chain length is minLineLen_\n\t *xCors:  In, pointer to the X coordinates of pixel chain;\n\t *yCors:  In, pointer to the Y coordinates of pixel chain;\n\t *offsetS:In, start index of this chain in array;\n\t *lineEquation: Out, [a,b] which are the coefficient of lines y=ax+b(horizontal) or x=ay+b(vertical);\n\t *return:  line fit error; -1:error happens;\n\t */\n\tdouble LeastSquaresLineFit_(unsigned int *xCors, unsigned int *yCors,\n\t                            unsigned int offsetS,   std::array<double, 2> &lineEquation);\n\t/*For an input pixel chain, find the best fit line. Only do the update based on new points.\n\t *For A*x=v,  Least square estimation of x = Inv(A^T * A) * (A^T * v);\n\t *If some new observations are added, i.e, [A; A'] * x = [v; v'],\n\t *then x' = Inv(A^T * A + (A')^T * A') * (A^T * v + (A')^T * v');\n\t *xCors:  In, pointer to the X coordinates of pixel chain;\n\t *yCors:  In, pointer to the Y coordinates of pixel chain;\n\t *offsetS:In, start index of this chain in array;\n\t *newOffsetS: In, start index of extended part;\n\t *offsetE:In, end index of this chain in array;\n\t *lineEquation: Out, [a,b] which are the coefficient of lines y=ax+b(horizontal) or x=ay+b(vertical);\n\t *return:  line fit error; -1:error happens;\n\t */\n\tdouble LeastSquaresLineFit_(unsigned int *xCors, unsigned int *yCors,\n\t                            unsigned int offsetS, unsigned int newOffsetS,\n\t                            unsigned int offsetE,   std::array<double, 2> &lineEquation);\n\t/* Validate line based on the Helmholtz principle, which basically states that\n\t * for a structure to be perceptually meaningful, the expectation of this structure\n\t * by chance must be very low.\n\t */\n\tbool LineValidation_(unsigned int *xCors, unsigned int *yCors,\n\t                     unsigned int offsetS, unsigned int offsetE,\n\t                     std::array<double, 3> &lineEquation, float &direction);\n\tbool bValidate_;//flag to decide whether line will be validated\n\tint ksize_; //the size of Gaussian kernel: ksize X ksize, default value is 5.\n\tfloat sigma_;//the sigma of Gaussian kernal, default value is 1.0.\n\t/*the threshold of pixel gradient magnitude.\n\t *Only those pixel whose gradient magnitude are larger than this threshold will be\n\t *taken as possible edge points. Default value is 36*/\n\tshort gradienThreshold_;\n\t/*If the pixel's gradient value is bigger than both of its neighbors by a\n\t *certain threshold (ANCHOR_THRESHOLD), the pixel is marked to be an anchor.\n\t *Default value is 8*/\n\tunsigned char anchorThreshold_;\n\t/*anchor testing can be performed at different scan intervals, i.e.,\n\t *every row/column, every second row/column etc.\n\t *Default value is 2*/\n\tunsigned int scanIntervals_;\n\tint minLineLen_;//minimal acceptable line length\n\t/*For example, there two edges in the image:\n\t *edge1 = [(7,4), (8,5), (9,6),| (10,7)|, (11, 8), (12,9)] and\n\t *edge2 = [(14,9), (15,10), (16,11), (17,12),| (18, 13)|, (19,14)] ; then we store them as following:\n\t *pFirstPartEdgeX_ = [10, 11, 12, 18, 19];//store the first part of each edge[from middle to end]\n\t *pFirstPartEdgeY_ = [7,  8,  9,  13, 14];\n\t *pFirstPartEdgeS_ = [0,3,5];// the index of start point of first part of each edge\n\t *pSecondPartEdgeX_ = [10, 9, 8, 7, 18, 17, 16, 15, 14];//store the second part of each edge[from middle to front]\n\t *pSecondPartEdgeY_ = [7,  6, 5, 4, 13, 12, 11, 10, 9];//anchor points(10, 7) and (18, 13) are stored again\n\t *pSecondPartEdgeS_ = [0, 4, 9];// the index of start point of second part of each edge\n\t *This type of storage order is because of the order of edge detection process.\n\t *For each edge, start from one anchor point, first go right, then go left or first go down, then go up*/\n\tunsigned int *pFirstPartEdgeX_;//store the X coordinates of the first part of the pixels for chains\n\tunsigned int *pFirstPartEdgeY_;//store the Y coordinates of the first part of the pixels for chains\n\tunsigned int *pFirstPartEdgeS_;//store the start index of every edge chain in the first part arrays\n\tunsigned int *pSecondPartEdgeX_;//store the X coordinates of the second part of the pixels for chains\n\tunsigned int *pSecondPartEdgeY_;//store the Y coordinates of the second part of the pixels for chains\n\tunsigned int *pSecondPartEdgeS_;//store the start index of every edge chain in the second part arrays\n\tunsigned int *pAnchorX_;//store the X coordinates of anchors\n\tunsigned int *pAnchorY_;//store the Y coordinates of anchors\n\tcv::Mat edgeImage_;\n\t/*The threshold of line fit error;\n\t *If lineFitErr is large than this threshold, then\n\t *the pixel chain is not accepted as a single line segment.*/\n\tdouble lineFitErrThreshold_;\n\n\n\tcv::Mat gImg_;//store the gradient image;\n\tcv::Mat dirImg_;//store the direction image\n\tdouble logNT_;\n\tcv::Mat_<float> ATA;     //the previous matrix of A^T * A;\n\tcv::Mat_<float> ATV;    //the previous vector of A^T * V;\n\tcv::Mat_<float> fitMatT;     //the matrix used in line fit function;\n\tcv::Mat_<float> fitVec;    //the vector used in line fit function;\n\tcv::Mat_<float> tempMatLineFit;  //the matrix used in line fit function;\n\tcv::Mat_<float> tempVecLineFit;    //the vector used in line fit function;\n\n\n\t/** Compare doubles by relative error.\n\t     The resulting rounding error after floating point computations\n\t     depend on the specific operations done. The same number computed by\n\t     different algorithms could present different rounding errors. For a\n\t     useful comparison, an estimation of the relative rounding error\n\t     should be considered and compared to a factor times EPS. The factor\n\t     should be related to the accumulated rounding error in the chain of\n\t     computation. Here, as a simplification, a fixed factor is used.\n\t */\n\tstatic int double_equal(double a, double b)\n\t{\n\t\tdouble abs_diff, aa, bb, abs_max;\n\t\t/* trivial case */\n\t\tif ( a == b ) return true;\n\t\tabs_diff = fabs(a - b);\n\t\taa = fabs(a);\n\t\tbb = fabs(b);\n\t\tabs_max = aa > bb ? aa : bb;\n\t\t/* DBL_MIN is the smallest normalized number, thus, the smallest\n\t\t  number whose relative error is bounded by DBL_EPSILON. For\n\t\t  smaller numbers, the same quantization steps as for DBL_MIN\n\t\t  are used. Then, for smaller numbers, a meaningful \"relative\"\n\t\t  error should be computed by dividing the difference by DBL_MIN. */\n\t\tif ( abs_max < DBL_MIN ) abs_max = DBL_MIN;\n\t\t/* equal if relative error <= factor x eps */\n\t\treturn (abs_diff / abs_max) <= (RELATIVE_ERROR_FACTOR * DBL_EPSILON);\n\t}\n\t/** Computes the natural logarithm of the absolute value of\n\t     the gamma function of x using the Lanczos approximation.\n\t     See http://www.rskey.org/gamma.htm\n\t     The formula used is\n\t     @f[\n\t       \\Gamma(x) = \\frac{ \\sum_{n=0}^{N} q_n x^n }{ \\Pi_{n=0}^{N} (x+n) }\n\t                   (x+5.5)^{x+0.5} e^{-(x+5.5)}\n\t     @f]\n\t     so\n\t     @f[\n\t       \\log\\Gamma(x) = \\log\\left( \\sum_{n=0}^{N} q_n x^n \\right)\n\t                       + (x+0.5) \\log(x+5.5) - (x+5.5) - \\sum_{n=0}^{N} \\log(x+n)\n\t     @f]\n\t     and\n\t       q0 = 75122.6331530,\n\t       q1 = 80916.6278952,\n\t       q2 = 36308.2951477,\n\t       q3 = 8687.24529705,\n\t       q4 = 1168.92649479,\n\t       q5 = 83.8676043424,\n\t       q6 = 2.50662827511.\n\t */\n\tstatic double log_gamma_lanczos(double x)\n\t{\n\t\tstatic double q[7] = { 75122.6331530, 80916.6278952, 36308.2951477,\n\t\t                       8687.24529705, 1168.92649479, 83.8676043424,\n\t\t                       2.50662827511\n\t\t                     };\n\t\tdouble a = (x + 0.5) * log(x + 5.5) - (x + 5.5);\n\t\tdouble b = 0.0;\n\t\tint n;\n\t\tfor (n = 0; n < 7; n++)\n\t\t{\n\t\t\ta -= log( x + (double) n );\n\t\t\tb += q[n] * pow( x, (double) n );\n\t\t}\n\t\treturn a + log(b);\n\t}\n\t/** Computes the natural logarithm of the absolute value of\n\t     the gamma function of x using Windschitl method.\n\t     See http://www.rskey.org/gamma.htm\n\t     The formula used is\n\t     @f[\n\t         \\Gamma(x) = \\sqrt{\\frac{2\\pi}{x}} \\left( \\frac{x}{e}\n\t                     \\sqrt{ x\\sinh(1/x) + \\frac{1}{810x^6} } \\right)^x\n\t     @f]\n\t     so\n\t     @f[\n\t         \\log\\Gamma(x) = 0.5\\log(2\\pi) + (x-0.5)\\log(x) - x\n\t                       + 0.5x\\log\\left( x\\sinh(1/x) + \\frac{1}{810x^6} \\right).\n\t     @f]\n\t     This formula is a good approximation when x > 15.\n\t */\n\tstatic double log_gamma_windschitl(double x)\n\t{\n\t\treturn 0.918938533204673 + (x - 0.5) * log(x) - x\n\t\t       + 0.5 * x * log( x * sinh(1 / x) + 1 / (810.0 * pow(x, 6.0)) );\n\t}\n\t/** Computes -log10(NFA).\n\t     NFA stands for Number of False Alarms:\n\t     @f[\n\t         \\mathrm{NFA} = NT \\cdot B(n,k,p)\n\t     @f]\n\t     - NT       - number of tests\n\t     - B(n,k,p) - tail of binomial distribution with parameters n,k and p:\n\t     @f[\n\t         B(n,k,p) = \\sum_{j=k}^n\n\t                    \\left(\\begin{array}{c}n\\\\j\\end{array}\\right)\n\t                    p^{j} (1-p)^{n-j}\n\t     @f]\n\t     The value -log10(NFA) is equivalent but more intuitive than NFA:\n\t     - -1 corresponds to 10 mean false alarms\n\t     -  0 corresponds to 1 mean false alarm\n\t     -  1 corresponds to 0.1 mean false alarms\n\t     -  2 corresponds to 0.01 mean false alarms\n\t     -  ...\n\t     Used this way, the bigger the value, better the detection,\n\t     and a logarithmic scale is used.\n\t     @param n,k,p binomial parameters.\n\t     @param logNT logarithm of Number of Tests\n\t     The computation is based in the gamma function by the following\n\t     relation:\n\t     @f[\n\t         \\left(\\begin{array}{c}n\\\\k\\end{array}\\right)\n\t         = \\frac{ \\Gamma(n+1) }{ \\Gamma(k+1) \\cdot \\Gamma(n-k+1) }.\n\t     @f]\n\t     We use efficient algorithms to compute the logarithm of\n\t     the gamma function.\n\t     To make the computation faster, not all the sum is computed, part\n\t     of the terms are neglected based on a bound to the error obtained\n\t     (an error of 10% in the result is accepted).\n\t */\n\tstatic double nfa(int n, int    k,  double p, double  logNT)\n\t{\n\t\tdouble tolerance = 0.1;       /* an error of 10% in the result is accepted */\n\t\tdouble log1term, term, bin_term, mult_term, bin_tail, err, p_term;\n\t\tint i;\n\n\t\t/* check parameters */\n\t\tif ( n < 0 || k < 0 || k > n || p <= 0.0 || p >= 1.0 )\n\t\t{\n\t\t\tstd::cout << \"nfa: wrong n, k or p values.\" << std::endl;\n\t\t\texit(0);\n\t\t}\n\t\t/* trivial cases */\n\t\tif ( n == 0 || k == 0 ) return -logNT;\n\t\tif ( n == k ) return -logNT - (double) n * log10(p);\n\n\t\t/* probability term */\n\t\tp_term = p / (1.0 - p);\n\n\t\t/* compute the first term of the series */\n\t\t/*\n\t\t  binomial_tail(n,k,p) = sum_{i=k}^n bincoef(n,i) * p^i * (1-p)^{n-i}\n\t\t  where bincoef(n,i) are the binomial coefficients.\n\t\t  But\n\t\t    bincoef(n,k) = gamma(n+1) / ( gamma(k+1) * gamma(n-k+1) ).\n\t\t  We use this to compute the first term. Actually the log of it.\n\t\t */\n\t\tlog1term = log_gamma( (double) n + 1.0 ) - log_gamma( (double) k + 1.0 )\n\t\t           - log_gamma( (double) (n - k) + 1.0 )\n\t\t           + (double) k * log(p) + (double) (n - k) * log(1.0 - p);\n\t\tterm = exp(log1term);\n\n\t\t/* in some cases no more computations are needed */\n\t\tif ( double_equal(term, 0.0) ) /* the first term is almost zero */\n\t\t{\n\t\t\tif ( (double) k > (double) n * p )    /* at begin or end of the tail?  */\n\t\t\t\treturn -log1term / M_LN10 - logNT;  /* end: use just the first term  */\n\t\t\telse\n\t\t\t\treturn -logNT;                      /* begin: the tail is roughly 1  */\n\t\t}\n\n\t\t/* compute more terms if needed */\n\t\tbin_tail = term;\n\t\tfor (i = k + 1; i <= n; i++)\n\t\t{\n\t\t\t/*    As\n\t\t\t    term_i = bincoef(n,i) * p^i * (1-p)^(n-i)\n\t\t\t  and\n\t\t\t    bincoef(n,i)/bincoef(n,i-1) = n-i+1 / i,\n\t\t\t  then,\n\t\t\t    term_i / term_i-1 = (n-i+1)/i * p/(1-p)\n\t\t\t  and\n\t\t\t    term_i = term_i-1 * (n-i+1)/i * p/(1-p).\n\t\t\t  p/(1-p) is computed only once and stored in 'p_term'.\n\t\t\t */\n\t\t\tbin_term = (double) (n - i + 1) / (double) i;\n\t\t\tmult_term = bin_term * p_term;\n\t\t\tterm *= mult_term;\n\t\t\tbin_tail += term;\n\t\t\tif (bin_term < 1.0)\n\t\t\t{\n\t\t\t\t/* When bin_term<1 then mult_term_j<mult_term_i for j>i.\n\t\t\t\t  Then, the error on the binomial tail when truncated at\n\t\t\t\t  the i term can be bounded by a geometric series of form\n\t\t\t\t  term_i * sum mult_term_i^j.                            */\n\t\t\t\terr = term * ( ( 1.0 - pow( mult_term, (double) (n - i + 1) ) ) /\n\t\t\t\t               (1.0 - mult_term) - 1.0 );\n\t\t\t\t/* One wants an error at most of tolerance*final_result, or:\n\t\t\t\t  tolerance * abs(-log10(bin_tail)-logNT).\n\t\t\t\t  Now, the error that can be accepted on bin_tail is\n\t\t\t\t  given by tolerance*final_result divided by the derivative\n\t\t\t\t  of -log10(x) when x=bin_tail. that is:\n\t\t\t\t  tolerance * abs(-log10(bin_tail)-logNT) / (1/bin_tail)\n\t\t\t\t  Finally, we truncate the tail if the error is less than:\n\t\t\t\t  tolerance * abs(-log10(bin_tail)-logNT) * bin_tail        */\n\t\t\t\tif ( err < tolerance * fabs(-log10(bin_tail) - logNT) * bin_tail ) break;\n\t\t\t}\n\t\t}\n\t\treturn -log10(bin_tail) - logNT;\n\t}\n};\n\n#endif /* EDLINEDETECTOR_HH_ */\n"
  },
  {
    "path": "thirdParty/json/json.hpp",
    "content": "/*\n    __ _____ _____ _____\n __|  |   __|     |   | |  JSON for Modern C++\n|  |  |__   |  |  | | | |  version 3.0.1\n|_____|_____|_____|_|___|  https://github.com/nlohmann/json\n\nLicensed under the MIT License <http://opensource.org/licenses/MIT>.\nCopyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>.\n\nPermission is hereby  granted, free of charge, to any  person obtaining a copy\nof this software and associated  documentation files (the \"Software\"), to deal\nin the Software  without restriction, including without  limitation the rights\nto  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell\ncopies  of  the Software,  and  to  permit persons  to  whom  the Software  is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE  IS PROVIDED \"AS  IS\", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR\nIMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,\nFITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE\nAUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER\nLIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#ifndef NLOHMANN_JSON_HPP\n#define NLOHMANN_JSON_HPP\n\n#include <algorithm> // all_of, copy, fill, find, for_each, generate_n, none_of, remove, reverse, transform\n#include <array> // array\n#include <cassert> // assert\n#include <ciso646> // and, not, or\n#include <clocale> // lconv, localeconv\n#include <cmath> // isfinite, labs, ldexp, signbit\n#include <cstddef> // nullptr_t, ptrdiff_t, size_t\n#include <cstdint> // int64_t, uint64_t\n#include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull\n#include <cstring> // memcpy, strlen\n#include <forward_list> // forward_list\n#include <functional> // function, hash, less\n#include <initializer_list> // initializer_list\n#include <iomanip> // hex\n#include <iosfwd>   // istream, ostream\n#include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator\n#include <limits> // numeric_limits\n#include <locale> // locale\n#include <map> // map\n#include <memory> // addressof, allocator, allocator_traits, unique_ptr\n#include <numeric> // accumulate\n#include <sstream> // stringstream\n#include <string> // getline, stoi, string, to_string\n#include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type\n#include <utility> // declval, forward, make_pair, move, pair, swap\n#include <valarray> // valarray\n#include <vector> // vector\n\n// exclude unsupported compilers\n#if defined(__clang__)\n    #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400\n        #error \"unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers\"\n    #endif\n#elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER))\n    #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40900\n        #error \"unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers\"\n    #endif\n#endif\n\n// disable float-equal warnings on GCC/clang\n#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)\n    #pragma GCC diagnostic push\n    #pragma GCC diagnostic ignored \"-Wfloat-equal\"\n#endif\n\n// disable documentation warnings on clang\n#if defined(__clang__)\n    #pragma GCC diagnostic push\n    #pragma GCC diagnostic ignored \"-Wdocumentation\"\n#endif\n\n// allow for portable deprecation warnings\n#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)\n    #define JSON_DEPRECATED __attribute__((deprecated))\n#elif defined(_MSC_VER)\n    #define JSON_DEPRECATED __declspec(deprecated)\n#else\n    #define JSON_DEPRECATED\n#endif\n\n// allow to disable exceptions\n#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && not defined(JSON_NOEXCEPTION)\n    #define JSON_THROW(exception) throw exception\n    #define JSON_TRY try\n    #define JSON_CATCH(exception) catch(exception)\n#else\n    #define JSON_THROW(exception) std::abort()\n    #define JSON_TRY if(true)\n    #define JSON_CATCH(exception) if(false)\n#endif\n\n// manual branch prediction\n#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)\n    #define JSON_LIKELY(x)      __builtin_expect(!!(x), 1)\n    #define JSON_UNLIKELY(x)    __builtin_expect(!!(x), 0)\n#else\n    #define JSON_LIKELY(x)      x\n    #define JSON_UNLIKELY(x)    x\n#endif\n\n// C++ language standard detection\n#if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464\n    #define JSON_HAS_CPP_17\n    #define JSON_HAS_CPP_14\n#elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1)\n    #define JSON_HAS_CPP_14\n#endif\n\n/*!\n@brief namespace for Niels Lohmann\n@see https://github.com/nlohmann\n@since version 1.0.0\n*/\nnamespace nlohmann\n{\ntemplate<typename = void, typename = void>\nstruct adl_serializer;\n\n// forward declaration of basic_json (required to split the class)\ntemplate<template<typename, typename, typename...> class ObjectType = std::map,\n         template<typename, typename...> class ArrayType = std::vector,\n         class StringType = std::string, class BooleanType = bool,\n         class NumberIntegerType = std::int64_t,\n         class NumberUnsignedType = std::uint64_t,\n         class NumberFloatType = double,\n         template<typename> class AllocatorType = std::allocator,\n         template<typename, typename = void> class JSONSerializer = adl_serializer>\nclass basic_json;\n\n// Ugly macros to avoid uglier copy-paste when specializing basic_json. They\n// may be removed in the future once the class is split.\n\n#define NLOHMANN_BASIC_JSON_TPL_DECLARATION                                \\\n    template<template<typename, typename, typename...> class ObjectType,   \\\n             template<typename, typename...> class ArrayType,              \\\n             class StringType, class BooleanType, class NumberIntegerType, \\\n             class NumberUnsignedType, class NumberFloatType,              \\\n             template<typename> class AllocatorType,                       \\\n             template<typename, typename = void> class JSONSerializer>\n\n#define NLOHMANN_BASIC_JSON_TPL                                            \\\n    basic_json<ObjectType, ArrayType, StringType, BooleanType,             \\\n    NumberIntegerType, NumberUnsignedType, NumberFloatType,                \\\n    AllocatorType, JSONSerializer>\n\n\n/*!\n@brief unnamed namespace with internal helper functions\n\nThis namespace collects some functions that could not be defined inside the\n@ref basic_json class.\n\n@since version 2.1.0\n*/\nnamespace detail\n{\n////////////////\n// exceptions //\n////////////////\n\n/*!\n@brief general exception of the @ref basic_json class\n\nThis class is an extension of `std::exception` objects with a member @a id for\nexception ids. It is used as the base class for all exceptions thrown by the\n@ref basic_json class. This class can hence be used as \"wildcard\" to catch\nexceptions.\n\nSubclasses:\n- @ref parse_error for exceptions indicating a parse error\n- @ref invalid_iterator for exceptions indicating errors with iterators\n- @ref type_error for exceptions indicating executing a member function with\n                  a wrong type\n- @ref out_of_range for exceptions indicating access out of the defined range\n- @ref other_error for exceptions indicating other library errors\n\n@internal\n@note To have nothrow-copy-constructible exceptions, we internally use\n      `std::runtime_error` which can cope with arbitrary-length error messages.\n      Intermediate strings are built with static functions and then passed to\n      the actual constructor.\n@endinternal\n\n@liveexample{The following code shows how arbitrary library exceptions can be\ncaught.,exception}\n\n@since version 3.0.0\n*/\nclass exception : public std::exception\n{\n  public:\n    /// returns the explanatory string\n    const char* what() const noexcept override\n    {\n        return m.what();\n    }\n\n    /// the id of the exception\n    const int id;\n\n  protected:\n    exception(int id_, const char* what_arg) : id(id_), m(what_arg) {}\n\n    static std::string name(const std::string& ename, int id_)\n    {\n        return \"[json.exception.\" + ename + \".\" + std::to_string(id_) + \"] \";\n    }\n\n  private:\n    /// an exception object as storage for error messages\n    std::runtime_error m;\n};\n\n/*!\n@brief exception indicating a parse error\n\nThis exception is thrown by the library when a parse error occurs. Parse errors\ncan occur during the deserialization of JSON text, CBOR, MessagePack, as well\nas when using JSON Patch.\n\nMember @a byte holds the byte index of the last read character in the input\nfile.\n\nExceptions have ids 1xx.\n\nname / id                      | example message | description\n------------------------------ | --------------- | -------------------------\njson.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position.\njson.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\\uxxxx` entries (\"surrogate pairs\"). This error indicates that the surrogate pair is incomplete or contains an invalid code point.\njson.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.\njson.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects.\njson.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one \"op\" member, whose value indicates the operation to perform. Its value must be one of \"add\", \"remove\", \"replace\", \"move\", \"copy\", or \"test\"; other values are errors.\njson.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`.\njson.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character.\njson.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences.\njson.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number.\njson.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.\njson.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read.\njson.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read.\n\n@note For an input with n bytes, 1 is the index of the first character and n+1\n      is the index of the terminating null byte or the end of file. This also\n      holds true when reading a byte vector (CBOR or MessagePack).\n\n@liveexample{The following code shows how a `parse_error` exception can be\ncaught.,parse_error}\n\n@sa @ref exception for the base class of the library exceptions\n@sa @ref invalid_iterator for exceptions indicating errors with iterators\n@sa @ref type_error for exceptions indicating executing a member function with\n                    a wrong type\n@sa @ref out_of_range for exceptions indicating access out of the defined range\n@sa @ref other_error for exceptions indicating other library errors\n\n@since version 3.0.0\n*/\nclass parse_error : public exception\n{\n  public:\n    /*!\n    @brief create a parse error exception\n    @param[in] id_       the id of the exception\n    @param[in] byte_     the byte index where the error occurred (or 0 if the\n                         position cannot be determined)\n    @param[in] what_arg  the explanatory string\n    @return parse_error object\n    */\n    static parse_error create(int id_, std::size_t byte_, const std::string& what_arg)\n    {\n        std::string w = exception::name(\"parse_error\", id_) + \"parse error\" +\n                        (byte_ != 0 ? (\" at \" + std::to_string(byte_)) : \"\") +\n                        \": \" + what_arg;\n        return parse_error(id_, byte_, w.c_str());\n    }\n\n    /*!\n    @brief byte index of the parse error\n\n    The byte index of the last read character in the input file.\n\n    @note For an input with n bytes, 1 is the index of the first character and\n          n+1 is the index of the terminating null byte or the end of file.\n          This also holds true when reading a byte vector (CBOR or MessagePack).\n    */\n    const std::size_t byte;\n\n  private:\n    parse_error(int id_, std::size_t byte_, const char* what_arg)\n        : exception(id_, what_arg), byte(byte_) {}\n};\n\n/*!\n@brief exception indicating errors with iterators\n\nThis exception is thrown if iterators passed to a library function do not match\nthe expected semantics.\n\nExceptions have ids 2xx.\n\nname / id                           | example message | description\n----------------------------------- | --------------- | -------------------------\njson.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.\njson.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.\njson.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.\njson.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid.\njson.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid.\njson.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range.\njson.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.\njson.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.\njson.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.\njson.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid.\njson.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to.\njson.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container.\njson.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered.\njson.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin().\n\n@liveexample{The following code shows how an `invalid_iterator` exception can be\ncaught.,invalid_iterator}\n\n@sa @ref exception for the base class of the library exceptions\n@sa @ref parse_error for exceptions indicating a parse error\n@sa @ref type_error for exceptions indicating executing a member function with\n                    a wrong type\n@sa @ref out_of_range for exceptions indicating access out of the defined range\n@sa @ref other_error for exceptions indicating other library errors\n\n@since version 3.0.0\n*/\nclass invalid_iterator : public exception\n{\n  public:\n    static invalid_iterator create(int id_, const std::string& what_arg)\n    {\n        std::string w = exception::name(\"invalid_iterator\", id_) + what_arg;\n        return invalid_iterator(id_, w.c_str());\n    }\n\n  private:\n    invalid_iterator(int id_, const char* what_arg)\n        : exception(id_, what_arg) {}\n};\n\n/*!\n@brief exception indicating executing a member function with a wrong type\n\nThis exception is thrown in case of a type error; that is, a library function is\nexecuted on a JSON value whose type does not match the expected semantics.\n\nExceptions have ids 3xx.\n\nname / id                     | example message | description\n----------------------------- | --------------- | -------------------------\njson.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.\njson.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.\njson.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&.\njson.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types.\njson.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types.\njson.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types.\njson.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types.\njson.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types.\njson.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types.\njson.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types.\njson.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types.\njson.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types.\njson.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined.\njson.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers.\njson.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive.\njson.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. |\n\n@liveexample{The following code shows how a `type_error` exception can be\ncaught.,type_error}\n\n@sa @ref exception for the base class of the library exceptions\n@sa @ref parse_error for exceptions indicating a parse error\n@sa @ref invalid_iterator for exceptions indicating errors with iterators\n@sa @ref out_of_range for exceptions indicating access out of the defined range\n@sa @ref other_error for exceptions indicating other library errors\n\n@since version 3.0.0\n*/\nclass type_error : public exception\n{\n  public:\n    static type_error create(int id_, const std::string& what_arg)\n    {\n        std::string w = exception::name(\"type_error\", id_) + what_arg;\n        return type_error(id_, w.c_str());\n    }\n\n  private:\n    type_error(int id_, const char* what_arg) : exception(id_, what_arg) {}\n};\n\n/*!\n@brief exception indicating access out of the defined range\n\nThis exception is thrown in case a library function is called on an input\nparameter that exceeds the expected range, for instance in case of array\nindices or nonexisting object keys.\n\nExceptions have ids 4xx.\n\nname / id                       | example message | description\n------------------------------- | --------------- | -------------------------\njson.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1.\njson.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.\njson.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object.\njson.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved.\njson.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value.\njson.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF.\n\n@liveexample{The following code shows how an `out_of_range` exception can be\ncaught.,out_of_range}\n\n@sa @ref exception for the base class of the library exceptions\n@sa @ref parse_error for exceptions indicating a parse error\n@sa @ref invalid_iterator for exceptions indicating errors with iterators\n@sa @ref type_error for exceptions indicating executing a member function with\n                    a wrong type\n@sa @ref other_error for exceptions indicating other library errors\n\n@since version 3.0.0\n*/\nclass out_of_range : public exception\n{\n  public:\n    static out_of_range create(int id_, const std::string& what_arg)\n    {\n        std::string w = exception::name(\"out_of_range\", id_) + what_arg;\n        return out_of_range(id_, w.c_str());\n    }\n\n  private:\n    out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {}\n};\n\n/*!\n@brief exception indicating other library errors\n\nThis exception is thrown in case of errors that cannot be classified with the\nother exception types.\n\nExceptions have ids 5xx.\n\nname / id                      | example message | description\n------------------------------ | --------------- | -------------------------\njson.exception.other_error.501 | unsuccessful: {\"op\":\"test\",\"path\":\"/baz\", \"value\":\"bar\"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed.\n\n@sa @ref exception for the base class of the library exceptions\n@sa @ref parse_error for exceptions indicating a parse error\n@sa @ref invalid_iterator for exceptions indicating errors with iterators\n@sa @ref type_error for exceptions indicating executing a member function with\n                    a wrong type\n@sa @ref out_of_range for exceptions indicating access out of the defined range\n\n@liveexample{The following code shows how an `other_error` exception can be\ncaught.,other_error}\n\n@since version 3.0.0\n*/\nclass other_error : public exception\n{\n  public:\n    static other_error create(int id_, const std::string& what_arg)\n    {\n        std::string w = exception::name(\"other_error\", id_) + what_arg;\n        return other_error(id_, w.c_str());\n    }\n\n  private:\n    other_error(int id_, const char* what_arg) : exception(id_, what_arg) {}\n};\n\n\n\n///////////////////////////\n// JSON type enumeration //\n///////////////////////////\n\n/*!\n@brief the JSON type enumeration\n\nThis enumeration collects the different JSON types. It is internally used to\ndistinguish the stored values, and the functions @ref basic_json::is_null(),\n@ref basic_json::is_object(), @ref basic_json::is_array(),\n@ref basic_json::is_string(), @ref basic_json::is_boolean(),\n@ref basic_json::is_number() (with @ref basic_json::is_number_integer(),\n@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),\n@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and\n@ref basic_json::is_structured() rely on it.\n\n@note There are three enumeration entries (number_integer, number_unsigned, and\nnumber_float), because the library distinguishes these three types for numbers:\n@ref basic_json::number_unsigned_t is used for unsigned integers,\n@ref basic_json::number_integer_t is used for signed integers, and\n@ref basic_json::number_float_t is used for floating-point numbers or to\napproximate integers which do not fit in the limits of their respective type.\n\n@sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON\nvalue with the default value for a given type\n\n@since version 1.0.0\n*/\nenum class value_t : uint8_t\n{\n    null,             ///< null value\n    object,           ///< object (unordered set of name/value pairs)\n    array,            ///< array (ordered collection of values)\n    string,           ///< string value\n    boolean,          ///< boolean value\n    number_integer,   ///< number value (signed integer)\n    number_unsigned,  ///< number value (unsigned integer)\n    number_float,     ///< number value (floating-point)\n    discarded         ///< discarded by the the parser callback function\n};\n\n/*!\n@brief comparison operator for JSON types\n\nReturns an ordering that is similar to Python:\n- order: null < boolean < number < object < array < string\n- furthermore, each type is not smaller than itself\n- discarded values are not comparable\n\n@since version 1.0.0\n*/\ninline bool operator<(const value_t lhs, const value_t rhs) noexcept\n{\n    static constexpr std::array<uint8_t, 8> order = {{\n            0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */,\n            1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */\n        }\n    };\n\n    const auto l_index = static_cast<std::size_t>(lhs);\n    const auto r_index = static_cast<std::size_t>(rhs);\n    return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index];\n}\n\n\n/////////////\n// helpers //\n/////////////\n\ntemplate<typename> struct is_basic_json : std::false_type {};\n\nNLOHMANN_BASIC_JSON_TPL_DECLARATION\nstruct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {};\n\n// alias templates to reduce boilerplate\ntemplate<bool B, typename T = void>\nusing enable_if_t = typename std::enable_if<B, T>::type;\n\ntemplate<typename T>\nusing uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;\n\n// implementation of C++14 index_sequence and affiliates\n// source: https://stackoverflow.com/a/32223343\ntemplate<std::size_t... Ints>\nstruct index_sequence\n{\n    using type = index_sequence;\n    using value_type = std::size_t;\n    static constexpr std::size_t size() noexcept\n    {\n        return sizeof...(Ints);\n    }\n};\n\ntemplate<class Sequence1, class Sequence2>\nstruct merge_and_renumber;\n\ntemplate<std::size_t... I1, std::size_t... I2>\nstruct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>>\n        : index_sequence < I1..., (sizeof...(I1) + I2)... > {};\n\ntemplate<std::size_t N>\nstruct make_index_sequence\n    : merge_and_renumber < typename make_index_sequence < N / 2 >::type,\n      typename make_index_sequence < N - N / 2 >::type > {};\n\ntemplate<> struct make_index_sequence<0> : index_sequence<> {};\ntemplate<> struct make_index_sequence<1> : index_sequence<0> {};\n\ntemplate<typename... Ts>\nusing index_sequence_for = make_index_sequence<sizeof...(Ts)>;\n\n/*\nImplementation of two C++17 constructs: conjunction, negation. This is needed\nto avoid evaluating all the traits in a condition\n\nFor example: not std::is_same<void, T>::value and has_value_type<T>::value\nwill not compile when T = void (on MSVC at least). Whereas\nconjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will\nstop evaluating if negation<...>::value == false\n\nPlease note that those constructs must be used with caution, since symbols can\nbecome very long quickly (which can slow down compilation and cause MSVC\ninternal compiler errors). Only use it when you have to (see example ahead).\n*/\ntemplate<class...> struct conjunction : std::true_type {};\ntemplate<class B1> struct conjunction<B1> : B1 {};\ntemplate<class B1, class... Bn>\nstruct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};\n\ntemplate<class B> struct negation : std::integral_constant<bool, not B::value> {};\n\n// dispatch utility (taken from ranges-v3)\ntemplate<unsigned N> struct priority_tag : priority_tag < N - 1 > {};\ntemplate<> struct priority_tag<0> {};\n\n\n//////////////////\n// constructors //\n//////////////////\n\ntemplate<value_t> struct external_constructor;\n\ntemplate<>\nstruct external_constructor<value_t::boolean>\n{\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept\n    {\n        j.m_type = value_t::boolean;\n        j.m_value = b;\n        j.assert_invariant();\n    }\n};\n\ntemplate<>\nstruct external_constructor<value_t::string>\n{\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)\n    {\n        j.m_type = value_t::string;\n        j.m_value = s;\n        j.assert_invariant();\n    }\n\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s)\n    {\n        j.m_type = value_t::string;\n        j.m_value = std::move(s);\n        j.assert_invariant();\n    }\n};\n\ntemplate<>\nstruct external_constructor<value_t::number_float>\n{\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept\n    {\n        j.m_type = value_t::number_float;\n        j.m_value = val;\n        j.assert_invariant();\n    }\n};\n\ntemplate<>\nstruct external_constructor<value_t::number_unsigned>\n{\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept\n    {\n        j.m_type = value_t::number_unsigned;\n        j.m_value = val;\n        j.assert_invariant();\n    }\n};\n\ntemplate<>\nstruct external_constructor<value_t::number_integer>\n{\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept\n    {\n        j.m_type = value_t::number_integer;\n        j.m_value = val;\n        j.assert_invariant();\n    }\n};\n\ntemplate<>\nstruct external_constructor<value_t::array>\n{\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)\n    {\n        j.m_type = value_t::array;\n        j.m_value = arr;\n        j.assert_invariant();\n    }\n\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr)\n    {\n        j.m_type = value_t::array;\n        j.m_value = std::move(arr);\n        j.assert_invariant();\n    }\n\n    template<typename BasicJsonType, typename CompatibleArrayType,\n             enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value,\n                         int> = 0>\n    static void construct(BasicJsonType& j, const CompatibleArrayType& arr)\n    {\n        using std::begin;\n        using std::end;\n        j.m_type = value_t::array;\n        j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));\n        j.assert_invariant();\n    }\n\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, const std::vector<bool>& arr)\n    {\n        j.m_type = value_t::array;\n        j.m_value = value_t::array;\n        j.m_value.array->reserve(arr.size());\n        for (const bool x : arr)\n        {\n            j.m_value.array->push_back(x);\n        }\n        j.assert_invariant();\n    }\n\n    template<typename BasicJsonType, typename T,\n             enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>\n    static void construct(BasicJsonType& j, const std::valarray<T>& arr)\n    {\n        j.m_type = value_t::array;\n        j.m_value = value_t::array;\n        j.m_value.array->resize(arr.size());\n        std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin());\n        j.assert_invariant();\n    }\n};\n\ntemplate<>\nstruct external_constructor<value_t::object>\n{\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)\n    {\n        j.m_type = value_t::object;\n        j.m_value = obj;\n        j.assert_invariant();\n    }\n\n    template<typename BasicJsonType>\n    static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj)\n    {\n        j.m_type = value_t::object;\n        j.m_value = std::move(obj);\n        j.assert_invariant();\n    }\n\n    template<typename BasicJsonType, typename CompatibleObjectType,\n             enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0>\n    static void construct(BasicJsonType& j, const CompatibleObjectType& obj)\n    {\n        using std::begin;\n        using std::end;\n\n        j.m_type = value_t::object;\n        j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));\n        j.assert_invariant();\n    }\n};\n\n\n////////////////////////\n// has_/is_ functions //\n////////////////////////\n\n/*!\n@brief Helper to determine whether there's a key_type for T.\n\nThis helper is used to tell associative containers apart from other containers\nsuch as sequence containers. For instance, `std::map` passes the test as it\ncontains a `mapped_type`, whereas `std::vector` fails the test.\n\n@sa http://stackoverflow.com/a/7728728/266378\n@since version 1.0.0, overworked in version 2.0.6\n*/\n#define NLOHMANN_JSON_HAS_HELPER(type)                                        \\\n    template<typename T> struct has_##type {                                  \\\n    private:                                                                  \\\n        template<typename U, typename = typename U::type>                     \\\n        static int detect(U &&);                                              \\\n        static void detect(...);                                              \\\n    public:                                                                   \\\n        static constexpr bool value =                                         \\\n                std::is_integral<decltype(detect(std::declval<T>()))>::value; \\\n    }\n\nNLOHMANN_JSON_HAS_HELPER(mapped_type);\nNLOHMANN_JSON_HAS_HELPER(key_type);\nNLOHMANN_JSON_HAS_HELPER(value_type);\nNLOHMANN_JSON_HAS_HELPER(iterator);\n\n#undef NLOHMANN_JSON_HAS_HELPER\n\n\ntemplate<bool B, class RealType, class CompatibleObjectType>\nstruct is_compatible_object_type_impl : std::false_type {};\n\ntemplate<class RealType, class CompatibleObjectType>\nstruct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>\n{\n    static constexpr auto value =\n        std::is_constructible<typename RealType::key_type, typename CompatibleObjectType::key_type>::value and\n        std::is_constructible<typename RealType::mapped_type, typename CompatibleObjectType::mapped_type>::value;\n};\n\ntemplate<class BasicJsonType, class CompatibleObjectType>\nstruct is_compatible_object_type\n{\n    static auto constexpr value = is_compatible_object_type_impl <\n                                  conjunction<negation<std::is_same<void, CompatibleObjectType>>,\n                                  has_mapped_type<CompatibleObjectType>,\n                                  has_key_type<CompatibleObjectType>>::value,\n                                  typename BasicJsonType::object_t, CompatibleObjectType >::value;\n};\n\ntemplate<typename BasicJsonType, typename T>\nstruct is_basic_json_nested_type\n{\n    static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or\n                                  std::is_same<T, typename BasicJsonType::const_iterator>::value or\n                                  std::is_same<T, typename BasicJsonType::reverse_iterator>::value or\n                                  std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value;\n};\n\ntemplate<class BasicJsonType, class CompatibleArrayType>\nstruct is_compatible_array_type\n{\n    static auto constexpr value =\n        conjunction<negation<std::is_same<void, CompatibleArrayType>>,\n        negation<is_compatible_object_type<\n        BasicJsonType, CompatibleArrayType>>,\n        negation<std::is_constructible<typename BasicJsonType::string_t,\n        CompatibleArrayType>>,\n        negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,\n        has_value_type<CompatibleArrayType>,\n        has_iterator<CompatibleArrayType>>::value;\n};\n\ntemplate<bool, typename, typename>\nstruct is_compatible_integer_type_impl : std::false_type {};\n\ntemplate<typename RealIntegerType, typename CompatibleNumberIntegerType>\nstruct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>\n{\n    // is there an assert somewhere on overflows?\n    using RealLimits = std::numeric_limits<RealIntegerType>;\n    using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;\n\n    static constexpr auto value =\n        std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and\n        CompatibleLimits::is_integer and\n        RealLimits::is_signed == CompatibleLimits::is_signed;\n};\n\ntemplate<typename RealIntegerType, typename CompatibleNumberIntegerType>\nstruct is_compatible_integer_type\n{\n    static constexpr auto value =\n        is_compatible_integer_type_impl <\n        std::is_integral<CompatibleNumberIntegerType>::value and\n        not std::is_same<bool, CompatibleNumberIntegerType>::value,\n        RealIntegerType, CompatibleNumberIntegerType >::value;\n};\n\n\n// trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists\ntemplate<typename BasicJsonType, typename T>\nstruct has_from_json\n{\n  private:\n    // also check the return type of from_json\n    template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(\n                 std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>\n    static int detect(U&&);\n    static void detect(...);\n\n  public:\n    static constexpr bool value = std::is_integral<decltype(\n                                      detect(std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;\n};\n\n// This trait checks if JSONSerializer<T>::from_json(json const&) exists\n// this overload is used for non-default-constructible user-defined-types\ntemplate<typename BasicJsonType, typename T>\nstruct has_non_default_from_json\n{\n  private:\n    template<typename U, typename =\n             enable_if_t<std::is_same<T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value>>\n    static int detect(U&&);\n    static void detect(...);\n\n  public:\n    static constexpr bool value = std::is_integral<decltype(detect(\n                                      std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;\n};\n\n// This trait checks if BasicJsonType::json_serializer<T>::to_json exists\ntemplate<typename BasicJsonType, typename T>\nstruct has_to_json\n{\n  private:\n    template<typename U, typename = decltype(uncvref_t<U>::to_json(\n                 std::declval<BasicJsonType&>(), std::declval<T>()))>\n    static int detect(U&&);\n    static void detect(...);\n\n  public:\n    static constexpr bool value = std::is_integral<decltype(detect(\n                                      std::declval<typename BasicJsonType::template json_serializer<T, void>>()))>::value;\n};\n\n\n/////////////\n// to_json //\n/////////////\n\ntemplate<typename BasicJsonType, typename T,\n         enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>\nvoid to_json(BasicJsonType& j, T b) noexcept\n{\n    external_constructor<value_t::boolean>::construct(j, b);\n}\n\ntemplate<typename BasicJsonType, typename CompatibleString,\n         enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0>\nvoid to_json(BasicJsonType& j, const CompatibleString& s)\n{\n    external_constructor<value_t::string>::construct(j, s);\n}\n\ntemplate<typename BasicJsonType>\nvoid to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s)\n{\n    external_constructor<value_t::string>::construct(j, std::move(s));\n}\n\ntemplate<typename BasicJsonType, typename FloatType,\n         enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>\nvoid to_json(BasicJsonType& j, FloatType val) noexcept\n{\n    external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));\n}\n\ntemplate<typename BasicJsonType, typename CompatibleNumberUnsignedType,\n         enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0>\nvoid to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept\n{\n    external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));\n}\n\ntemplate<typename BasicJsonType, typename CompatibleNumberIntegerType,\n         enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0>\nvoid to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept\n{\n    external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));\n}\n\ntemplate<typename BasicJsonType, typename EnumType,\n         enable_if_t<std::is_enum<EnumType>::value, int> = 0>\nvoid to_json(BasicJsonType& j, EnumType e) noexcept\n{\n    using underlying_type = typename std::underlying_type<EnumType>::type;\n    external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e));\n}\n\ntemplate<typename BasicJsonType>\nvoid to_json(BasicJsonType& j, const std::vector<bool>& e)\n{\n    external_constructor<value_t::array>::construct(j, e);\n}\n\ntemplate<typename BasicJsonType, typename CompatibleArrayType,\n         enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or\n                     std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,\n                     int> = 0>\nvoid to_json(BasicJsonType& j, const CompatibleArrayType& arr)\n{\n    external_constructor<value_t::array>::construct(j, arr);\n}\n\ntemplate<typename BasicJsonType, typename T,\n         enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0>\nvoid to_json(BasicJsonType& j, std::valarray<T> arr)\n{\n    external_constructor<value_t::array>::construct(j, std::move(arr));\n}\n\ntemplate<typename BasicJsonType>\nvoid to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr)\n{\n    external_constructor<value_t::array>::construct(j, std::move(arr));\n}\n\ntemplate<typename BasicJsonType, typename CompatibleObjectType,\n         enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>\nvoid to_json(BasicJsonType& j, const CompatibleObjectType& obj)\n{\n    external_constructor<value_t::object>::construct(j, obj);\n}\n\ntemplate<typename BasicJsonType>\nvoid to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)\n{\n    external_constructor<value_t::object>::construct(j, std::move(obj));\n}\n\ntemplate<typename BasicJsonType, typename T, std::size_t N,\n         enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, T (&)[N]>::value, int> = 0>\nvoid to_json(BasicJsonType& j, T (&arr)[N])\n{\n    external_constructor<value_t::array>::construct(j, arr);\n}\n\ntemplate<typename BasicJsonType, typename... Args>\nvoid to_json(BasicJsonType& j, const std::pair<Args...>& p)\n{\n    j = {p.first, p.second};\n}\n\ntemplate<typename BasicJsonType, typename Tuple, std::size_t... Idx>\nvoid to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...>)\n{\n    j = {std::get<Idx>(t)...};\n}\n\ntemplate<typename BasicJsonType, typename... Args>\nvoid to_json(BasicJsonType& j, const std::tuple<Args...>& t)\n{\n    to_json_tuple_impl(j, t, index_sequence_for<Args...> {});\n}\n\n///////////////\n// from_json //\n///////////////\n\n// overloads for basic_json template parameters\ntemplate<typename BasicJsonType, typename ArithmeticType,\n         enable_if_t<std::is_arithmetic<ArithmeticType>::value and\n                     not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,\n                     int> = 0>\nvoid get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)\n{\n    switch (static_cast<value_t>(j))\n    {\n        case value_t::number_unsigned:\n        {\n            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());\n            break;\n        }\n        case value_t::number_integer:\n        {\n            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());\n            break;\n        }\n        case value_t::number_float:\n        {\n            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());\n            break;\n        }\n\n        default:\n            JSON_THROW(type_error::create(302, \"type must be number, but is \" + std::string(j.type_name())));\n    }\n}\n\ntemplate<typename BasicJsonType>\nvoid from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)\n{\n    if (JSON_UNLIKELY(not j.is_boolean()))\n    {\n        JSON_THROW(type_error::create(302, \"type must be boolean, but is \" + std::string(j.type_name())));\n    }\n    b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();\n}\n\ntemplate<typename BasicJsonType>\nvoid from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)\n{\n    if (JSON_UNLIKELY(not j.is_string()))\n    {\n        JSON_THROW(type_error::create(302, \"type must be string, but is \" + std::string(j.type_name())));\n    }\n    s = *j.template get_ptr<const typename BasicJsonType::string_t*>();\n}\n\ntemplate<typename BasicJsonType>\nvoid from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)\n{\n    get_arithmetic_value(j, val);\n}\n\ntemplate<typename BasicJsonType>\nvoid from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)\n{\n    get_arithmetic_value(j, val);\n}\n\ntemplate<typename BasicJsonType>\nvoid from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)\n{\n    get_arithmetic_value(j, val);\n}\n\ntemplate<typename BasicJsonType, typename EnumType,\n         enable_if_t<std::is_enum<EnumType>::value, int> = 0>\nvoid from_json(const BasicJsonType& j, EnumType& e)\n{\n    typename std::underlying_type<EnumType>::type val;\n    get_arithmetic_value(j, val);\n    e = static_cast<EnumType>(val);\n}\n\ntemplate<typename BasicJsonType>\nvoid from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)\n{\n    if (JSON_UNLIKELY(not j.is_array()))\n    {\n        JSON_THROW(type_error::create(302, \"type must be array, but is \" + std::string(j.type_name())));\n    }\n    arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();\n}\n\n// forward_list doesn't have an insert method\ntemplate<typename BasicJsonType, typename T, typename Allocator,\n         enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>\nvoid from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)\n{\n    if (JSON_UNLIKELY(not j.is_array()))\n    {\n        JSON_THROW(type_error::create(302, \"type must be array, but is \" + std::string(j.type_name())));\n    }\n    std::transform(j.rbegin(), j.rend(),\n                   std::front_inserter(l), [](const BasicJsonType & i)\n    {\n        return i.template get<T>();\n    });\n}\n\n// valarray doesn't have an insert method\ntemplate<typename BasicJsonType, typename T,\n         enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0>\nvoid from_json(const BasicJsonType& j, std::valarray<T>& l)\n{\n    if (JSON_UNLIKELY(not j.is_array()))\n    {\n        JSON_THROW(type_error::create(302, \"type must be array, but is \" + std::string(j.type_name())));\n    }\n    l.resize(j.size());\n    std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l));\n}\n\ntemplate<typename BasicJsonType, typename CompatibleArrayType>\nvoid from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0> /*unused*/)\n{\n    using std::end;\n\n    std::transform(j.begin(), j.end(),\n                   std::inserter(arr, end(arr)), [](const BasicJsonType & i)\n    {\n        // get<BasicJsonType>() returns *this, this won't call a from_json\n        // method when value_type is BasicJsonType\n        return i.template get<typename CompatibleArrayType::value_type>();\n    });\n}\n\ntemplate<typename BasicJsonType, typename CompatibleArrayType>\nauto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1> /*unused*/)\n-> decltype(\n    arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),\n    void())\n{\n    using std::end;\n\n    arr.reserve(j.size());\n    std::transform(j.begin(), j.end(),\n                   std::inserter(arr, end(arr)), [](const BasicJsonType & i)\n    {\n        // get<BasicJsonType>() returns *this, this won't call a from_json\n        // method when value_type is BasicJsonType\n        return i.template get<typename CompatibleArrayType::value_type>();\n    });\n}\n\ntemplate<typename BasicJsonType, typename T, std::size_t N>\nvoid from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/)\n{\n    for (std::size_t i = 0; i < N; ++i)\n    {\n        arr[i] = j.at(i).template get<T>();\n    }\n}\n\ntemplate<typename BasicJsonType, typename CompatibleArrayType,\n         enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and\n                     std::is_convertible<BasicJsonType, typename CompatibleArrayType::value_type>::value and\n                     not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>\nvoid from_json(const BasicJsonType& j, CompatibleArrayType& arr)\n{\n    if (JSON_UNLIKELY(not j.is_array()))\n    {\n        JSON_THROW(type_error::create(302, \"type must be array, but is \" + std::string(j.type_name())));\n    }\n\n    from_json_array_impl(j, arr, priority_tag<2> {});\n}\n\ntemplate<typename BasicJsonType, typename CompatibleObjectType,\n         enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>\nvoid from_json(const BasicJsonType& j, CompatibleObjectType& obj)\n{\n    if (JSON_UNLIKELY(not j.is_object()))\n    {\n        JSON_THROW(type_error::create(302, \"type must be object, but is \" + std::string(j.type_name())));\n    }\n\n    auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();\n    using value_type = typename CompatibleObjectType::value_type;\n    std::transform(\n        inner_object->begin(), inner_object->end(),\n        std::inserter(obj, obj.begin()),\n        [](typename BasicJsonType::object_t::value_type const & p)\n    {\n        return value_type(p.first, p.second.template get<typename CompatibleObjectType::mapped_type>());\n    });\n}\n\n// overload for arithmetic types, not chosen for basic_json template arguments\n// (BooleanType, etc..); note: Is it really necessary to provide explicit\n// overloads for boolean_t etc. in case of a custom BooleanType which is not\n// an arithmetic type?\ntemplate<typename BasicJsonType, typename ArithmeticType,\n         enable_if_t <\n             std::is_arithmetic<ArithmeticType>::value and\n             not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and\n             not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and\n             not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and\n             not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,\n             int> = 0>\nvoid from_json(const BasicJsonType& j, ArithmeticType& val)\n{\n    switch (static_cast<value_t>(j))\n    {\n        case value_t::number_unsigned:\n        {\n            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());\n            break;\n        }\n        case value_t::number_integer:\n        {\n            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());\n            break;\n        }\n        case value_t::number_float:\n        {\n            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());\n            break;\n        }\n        case value_t::boolean:\n        {\n            val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());\n            break;\n        }\n\n        default:\n            JSON_THROW(type_error::create(302, \"type must be number, but is \" + std::string(j.type_name())));\n    }\n}\n\ntemplate<typename BasicJsonType, typename A1, typename A2>\nvoid from_json(const BasicJsonType& j, std::pair<A1, A2>& p)\n{\n    p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()};\n}\n\ntemplate<typename BasicJsonType, typename Tuple, std::size_t... Idx>\nvoid from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...>)\n{\n    t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...);\n}\n\ntemplate<typename BasicJsonType, typename... Args>\nvoid from_json(const BasicJsonType& j, std::tuple<Args...>& t)\n{\n    from_json_tuple_impl(j, t, index_sequence_for<Args...> {});\n}\n\nstruct to_json_fn\n{\n  private:\n    template<typename BasicJsonType, typename T>\n    auto call(BasicJsonType& j, T&& val, priority_tag<1> /*unused*/) const noexcept(noexcept(to_json(j, std::forward<T>(val))))\n    -> decltype(to_json(j, std::forward<T>(val)), void())\n    {\n        return to_json(j, std::forward<T>(val));\n    }\n\n    template<typename BasicJsonType, typename T>\n    void call(BasicJsonType& /*unused*/, T&& /*unused*/, priority_tag<0> /*unused*/) const noexcept\n    {\n        static_assert(sizeof(BasicJsonType) == 0,\n                      \"could not find to_json() method in T's namespace\");\n\n#ifdef _MSC_VER\n        // MSVC does not show a stacktrace for the above assert\n        using decayed = uncvref_t<T>;\n        static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,\n                      \"forcing MSVC stacktrace to show which T we're talking about.\");\n#endif\n    }\n\n  public:\n    template<typename BasicJsonType, typename T>\n    void operator()(BasicJsonType& j, T&& val) const\n    noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))\n    {\n        return call(j, std::forward<T>(val), priority_tag<1> {});\n    }\n};\n\nstruct from_json_fn\n{\n  private:\n    template<typename BasicJsonType, typename T>\n    auto call(const BasicJsonType& j, T& val, priority_tag<1> /*unused*/) const\n    noexcept(noexcept(from_json(j, val)))\n    -> decltype(from_json(j, val), void())\n    {\n        return from_json(j, val);\n    }\n\n    template<typename BasicJsonType, typename T>\n    void call(const BasicJsonType& /*unused*/, T& /*unused*/, priority_tag<0> /*unused*/) const noexcept\n    {\n        static_assert(sizeof(BasicJsonType) == 0,\n                      \"could not find from_json() method in T's namespace\");\n#ifdef _MSC_VER\n        // MSVC does not show a stacktrace for the above assert\n        using decayed = uncvref_t<T>;\n        static_assert(sizeof(typename decayed::force_msvc_stacktrace) == 0,\n                      \"forcing MSVC stacktrace to show which T we're talking about.\");\n#endif\n    }\n\n  public:\n    template<typename BasicJsonType, typename T>\n    void operator()(const BasicJsonType& j, T& val) const\n    noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))\n    {\n        return call(j, val, priority_tag<1> {});\n    }\n};\n\n// taken from ranges-v3\ntemplate<typename T>\nstruct static_const\n{\n    static constexpr T value{};\n};\n\ntemplate<typename T>\nconstexpr T static_const<T>::value;\n\n////////////////////\n// input adapters //\n////////////////////\n\n/*!\n@brief abstract input adapter interface\n\nProduces a stream of std::char_traits<char>::int_type characters from a\nstd::istream, a buffer, or some other input type.  Accepts the return of exactly\none non-EOF character for future input.  The int_type characters returned\nconsist of all valid char values as positive values (typically unsigned char),\nplus an EOF value outside that range, specified by the value of the function\nstd::char_traits<char>::eof().  This value is typically -1, but could be any\narbitrary value which is not a valid char value.\n*/\nstruct input_adapter_protocol\n{\n    /// get a character [0,255] or std::char_traits<char>::eof().\n    virtual std::char_traits<char>::int_type get_character() = 0;\n    /// restore the last non-eof() character to input\n    virtual void unget_character() = 0;\n    virtual ~input_adapter_protocol() = default;\n};\n\n/// a type to simplify interfaces\nusing input_adapter_t = std::shared_ptr<input_adapter_protocol>;\n\n/*!\nInput adapter for a (caching) istream. Ignores a UFT Byte Order Mark at\nbeginning of input. Does not support changing the underlying std::streambuf\nin mid-input. Maintains underlying std::istream and std::streambuf to support\nsubsequent use of standard std::istream operations to process any input\ncharacters following those used in parsing the JSON input.  Clears the\nstd::istream flags; any input errors (e.g., EOF) will be detected by the first\nsubsequent call for input from the std::istream.\n*/\nclass input_stream_adapter : public input_adapter_protocol\n{\n  public:\n    ~input_stream_adapter() override\n    {\n        // clear stream flags; we use underlying streambuf I/O, do not\n        // maintain ifstream flags\n        is.clear();\n    }\n\n    explicit input_stream_adapter(std::istream& i)\n        : is(i), sb(*i.rdbuf())\n    {\n        // skip byte order mark\n        std::char_traits<char>::int_type c;\n        if ((c = get_character()) == 0xEF)\n        {\n            if ((c = get_character()) == 0xBB)\n            {\n                if ((c = get_character()) == 0xBF)\n                {\n                    return; // Ignore BOM\n                }\n                else if (c != std::char_traits<char>::eof())\n                {\n                    is.unget();\n                }\n                is.putback('\\xBB');\n            }\n            else if (c != std::char_traits<char>::eof())\n            {\n                is.unget();\n            }\n            is.putback('\\xEF');\n        }\n        else if (c != std::char_traits<char>::eof())\n        {\n            is.unget(); // no byte order mark; process as usual\n        }\n    }\n\n    // delete because of pointer members\n    input_stream_adapter(const input_stream_adapter&) = delete;\n    input_stream_adapter& operator=(input_stream_adapter&) = delete;\n\n    // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to\n    // ensure that std::char_traits<char>::eof() and the character 0xFF do not\n    // end up as the same value, eg. 0xFFFFFFFF.\n    std::char_traits<char>::int_type get_character() override\n    {\n        return sb.sbumpc();\n    }\n\n    void unget_character() override\n    {\n        sb.sungetc();  // is.unget() avoided for performance\n    }\n\n  private:\n    /// the associated input stream\n    std::istream& is;\n    std::streambuf& sb;\n};\n\n/// input adapter for buffer input\nclass input_buffer_adapter : public input_adapter_protocol\n{\n  public:\n    input_buffer_adapter(const char* b, const std::size_t l)\n        : cursor(b), limit(b + l), start(b)\n    {\n        // skip byte order mark\n        if (l >= 3 and b[0] == '\\xEF' and b[1] == '\\xBB' and b[2] == '\\xBF')\n        {\n            cursor += 3;\n        }\n    }\n\n    // delete because of pointer members\n    input_buffer_adapter(const input_buffer_adapter&) = delete;\n    input_buffer_adapter& operator=(input_buffer_adapter&) = delete;\n\n    std::char_traits<char>::int_type get_character() noexcept override\n    {\n        if (JSON_LIKELY(cursor < limit))\n        {\n            return std::char_traits<char>::to_int_type(*(cursor++));\n        }\n\n        return std::char_traits<char>::eof();\n    }\n\n    void unget_character() noexcept override\n    {\n        if (JSON_LIKELY(cursor > start))\n        {\n            --cursor;\n        }\n    }\n\n  private:\n    /// pointer to the current character\n    const char* cursor;\n    /// pointer past the last character\n    const char* limit;\n    /// pointer to the first character\n    const char* start;\n};\n\nclass input_adapter\n{\n  public:\n    // native support\n\n    /// input adapter for input stream\n    input_adapter(std::istream& i)\n        : ia(std::make_shared<input_stream_adapter>(i)) {}\n\n    /// input adapter for input stream\n    input_adapter(std::istream&& i)\n        : ia(std::make_shared<input_stream_adapter>(i)) {}\n\n    /// input adapter for buffer\n    template<typename CharT,\n             typename std::enable_if<\n                 std::is_pointer<CharT>::value and\n                 std::is_integral<typename std::remove_pointer<CharT>::type>::value and\n                 sizeof(typename std::remove_pointer<CharT>::type) == 1,\n                 int>::type = 0>\n    input_adapter(CharT b, std::size_t l)\n        : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {}\n\n    // derived support\n\n    /// input adapter for string literal\n    template<typename CharT,\n             typename std::enable_if<\n                 std::is_pointer<CharT>::value and\n                 std::is_integral<typename std::remove_pointer<CharT>::type>::value and\n                 sizeof(typename std::remove_pointer<CharT>::type) == 1,\n                 int>::type = 0>\n    input_adapter(CharT b)\n        : input_adapter(reinterpret_cast<const char*>(b),\n                        std::strlen(reinterpret_cast<const char*>(b))) {}\n\n    /// input adapter for iterator range with contiguous storage\n    template<class IteratorType,\n             typename std::enable_if<\n                 std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value,\n                 int>::type = 0>\n    input_adapter(IteratorType first, IteratorType last)\n    {\n        // assertion to check that the iterator range is indeed contiguous,\n        // see http://stackoverflow.com/a/35008842/266378 for more discussion\n        assert(std::accumulate(\n                   first, last, std::pair<bool, int>(true, 0),\n                   [&first](std::pair<bool, int> res, decltype(*first) val)\n        {\n            res.first &= (val == *(std::next(std::addressof(*first), res.second++)));\n            return res;\n        }).first);\n\n        // assertion to check that each element is 1 byte long\n        static_assert(\n            sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,\n            \"each element in the iterator range must have the size of 1 byte\");\n\n        const auto len = static_cast<size_t>(std::distance(first, last));\n        if (JSON_LIKELY(len > 0))\n        {\n            // there is at least one element: use the address of first\n            ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len);\n        }\n        else\n        {\n            // the address of first cannot be used: use nullptr\n            ia = std::make_shared<input_buffer_adapter>(nullptr, len);\n        }\n    }\n\n    /// input adapter for array\n    template<class T, std::size_t N>\n    input_adapter(T (&array)[N])\n        : input_adapter(std::begin(array), std::end(array)) {}\n\n    /// input adapter for contiguous container\n    template<class ContiguousContainer, typename\n             std::enable_if<not std::is_pointer<ContiguousContainer>::value and\n                            std::is_base_of<std::random_access_iterator_tag, typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value,\n                            int>::type = 0>\n    input_adapter(const ContiguousContainer& c)\n        : input_adapter(std::begin(c), std::end(c)) {}\n\n    operator input_adapter_t()\n    {\n        return ia;\n    }\n\n  private:\n    /// the actual adapter\n    input_adapter_t ia = nullptr;\n};\n\n//////////////////////\n// lexer and parser //\n//////////////////////\n\n/*!\n@brief lexical analysis\n\nThis class organizes the lexical analysis during JSON deserialization.\n*/\ntemplate<typename BasicJsonType>\nclass lexer\n{\n    using number_integer_t = typename BasicJsonType::number_integer_t;\n    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n    using number_float_t = typename BasicJsonType::number_float_t;\n\n  public:\n    /// token types for the parser\n    enum class token_type\n    {\n        uninitialized,    ///< indicating the scanner is uninitialized\n        literal_true,     ///< the `true` literal\n        literal_false,    ///< the `false` literal\n        literal_null,     ///< the `null` literal\n        value_string,     ///< a string -- use get_string() for actual value\n        value_unsigned,   ///< an unsigned integer -- use get_number_unsigned() for actual value\n        value_integer,    ///< a signed integer -- use get_number_integer() for actual value\n        value_float,      ///< an floating point number -- use get_number_float() for actual value\n        begin_array,      ///< the character for array begin `[`\n        begin_object,     ///< the character for object begin `{`\n        end_array,        ///< the character for array end `]`\n        end_object,       ///< the character for object end `}`\n        name_separator,   ///< the name separator `:`\n        value_separator,  ///< the value separator `,`\n        parse_error,      ///< indicating a parse error\n        end_of_input,     ///< indicating the end of the input buffer\n        literal_or_value  ///< a literal or the begin of a value (only for diagnostics)\n    };\n\n    /// return name of values of type token_type (only used for errors)\n    static const char* token_type_name(const token_type t) noexcept\n    {\n        switch (t)\n        {\n            case token_type::uninitialized:\n                return \"<uninitialized>\";\n            case token_type::literal_true:\n                return \"true literal\";\n            case token_type::literal_false:\n                return \"false literal\";\n            case token_type::literal_null:\n                return \"null literal\";\n            case token_type::value_string:\n                return \"string literal\";\n            case lexer::token_type::value_unsigned:\n            case lexer::token_type::value_integer:\n            case lexer::token_type::value_float:\n                return \"number literal\";\n            case token_type::begin_array:\n                return \"'['\";\n            case token_type::begin_object:\n                return \"'{'\";\n            case token_type::end_array:\n                return \"']'\";\n            case token_type::end_object:\n                return \"'}'\";\n            case token_type::name_separator:\n                return \"':'\";\n            case token_type::value_separator:\n                return \"','\";\n            case token_type::parse_error:\n                return \"<parse error>\";\n            case token_type::end_of_input:\n                return \"end of input\";\n            case token_type::literal_or_value:\n                return \"'[', '{', or a literal\";\n            default: // catch non-enum values\n                return \"unknown token\"; // LCOV_EXCL_LINE\n        }\n    }\n\n    explicit lexer(detail::input_adapter_t adapter)\n        : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {}\n\n    // delete because of pointer members\n    lexer(const lexer&) = delete;\n    lexer& operator=(lexer&) = delete;\n\n  private:\n    /////////////////////\n    // locales\n    /////////////////////\n\n    /// return the locale-dependent decimal point\n    static char get_decimal_point() noexcept\n    {\n        const auto loc = localeconv();\n        assert(loc != nullptr);\n        return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point);\n    }\n\n    /////////////////////\n    // scan functions\n    /////////////////////\n\n    /*!\n    @brief get codepoint from 4 hex characters following `\\u`\n\n    For input \"\\u c1 c2 c3 c4\" the codepoint is:\n      (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4\n    = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0)\n\n    Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f'\n    must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The\n    conversion is done by subtracting the offset (0x30, 0x37, and 0x57)\n    between the ASCII value of the character and the desired integer value.\n\n    @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or\n            non-hex character)\n    */\n    int get_codepoint()\n    {\n        // this function only makes sense after reading `\\u`\n        assert(current == 'u');\n        int codepoint = 0;\n\n        const auto factors = { 12, 8, 4, 0 };\n        for (const auto factor : factors)\n        {\n            get();\n\n            if (current >= '0' and current <= '9')\n            {\n                codepoint += ((current - 0x30) << factor);\n            }\n            else if (current >= 'A' and current <= 'F')\n            {\n                codepoint += ((current - 0x37) << factor);\n            }\n            else if (current >= 'a' and current <= 'f')\n            {\n                codepoint += ((current - 0x57) << factor);\n            }\n            else\n            {\n                return -1;\n            }\n        }\n\n        assert(0x0000 <= codepoint and codepoint <= 0xFFFF);\n        return codepoint;\n    }\n\n    /*!\n    @brief check if the next byte(s) are inside a given range\n\n    Adds the current byte and, for each passed range, reads a new byte and\n    checks if it is inside the range. If a violation was detected, set up an\n    error message and return false. Otherwise, return true.\n\n    @param[in] ranges  list of integers; interpreted as list of pairs of\n                       inclusive lower and upper bound, respectively\n\n    @pre The passed list @a ranges must have 2, 4, or 6 elements; that is,\n         1, 2, or 3 pairs. This precondition is enforced by an assertion.\n\n    @return true if and only if no range violation was detected\n    */\n    bool next_byte_in_range(std::initializer_list<int> ranges)\n    {\n        assert(ranges.size() == 2 or ranges.size() == 4 or ranges.size() == 6);\n        add(current);\n\n        for (auto range = ranges.begin(); range != ranges.end(); ++range)\n        {\n            get();\n            if (JSON_LIKELY(*range <= current and current <= *(++range)))\n            {\n                add(current);\n            }\n            else\n            {\n                error_message = \"invalid string: ill-formed UTF-8 byte\";\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    /*!\n    @brief scan a string literal\n\n    This function scans a string according to Sect. 7 of RFC 7159. While\n    scanning, bytes are escaped and copied into buffer yytext. Then the function\n    returns successfully, yytext is *not* null-terminated (as it may contain \\0\n    bytes), and yytext.size() is the number of bytes in the string.\n\n    @return token_type::value_string if string could be successfully scanned,\n            token_type::parse_error otherwise\n\n    @note In case of errors, variable error_message contains a textual\n          description.\n    */\n    token_type scan_string()\n    {\n        // reset yytext (ignore opening quote)\n        reset();\n\n        // we entered the function by reading an open quote\n        assert(current == '\\\"');\n\n        while (true)\n        {\n            // get next character\n            switch (get())\n            {\n                // end of file while parsing string\n                case std::char_traits<char>::eof():\n                {\n                    error_message = \"invalid string: missing closing quote\";\n                    return token_type::parse_error;\n                }\n\n                // closing quote\n                case '\\\"':\n                {\n                    return token_type::value_string;\n                }\n\n                // escapes\n                case '\\\\':\n                {\n                    switch (get())\n                    {\n                        // quotation mark\n                        case '\\\"':\n                            add('\\\"');\n                            break;\n                        // reverse solidus\n                        case '\\\\':\n                            add('\\\\');\n                            break;\n                        // solidus\n                        case '/':\n                            add('/');\n                            break;\n                        // backspace\n                        case 'b':\n                            add('\\b');\n                            break;\n                        // form feed\n                        case 'f':\n                            add('\\f');\n                            break;\n                        // line feed\n                        case 'n':\n                            add('\\n');\n                            break;\n                        // carriage return\n                        case 'r':\n                            add('\\r');\n                            break;\n                        // tab\n                        case 't':\n                            add('\\t');\n                            break;\n\n                        // unicode escapes\n                        case 'u':\n                        {\n                            const int codepoint1 = get_codepoint();\n                            int codepoint = codepoint1; // start with codepoint1\n\n                            if (JSON_UNLIKELY(codepoint1 == -1))\n                            {\n                                error_message = \"invalid string: '\\\\u' must be followed by 4 hex digits\";\n                                return token_type::parse_error;\n                            }\n\n                            // check if code point is a high surrogate\n                            if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF)\n                            {\n                                // expect next \\uxxxx entry\n                                if (JSON_LIKELY(get() == '\\\\' and get() == 'u'))\n                                {\n                                    const int codepoint2 = get_codepoint();\n\n                                    if (JSON_UNLIKELY(codepoint2 == -1))\n                                    {\n                                        error_message = \"invalid string: '\\\\u' must be followed by 4 hex digits\";\n                                        return token_type::parse_error;\n                                    }\n\n                                    // check if codepoint2 is a low surrogate\n                                    if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF))\n                                    {\n                                        // overwrite codepoint\n                                        codepoint =\n                                            // high surrogate occupies the most significant 22 bits\n                                            (codepoint1 << 10)\n                                            // low surrogate occupies the least significant 15 bits\n                                            + codepoint2\n                                            // there is still the 0xD800, 0xDC00 and 0x10000 noise\n                                            // in the result so we have to subtract with:\n                                            // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00\n                                            - 0x35FDC00;\n                                    }\n                                    else\n                                    {\n                                        error_message = \"invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF\";\n                                        return token_type::parse_error;\n                                    }\n                                }\n                                else\n                                {\n                                    error_message = \"invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF\";\n                                    return token_type::parse_error;\n                                }\n                            }\n                            else\n                            {\n                                if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF))\n                                {\n                                    error_message = \"invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF\";\n                                    return token_type::parse_error;\n                                }\n                            }\n\n                            // result of the above calculation yields a proper codepoint\n                            assert(0x00 <= codepoint and codepoint <= 0x10FFFF);\n\n                            // translate codepoint into bytes\n                            if (codepoint < 0x80)\n                            {\n                                // 1-byte characters: 0xxxxxxx (ASCII)\n                                add(codepoint);\n                            }\n                            else if (codepoint <= 0x7FF)\n                            {\n                                // 2-byte characters: 110xxxxx 10xxxxxx\n                                add(0xC0 | (codepoint >> 6));\n                                add(0x80 | (codepoint & 0x3F));\n                            }\n                            else if (codepoint <= 0xFFFF)\n                            {\n                                // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx\n                                add(0xE0 | (codepoint >> 12));\n                                add(0x80 | ((codepoint >> 6) & 0x3F));\n                                add(0x80 | (codepoint & 0x3F));\n                            }\n                            else\n                            {\n                                // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n                                add(0xF0 | (codepoint >> 18));\n                                add(0x80 | ((codepoint >> 12) & 0x3F));\n                                add(0x80 | ((codepoint >> 6) & 0x3F));\n                                add(0x80 | (codepoint & 0x3F));\n                            }\n\n                            break;\n                        }\n\n                        // other characters after escape\n                        default:\n                            error_message = \"invalid string: forbidden character after backslash\";\n                            return token_type::parse_error;\n                    }\n\n                    break;\n                }\n\n                // invalid control characters\n                case 0x00:\n                case 0x01:\n                case 0x02:\n                case 0x03:\n                case 0x04:\n                case 0x05:\n                case 0x06:\n                case 0x07:\n                case 0x08:\n                case 0x09:\n                case 0x0A:\n                case 0x0B:\n                case 0x0C:\n                case 0x0D:\n                case 0x0E:\n                case 0x0F:\n                case 0x10:\n                case 0x11:\n                case 0x12:\n                case 0x13:\n                case 0x14:\n                case 0x15:\n                case 0x16:\n                case 0x17:\n                case 0x18:\n                case 0x19:\n                case 0x1A:\n                case 0x1B:\n                case 0x1C:\n                case 0x1D:\n                case 0x1E:\n                case 0x1F:\n                {\n                    error_message = \"invalid string: control character must be escaped\";\n                    return token_type::parse_error;\n                }\n\n                // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace))\n                case 0x20:\n                case 0x21:\n                case 0x23:\n                case 0x24:\n                case 0x25:\n                case 0x26:\n                case 0x27:\n                case 0x28:\n                case 0x29:\n                case 0x2A:\n                case 0x2B:\n                case 0x2C:\n                case 0x2D:\n                case 0x2E:\n                case 0x2F:\n                case 0x30:\n                case 0x31:\n                case 0x32:\n                case 0x33:\n                case 0x34:\n                case 0x35:\n                case 0x36:\n                case 0x37:\n                case 0x38:\n                case 0x39:\n                case 0x3A:\n                case 0x3B:\n                case 0x3C:\n                case 0x3D:\n                case 0x3E:\n                case 0x3F:\n                case 0x40:\n                case 0x41:\n                case 0x42:\n                case 0x43:\n                case 0x44:\n                case 0x45:\n                case 0x46:\n                case 0x47:\n                case 0x48:\n                case 0x49:\n                case 0x4A:\n                case 0x4B:\n                case 0x4C:\n                case 0x4D:\n                case 0x4E:\n                case 0x4F:\n                case 0x50:\n                case 0x51:\n                case 0x52:\n                case 0x53:\n                case 0x54:\n                case 0x55:\n                case 0x56:\n                case 0x57:\n                case 0x58:\n                case 0x59:\n                case 0x5A:\n                case 0x5B:\n                case 0x5D:\n                case 0x5E:\n                case 0x5F:\n                case 0x60:\n                case 0x61:\n                case 0x62:\n                case 0x63:\n                case 0x64:\n                case 0x65:\n                case 0x66:\n                case 0x67:\n                case 0x68:\n                case 0x69:\n                case 0x6A:\n                case 0x6B:\n                case 0x6C:\n                case 0x6D:\n                case 0x6E:\n                case 0x6F:\n                case 0x70:\n                case 0x71:\n                case 0x72:\n                case 0x73:\n                case 0x74:\n                case 0x75:\n                case 0x76:\n                case 0x77:\n                case 0x78:\n                case 0x79:\n                case 0x7A:\n                case 0x7B:\n                case 0x7C:\n                case 0x7D:\n                case 0x7E:\n                case 0x7F:\n                {\n                    add(current);\n                    break;\n                }\n\n                // U+0080..U+07FF: bytes C2..DF 80..BF\n                case 0xC2:\n                case 0xC3:\n                case 0xC4:\n                case 0xC5:\n                case 0xC6:\n                case 0xC7:\n                case 0xC8:\n                case 0xC9:\n                case 0xCA:\n                case 0xCB:\n                case 0xCC:\n                case 0xCD:\n                case 0xCE:\n                case 0xCF:\n                case 0xD0:\n                case 0xD1:\n                case 0xD2:\n                case 0xD3:\n                case 0xD4:\n                case 0xD5:\n                case 0xD6:\n                case 0xD7:\n                case 0xD8:\n                case 0xD9:\n                case 0xDA:\n                case 0xDB:\n                case 0xDC:\n                case 0xDD:\n                case 0xDE:\n                case 0xDF:\n                {\n                    if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF})))\n                    {\n                        return token_type::parse_error;\n                    }\n                    break;\n                }\n\n                // U+0800..U+0FFF: bytes E0 A0..BF 80..BF\n                case 0xE0:\n                {\n                    if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF}))))\n                    {\n                        return token_type::parse_error;\n                    }\n                    break;\n                }\n\n                // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF\n                // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF\n                case 0xE1:\n                case 0xE2:\n                case 0xE3:\n                case 0xE4:\n                case 0xE5:\n                case 0xE6:\n                case 0xE7:\n                case 0xE8:\n                case 0xE9:\n                case 0xEA:\n                case 0xEB:\n                case 0xEC:\n                case 0xEE:\n                case 0xEF:\n                {\n                    if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF}))))\n                    {\n                        return token_type::parse_error;\n                    }\n                    break;\n                }\n\n                // U+D000..U+D7FF: bytes ED 80..9F 80..BF\n                case 0xED:\n                {\n                    if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF}))))\n                    {\n                        return token_type::parse_error;\n                    }\n                    break;\n                }\n\n                // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF\n                case 0xF0:\n                {\n                    if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))\n                    {\n                        return token_type::parse_error;\n                    }\n                    break;\n                }\n\n                // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF\n                case 0xF1:\n                case 0xF2:\n                case 0xF3:\n                {\n                    if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF}))))\n                    {\n                        return token_type::parse_error;\n                    }\n                    break;\n                }\n\n                // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF\n                case 0xF4:\n                {\n                    if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF}))))\n                    {\n                        return token_type::parse_error;\n                    }\n                    break;\n                }\n\n                // remaining bytes (80..C1 and F5..FF) are ill-formed\n                default:\n                {\n                    error_message = \"invalid string: ill-formed UTF-8 byte\";\n                    return token_type::parse_error;\n                }\n            }\n        }\n    }\n\n    static void strtof(float& f, const char* str, char** endptr) noexcept\n    {\n        f = std::strtof(str, endptr);\n    }\n\n    static void strtof(double& f, const char* str, char** endptr) noexcept\n    {\n        f = std::strtod(str, endptr);\n    }\n\n    static void strtof(long double& f, const char* str, char** endptr) noexcept\n    {\n        f = std::strtold(str, endptr);\n    }\n\n    /*!\n    @brief scan a number literal\n\n    This function scans a string according to Sect. 6 of RFC 7159.\n\n    The function is realized with a deterministic finite state machine derived\n    from the grammar described in RFC 7159. Starting in state \"init\", the\n    input is read and used to determined the next state. Only state \"done\"\n    accepts the number. State \"error\" is a trap state to model errors. In the\n    table below, \"anything\" means any character but the ones listed before.\n\n    state    | 0        | 1-9      | e E      | +       | -       | .        | anything\n    ---------|----------|----------|----------|---------|---------|----------|-----------\n    init     | zero     | any1     | [error]  | [error] | minus   | [error]  | [error]\n    minus    | zero     | any1     | [error]  | [error] | [error] | [error]  | [error]\n    zero     | done     | done     | exponent | done    | done    | decimal1 | done\n    any1     | any1     | any1     | exponent | done    | done    | decimal1 | done\n    decimal1 | decimal2 | [error]  | [error]  | [error] | [error] | [error]  | [error]\n    decimal2 | decimal2 | decimal2 | exponent | done    | done    | done     | done\n    exponent | any2     | any2     | [error]  | sign    | sign    | [error]  | [error]\n    sign     | any2     | any2     | [error]  | [error] | [error] | [error]  | [error]\n    any2     | any2     | any2     | done     | done    | done    | done     | done\n\n    The state machine is realized with one label per state (prefixed with\n    \"scan_number_\") and `goto` statements between them. The state machine\n    contains cycles, but any cycle can be left when EOF is read. Therefore,\n    the function is guaranteed to terminate.\n\n    During scanning, the read bytes are stored in yytext. This string is\n    then converted to a signed integer, an unsigned integer, or a\n    floating-point number.\n\n    @return token_type::value_unsigned, token_type::value_integer, or\n            token_type::value_float if number could be successfully scanned,\n            token_type::parse_error otherwise\n\n    @note The scanner is independent of the current locale. Internally, the\n          locale's decimal point is used instead of `.` to work with the\n          locale-dependent converters.\n    */\n    token_type scan_number()\n    {\n        // reset yytext to store the number's bytes\n        reset();\n\n        // the type of the parsed number; initially set to unsigned; will be\n        // changed if minus sign, decimal point or exponent is read\n        token_type number_type = token_type::value_unsigned;\n\n        // state (init): we just found out we need to scan a number\n        switch (current)\n        {\n            case '-':\n            {\n                add(current);\n                goto scan_number_minus;\n            }\n\n            case '0':\n            {\n                add(current);\n                goto scan_number_zero;\n            }\n\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n            {\n                add(current);\n                goto scan_number_any1;\n            }\n\n            default:\n            {\n                // all other characters are rejected outside scan_number()\n                assert(false); // LCOV_EXCL_LINE\n            }\n        }\n\nscan_number_minus:\n        // state: we just parsed a leading minus sign\n        number_type = token_type::value_integer;\n        switch (get())\n        {\n            case '0':\n            {\n                add(current);\n                goto scan_number_zero;\n            }\n\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n            {\n                add(current);\n                goto scan_number_any1;\n            }\n\n            default:\n            {\n                error_message = \"invalid number; expected digit after '-'\";\n                return token_type::parse_error;\n            }\n        }\n\nscan_number_zero:\n        // state: we just parse a zero (maybe with a leading minus sign)\n        switch (get())\n        {\n            case '.':\n            {\n                add(decimal_point_char);\n                goto scan_number_decimal1;\n            }\n\n            case 'e':\n            case 'E':\n            {\n                add(current);\n                goto scan_number_exponent;\n            }\n\n            default:\n                goto scan_number_done;\n        }\n\nscan_number_any1:\n        // state: we just parsed a number 0-9 (maybe with a leading minus sign)\n        switch (get())\n        {\n            case '0':\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n            {\n                add(current);\n                goto scan_number_any1;\n            }\n\n            case '.':\n            {\n                add(decimal_point_char);\n                goto scan_number_decimal1;\n            }\n\n            case 'e':\n            case 'E':\n            {\n                add(current);\n                goto scan_number_exponent;\n            }\n\n            default:\n                goto scan_number_done;\n        }\n\nscan_number_decimal1:\n        // state: we just parsed a decimal point\n        number_type = token_type::value_float;\n        switch (get())\n        {\n            case '0':\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n            {\n                add(current);\n                goto scan_number_decimal2;\n            }\n\n            default:\n            {\n                error_message = \"invalid number; expected digit after '.'\";\n                return token_type::parse_error;\n            }\n        }\n\nscan_number_decimal2:\n        // we just parsed at least one number after a decimal point\n        switch (get())\n        {\n            case '0':\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n            {\n                add(current);\n                goto scan_number_decimal2;\n            }\n\n            case 'e':\n            case 'E':\n            {\n                add(current);\n                goto scan_number_exponent;\n            }\n\n            default:\n                goto scan_number_done;\n        }\n\nscan_number_exponent:\n        // we just parsed an exponent\n        number_type = token_type::value_float;\n        switch (get())\n        {\n            case '+':\n            case '-':\n            {\n                add(current);\n                goto scan_number_sign;\n            }\n\n            case '0':\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n            {\n                add(current);\n                goto scan_number_any2;\n            }\n\n            default:\n            {\n                error_message =\n                    \"invalid number; expected '+', '-', or digit after exponent\";\n                return token_type::parse_error;\n            }\n        }\n\nscan_number_sign:\n        // we just parsed an exponent sign\n        switch (get())\n        {\n            case '0':\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n            {\n                add(current);\n                goto scan_number_any2;\n            }\n\n            default:\n            {\n                error_message = \"invalid number; expected digit after exponent sign\";\n                return token_type::parse_error;\n            }\n        }\n\nscan_number_any2:\n        // we just parsed a number after the exponent or exponent sign\n        switch (get())\n        {\n            case '0':\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n            {\n                add(current);\n                goto scan_number_any2;\n            }\n\n            default:\n                goto scan_number_done;\n        }\n\nscan_number_done:\n        // unget the character after the number (we only read it to know that\n        // we are done scanning a number)\n        unget();\n\n        char* endptr = nullptr;\n        errno = 0;\n\n        // try to parse integers first and fall back to floats\n        if (number_type == token_type::value_unsigned)\n        {\n            const auto x = std::strtoull(yytext.data(), &endptr, 10);\n\n            // we checked the number format before\n            assert(endptr == yytext.data() + yytext.size());\n\n            if (errno == 0)\n            {\n                value_unsigned = static_cast<number_unsigned_t>(x);\n                if (value_unsigned == x)\n                {\n                    return token_type::value_unsigned;\n                }\n            }\n        }\n        else if (number_type == token_type::value_integer)\n        {\n            const auto x = std::strtoll(yytext.data(), &endptr, 10);\n\n            // we checked the number format before\n            assert(endptr == yytext.data() + yytext.size());\n\n            if (errno == 0)\n            {\n                value_integer = static_cast<number_integer_t>(x);\n                if (value_integer == x)\n                {\n                    return token_type::value_integer;\n                }\n            }\n        }\n\n        // this code is reached if we parse a floating-point number or if an\n        // integer conversion above failed\n        strtof(value_float, yytext.data(), &endptr);\n\n        // we checked the number format before\n        assert(endptr == yytext.data() + yytext.size());\n\n        return token_type::value_float;\n    }\n\n    /*!\n    @param[in] literal_text  the literal text to expect\n    @param[in] length        the length of the passed literal text\n    @param[in] return_type   the token type to return on success\n    */\n    token_type scan_literal(const char* literal_text, const std::size_t length,\n                            token_type return_type)\n    {\n        assert(current == literal_text[0]);\n        for (std::size_t i = 1; i < length; ++i)\n        {\n            if (JSON_UNLIKELY(get() != literal_text[i]))\n            {\n                error_message = \"invalid literal\";\n                return token_type::parse_error;\n            }\n        }\n        return return_type;\n    }\n\n    /////////////////////\n    // input management\n    /////////////////////\n\n    /// reset yytext; current character is beginning of token\n    void reset() noexcept\n    {\n        yytext.clear();\n        token_string.clear();\n        token_string.push_back(std::char_traits<char>::to_char_type(current));\n    }\n\n    /*\n    @brief get next character from the input\n\n    This function provides the interface to the used input adapter. It does\n    not throw in case the input reached EOF, but returns a\n    `std::char_traits<char>::eof()` in that case.  Stores the scanned characters\n    for use in error messages.\n\n    @return character read from the input\n    */\n    std::char_traits<char>::int_type get()\n    {\n        ++chars_read;\n        current = ia->get_character();\n        if (JSON_LIKELY(current != std::char_traits<char>::eof()))\n        {\n            token_string.push_back(std::char_traits<char>::to_char_type(current));\n        }\n        return current;\n    }\n\n    /// unget current character (return it again on next get)\n    void unget()\n    {\n        --chars_read;\n        if (JSON_LIKELY(current != std::char_traits<char>::eof()))\n        {\n            ia->unget_character();\n            assert(token_string.size() != 0);\n            token_string.pop_back();\n        }\n    }\n\n    /// add a character to yytext\n    void add(int c)\n    {\n        yytext.push_back(std::char_traits<char>::to_char_type(c));\n    }\n\n  public:\n    /////////////////////\n    // value getters\n    /////////////////////\n\n    /// return integer value\n    constexpr number_integer_t get_number_integer() const noexcept\n    {\n        return value_integer;\n    }\n\n    /// return unsigned integer value\n    constexpr number_unsigned_t get_number_unsigned() const noexcept\n    {\n        return value_unsigned;\n    }\n\n    /// return floating-point value\n    constexpr number_float_t get_number_float() const noexcept\n    {\n        return value_float;\n    }\n\n    /// return current string value (implicitly resets the token; useful only once)\n    std::string move_string()\n    {\n        return std::move(yytext);\n    }\n\n    /////////////////////\n    // diagnostics\n    /////////////////////\n\n    /// return position of last read token\n    constexpr std::size_t get_position() const noexcept\n    {\n        return chars_read;\n    }\n\n    /// return the last read token (for errors only).  Will never contain EOF\n    /// (an arbitrary value that is not a valid char value, often -1), because\n    /// 255 may legitimately occur.  May contain NUL, which should be escaped.\n    std::string get_token_string() const\n    {\n        // escape control characters\n        std::string result;\n        for (const auto c : token_string)\n        {\n            if ('\\x00' <= c and c <= '\\x1F')\n            {\n                // escape control characters\n                std::stringstream ss;\n                ss << \"<U+\" << std::setw(4) << std::uppercase << std::setfill('0')\n                   << std::hex << static_cast<int>(c) << \">\";\n                result += ss.str();\n            }\n            else\n            {\n                // add character as is\n                result.push_back(c);\n            }\n        }\n\n        return result;\n    }\n\n    /// return syntax error message\n    constexpr const char* get_error_message() const noexcept\n    {\n        return error_message;\n    }\n\n    /////////////////////\n    // actual scanner\n    /////////////////////\n\n    token_type scan()\n    {\n        // read next character and ignore whitespace\n        do\n        {\n            get();\n        }\n        while (current == ' ' or current == '\\t' or current == '\\n' or current == '\\r');\n\n        switch (current)\n        {\n            // structural characters\n            case '[':\n                return token_type::begin_array;\n            case ']':\n                return token_type::end_array;\n            case '{':\n                return token_type::begin_object;\n            case '}':\n                return token_type::end_object;\n            case ':':\n                return token_type::name_separator;\n            case ',':\n                return token_type::value_separator;\n\n            // literals\n            case 't':\n                return scan_literal(\"true\", 4, token_type::literal_true);\n            case 'f':\n                return scan_literal(\"false\", 5, token_type::literal_false);\n            case 'n':\n                return scan_literal(\"null\", 4, token_type::literal_null);\n\n            // string\n            case '\\\"':\n                return scan_string();\n\n            // number\n            case '-':\n            case '0':\n            case '1':\n            case '2':\n            case '3':\n            case '4':\n            case '5':\n            case '6':\n            case '7':\n            case '8':\n            case '9':\n                return scan_number();\n\n            // end of input (the null byte is needed when parsing from\n            // string literals)\n            case '\\0':\n            case std::char_traits<char>::eof():\n                return token_type::end_of_input;\n\n            // error\n            default:\n                error_message = \"invalid literal\";\n                return token_type::parse_error;\n        }\n    }\n\n  private:\n    /// input adapter\n    detail::input_adapter_t ia = nullptr;\n\n    /// the current character\n    std::char_traits<char>::int_type current = std::char_traits<char>::eof();\n\n    /// the number of characters read\n    std::size_t chars_read = 0;\n\n    /// raw input token string (for error messages)\n    std::vector<char> token_string {};\n\n    /// buffer for variable-length tokens (numbers, strings)\n    std::string yytext {};\n\n    /// a description of occurred lexer errors\n    const char* error_message = \"\";\n\n    // number values\n    number_integer_t value_integer = 0;\n    number_unsigned_t value_unsigned = 0;\n    number_float_t value_float = 0;\n\n    /// the decimal point\n    const char decimal_point_char = '.';\n};\n\n/*!\n@brief syntax analysis\n\nThis class implements a recursive decent parser.\n*/\ntemplate<typename BasicJsonType>\nclass parser\n{\n    using number_integer_t = typename BasicJsonType::number_integer_t;\n    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n    using number_float_t = typename BasicJsonType::number_float_t;\n    using lexer_t = lexer<BasicJsonType>;\n    using token_type = typename lexer_t::token_type;\n\n  public:\n    enum class parse_event_t : uint8_t\n    {\n        /// the parser read `{` and started to process a JSON object\n        object_start,\n        /// the parser read `}` and finished processing a JSON object\n        object_end,\n        /// the parser read `[` and started to process a JSON array\n        array_start,\n        /// the parser read `]` and finished processing a JSON array\n        array_end,\n        /// the parser read a key of a value in an object\n        key,\n        /// the parser finished reading a JSON value\n        value\n    };\n\n    using parser_callback_t =\n        std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>;\n\n    /// a parser reading from an input adapter\n    explicit parser(detail::input_adapter_t adapter,\n                    const parser_callback_t cb = nullptr,\n                    const bool allow_exceptions_ = true)\n        : callback(cb), m_lexer(adapter), allow_exceptions(allow_exceptions_)\n    {}\n\n    /*!\n    @brief public parser interface\n\n    @param[in] strict      whether to expect the last token to be EOF\n    @param[in,out] result  parsed JSON value\n\n    @throw parse_error.101 in case of an unexpected token\n    @throw parse_error.102 if to_unicode fails or surrogate error\n    @throw parse_error.103 if to_unicode fails\n    */\n    void parse(const bool strict, BasicJsonType& result)\n    {\n        // read first token\n        get_token();\n\n        parse_internal(true, result);\n        result.assert_invariant();\n\n        // in strict mode, input must be completely read\n        if (strict)\n        {\n            get_token();\n            expect(token_type::end_of_input);\n        }\n\n        // in case of an error, return discarded value\n        if (errored)\n        {\n            result = value_t::discarded;\n            return;\n        }\n\n        // set top-level value to null if it was discarded by the callback\n        // function\n        if (result.is_discarded())\n        {\n            result = nullptr;\n        }\n    }\n\n    /*!\n    @brief public accept interface\n\n    @param[in] strict  whether to expect the last token to be EOF\n    @return whether the input is a proper JSON text\n    */\n    bool accept(const bool strict = true)\n    {\n        // read first token\n        get_token();\n\n        if (not accept_internal())\n        {\n            return false;\n        }\n\n        // strict => last token must be EOF\n        return not strict or (get_token() == token_type::end_of_input);\n    }\n\n  private:\n    /*!\n    @brief the actual parser\n    @throw parse_error.101 in case of an unexpected token\n    @throw parse_error.102 if to_unicode fails or surrogate error\n    @throw parse_error.103 if to_unicode fails\n    */\n    void parse_internal(bool keep, BasicJsonType& result)\n    {\n        // never parse after a parse error was detected\n        assert(not errored);\n\n        // start with a discarded value\n        if (not result.is_discarded())\n        {\n            result.m_value.destroy(result.m_type);\n            result.m_type = value_t::discarded;\n        }\n\n        switch (last_token)\n        {\n            case token_type::begin_object:\n            {\n                if (keep)\n                {\n                    if (callback)\n                    {\n                        keep = callback(depth++, parse_event_t::object_start, result);\n                    }\n\n                    if (not callback or keep)\n                    {\n                        // explicitly set result to object to cope with {}\n                        result.m_type = value_t::object;\n                        result.m_value = value_t::object;\n                    }\n                }\n\n                // read next token\n                get_token();\n\n                // closing } -> we are done\n                if (last_token == token_type::end_object)\n                {\n                    if (keep and callback and not callback(--depth, parse_event_t::object_end, result))\n                    {\n                        result.m_value.destroy(result.m_type);\n                        result.m_type = value_t::discarded;\n                    }\n                    break;\n                }\n\n                // parse values\n                std::string key;\n                BasicJsonType value;\n                while (true)\n                {\n                    // store key\n                    if (not expect(token_type::value_string))\n                    {\n                        return;\n                    }\n                    key = m_lexer.move_string();\n\n                    bool keep_tag = false;\n                    if (keep)\n                    {\n                        if (callback)\n                        {\n                            BasicJsonType k(key);\n                            keep_tag = callback(depth, parse_event_t::key, k);\n                        }\n                        else\n                        {\n                            keep_tag = true;\n                        }\n                    }\n\n                    // parse separator (:)\n                    get_token();\n                    if (not expect(token_type::name_separator))\n                    {\n                        return;\n                    }\n\n                    // parse and add value\n                    get_token();\n                    value.m_value.destroy(value.m_type);\n                    value.m_type = value_t::discarded;\n                    parse_internal(keep, value);\n\n                    if (JSON_UNLIKELY(errored))\n                    {\n                        return;\n                    }\n\n                    if (keep and keep_tag and not value.is_discarded())\n                    {\n                        result.m_value.object->emplace(std::move(key), std::move(value));\n                    }\n\n                    // comma -> next value\n                    get_token();\n                    if (last_token == token_type::value_separator)\n                    {\n                        get_token();\n                        continue;\n                    }\n\n                    // closing }\n                    if (not expect(token_type::end_object))\n                    {\n                        return;\n                    }\n                    break;\n                }\n\n                if (keep and callback and not callback(--depth, parse_event_t::object_end, result))\n                {\n                    result.m_value.destroy(result.m_type);\n                    result.m_type = value_t::discarded;\n                }\n                break;\n            }\n\n            case token_type::begin_array:\n            {\n                if (keep)\n                {\n                    if (callback)\n                    {\n                        keep = callback(depth++, parse_event_t::array_start, result);\n                    }\n\n                    if (not callback or keep)\n                    {\n                        // explicitly set result to array to cope with []\n                        result.m_type = value_t::array;\n                        result.m_value = value_t::array;\n                    }\n                }\n\n                // read next token\n                get_token();\n\n                // closing ] -> we are done\n                if (last_token == token_type::end_array)\n                {\n                    if (callback and not callback(--depth, parse_event_t::array_end, result))\n                    {\n                        result.m_value.destroy(result.m_type);\n                        result.m_type = value_t::discarded;\n                    }\n                    break;\n                }\n\n                // parse values\n                BasicJsonType value;\n                while (true)\n                {\n                    // parse value\n                    value.m_value.destroy(value.m_type);\n                    value.m_type = value_t::discarded;\n                    parse_internal(keep, value);\n\n                    if (JSON_UNLIKELY(errored))\n                    {\n                        return;\n                    }\n\n                    if (keep and not value.is_discarded())\n                    {\n                        result.m_value.array->push_back(std::move(value));\n                    }\n\n                    // comma -> next value\n                    get_token();\n                    if (last_token == token_type::value_separator)\n                    {\n                        get_token();\n                        continue;\n                    }\n\n                    // closing ]\n                    if (not expect(token_type::end_array))\n                    {\n                        return;\n                    }\n                    break;\n                }\n\n                if (keep and callback and not callback(--depth, parse_event_t::array_end, result))\n                {\n                    result.m_value.destroy(result.m_type);\n                    result.m_type = value_t::discarded;\n                }\n                break;\n            }\n\n            case token_type::literal_null:\n            {\n                result.m_type = value_t::null;\n                break;\n            }\n\n            case token_type::value_string:\n            {\n                result.m_type = value_t::string;\n                result.m_value = m_lexer.move_string();\n                break;\n            }\n\n            case token_type::literal_true:\n            {\n                result.m_type = value_t::boolean;\n                result.m_value = true;\n                break;\n            }\n\n            case token_type::literal_false:\n            {\n                result.m_type = value_t::boolean;\n                result.m_value = false;\n                break;\n            }\n\n            case token_type::value_unsigned:\n            {\n                result.m_type = value_t::number_unsigned;\n                result.m_value = m_lexer.get_number_unsigned();\n                break;\n            }\n\n            case token_type::value_integer:\n            {\n                result.m_type = value_t::number_integer;\n                result.m_value = m_lexer.get_number_integer();\n                break;\n            }\n\n            case token_type::value_float:\n            {\n                result.m_type = value_t::number_float;\n                result.m_value = m_lexer.get_number_float();\n\n                // throw in case of infinity or NAN\n                if (JSON_UNLIKELY(not std::isfinite(result.m_value.number_float)))\n                {\n                    if (allow_exceptions)\n                    {\n                        JSON_THROW(out_of_range::create(406, \"number overflow parsing '\" +\n                                                        m_lexer.get_token_string() + \"'\"));\n                    }\n                    expect(token_type::uninitialized);\n                }\n                break;\n            }\n\n            case token_type::parse_error:\n            {\n                // using \"uninitialized\" to avoid \"expected\" message\n                if (not expect(token_type::uninitialized))\n                {\n                    return;\n                }\n                break; // LCOV_EXCL_LINE\n            }\n\n            default:\n            {\n                // the last token was unexpected; we expected a value\n                if (not expect(token_type::literal_or_value))\n                {\n                    return;\n                }\n                break; // LCOV_EXCL_LINE\n            }\n        }\n\n        if (keep and callback and not callback(depth, parse_event_t::value, result))\n        {\n            result.m_type = value_t::discarded;\n        }\n    }\n\n    /*!\n    @brief the actual acceptor\n\n    @invariant 1. The last token is not yet processed. Therefore, the caller\n                  of this function must make sure a token has been read.\n               2. When this function returns, the last token is processed.\n                  That is, the last read character was already considered.\n\n    This invariant makes sure that no token needs to be \"unput\".\n    */\n    bool accept_internal()\n    {\n        switch (last_token)\n        {\n            case token_type::begin_object:\n            {\n                // read next token\n                get_token();\n\n                // closing } -> we are done\n                if (last_token == token_type::end_object)\n                {\n                    return true;\n                }\n\n                // parse values\n                while (true)\n                {\n                    // parse key\n                    if (last_token != token_type::value_string)\n                    {\n                        return false;\n                    }\n\n                    // parse separator (:)\n                    get_token();\n                    if (last_token != token_type::name_separator)\n                    {\n                        return false;\n                    }\n\n                    // parse value\n                    get_token();\n                    if (not accept_internal())\n                    {\n                        return false;\n                    }\n\n                    // comma -> next value\n                    get_token();\n                    if (last_token == token_type::value_separator)\n                    {\n                        get_token();\n                        continue;\n                    }\n\n                    // closing }\n                    return (last_token == token_type::end_object);\n                }\n            }\n\n            case token_type::begin_array:\n            {\n                // read next token\n                get_token();\n\n                // closing ] -> we are done\n                if (last_token == token_type::end_array)\n                {\n                    return true;\n                }\n\n                // parse values\n                while (true)\n                {\n                    // parse value\n                    if (not accept_internal())\n                    {\n                        return false;\n                    }\n\n                    // comma -> next value\n                    get_token();\n                    if (last_token == token_type::value_separator)\n                    {\n                        get_token();\n                        continue;\n                    }\n\n                    // closing ]\n                    return (last_token == token_type::end_array);\n                }\n            }\n\n            case token_type::value_float:\n            {\n                // reject infinity or NAN\n                return std::isfinite(m_lexer.get_number_float());\n            }\n\n            case token_type::literal_false:\n            case token_type::literal_null:\n            case token_type::literal_true:\n            case token_type::value_integer:\n            case token_type::value_string:\n            case token_type::value_unsigned:\n                return true;\n\n            default: // the last token was unexpected\n                return false;\n        }\n    }\n\n    /// get next token from lexer\n    token_type get_token()\n    {\n        return (last_token = m_lexer.scan());\n    }\n\n    /*!\n    @throw parse_error.101 if expected token did not occur\n    */\n    bool expect(token_type t)\n    {\n        if (JSON_UNLIKELY(t != last_token))\n        {\n            errored = true;\n            expected = t;\n            if (allow_exceptions)\n            {\n                throw_exception();\n            }\n            else\n            {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    [[noreturn]] void throw_exception() const\n    {\n        std::string error_msg = \"syntax error - \";\n        if (last_token == token_type::parse_error)\n        {\n            error_msg += std::string(m_lexer.get_error_message()) + \"; last read: '\" +\n                         m_lexer.get_token_string() + \"'\";\n        }\n        else\n        {\n            error_msg += \"unexpected \" + std::string(lexer_t::token_type_name(last_token));\n        }\n\n        if (expected != token_type::uninitialized)\n        {\n            error_msg += \"; expected \" + std::string(lexer_t::token_type_name(expected));\n        }\n\n        JSON_THROW(parse_error::create(101, m_lexer.get_position(), error_msg));\n    }\n\n  private:\n    /// current level of recursion\n    int depth = 0;\n    /// callback function\n    const parser_callback_t callback = nullptr;\n    /// the type of the last read token\n    token_type last_token = token_type::uninitialized;\n    /// the lexer\n    lexer_t m_lexer;\n    /// whether a syntax error occurred\n    bool errored = false;\n    /// possible reason for the syntax error\n    token_type expected = token_type::uninitialized;\n    /// whether to throw exceptions in case of errors\n    const bool allow_exceptions = true;\n};\n\n///////////////\n// iterators //\n///////////////\n\n/*!\n@brief an iterator for primitive JSON types\n\nThis class models an iterator for primitive JSON types (boolean, number,\nstring). It's only purpose is to allow the iterator/const_iterator classes\nto \"iterate\" over primitive values. Internally, the iterator is modeled by\na `difference_type` variable. Value begin_value (`0`) models the begin,\nend_value (`1`) models past the end.\n*/\nclass primitive_iterator_t\n{\n  public:\n    using difference_type = std::ptrdiff_t;\n\n    constexpr difference_type get_value() const noexcept\n    {\n        return m_it;\n    }\n\n    /// set iterator to a defined beginning\n    void set_begin() noexcept\n    {\n        m_it = begin_value;\n    }\n\n    /// set iterator to a defined past the end\n    void set_end() noexcept\n    {\n        m_it = end_value;\n    }\n\n    /// return whether the iterator can be dereferenced\n    constexpr bool is_begin() const noexcept\n    {\n        return m_it == begin_value;\n    }\n\n    /// return whether the iterator is at end\n    constexpr bool is_end() const noexcept\n    {\n        return m_it == end_value;\n    }\n\n    friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept\n    {\n        return lhs.m_it == rhs.m_it;\n    }\n\n    friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept\n    {\n        return lhs.m_it < rhs.m_it;\n    }\n\n    primitive_iterator_t operator+(difference_type i)\n    {\n        auto result = *this;\n        result += i;\n        return result;\n    }\n\n    friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept\n    {\n        return lhs.m_it - rhs.m_it;\n    }\n\n    friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it)\n    {\n        return os << it.m_it;\n    }\n\n    primitive_iterator_t& operator++()\n    {\n        ++m_it;\n        return *this;\n    }\n\n    primitive_iterator_t const operator++(int)\n    {\n        auto result = *this;\n        m_it++;\n        return result;\n    }\n\n    primitive_iterator_t& operator--()\n    {\n        --m_it;\n        return *this;\n    }\n\n    primitive_iterator_t const operator--(int)\n    {\n        auto result = *this;\n        m_it--;\n        return result;\n    }\n\n    primitive_iterator_t& operator+=(difference_type n)\n    {\n        m_it += n;\n        return *this;\n    }\n\n    primitive_iterator_t& operator-=(difference_type n)\n    {\n        m_it -= n;\n        return *this;\n    }\n\n  private:\n    static constexpr difference_type begin_value = 0;\n    static constexpr difference_type end_value = begin_value + 1;\n\n    /// iterator as signed integer type\n    difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)();\n};\n\n/*!\n@brief an iterator value\n\n@note This structure could easily be a union, but MSVC currently does not allow\nunions members with complex constructors, see https://github.com/nlohmann/json/pull/105.\n*/\ntemplate<typename BasicJsonType> struct internal_iterator\n{\n    /// iterator for JSON objects\n    typename BasicJsonType::object_t::iterator object_iterator {};\n    /// iterator for JSON arrays\n    typename BasicJsonType::array_t::iterator array_iterator {};\n    /// generic iterator for all other types\n    primitive_iterator_t primitive_iterator {};\n};\n\ntemplate<typename IteratorType> class iteration_proxy;\n\n/*!\n@brief a template for a bidirectional iterator for the @ref basic_json class\n\nThis class implements a both iterators (iterator and const_iterator) for the\n@ref basic_json class.\n\n@note An iterator is called *initialized* when a pointer to a JSON value has\n      been set (e.g., by a constructor or a copy assignment). If the iterator is\n      default-constructed, it is *uninitialized* and most methods are undefined.\n      **The library uses assertions to detect calls on uninitialized iterators.**\n\n@requirement The class satisfies the following concept requirements:\n-\n[BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):\n  The iterator that can be moved can be moved in both directions (i.e.\n  incremented and decremented).\n\n@since version 1.0.0, simplified in version 2.0.9, change to bidirectional\n       iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593)\n*/\ntemplate<typename BasicJsonType>\nclass iter_impl\n{\n    /// allow basic_json to access private members\n    friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>;\n    friend BasicJsonType;\n    friend iteration_proxy<iter_impl>;\n\n    using object_t = typename BasicJsonType::object_t;\n    using array_t = typename BasicJsonType::array_t;\n    // make sure BasicJsonType is basic_json or const basic_json\n    static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value,\n                  \"iter_impl only accepts (const) basic_json\");\n\n  public:\n\n    /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17.\n    /// The C++ Standard has never required user-defined iterators to derive from std::iterator.\n    /// A user-defined iterator should provide publicly accessible typedefs named\n    /// iterator_category, value_type, difference_type, pointer, and reference.\n    /// Note that value_type is required to be non-const, even for constant iterators.\n    using iterator_category = std::bidirectional_iterator_tag;\n\n    /// the type of the values when the iterator is dereferenced\n    using value_type = typename BasicJsonType::value_type;\n    /// a type to represent differences between iterators\n    using difference_type = typename BasicJsonType::difference_type;\n    /// defines a pointer to the type iterated over (value_type)\n    using pointer = typename std::conditional<std::is_const<BasicJsonType>::value,\n          typename BasicJsonType::const_pointer,\n          typename BasicJsonType::pointer>::type;\n    /// defines a reference to the type iterated over (value_type)\n    using reference =\n        typename std::conditional<std::is_const<BasicJsonType>::value,\n        typename BasicJsonType::const_reference,\n        typename BasicJsonType::reference>::type;\n\n    /// default constructor\n    iter_impl() = default;\n\n    /*!\n    @brief constructor for a given JSON instance\n    @param[in] object  pointer to a JSON object for this iterator\n    @pre object != nullptr\n    @post The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    explicit iter_impl(pointer object) noexcept : m_object(object)\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n            {\n                m_it.object_iterator = typename object_t::iterator();\n                break;\n            }\n\n            case value_t::array:\n            {\n                m_it.array_iterator = typename array_t::iterator();\n                break;\n            }\n\n            default:\n            {\n                m_it.primitive_iterator = primitive_iterator_t();\n                break;\n            }\n        }\n    }\n\n    /*!\n    @note The conventional copy constructor and copy assignment are implicitly\n          defined. Combined with the following converting constructor and\n          assignment, they support: (1) copy from iterator to iterator, (2)\n          copy from const iterator to const iterator, and (3) conversion from\n          iterator to const iterator. However conversion from const iterator\n          to iterator is not defined.\n    */\n\n    /*!\n    @brief converting constructor\n    @param[in] other  non-const iterator to copy from\n    @note It is not checked whether @a other is initialized.\n    */\n    iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept\n        : m_object(other.m_object), m_it(other.m_it) {}\n\n    /*!\n    @brief converting assignment\n    @param[in,out] other  non-const iterator to copy from\n    @return const/non-const iterator\n    @note It is not checked whether @a other is initialized.\n    */\n    iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept\n    {\n        m_object = other.m_object;\n        m_it = other.m_it;\n        return *this;\n    }\n\n  private:\n    /*!\n    @brief set the iterator to the first value\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    void set_begin() noexcept\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n            {\n                m_it.object_iterator = m_object->m_value.object->begin();\n                break;\n            }\n\n            case value_t::array:\n            {\n                m_it.array_iterator = m_object->m_value.array->begin();\n                break;\n            }\n\n            case value_t::null:\n            {\n                // set to end so begin()==end() is true: null is empty\n                m_it.primitive_iterator.set_end();\n                break;\n            }\n\n            default:\n            {\n                m_it.primitive_iterator.set_begin();\n                break;\n            }\n        }\n    }\n\n    /*!\n    @brief set the iterator past the last value\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    void set_end() noexcept\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n            {\n                m_it.object_iterator = m_object->m_value.object->end();\n                break;\n            }\n\n            case value_t::array:\n            {\n                m_it.array_iterator = m_object->m_value.array->end();\n                break;\n            }\n\n            default:\n            {\n                m_it.primitive_iterator.set_end();\n                break;\n            }\n        }\n    }\n\n  public:\n    /*!\n    @brief return a reference to the value pointed to by the iterator\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    reference operator*() const\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n            {\n                assert(m_it.object_iterator != m_object->m_value.object->end());\n                return m_it.object_iterator->second;\n            }\n\n            case value_t::array:\n            {\n                assert(m_it.array_iterator != m_object->m_value.array->end());\n                return *m_it.array_iterator;\n            }\n\n            case value_t::null:\n                JSON_THROW(invalid_iterator::create(214, \"cannot get value\"));\n\n            default:\n            {\n                if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))\n                {\n                    return *m_object;\n                }\n\n                JSON_THROW(invalid_iterator::create(214, \"cannot get value\"));\n            }\n        }\n    }\n\n    /*!\n    @brief dereference the iterator\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    pointer operator->() const\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n            {\n                assert(m_it.object_iterator != m_object->m_value.object->end());\n                return &(m_it.object_iterator->second);\n            }\n\n            case value_t::array:\n            {\n                assert(m_it.array_iterator != m_object->m_value.array->end());\n                return &*m_it.array_iterator;\n            }\n\n            default:\n            {\n                if (JSON_LIKELY(m_it.primitive_iterator.is_begin()))\n                {\n                    return m_object;\n                }\n\n                JSON_THROW(invalid_iterator::create(214, \"cannot get value\"));\n            }\n        }\n    }\n\n    /*!\n    @brief post-increment (it++)\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    iter_impl const operator++(int)\n    {\n        auto result = *this;\n        ++(*this);\n        return result;\n    }\n\n    /*!\n    @brief pre-increment (++it)\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    iter_impl& operator++()\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n            {\n                std::advance(m_it.object_iterator, 1);\n                break;\n            }\n\n            case value_t::array:\n            {\n                std::advance(m_it.array_iterator, 1);\n                break;\n            }\n\n            default:\n            {\n                ++m_it.primitive_iterator;\n                break;\n            }\n        }\n\n        return *this;\n    }\n\n    /*!\n    @brief post-decrement (it--)\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    iter_impl const operator--(int)\n    {\n        auto result = *this;\n        --(*this);\n        return result;\n    }\n\n    /*!\n    @brief pre-decrement (--it)\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    iter_impl& operator--()\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n            {\n                std::advance(m_it.object_iterator, -1);\n                break;\n            }\n\n            case value_t::array:\n            {\n                std::advance(m_it.array_iterator, -1);\n                break;\n            }\n\n            default:\n            {\n                --m_it.primitive_iterator;\n                break;\n            }\n        }\n\n        return *this;\n    }\n\n    /*!\n    @brief  comparison: equal\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    bool operator==(const iter_impl& other) const\n    {\n        // if objects are not the same, the comparison is undefined\n        if (JSON_UNLIKELY(m_object != other.m_object))\n        {\n            JSON_THROW(invalid_iterator::create(212, \"cannot compare iterators of different containers\"));\n        }\n\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n                return (m_it.object_iterator == other.m_it.object_iterator);\n\n            case value_t::array:\n                return (m_it.array_iterator == other.m_it.array_iterator);\n\n            default:\n                return (m_it.primitive_iterator == other.m_it.primitive_iterator);\n        }\n    }\n\n    /*!\n    @brief  comparison: not equal\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    bool operator!=(const iter_impl& other) const\n    {\n        return not operator==(other);\n    }\n\n    /*!\n    @brief  comparison: smaller\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    bool operator<(const iter_impl& other) const\n    {\n        // if objects are not the same, the comparison is undefined\n        if (JSON_UNLIKELY(m_object != other.m_object))\n        {\n            JSON_THROW(invalid_iterator::create(212, \"cannot compare iterators of different containers\"));\n        }\n\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n                JSON_THROW(invalid_iterator::create(213, \"cannot compare order of object iterators\"));\n\n            case value_t::array:\n                return (m_it.array_iterator < other.m_it.array_iterator);\n\n            default:\n                return (m_it.primitive_iterator < other.m_it.primitive_iterator);\n        }\n    }\n\n    /*!\n    @brief  comparison: less than or equal\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    bool operator<=(const iter_impl& other) const\n    {\n        return not other.operator < (*this);\n    }\n\n    /*!\n    @brief  comparison: greater than\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    bool operator>(const iter_impl& other) const\n    {\n        return not operator<=(other);\n    }\n\n    /*!\n    @brief  comparison: greater than or equal\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    bool operator>=(const iter_impl& other) const\n    {\n        return not operator<(other);\n    }\n\n    /*!\n    @brief  add to iterator\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    iter_impl& operator+=(difference_type i)\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n                JSON_THROW(invalid_iterator::create(209, \"cannot use offsets with object iterators\"));\n\n            case value_t::array:\n            {\n                std::advance(m_it.array_iterator, i);\n                break;\n            }\n\n            default:\n            {\n                m_it.primitive_iterator += i;\n                break;\n            }\n        }\n\n        return *this;\n    }\n\n    /*!\n    @brief  subtract from iterator\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    iter_impl& operator-=(difference_type i)\n    {\n        return operator+=(-i);\n    }\n\n    /*!\n    @brief  add to iterator\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    iter_impl operator+(difference_type i) const\n    {\n        auto result = *this;\n        result += i;\n        return result;\n    }\n\n    /*!\n    @brief  addition of distance and iterator\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    friend iter_impl operator+(difference_type i, const iter_impl& it)\n    {\n        auto result = it;\n        result += i;\n        return result;\n    }\n\n    /*!\n    @brief  subtract from iterator\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    iter_impl operator-(difference_type i) const\n    {\n        auto result = *this;\n        result -= i;\n        return result;\n    }\n\n    /*!\n    @brief  return difference\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    difference_type operator-(const iter_impl& other) const\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n                JSON_THROW(invalid_iterator::create(209, \"cannot use offsets with object iterators\"));\n\n            case value_t::array:\n                return m_it.array_iterator - other.m_it.array_iterator;\n\n            default:\n                return m_it.primitive_iterator - other.m_it.primitive_iterator;\n        }\n    }\n\n    /*!\n    @brief  access to successor\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    reference operator[](difference_type n) const\n    {\n        assert(m_object != nullptr);\n\n        switch (m_object->m_type)\n        {\n            case value_t::object:\n                JSON_THROW(invalid_iterator::create(208, \"cannot use operator[] for object iterators\"));\n\n            case value_t::array:\n                return *std::next(m_it.array_iterator, n);\n\n            case value_t::null:\n                JSON_THROW(invalid_iterator::create(214, \"cannot get value\"));\n\n            default:\n            {\n                if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n))\n                {\n                    return *m_object;\n                }\n\n                JSON_THROW(invalid_iterator::create(214, \"cannot get value\"));\n            }\n        }\n    }\n\n    /*!\n    @brief  return the key of an object iterator\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    typename object_t::key_type key() const\n    {\n        assert(m_object != nullptr);\n\n        if (JSON_LIKELY(m_object->is_object()))\n        {\n            return m_it.object_iterator->first;\n        }\n\n        JSON_THROW(invalid_iterator::create(207, \"cannot use key() for non-object iterators\"));\n    }\n\n    /*!\n    @brief  return the value of an iterator\n    @pre The iterator is initialized; i.e. `m_object != nullptr`.\n    */\n    reference value() const\n    {\n        return operator*();\n    }\n\n  private:\n    /// associated JSON instance\n    pointer m_object = nullptr;\n    /// the actual iterator of the associated instance\n    internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it = {};\n};\n\n/// proxy class for the iterator_wrapper functions\ntemplate<typename IteratorType> class iteration_proxy\n{\n  private:\n    /// helper class for iteration\n    class iteration_proxy_internal\n    {\n      private:\n        /// the iterator\n        IteratorType anchor;\n        /// an index for arrays (used to create key names)\n        std::size_t array_index = 0;\n\n      public:\n        explicit iteration_proxy_internal(IteratorType it) noexcept : anchor(it) {}\n\n        /// dereference operator (needed for range-based for)\n        iteration_proxy_internal& operator*()\n        {\n            return *this;\n        }\n\n        /// increment operator (needed for range-based for)\n        iteration_proxy_internal& operator++()\n        {\n            ++anchor;\n            ++array_index;\n\n            return *this;\n        }\n\n        /// inequality operator (needed for range-based for)\n        bool operator!=(const iteration_proxy_internal& o) const noexcept\n        {\n            return anchor != o.anchor;\n        }\n\n        /// return key of the iterator\n        std::string key() const\n        {\n            assert(anchor.m_object != nullptr);\n\n            switch (anchor.m_object->type())\n            {\n                // use integer array index as key\n                case value_t::array:\n                    return std::to_string(array_index);\n\n                // use key from the object\n                case value_t::object:\n                    return anchor.key();\n\n                // use an empty key for all primitive types\n                default:\n                    return \"\";\n            }\n        }\n\n        /// return value of the iterator\n        typename IteratorType::reference value() const\n        {\n            return anchor.value();\n        }\n    };\n\n    /// the container to iterate\n    typename IteratorType::reference container;\n\n  public:\n    /// construct iteration proxy from a container\n    explicit iteration_proxy(typename IteratorType::reference cont)\n        : container(cont) {}\n\n    /// return iterator begin (needed for range-based for)\n    iteration_proxy_internal begin() noexcept\n    {\n        return iteration_proxy_internal(container.begin());\n    }\n\n    /// return iterator end (needed for range-based for)\n    iteration_proxy_internal end() noexcept\n    {\n        return iteration_proxy_internal(container.end());\n    }\n};\n\n/*!\n@brief a template for a reverse iterator class\n\n@tparam Base the base iterator type to reverse. Valid types are @ref\niterator (to create @ref reverse_iterator) and @ref const_iterator (to\ncreate @ref const_reverse_iterator).\n\n@requirement The class satisfies the following concept requirements:\n-\n[BidirectionalIterator](http://en.cppreference.com/w/cpp/concept/BidirectionalIterator):\n  The iterator that can be moved can be moved in both directions (i.e.\n  incremented and decremented).\n- [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):\n  It is possible to write to the pointed-to element (only if @a Base is\n  @ref iterator).\n\n@since version 1.0.0\n*/\ntemplate<typename Base>\nclass json_reverse_iterator : public std::reverse_iterator<Base>\n{\n  public:\n    using difference_type = std::ptrdiff_t;\n    /// shortcut to the reverse iterator adapter\n    using base_iterator = std::reverse_iterator<Base>;\n    /// the reference type for the pointed-to element\n    using reference = typename Base::reference;\n\n    /// create reverse iterator from iterator\n    json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept\n        : base_iterator(it) {}\n\n    /// create reverse iterator from base class\n    json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {}\n\n    /// post-increment (it++)\n    json_reverse_iterator const operator++(int)\n    {\n        return static_cast<json_reverse_iterator>(base_iterator::operator++(1));\n    }\n\n    /// pre-increment (++it)\n    json_reverse_iterator& operator++()\n    {\n        return static_cast<json_reverse_iterator&>(base_iterator::operator++());\n    }\n\n    /// post-decrement (it--)\n    json_reverse_iterator const operator--(int)\n    {\n        return static_cast<json_reverse_iterator>(base_iterator::operator--(1));\n    }\n\n    /// pre-decrement (--it)\n    json_reverse_iterator& operator--()\n    {\n        return static_cast<json_reverse_iterator&>(base_iterator::operator--());\n    }\n\n    /// add to iterator\n    json_reverse_iterator& operator+=(difference_type i)\n    {\n        return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i));\n    }\n\n    /// add to iterator\n    json_reverse_iterator operator+(difference_type i) const\n    {\n        return static_cast<json_reverse_iterator>(base_iterator::operator+(i));\n    }\n\n    /// subtract from iterator\n    json_reverse_iterator operator-(difference_type i) const\n    {\n        return static_cast<json_reverse_iterator>(base_iterator::operator-(i));\n    }\n\n    /// return difference\n    difference_type operator-(const json_reverse_iterator& other) const\n    {\n        return base_iterator(*this) - base_iterator(other);\n    }\n\n    /// access to successor\n    reference operator[](difference_type n) const\n    {\n        return *(this->operator+(n));\n    }\n\n    /// return the key of an object iterator\n    auto key() const -> decltype(std::declval<Base>().key())\n    {\n        auto it = --this->base();\n        return it.key();\n    }\n\n    /// return the value of an iterator\n    reference value() const\n    {\n        auto it = --this->base();\n        return it.operator * ();\n    }\n};\n\n/////////////////////\n// output adapters //\n/////////////////////\n\n/// abstract output adapter interface\ntemplate<typename CharType> struct output_adapter_protocol\n{\n    virtual void write_character(CharType c) = 0;\n    virtual void write_characters(const CharType* s, std::size_t length) = 0;\n    virtual ~output_adapter_protocol() = default;\n};\n\n/// a type to simplify interfaces\ntemplate<typename CharType>\nusing output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>;\n\n/// output adapter for byte vectors\ntemplate<typename CharType>\nclass output_vector_adapter : public output_adapter_protocol<CharType>\n{\n  public:\n    explicit output_vector_adapter(std::vector<CharType>& vec) : v(vec) {}\n\n    void write_character(CharType c) override\n    {\n        v.push_back(c);\n    }\n\n    void write_characters(const CharType* s, std::size_t length) override\n    {\n        std::copy(s, s + length, std::back_inserter(v));\n    }\n\n  private:\n    std::vector<CharType>& v;\n};\n\n/// output adapter for output streams\ntemplate<typename CharType>\nclass output_stream_adapter : public output_adapter_protocol<CharType>\n{\n  public:\n    explicit output_stream_adapter(std::basic_ostream<CharType>& s) : stream(s) {}\n\n    void write_character(CharType c) override\n    {\n        stream.put(c);\n    }\n\n    void write_characters(const CharType* s, std::size_t length) override\n    {\n        stream.write(s, static_cast<std::streamsize>(length));\n    }\n\n  private:\n    std::basic_ostream<CharType>& stream;\n};\n\n/// output adapter for basic_string\ntemplate<typename CharType>\nclass output_string_adapter : public output_adapter_protocol<CharType>\n{\n  public:\n    explicit output_string_adapter(std::basic_string<CharType>& s) : str(s) {}\n\n    void write_character(CharType c) override\n    {\n        str.push_back(c);\n    }\n\n    void write_characters(const CharType* s, std::size_t length) override\n    {\n        str.append(s, length);\n    }\n\n  private:\n    std::basic_string<CharType>& str;\n};\n\ntemplate<typename CharType>\nclass output_adapter\n{\n  public:\n    output_adapter(std::vector<CharType>& vec)\n        : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {}\n\n    output_adapter(std::basic_ostream<CharType>& s)\n        : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {}\n\n    output_adapter(std::basic_string<CharType>& s)\n        : oa(std::make_shared<output_string_adapter<CharType>>(s)) {}\n\n    operator output_adapter_t<CharType>()\n    {\n        return oa;\n    }\n\n  private:\n    output_adapter_t<CharType> oa = nullptr;\n};\n\n//////////////////////////////\n// binary reader and writer //\n//////////////////////////////\n\n/*!\n@brief deserialization of CBOR and MessagePack values\n*/\ntemplate<typename BasicJsonType>\nclass binary_reader\n{\n    using number_integer_t = typename BasicJsonType::number_integer_t;\n    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n\n  public:\n    /*!\n    @brief create a binary reader\n\n    @param[in] adapter  input adapter to read from\n    */\n    explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter))\n    {\n        assert(ia);\n    }\n\n    /*!\n    @brief create a JSON value from CBOR input\n\n    @param[in] strict  whether to expect the input to be consumed completed\n    @return JSON value created from CBOR input\n\n    @throw parse_error.110 if input ended unexpectedly or the end of file was\n                           not reached when @a strict was set to true\n    @throw parse_error.112 if unsupported byte was read\n    */\n    BasicJsonType parse_cbor(const bool strict)\n    {\n        const auto res = parse_cbor_internal();\n        if (strict)\n        {\n            get();\n            check_eof(true);\n        }\n        return res;\n    }\n\n    /*!\n    @brief create a JSON value from MessagePack input\n\n    @param[in] strict  whether to expect the input to be consumed completed\n    @return JSON value created from MessagePack input\n\n    @throw parse_error.110 if input ended unexpectedly or the end of file was\n                           not reached when @a strict was set to true\n    @throw parse_error.112 if unsupported byte was read\n    */\n    BasicJsonType parse_msgpack(const bool strict)\n    {\n        const auto res = parse_msgpack_internal();\n        if (strict)\n        {\n            get();\n            check_eof(true);\n        }\n        return res;\n    }\n\n    /*!\n    @brief determine system byte order\n\n    @return true if and only if system's byte order is little endian\n\n    @note from http://stackoverflow.com/a/1001328/266378\n    */\n    static constexpr bool little_endianess(int num = 1) noexcept\n    {\n        return (*reinterpret_cast<char*>(&num) == 1);\n    }\n\n  private:\n    /*!\n    @param[in] get_char  whether a new character should be retrieved from the\n                         input (true, default) or whether the last read\n                         character should be considered instead\n    */\n    BasicJsonType parse_cbor_internal(const bool get_char = true)\n    {\n        switch (get_char ? get() : current)\n        {\n            // EOF\n            case std::char_traits<char>::eof():\n                JSON_THROW(parse_error::create(110, chars_read, \"unexpected end of input\"));\n\n            // Integer 0x00..0x17 (0..23)\n            case 0x00:\n            case 0x01:\n            case 0x02:\n            case 0x03:\n            case 0x04:\n            case 0x05:\n            case 0x06:\n            case 0x07:\n            case 0x08:\n            case 0x09:\n            case 0x0A:\n            case 0x0B:\n            case 0x0C:\n            case 0x0D:\n            case 0x0E:\n            case 0x0F:\n            case 0x10:\n            case 0x11:\n            case 0x12:\n            case 0x13:\n            case 0x14:\n            case 0x15:\n            case 0x16:\n            case 0x17:\n                return static_cast<number_unsigned_t>(current);\n\n            case 0x18: // Unsigned integer (one-byte uint8_t follows)\n                return get_number<uint8_t>();\n\n            case 0x19: // Unsigned integer (two-byte uint16_t follows)\n                return get_number<uint16_t>();\n\n            case 0x1A: // Unsigned integer (four-byte uint32_t follows)\n                return get_number<uint32_t>();\n\n            case 0x1B: // Unsigned integer (eight-byte uint64_t follows)\n                return get_number<uint64_t>();\n\n            // Negative integer -1-0x00..-1-0x17 (-1..-24)\n            case 0x20:\n            case 0x21:\n            case 0x22:\n            case 0x23:\n            case 0x24:\n            case 0x25:\n            case 0x26:\n            case 0x27:\n            case 0x28:\n            case 0x29:\n            case 0x2A:\n            case 0x2B:\n            case 0x2C:\n            case 0x2D:\n            case 0x2E:\n            case 0x2F:\n            case 0x30:\n            case 0x31:\n            case 0x32:\n            case 0x33:\n            case 0x34:\n            case 0x35:\n            case 0x36:\n            case 0x37:\n                return static_cast<int8_t>(0x20 - 1 - current);\n\n            case 0x38: // Negative integer (one-byte uint8_t follows)\n            {\n                // must be uint8_t !\n                return static_cast<number_integer_t>(-1) - get_number<uint8_t>();\n            }\n\n            case 0x39: // Negative integer -1-n (two-byte uint16_t follows)\n            {\n                return static_cast<number_integer_t>(-1) - get_number<uint16_t>();\n            }\n\n            case 0x3A: // Negative integer -1-n (four-byte uint32_t follows)\n            {\n                return static_cast<number_integer_t>(-1) - get_number<uint32_t>();\n            }\n\n            case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows)\n            {\n                return static_cast<number_integer_t>(-1) -\n                       static_cast<number_integer_t>(get_number<uint64_t>());\n            }\n\n            // UTF-8 string (0x00..0x17 bytes follow)\n            case 0x60:\n            case 0x61:\n            case 0x62:\n            case 0x63:\n            case 0x64:\n            case 0x65:\n            case 0x66:\n            case 0x67:\n            case 0x68:\n            case 0x69:\n            case 0x6A:\n            case 0x6B:\n            case 0x6C:\n            case 0x6D:\n            case 0x6E:\n            case 0x6F:\n            case 0x70:\n            case 0x71:\n            case 0x72:\n            case 0x73:\n            case 0x74:\n            case 0x75:\n            case 0x76:\n            case 0x77:\n            case 0x78: // UTF-8 string (one-byte uint8_t for n follows)\n            case 0x79: // UTF-8 string (two-byte uint16_t for n follow)\n            case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)\n            case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)\n            case 0x7F: // UTF-8 string (indefinite length)\n            {\n                return get_cbor_string();\n            }\n\n            // array (0x00..0x17 data items follow)\n            case 0x80:\n            case 0x81:\n            case 0x82:\n            case 0x83:\n            case 0x84:\n            case 0x85:\n            case 0x86:\n            case 0x87:\n            case 0x88:\n            case 0x89:\n            case 0x8A:\n            case 0x8B:\n            case 0x8C:\n            case 0x8D:\n            case 0x8E:\n            case 0x8F:\n            case 0x90:\n            case 0x91:\n            case 0x92:\n            case 0x93:\n            case 0x94:\n            case 0x95:\n            case 0x96:\n            case 0x97:\n            {\n                return get_cbor_array(current & 0x1F);\n            }\n\n            case 0x98: // array (one-byte uint8_t for n follows)\n            {\n                return get_cbor_array(get_number<uint8_t>());\n            }\n\n            case 0x99: // array (two-byte uint16_t for n follow)\n            {\n                return get_cbor_array(get_number<uint16_t>());\n            }\n\n            case 0x9A: // array (four-byte uint32_t for n follow)\n            {\n                return get_cbor_array(get_number<uint32_t>());\n            }\n\n            case 0x9B: // array (eight-byte uint64_t for n follow)\n            {\n                return get_cbor_array(get_number<uint64_t>());\n            }\n\n            case 0x9F: // array (indefinite length)\n            {\n                BasicJsonType result = value_t::array;\n                while (get() != 0xFF)\n                {\n                    result.push_back(parse_cbor_internal(false));\n                }\n                return result;\n            }\n\n            // map (0x00..0x17 pairs of data items follow)\n            case 0xA0:\n            case 0xA1:\n            case 0xA2:\n            case 0xA3:\n            case 0xA4:\n            case 0xA5:\n            case 0xA6:\n            case 0xA7:\n            case 0xA8:\n            case 0xA9:\n            case 0xAA:\n            case 0xAB:\n            case 0xAC:\n            case 0xAD:\n            case 0xAE:\n            case 0xAF:\n            case 0xB0:\n            case 0xB1:\n            case 0xB2:\n            case 0xB3:\n            case 0xB4:\n            case 0xB5:\n            case 0xB6:\n            case 0xB7:\n            {\n                return get_cbor_object(current & 0x1F);\n            }\n\n            case 0xB8: // map (one-byte uint8_t for n follows)\n            {\n                return get_cbor_object(get_number<uint8_t>());\n            }\n\n            case 0xB9: // map (two-byte uint16_t for n follow)\n            {\n                return get_cbor_object(get_number<uint16_t>());\n            }\n\n            case 0xBA: // map (four-byte uint32_t for n follow)\n            {\n                return get_cbor_object(get_number<uint32_t>());\n            }\n\n            case 0xBB: // map (eight-byte uint64_t for n follow)\n            {\n                return get_cbor_object(get_number<uint64_t>());\n            }\n\n            case 0xBF: // map (indefinite length)\n            {\n                BasicJsonType result = value_t::object;\n                while (get() != 0xFF)\n                {\n                    auto key = get_cbor_string();\n                    result[key] = parse_cbor_internal();\n                }\n                return result;\n            }\n\n            case 0xF4: // false\n            {\n                return false;\n            }\n\n            case 0xF5: // true\n            {\n                return true;\n            }\n\n            case 0xF6: // null\n            {\n                return value_t::null;\n            }\n\n            case 0xF9: // Half-Precision Float (two-byte IEEE 754)\n            {\n                const int byte1 = get();\n                check_eof();\n                const int byte2 = get();\n                check_eof();\n\n                // code from RFC 7049, Appendix D, Figure 3:\n                // As half-precision floating-point numbers were only added\n                // to IEEE 754 in 2008, today's programming platforms often\n                // still only have limited support for them. It is very\n                // easy to include at least decoding support for them even\n                // without such support. An example of a small decoder for\n                // half-precision floating-point numbers in the C language\n                // is shown in Fig. 3.\n                const int half = (byte1 << 8) + byte2;\n                const int exp = (half >> 10) & 0x1F;\n                const int mant = half & 0x3FF;\n                double val;\n                if (exp == 0)\n                {\n                    val = std::ldexp(mant, -24);\n                }\n                else if (exp != 31)\n                {\n                    val = std::ldexp(mant + 1024, exp - 25);\n                }\n                else\n                {\n                    val = (mant == 0) ? std::numeric_limits<double>::infinity()\n                          : std::numeric_limits<double>::quiet_NaN();\n                }\n                return (half & 0x8000) != 0 ? -val : val;\n            }\n\n            case 0xFA: // Single-Precision Float (four-byte IEEE 754)\n            {\n                return get_number<float>();\n            }\n\n            case 0xFB: // Double-Precision Float (eight-byte IEEE 754)\n            {\n                return get_number<double>();\n            }\n\n            default: // anything else (0xFF is handled inside the other types)\n            {\n                std::stringstream ss;\n                ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;\n                JSON_THROW(parse_error::create(112, chars_read, \"error reading CBOR; last byte: 0x\" + ss.str()));\n            }\n        }\n    }\n\n    BasicJsonType parse_msgpack_internal()\n    {\n        switch (get())\n        {\n            // EOF\n            case std::char_traits<char>::eof():\n                JSON_THROW(parse_error::create(110, chars_read, \"unexpected end of input\"));\n\n            // positive fixint\n            case 0x00:\n            case 0x01:\n            case 0x02:\n            case 0x03:\n            case 0x04:\n            case 0x05:\n            case 0x06:\n            case 0x07:\n            case 0x08:\n            case 0x09:\n            case 0x0A:\n            case 0x0B:\n            case 0x0C:\n            case 0x0D:\n            case 0x0E:\n            case 0x0F:\n            case 0x10:\n            case 0x11:\n            case 0x12:\n            case 0x13:\n            case 0x14:\n            case 0x15:\n            case 0x16:\n            case 0x17:\n            case 0x18:\n            case 0x19:\n            case 0x1A:\n            case 0x1B:\n            case 0x1C:\n            case 0x1D:\n            case 0x1E:\n            case 0x1F:\n            case 0x20:\n            case 0x21:\n            case 0x22:\n            case 0x23:\n            case 0x24:\n            case 0x25:\n            case 0x26:\n            case 0x27:\n            case 0x28:\n            case 0x29:\n            case 0x2A:\n            case 0x2B:\n            case 0x2C:\n            case 0x2D:\n            case 0x2E:\n            case 0x2F:\n            case 0x30:\n            case 0x31:\n            case 0x32:\n            case 0x33:\n            case 0x34:\n            case 0x35:\n            case 0x36:\n            case 0x37:\n            case 0x38:\n            case 0x39:\n            case 0x3A:\n            case 0x3B:\n            case 0x3C:\n            case 0x3D:\n            case 0x3E:\n            case 0x3F:\n            case 0x40:\n            case 0x41:\n            case 0x42:\n            case 0x43:\n            case 0x44:\n            case 0x45:\n            case 0x46:\n            case 0x47:\n            case 0x48:\n            case 0x49:\n            case 0x4A:\n            case 0x4B:\n            case 0x4C:\n            case 0x4D:\n            case 0x4E:\n            case 0x4F:\n            case 0x50:\n            case 0x51:\n            case 0x52:\n            case 0x53:\n            case 0x54:\n            case 0x55:\n            case 0x56:\n            case 0x57:\n            case 0x58:\n            case 0x59:\n            case 0x5A:\n            case 0x5B:\n            case 0x5C:\n            case 0x5D:\n            case 0x5E:\n            case 0x5F:\n            case 0x60:\n            case 0x61:\n            case 0x62:\n            case 0x63:\n            case 0x64:\n            case 0x65:\n            case 0x66:\n            case 0x67:\n            case 0x68:\n            case 0x69:\n            case 0x6A:\n            case 0x6B:\n            case 0x6C:\n            case 0x6D:\n            case 0x6E:\n            case 0x6F:\n            case 0x70:\n            case 0x71:\n            case 0x72:\n            case 0x73:\n            case 0x74:\n            case 0x75:\n            case 0x76:\n            case 0x77:\n            case 0x78:\n            case 0x79:\n            case 0x7A:\n            case 0x7B:\n            case 0x7C:\n            case 0x7D:\n            case 0x7E:\n            case 0x7F:\n                return static_cast<number_unsigned_t>(current);\n\n            // fixmap\n            case 0x80:\n            case 0x81:\n            case 0x82:\n            case 0x83:\n            case 0x84:\n            case 0x85:\n            case 0x86:\n            case 0x87:\n            case 0x88:\n            case 0x89:\n            case 0x8A:\n            case 0x8B:\n            case 0x8C:\n            case 0x8D:\n            case 0x8E:\n            case 0x8F:\n            {\n                return get_msgpack_object(current & 0x0F);\n            }\n\n            // fixarray\n            case 0x90:\n            case 0x91:\n            case 0x92:\n            case 0x93:\n            case 0x94:\n            case 0x95:\n            case 0x96:\n            case 0x97:\n            case 0x98:\n            case 0x99:\n            case 0x9A:\n            case 0x9B:\n            case 0x9C:\n            case 0x9D:\n            case 0x9E:\n            case 0x9F:\n            {\n                return get_msgpack_array(current & 0x0F);\n            }\n\n            // fixstr\n            case 0xA0:\n            case 0xA1:\n            case 0xA2:\n            case 0xA3:\n            case 0xA4:\n            case 0xA5:\n            case 0xA6:\n            case 0xA7:\n            case 0xA8:\n            case 0xA9:\n            case 0xAA:\n            case 0xAB:\n            case 0xAC:\n            case 0xAD:\n            case 0xAE:\n            case 0xAF:\n            case 0xB0:\n            case 0xB1:\n            case 0xB2:\n            case 0xB3:\n            case 0xB4:\n            case 0xB5:\n            case 0xB6:\n            case 0xB7:\n            case 0xB8:\n            case 0xB9:\n            case 0xBA:\n            case 0xBB:\n            case 0xBC:\n            case 0xBD:\n            case 0xBE:\n            case 0xBF:\n                return get_msgpack_string();\n\n            case 0xC0: // nil\n                return value_t::null;\n\n            case 0xC2: // false\n                return false;\n\n            case 0xC3: // true\n                return true;\n\n            case 0xCA: // float 32\n                return get_number<float>();\n\n            case 0xCB: // float 64\n                return get_number<double>();\n\n            case 0xCC: // uint 8\n                return get_number<uint8_t>();\n\n            case 0xCD: // uint 16\n                return get_number<uint16_t>();\n\n            case 0xCE: // uint 32\n                return get_number<uint32_t>();\n\n            case 0xCF: // uint 64\n                return get_number<uint64_t>();\n\n            case 0xD0: // int 8\n                return get_number<int8_t>();\n\n            case 0xD1: // int 16\n                return get_number<int16_t>();\n\n            case 0xD2: // int 32\n                return get_number<int32_t>();\n\n            case 0xD3: // int 64\n                return get_number<int64_t>();\n\n            case 0xD9: // str 8\n            case 0xDA: // str 16\n            case 0xDB: // str 32\n                return get_msgpack_string();\n\n            case 0xDC: // array 16\n            {\n                return get_msgpack_array(get_number<uint16_t>());\n            }\n\n            case 0xDD: // array 32\n            {\n                return get_msgpack_array(get_number<uint32_t>());\n            }\n\n            case 0xDE: // map 16\n            {\n                return get_msgpack_object(get_number<uint16_t>());\n            }\n\n            case 0xDF: // map 32\n            {\n                return get_msgpack_object(get_number<uint32_t>());\n            }\n\n            // positive fixint\n            case 0xE0:\n            case 0xE1:\n            case 0xE2:\n            case 0xE3:\n            case 0xE4:\n            case 0xE5:\n            case 0xE6:\n            case 0xE7:\n            case 0xE8:\n            case 0xE9:\n            case 0xEA:\n            case 0xEB:\n            case 0xEC:\n            case 0xED:\n            case 0xEE:\n            case 0xEF:\n            case 0xF0:\n            case 0xF1:\n            case 0xF2:\n            case 0xF3:\n            case 0xF4:\n            case 0xF5:\n            case 0xF6:\n            case 0xF7:\n            case 0xF8:\n            case 0xF9:\n            case 0xFA:\n            case 0xFB:\n            case 0xFC:\n            case 0xFD:\n            case 0xFE:\n            case 0xFF:\n                return static_cast<int8_t>(current);\n\n            default: // anything else\n            {\n                std::stringstream ss;\n                ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;\n                JSON_THROW(parse_error::create(112, chars_read,\n                                               \"error reading MessagePack; last byte: 0x\" + ss.str()));\n            }\n        }\n    }\n\n    /*!\n    @brief get next character from the input\n\n    This function provides the interface to the used input adapter. It does\n    not throw in case the input reached EOF, but returns a -'ve valued\n    `std::char_traits<char>::eof()` in that case.\n\n    @return character read from the input\n    */\n    int get()\n    {\n        ++chars_read;\n        return (current = ia->get_character());\n    }\n\n    /*\n    @brief read a number from the input\n\n    @tparam NumberType the type of the number\n\n    @return number of type @a NumberType\n\n    @note This function needs to respect the system's endianess, because\n          bytes in CBOR and MessagePack are stored in network order (big\n          endian) and therefore need reordering on little endian systems.\n\n    @throw parse_error.110 if input has less than `sizeof(NumberType)` bytes\n    */\n    template<typename NumberType> NumberType get_number()\n    {\n        // step 1: read input into array with system's byte order\n        std::array<uint8_t, sizeof(NumberType)> vec;\n        for (std::size_t i = 0; i < sizeof(NumberType); ++i)\n        {\n            get();\n            check_eof();\n\n            // reverse byte order prior to conversion if necessary\n            if (is_little_endian)\n            {\n                vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current);\n            }\n            else\n            {\n                vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE\n            }\n        }\n\n        // step 2: convert array into number of type T and return\n        NumberType result;\n        std::memcpy(&result, vec.data(), sizeof(NumberType));\n        return result;\n    }\n\n    /*!\n    @brief create a string by reading characters from the input\n\n    @param[in] len number of bytes to read\n\n    @note We can not reserve @a len bytes for the result, because @a len\n          may be too large. Usually, @ref check_eof() detects the end of\n          the input before we run out of string memory.\n\n    @return string created by reading @a len bytes\n\n    @throw parse_error.110 if input has less than @a len bytes\n    */\n    template<typename NumberType>\n    std::string get_string(const NumberType len)\n    {\n        std::string result;\n        std::generate_n(std::back_inserter(result), len, [this]()\n        {\n            get();\n            check_eof();\n            return static_cast<char>(current);\n        });\n        return result;\n    }\n\n    /*!\n    @brief reads a CBOR string\n\n    This function first reads starting bytes to determine the expected\n    string length and then copies this number of bytes into a string.\n    Additionally, CBOR's strings with indefinite lengths are supported.\n\n    @return string\n\n    @throw parse_error.110 if input ended\n    @throw parse_error.113 if an unexpected byte is read\n    */\n    std::string get_cbor_string()\n    {\n        check_eof();\n\n        switch (current)\n        {\n            // UTF-8 string (0x00..0x17 bytes follow)\n            case 0x60:\n            case 0x61:\n            case 0x62:\n            case 0x63:\n            case 0x64:\n            case 0x65:\n            case 0x66:\n            case 0x67:\n            case 0x68:\n            case 0x69:\n            case 0x6A:\n            case 0x6B:\n            case 0x6C:\n            case 0x6D:\n            case 0x6E:\n            case 0x6F:\n            case 0x70:\n            case 0x71:\n            case 0x72:\n            case 0x73:\n            case 0x74:\n            case 0x75:\n            case 0x76:\n            case 0x77:\n            {\n                return get_string(current & 0x1F);\n            }\n\n            case 0x78: // UTF-8 string (one-byte uint8_t for n follows)\n            {\n                return get_string(get_number<uint8_t>());\n            }\n\n            case 0x79: // UTF-8 string (two-byte uint16_t for n follow)\n            {\n                return get_string(get_number<uint16_t>());\n            }\n\n            case 0x7A: // UTF-8 string (four-byte uint32_t for n follow)\n            {\n                return get_string(get_number<uint32_t>());\n            }\n\n            case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow)\n            {\n                return get_string(get_number<uint64_t>());\n            }\n\n            case 0x7F: // UTF-8 string (indefinite length)\n            {\n                std::string result;\n                while (get() != 0xFF)\n                {\n                    check_eof();\n                    result.push_back(static_cast<char>(current));\n                }\n                return result;\n            }\n\n            default:\n            {\n                std::stringstream ss;\n                ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;\n                JSON_THROW(parse_error::create(113, chars_read, \"expected a CBOR string; last byte: 0x\" + ss.str()));\n            }\n        }\n    }\n\n    template<typename NumberType>\n    BasicJsonType get_cbor_array(const NumberType len)\n    {\n        BasicJsonType result = value_t::array;\n        std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()\n        {\n            return parse_cbor_internal();\n        });\n        return result;\n    }\n\n    template<typename NumberType>\n    BasicJsonType get_cbor_object(const NumberType len)\n    {\n        BasicJsonType result = value_t::object;\n        std::generate_n(std::inserter(*result.m_value.object,\n                                      result.m_value.object->end()),\n                        len, [this]()\n        {\n            get();\n            auto key = get_cbor_string();\n            auto val = parse_cbor_internal();\n            return std::make_pair(std::move(key), std::move(val));\n        });\n        return result;\n    }\n\n    /*!\n    @brief reads a MessagePack string\n\n    This function first reads starting bytes to determine the expected\n    string length and then copies this number of bytes into a string.\n\n    @return string\n\n    @throw parse_error.110 if input ended\n    @throw parse_error.113 if an unexpected byte is read\n    */\n    std::string get_msgpack_string()\n    {\n        check_eof();\n\n        switch (current)\n        {\n            // fixstr\n            case 0xA0:\n            case 0xA1:\n            case 0xA2:\n            case 0xA3:\n            case 0xA4:\n            case 0xA5:\n            case 0xA6:\n            case 0xA7:\n            case 0xA8:\n            case 0xA9:\n            case 0xAA:\n            case 0xAB:\n            case 0xAC:\n            case 0xAD:\n            case 0xAE:\n            case 0xAF:\n            case 0xB0:\n            case 0xB1:\n            case 0xB2:\n            case 0xB3:\n            case 0xB4:\n            case 0xB5:\n            case 0xB6:\n            case 0xB7:\n            case 0xB8:\n            case 0xB9:\n            case 0xBA:\n            case 0xBB:\n            case 0xBC:\n            case 0xBD:\n            case 0xBE:\n            case 0xBF:\n            {\n                return get_string(current & 0x1F);\n            }\n\n            case 0xD9: // str 8\n            {\n                return get_string(get_number<uint8_t>());\n            }\n\n            case 0xDA: // str 16\n            {\n                return get_string(get_number<uint16_t>());\n            }\n\n            case 0xDB: // str 32\n            {\n                return get_string(get_number<uint32_t>());\n            }\n\n            default:\n            {\n                std::stringstream ss;\n                ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << current;\n                JSON_THROW(parse_error::create(113, chars_read,\n                                               \"expected a MessagePack string; last byte: 0x\" + ss.str()));\n            }\n        }\n    }\n\n    template<typename NumberType>\n    BasicJsonType get_msgpack_array(const NumberType len)\n    {\n        BasicJsonType result = value_t::array;\n        std::generate_n(std::back_inserter(*result.m_value.array), len, [this]()\n        {\n            return parse_msgpack_internal();\n        });\n        return result;\n    }\n\n    template<typename NumberType>\n    BasicJsonType get_msgpack_object(const NumberType len)\n    {\n        BasicJsonType result = value_t::object;\n        std::generate_n(std::inserter(*result.m_value.object,\n                                      result.m_value.object->end()),\n                        len, [this]()\n        {\n            get();\n            auto key = get_msgpack_string();\n            auto val = parse_msgpack_internal();\n            return std::make_pair(std::move(key), std::move(val));\n        });\n        return result;\n    }\n\n    /*!\n    @brief check if input ended\n    @throw parse_error.110 if input ended\n    */\n    void check_eof(const bool expect_eof = false) const\n    {\n        if (expect_eof)\n        {\n            if (JSON_UNLIKELY(current != std::char_traits<char>::eof()))\n            {\n                JSON_THROW(parse_error::create(110, chars_read, \"expected end of input\"));\n            }\n        }\n        else\n        {\n            if (JSON_UNLIKELY(current == std::char_traits<char>::eof()))\n            {\n                JSON_THROW(parse_error::create(110, chars_read, \"unexpected end of input\"));\n            }\n        }\n    }\n\n  private:\n    /// input adapter\n    input_adapter_t ia = nullptr;\n\n    /// the current character\n    int current = std::char_traits<char>::eof();\n\n    /// the number of characters read\n    std::size_t chars_read = 0;\n\n    /// whether we can assume little endianess\n    const bool is_little_endian = little_endianess();\n};\n\n/*!\n@brief serialization to CBOR and MessagePack values\n*/\ntemplate<typename BasicJsonType, typename CharType>\nclass binary_writer\n{\n  public:\n    /*!\n    @brief create a binary writer\n\n    @param[in] adapter  output adapter to write to\n    */\n    explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter)\n    {\n        assert(oa);\n    }\n\n    /*!\n    @brief[in] j  JSON value to serialize\n    */\n    void write_cbor(const BasicJsonType& j)\n    {\n        switch (j.type())\n        {\n            case value_t::null:\n            {\n                oa->write_character(static_cast<CharType>(0xF6));\n                break;\n            }\n\n            case value_t::boolean:\n            {\n                oa->write_character(j.m_value.boolean\n                                    ? static_cast<CharType>(0xF5)\n                                    : static_cast<CharType>(0xF4));\n                break;\n            }\n\n            case value_t::number_integer:\n            {\n                if (j.m_value.number_integer >= 0)\n                {\n                    // CBOR does not differentiate between positive signed\n                    // integers and unsigned integers. Therefore, we used the\n                    // code from the value_t::number_unsigned case here.\n                    if (j.m_value.number_integer <= 0x17)\n                    {\n                        write_number(static_cast<uint8_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)())\n                    {\n                        oa->write_character(static_cast<CharType>(0x18));\n                        write_number(static_cast<uint8_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)())\n                    {\n                        oa->write_character(static_cast<CharType>(0x19));\n                        write_number(static_cast<uint16_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)())\n                    {\n                        oa->write_character(static_cast<CharType>(0x1A));\n                        write_number(static_cast<uint32_t>(j.m_value.number_integer));\n                    }\n                    else\n                    {\n                        oa->write_character(static_cast<CharType>(0x1B));\n                        write_number(static_cast<uint64_t>(j.m_value.number_integer));\n                    }\n                }\n                else\n                {\n                    // The conversions below encode the sign in the first\n                    // byte, and the value is converted to a positive number.\n                    const auto positive_number = -1 - j.m_value.number_integer;\n                    if (j.m_value.number_integer >= -24)\n                    {\n                        write_number(static_cast<uint8_t>(0x20 + positive_number));\n                    }\n                    else if (positive_number <= (std::numeric_limits<uint8_t>::max)())\n                    {\n                        oa->write_character(static_cast<CharType>(0x38));\n                        write_number(static_cast<uint8_t>(positive_number));\n                    }\n                    else if (positive_number <= (std::numeric_limits<uint16_t>::max)())\n                    {\n                        oa->write_character(static_cast<CharType>(0x39));\n                        write_number(static_cast<uint16_t>(positive_number));\n                    }\n                    else if (positive_number <= (std::numeric_limits<uint32_t>::max)())\n                    {\n                        oa->write_character(static_cast<CharType>(0x3A));\n                        write_number(static_cast<uint32_t>(positive_number));\n                    }\n                    else\n                    {\n                        oa->write_character(static_cast<CharType>(0x3B));\n                        write_number(static_cast<uint64_t>(positive_number));\n                    }\n                }\n                break;\n            }\n\n            case value_t::number_unsigned:\n            {\n                if (j.m_value.number_unsigned <= 0x17)\n                {\n                    write_number(static_cast<uint8_t>(j.m_value.number_unsigned));\n                }\n                else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())\n                {\n                    oa->write_character(static_cast<CharType>(0x18));\n                    write_number(static_cast<uint8_t>(j.m_value.number_unsigned));\n                }\n                else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())\n                {\n                    oa->write_character(static_cast<CharType>(0x19));\n                    write_number(static_cast<uint16_t>(j.m_value.number_unsigned));\n                }\n                else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())\n                {\n                    oa->write_character(static_cast<CharType>(0x1A));\n                    write_number(static_cast<uint32_t>(j.m_value.number_unsigned));\n                }\n                else\n                {\n                    oa->write_character(static_cast<CharType>(0x1B));\n                    write_number(static_cast<uint64_t>(j.m_value.number_unsigned));\n                }\n                break;\n            }\n\n            case value_t::number_float: // Double-Precision Float\n            {\n                oa->write_character(static_cast<CharType>(0xFB));\n                write_number(j.m_value.number_float);\n                break;\n            }\n\n            case value_t::string:\n            {\n                // step 1: write control byte and the string length\n                const auto N = j.m_value.string->size();\n                if (N <= 0x17)\n                {\n                    write_number(static_cast<uint8_t>(0x60 + N));\n                }\n                else if (N <= 0xFF)\n                {\n                    oa->write_character(static_cast<CharType>(0x78));\n                    write_number(static_cast<uint8_t>(N));\n                }\n                else if (N <= 0xFFFF)\n                {\n                    oa->write_character(static_cast<CharType>(0x79));\n                    write_number(static_cast<uint16_t>(N));\n                }\n                else if (N <= 0xFFFFFFFF)\n                {\n                    oa->write_character(static_cast<CharType>(0x7A));\n                    write_number(static_cast<uint32_t>(N));\n                }\n                // LCOV_EXCL_START\n                else if (N <= 0xFFFFFFFFFFFFFFFF)\n                {\n                    oa->write_character(static_cast<CharType>(0x7B));\n                    write_number(static_cast<uint64_t>(N));\n                }\n                // LCOV_EXCL_STOP\n\n                // step 2: write the string\n                oa->write_characters(\n                    reinterpret_cast<const CharType*>(j.m_value.string->c_str()),\n                    j.m_value.string->size());\n                break;\n            }\n\n            case value_t::array:\n            {\n                // step 1: write control byte and the array size\n                const auto N = j.m_value.array->size();\n                if (N <= 0x17)\n                {\n                    write_number(static_cast<uint8_t>(0x80 + N));\n                }\n                else if (N <= 0xFF)\n                {\n                    oa->write_character(static_cast<CharType>(0x98));\n                    write_number(static_cast<uint8_t>(N));\n                }\n                else if (N <= 0xFFFF)\n                {\n                    oa->write_character(static_cast<CharType>(0x99));\n                    write_number(static_cast<uint16_t>(N));\n                }\n                else if (N <= 0xFFFFFFFF)\n                {\n                    oa->write_character(static_cast<CharType>(0x9A));\n                    write_number(static_cast<uint32_t>(N));\n                }\n                // LCOV_EXCL_START\n                else if (N <= 0xFFFFFFFFFFFFFFFF)\n                {\n                    oa->write_character(static_cast<CharType>(0x9B));\n                    write_number(static_cast<uint64_t>(N));\n                }\n                // LCOV_EXCL_STOP\n\n                // step 2: write each element\n                for (const auto& el : *j.m_value.array)\n                {\n                    write_cbor(el);\n                }\n                break;\n            }\n\n            case value_t::object:\n            {\n                // step 1: write control byte and the object size\n                const auto N = j.m_value.object->size();\n                if (N <= 0x17)\n                {\n                    write_number(static_cast<uint8_t>(0xA0 + N));\n                }\n                else if (N <= 0xFF)\n                {\n                    oa->write_character(static_cast<CharType>(0xB8));\n                    write_number(static_cast<uint8_t>(N));\n                }\n                else if (N <= 0xFFFF)\n                {\n                    oa->write_character(static_cast<CharType>(0xB9));\n                    write_number(static_cast<uint16_t>(N));\n                }\n                else if (N <= 0xFFFFFFFF)\n                {\n                    oa->write_character(static_cast<CharType>(0xBA));\n                    write_number(static_cast<uint32_t>(N));\n                }\n                // LCOV_EXCL_START\n                else if (N <= 0xFFFFFFFFFFFFFFFF)\n                {\n                    oa->write_character(static_cast<CharType>(0xBB));\n                    write_number(static_cast<uint64_t>(N));\n                }\n                // LCOV_EXCL_STOP\n\n                // step 2: write each element\n                for (const auto& el : *j.m_value.object)\n                {\n                    write_cbor(el.first);\n                    write_cbor(el.second);\n                }\n                break;\n            }\n\n            default:\n                break;\n        }\n    }\n\n    /*!\n    @brief[in] j  JSON value to serialize\n    */\n    void write_msgpack(const BasicJsonType& j)\n    {\n        switch (j.type())\n        {\n            case value_t::null: // nil\n            {\n                oa->write_character(static_cast<CharType>(0xC0));\n                break;\n            }\n\n            case value_t::boolean: // true and false\n            {\n                oa->write_character(j.m_value.boolean\n                                    ? static_cast<CharType>(0xC3)\n                                    : static_cast<CharType>(0xC2));\n                break;\n            }\n\n            case value_t::number_integer:\n            {\n                if (j.m_value.number_integer >= 0)\n                {\n                    // MessagePack does not differentiate between positive\n                    // signed integers and unsigned integers. Therefore, we used\n                    // the code from the value_t::number_unsigned case here.\n                    if (j.m_value.number_unsigned < 128)\n                    {\n                        // positive fixnum\n                        write_number(static_cast<uint8_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())\n                    {\n                        // uint 8\n                        oa->write_character(static_cast<CharType>(0xCC));\n                        write_number(static_cast<uint8_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())\n                    {\n                        // uint 16\n                        oa->write_character(static_cast<CharType>(0xCD));\n                        write_number(static_cast<uint16_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())\n                    {\n                        // uint 32\n                        oa->write_character(static_cast<CharType>(0xCE));\n                        write_number(static_cast<uint32_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())\n                    {\n                        // uint 64\n                        oa->write_character(static_cast<CharType>(0xCF));\n                        write_number(static_cast<uint64_t>(j.m_value.number_integer));\n                    }\n                }\n                else\n                {\n                    if (j.m_value.number_integer >= -32)\n                    {\n                        // negative fixnum\n                        write_number(static_cast<int8_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and\n                             j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)())\n                    {\n                        // int 8\n                        oa->write_character(static_cast<CharType>(0xD0));\n                        write_number(static_cast<int8_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and\n                             j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)())\n                    {\n                        // int 16\n                        oa->write_character(static_cast<CharType>(0xD1));\n                        write_number(static_cast<int16_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and\n                             j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)())\n                    {\n                        // int 32\n                        oa->write_character(static_cast<CharType>(0xD2));\n                        write_number(static_cast<int32_t>(j.m_value.number_integer));\n                    }\n                    else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and\n                             j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)())\n                    {\n                        // int 64\n                        oa->write_character(static_cast<CharType>(0xD3));\n                        write_number(static_cast<int64_t>(j.m_value.number_integer));\n                    }\n                }\n                break;\n            }\n\n            case value_t::number_unsigned:\n            {\n                if (j.m_value.number_unsigned < 128)\n                {\n                    // positive fixnum\n                    write_number(static_cast<uint8_t>(j.m_value.number_integer));\n                }\n                else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)())\n                {\n                    // uint 8\n                    oa->write_character(static_cast<CharType>(0xCC));\n                    write_number(static_cast<uint8_t>(j.m_value.number_integer));\n                }\n                else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)())\n                {\n                    // uint 16\n                    oa->write_character(static_cast<CharType>(0xCD));\n                    write_number(static_cast<uint16_t>(j.m_value.number_integer));\n                }\n                else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)())\n                {\n                    // uint 32\n                    oa->write_character(static_cast<CharType>(0xCE));\n                    write_number(static_cast<uint32_t>(j.m_value.number_integer));\n                }\n                else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)())\n                {\n                    // uint 64\n                    oa->write_character(static_cast<CharType>(0xCF));\n                    write_number(static_cast<uint64_t>(j.m_value.number_integer));\n                }\n                break;\n            }\n\n            case value_t::number_float: // float 64\n            {\n                oa->write_character(static_cast<CharType>(0xCB));\n                write_number(j.m_value.number_float);\n                break;\n            }\n\n            case value_t::string:\n            {\n                // step 1: write control byte and the string length\n                const auto N = j.m_value.string->size();\n                if (N <= 31)\n                {\n                    // fixstr\n                    write_number(static_cast<uint8_t>(0xA0 | N));\n                }\n                else if (N <= 255)\n                {\n                    // str 8\n                    oa->write_character(static_cast<CharType>(0xD9));\n                    write_number(static_cast<uint8_t>(N));\n                }\n                else if (N <= 65535)\n                {\n                    // str 16\n                    oa->write_character(static_cast<CharType>(0xDA));\n                    write_number(static_cast<uint16_t>(N));\n                }\n                else if (N <= 4294967295)\n                {\n                    // str 32\n                    oa->write_character(static_cast<CharType>(0xDB));\n                    write_number(static_cast<uint32_t>(N));\n                }\n\n                // step 2: write the string\n                oa->write_characters(\n                    reinterpret_cast<const CharType*>(j.m_value.string->c_str()),\n                    j.m_value.string->size());\n                break;\n            }\n\n            case value_t::array:\n            {\n                // step 1: write control byte and the array size\n                const auto N = j.m_value.array->size();\n                if (N <= 15)\n                {\n                    // fixarray\n                    write_number(static_cast<uint8_t>(0x90 | N));\n                }\n                else if (N <= 0xFFFF)\n                {\n                    // array 16\n                    oa->write_character(static_cast<CharType>(0xDC));\n                    write_number(static_cast<uint16_t>(N));\n                }\n                else if (N <= 0xFFFFFFFF)\n                {\n                    // array 32\n                    oa->write_character(static_cast<CharType>(0xDD));\n                    write_number(static_cast<uint32_t>(N));\n                }\n\n                // step 2: write each element\n                for (const auto& el : *j.m_value.array)\n                {\n                    write_msgpack(el);\n                }\n                break;\n            }\n\n            case value_t::object:\n            {\n                // step 1: write control byte and the object size\n                const auto N = j.m_value.object->size();\n                if (N <= 15)\n                {\n                    // fixmap\n                    write_number(static_cast<uint8_t>(0x80 | (N & 0xF)));\n                }\n                else if (N <= 65535)\n                {\n                    // map 16\n                    oa->write_character(static_cast<CharType>(0xDE));\n                    write_number(static_cast<uint16_t>(N));\n                }\n                else if (N <= 4294967295)\n                {\n                    // map 32\n                    oa->write_character(static_cast<CharType>(0xDF));\n                    write_number(static_cast<uint32_t>(N));\n                }\n\n                // step 2: write each element\n                for (const auto& el : *j.m_value.object)\n                {\n                    write_msgpack(el.first);\n                    write_msgpack(el.second);\n                }\n                break;\n            }\n\n            default:\n                break;\n        }\n    }\n\n  private:\n    /*\n    @brief write a number to output input\n\n    @param[in] n number of type @a NumberType\n    @tparam NumberType the type of the number\n\n    @note This function needs to respect the system's endianess, because bytes\n          in CBOR and MessagePack are stored in network order (big endian) and\n          therefore need reordering on little endian systems.\n    */\n    template<typename NumberType> void write_number(NumberType n)\n    {\n        // step 1: write number to array of length NumberType\n        std::array<CharType, sizeof(NumberType)> vec;\n        std::memcpy(vec.data(), &n, sizeof(NumberType));\n\n        // step 2: write array to output (with possible reordering)\n        if (is_little_endian)\n        {\n            // reverse byte order prior to conversion if necessary\n            std::reverse(vec.begin(), vec.end());\n        }\n\n        oa->write_characters(vec.data(), sizeof(NumberType));\n    }\n\n  private:\n    /// whether we can assume little endianess\n    const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess();\n\n    /// the output\n    output_adapter_t<CharType> oa = nullptr;\n};\n\n///////////////////\n// serialization //\n///////////////////\n\ntemplate<typename BasicJsonType>\nclass serializer\n{\n    using string_t = typename BasicJsonType::string_t;\n    using number_float_t = typename BasicJsonType::number_float_t;\n    using number_integer_t = typename BasicJsonType::number_integer_t;\n    using number_unsigned_t = typename BasicJsonType::number_unsigned_t;\n  public:\n    /*!\n    @param[in] s  output stream to serialize to\n    @param[in] ichar  indentation character to use\n    */\n    serializer(output_adapter_t<char> s, const char ichar)\n        : o(std::move(s)), loc(std::localeconv()),\n          thousands_sep(loc->thousands_sep == nullptr ? '\\0' : * (loc->thousands_sep)),\n          decimal_point(loc->decimal_point == nullptr ? '\\0' : * (loc->decimal_point)),\n          indent_char(ichar), indent_string(512, indent_char) {}\n\n    // delete because of pointer members\n    serializer(const serializer&) = delete;\n    serializer& operator=(const serializer&) = delete;\n\n    /*!\n    @brief internal implementation of the serialization function\n\n    This function is called by the public member function dump and organizes\n    the serialization internally. The indentation level is propagated as\n    additional parameter. In case of arrays and objects, the function is\n    called recursively.\n\n    - strings and object keys are escaped using `escape_string()`\n    - integer numbers are converted implicitly via `operator<<`\n    - floating-point numbers are converted to a string using `\"%g\"` format\n\n    @param[in] val             value to serialize\n    @param[in] pretty_print    whether the output shall be pretty-printed\n    @param[in] indent_step     the indent level\n    @param[in] current_indent  the current indent level (only used internally)\n    */\n    void dump(const BasicJsonType& val, const bool pretty_print,\n              const bool ensure_ascii,\n              const unsigned int indent_step,\n              const unsigned int current_indent = 0)\n    {\n        switch (val.m_type)\n        {\n            case value_t::object:\n            {\n                if (val.m_value.object->empty())\n                {\n                    o->write_characters(\"{}\", 2);\n                    return;\n                }\n\n                if (pretty_print)\n                {\n                    o->write_characters(\"{\\n\", 2);\n\n                    // variable to hold indentation for recursive calls\n                    const auto new_indent = current_indent + indent_step;\n                    if (JSON_UNLIKELY(indent_string.size() < new_indent))\n                    {\n                        indent_string.resize(indent_string.size() * 2, ' ');\n                    }\n\n                    // first n-1 elements\n                    auto i = val.m_value.object->cbegin();\n                    for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)\n                    {\n                        o->write_characters(indent_string.c_str(), new_indent);\n                        o->write_character('\\\"');\n                        dump_escaped(i->first, ensure_ascii);\n                        o->write_characters(\"\\\": \", 3);\n                        dump(i->second, true, ensure_ascii, indent_step, new_indent);\n                        o->write_characters(\",\\n\", 2);\n                    }\n\n                    // last element\n                    assert(i != val.m_value.object->cend());\n                    assert(std::next(i) == val.m_value.object->cend());\n                    o->write_characters(indent_string.c_str(), new_indent);\n                    o->write_character('\\\"');\n                    dump_escaped(i->first, ensure_ascii);\n                    o->write_characters(\"\\\": \", 3);\n                    dump(i->second, true, ensure_ascii, indent_step, new_indent);\n\n                    o->write_character('\\n');\n                    o->write_characters(indent_string.c_str(), current_indent);\n                    o->write_character('}');\n                }\n                else\n                {\n                    o->write_character('{');\n\n                    // first n-1 elements\n                    auto i = val.m_value.object->cbegin();\n                    for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i)\n                    {\n                        o->write_character('\\\"');\n                        dump_escaped(i->first, ensure_ascii);\n                        o->write_characters(\"\\\":\", 2);\n                        dump(i->second, false, ensure_ascii, indent_step, current_indent);\n                        o->write_character(',');\n                    }\n\n                    // last element\n                    assert(i != val.m_value.object->cend());\n                    assert(std::next(i) == val.m_value.object->cend());\n                    o->write_character('\\\"');\n                    dump_escaped(i->first, ensure_ascii);\n                    o->write_characters(\"\\\":\", 2);\n                    dump(i->second, false, ensure_ascii, indent_step, current_indent);\n\n                    o->write_character('}');\n                }\n\n                return;\n            }\n\n            case value_t::array:\n            {\n                if (val.m_value.array->empty())\n                {\n                    o->write_characters(\"[]\", 2);\n                    return;\n                }\n\n                if (pretty_print)\n                {\n                    o->write_characters(\"[\\n\", 2);\n\n                    // variable to hold indentation for recursive calls\n                    const auto new_indent = current_indent + indent_step;\n                    if (JSON_UNLIKELY(indent_string.size() < new_indent))\n                    {\n                        indent_string.resize(indent_string.size() * 2, ' ');\n                    }\n\n                    // first n-1 elements\n                    for (auto i = val.m_value.array->cbegin();\n                            i != val.m_value.array->cend() - 1; ++i)\n                    {\n                        o->write_characters(indent_string.c_str(), new_indent);\n                        dump(*i, true, ensure_ascii, indent_step, new_indent);\n                        o->write_characters(\",\\n\", 2);\n                    }\n\n                    // last element\n                    assert(not val.m_value.array->empty());\n                    o->write_characters(indent_string.c_str(), new_indent);\n                    dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent);\n\n                    o->write_character('\\n');\n                    o->write_characters(indent_string.c_str(), current_indent);\n                    o->write_character(']');\n                }\n                else\n                {\n                    o->write_character('[');\n\n                    // first n-1 elements\n                    for (auto i = val.m_value.array->cbegin();\n                            i != val.m_value.array->cend() - 1; ++i)\n                    {\n                        dump(*i, false, ensure_ascii, indent_step, current_indent);\n                        o->write_character(',');\n                    }\n\n                    // last element\n                    assert(not val.m_value.array->empty());\n                    dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent);\n\n                    o->write_character(']');\n                }\n\n                return;\n            }\n\n            case value_t::string:\n            {\n                o->write_character('\\\"');\n                dump_escaped(*val.m_value.string, ensure_ascii);\n                o->write_character('\\\"');\n                return;\n            }\n\n            case value_t::boolean:\n            {\n                if (val.m_value.boolean)\n                {\n                    o->write_characters(\"true\", 4);\n                }\n                else\n                {\n                    o->write_characters(\"false\", 5);\n                }\n                return;\n            }\n\n            case value_t::number_integer:\n            {\n                dump_integer(val.m_value.number_integer);\n                return;\n            }\n\n            case value_t::number_unsigned:\n            {\n                dump_integer(val.m_value.number_unsigned);\n                return;\n            }\n\n            case value_t::number_float:\n            {\n                dump_float(val.m_value.number_float);\n                return;\n            }\n\n            case value_t::discarded:\n            {\n                o->write_characters(\"<discarded>\", 11);\n                return;\n            }\n\n            case value_t::null:\n            {\n                o->write_characters(\"null\", 4);\n                return;\n            }\n        }\n    }\n\n  private:\n    /*!\n    @brief returns the number of expected bytes following in UTF-8 string\n\n    @param[in]  u  the first byte of a UTF-8 string\n    @return  the number of expected bytes following\n    */\n    static constexpr std::size_t bytes_following(const uint8_t u)\n    {\n        return ((u <= 127) ? 0\n                : ((192 <= u and u <= 223) ? 1\n                   : ((224 <= u and u <= 239) ? 2\n                      : ((240 <= u and u <= 247) ? 3 : std::string::npos))));\n    }\n\n    /*!\n    @brief calculates the extra space to escape a JSON string\n\n    @param[in] s  the string to escape\n    @param[in] ensure_ascii  whether to escape non-ASCII characters with\n                             \\uXXXX sequences\n    @return the number of characters required to escape string @a s\n\n    @complexity Linear in the length of string @a s.\n    */\n    static std::size_t extra_space(const string_t& s,\n                                   const bool ensure_ascii) noexcept\n    {\n        std::size_t res = 0;\n\n        for (std::size_t i = 0; i < s.size(); ++i)\n        {\n            switch (s[i])\n            {\n                // control characters that can be escaped with a backslash\n                case '\"':\n                case '\\\\':\n                case '\\b':\n                case '\\f':\n                case '\\n':\n                case '\\r':\n                case '\\t':\n                {\n                    // from c (1 byte) to \\x (2 bytes)\n                    res += 1;\n                    break;\n                }\n\n                // control characters that need \\uxxxx escaping\n                case 0x00:\n                case 0x01:\n                case 0x02:\n                case 0x03:\n                case 0x04:\n                case 0x05:\n                case 0x06:\n                case 0x07:\n                case 0x0B:\n                case 0x0E:\n                case 0x0F:\n                case 0x10:\n                case 0x11:\n                case 0x12:\n                case 0x13:\n                case 0x14:\n                case 0x15:\n                case 0x16:\n                case 0x17:\n                case 0x18:\n                case 0x19:\n                case 0x1A:\n                case 0x1B:\n                case 0x1C:\n                case 0x1D:\n                case 0x1E:\n                case 0x1F:\n                {\n                    // from c (1 byte) to \\uxxxx (6 bytes)\n                    res += 5;\n                    break;\n                }\n\n                default:\n                {\n                    if (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F))\n                    {\n                        const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));\n                        // invalid characters will be detected by throw_if_invalid_utf8\n                        assert (bytes != std::string::npos);\n\n                        if (bytes == 3)\n                        {\n                            // codepoints that need 4 bytes (i.e., 3 additional\n                            // bytes) in UTF-8 need a surrogate pair when \\u\n                            // escaping is used: from 4 bytes to \\uxxxx\\uxxxx\n                            // (12 bytes)\n                            res += (12 - bytes - 1);\n                        }\n                        else\n                        {\n                            // from x bytes to \\uxxxx (6 bytes)\n                            res += (6 - bytes - 1);\n                        }\n\n                        // skip the additional bytes\n                        i += bytes;\n                    }\n                    break;\n                }\n            }\n        }\n\n        return res;\n    }\n\n    static void escape_codepoint(int codepoint, string_t& result, std::size_t& pos)\n    {\n        // expecting a proper codepoint\n        assert(0x00 <= codepoint and codepoint <= 0x10FFFF);\n\n        // the last written character was the backslash before the 'u'\n        assert(result[pos] == '\\\\');\n\n        // write the 'u'\n        result[++pos] = 'u';\n\n        // convert a number 0..15 to its hex representation (0..f)\n        static const std::array<char, 16> hexify =\n        {\n            {\n                '0', '1', '2', '3', '4', '5', '6', '7',\n                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'\n            }\n        };\n\n        if (codepoint < 0x10000)\n        {\n            // codepoints U+0000..U+FFFF can be represented as \\uxxxx.\n            result[++pos] = hexify[(codepoint >> 12) & 0x0F];\n            result[++pos] = hexify[(codepoint >> 8) & 0x0F];\n            result[++pos] = hexify[(codepoint >> 4) & 0x0F];\n            result[++pos] = hexify[codepoint & 0x0F];\n        }\n        else\n        {\n            // codepoints U+10000..U+10FFFF need a surrogate pair to be\n            // represented as \\uxxxx\\uxxxx.\n            // http://www.unicode.org/faq/utf_bom.html#utf16-4\n            codepoint -= 0x10000;\n            const int high_surrogate = 0xD800 | ((codepoint >> 10) & 0x3FF);\n            const int low_surrogate = 0xDC00 | (codepoint & 0x3FF);\n            result[++pos] = hexify[(high_surrogate >> 12) & 0x0F];\n            result[++pos] = hexify[(high_surrogate >> 8) & 0x0F];\n            result[++pos] = hexify[(high_surrogate >> 4) & 0x0F];\n            result[++pos] = hexify[high_surrogate & 0x0F];\n            ++pos;  // backslash is already in output\n            result[++pos] = 'u';\n            result[++pos] = hexify[(low_surrogate >> 12) & 0x0F];\n            result[++pos] = hexify[(low_surrogate >> 8) & 0x0F];\n            result[++pos] = hexify[(low_surrogate >> 4) & 0x0F];\n            result[++pos] = hexify[low_surrogate & 0x0F];\n        }\n\n        ++pos;\n    }\n\n    /*!\n    @brief dump escaped string\n\n    Escape a string by replacing certain special characters by a sequence of an\n    escape character (backslash) and another character and other control\n    characters by a sequence of \"\\u\" followed by a four-digit hex\n    representation. The escaped string is written to output stream @a o.\n\n    @param[in] s  the string to escape\n    @param[in] ensure_ascii  whether to escape non-ASCII characters with\n                             \\uXXXX sequences\n\n    @complexity Linear in the length of string @a s.\n    */\n    void dump_escaped(const string_t& s, const bool ensure_ascii) const\n    {\n        throw_if_invalid_utf8(s);\n\n        const auto space = extra_space(s, ensure_ascii);\n        if (space == 0)\n        {\n            o->write_characters(s.c_str(), s.size());\n            return;\n        }\n\n        // create a result string of necessary size\n        string_t result(s.size() + space, '\\\\');\n        std::size_t pos = 0;\n\n        for (std::size_t i = 0; i < s.size(); ++i)\n        {\n            switch (s[i])\n            {\n                case '\"': // quotation mark (0x22)\n                {\n                    result[pos + 1] = '\"';\n                    pos += 2;\n                    break;\n                }\n\n                case '\\\\': // reverse solidus (0x5C)\n                {\n                    // nothing to change\n                    pos += 2;\n                    break;\n                }\n\n                case '\\b': // backspace (0x08)\n                {\n                    result[pos + 1] = 'b';\n                    pos += 2;\n                    break;\n                }\n\n                case '\\f': // formfeed (0x0C)\n                {\n                    result[pos + 1] = 'f';\n                    pos += 2;\n                    break;\n                }\n\n                case '\\n': // newline (0x0A)\n                {\n                    result[pos + 1] = 'n';\n                    pos += 2;\n                    break;\n                }\n\n                case '\\r': // carriage return (0x0D)\n                {\n                    result[pos + 1] = 'r';\n                    pos += 2;\n                    break;\n                }\n\n                case '\\t': // horizontal tab (0x09)\n                {\n                    result[pos + 1] = 't';\n                    pos += 2;\n                    break;\n                }\n\n                default:\n                {\n                    // escape control characters (0x00..0x1F) or, if\n                    // ensure_ascii parameter is used, non-ASCII characters\n                    if ((0x00 <= s[i] and s[i] <= 0x1F) or\n                            (ensure_ascii and (s[i] & 0x80 or s[i] == 0x7F)))\n                    {\n                        const auto bytes = bytes_following(static_cast<uint8_t>(s[i]));\n                        // invalid characters will be detected by throw_if_invalid_utf8\n                        assert (bytes != std::string::npos);\n\n                        // check that the additional bytes are present\n                        assert(i + bytes < s.size());\n\n                        // to use \\uxxxx escaping, we first need to calculate\n                        // the codepoint from the UTF-8 bytes\n                        int codepoint = 0;\n\n                        // bytes is unsigned type:\n                        assert(bytes <= 3);\n                        switch (bytes)\n                        {\n                            case 0:\n                            {\n                                codepoint = s[i] & 0xFF;\n                                break;\n                            }\n\n                            case 1:\n                            {\n                                codepoint = ((s[i] & 0x3F) << 6)\n                                            + (s[i + 1] & 0x7F);\n                                break;\n                            }\n\n                            case 2:\n                            {\n                                codepoint = ((s[i] & 0x1F) << 12)\n                                            + ((s[i + 1] & 0x7F) << 6)\n                                            + (s[i + 2] & 0x7F);\n                                break;\n                            }\n\n                            case 3:\n                            {\n                                codepoint = ((s[i] & 0xF) << 18)\n                                            + ((s[i + 1] & 0x7F) << 12)\n                                            + ((s[i + 2] & 0x7F) << 6)\n                                            + (s[i + 3] & 0x7F);\n                                break;\n                            }\n\n                            default:\n                                break;  // LCOV_EXCL_LINE\n                        }\n\n                        escape_codepoint(codepoint, result, pos);\n                        i += bytes;\n                    }\n                    else\n                    {\n                        // all other characters are added as-is\n                        result[pos++] = s[i];\n                    }\n                    break;\n                }\n            }\n        }\n\n        assert(pos == result.size());\n        o->write_characters(result.c_str(), result.size());\n    }\n\n    /*!\n    @brief dump an integer\n\n    Dump a given integer to output stream @a o. Works internally with\n    @a number_buffer.\n\n    @param[in] x  integer number (signed or unsigned) to dump\n    @tparam NumberType either @a number_integer_t or @a number_unsigned_t\n    */\n    template<typename NumberType, detail::enable_if_t<\n                 std::is_same<NumberType, number_unsigned_t>::value or\n                 std::is_same<NumberType, number_integer_t>::value,\n                 int> = 0>\n    void dump_integer(NumberType x)\n    {\n        // special case for \"0\"\n        if (x == 0)\n        {\n            o->write_character('0');\n            return;\n        }\n\n        const bool is_negative = (x <= 0) and (x != 0);  // see issue #755\n        std::size_t i = 0;\n\n        while (x != 0)\n        {\n            // spare 1 byte for '\\0'\n            assert(i < number_buffer.size() - 1);\n\n            const auto digit = std::labs(static_cast<long>(x % 10));\n            number_buffer[i++] = static_cast<char>('0' + digit);\n            x /= 10;\n        }\n\n        if (is_negative)\n        {\n            // make sure there is capacity for the '-'\n            assert(i < number_buffer.size() - 2);\n            number_buffer[i++] = '-';\n        }\n\n        std::reverse(number_buffer.begin(), number_buffer.begin() + i);\n        o->write_characters(number_buffer.data(), i);\n    }\n\n    /*!\n    @brief dump a floating-point number\n\n    Dump a given floating-point number to output stream @a o. Works internally\n    with @a number_buffer.\n\n    @param[in] x  floating-point number to dump\n    */\n    void dump_float(number_float_t x)\n    {\n        // NaN / inf\n        if (not std::isfinite(x) or std::isnan(x))\n        {\n            o->write_characters(\"null\", 4);\n            return;\n        }\n\n        // get number of digits for a text -> float -> text round-trip\n        static constexpr auto d = std::numeric_limits<number_float_t>::digits10;\n\n        // the actual conversion\n        std::ptrdiff_t len = snprintf(number_buffer.data(), number_buffer.size(), \"%.*g\", d, x);\n\n        // negative value indicates an error\n        assert(len > 0);\n        // check if buffer was large enough\n        assert(static_cast<std::size_t>(len) < number_buffer.size());\n\n        // erase thousands separator\n        if (thousands_sep != '\\0')\n        {\n            const auto end = std::remove(number_buffer.begin(),\n                                         number_buffer.begin() + len, thousands_sep);\n            std::fill(end, number_buffer.end(), '\\0');\n            assert((end - number_buffer.begin()) <= len);\n            len = (end - number_buffer.begin());\n        }\n\n        // convert decimal point to '.'\n        if (decimal_point != '\\0' and decimal_point != '.')\n        {\n            const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point);\n            if (dec_pos != number_buffer.end())\n            {\n                *dec_pos = '.';\n            }\n        }\n\n        o->write_characters(number_buffer.data(), static_cast<std::size_t>(len));\n\n        // determine if need to append \".0\"\n        const bool value_is_int_like =\n            std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1,\n                         [](char c)\n        {\n            return (c == '.' or c == 'e');\n        });\n\n        if (value_is_int_like)\n        {\n            o->write_characters(\".0\", 2);\n        }\n    }\n\n    /*!\n    @brief check whether a string is UTF-8 encoded\n\n    The function checks each byte of a string whether it is UTF-8 encoded. The\n    result of the check is stored in the @a state parameter. The function must\n    be called initially with state 0 (accept). State 1 means the string must\n    be rejected, because the current byte is not allowed. If the string is\n    completely processed, but the state is non-zero, the string ended\n    prematurely; that is, the last byte indicated more bytes should have\n    followed.\n\n    @param[in,out] state  the state of the decoding\n    @param[in] byte       next byte to decode\n\n    @note The function has been edited: a std::array is used and the code\n          point is not calculated.\n\n    @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>\n    @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/\n    */\n    static void decode(uint8_t& state, const uint8_t byte)\n    {\n        static const std::array<uint8_t, 400> utf8d =\n        {\n            {\n                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F\n                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F\n                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F\n                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F\n                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F\n                7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF\n                8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF\n                0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF\n                0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF\n                0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0\n                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2\n                1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4\n                1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6\n                1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8\n            }\n        };\n\n        const uint8_t type = utf8d[byte];\n        state = utf8d[256u + state * 16u + type];\n    }\n\n    /*!\n    @brief throw an exception if a string is not UTF-8 encoded\n\n    @param[in] str  UTF-8 string to check\n    @throw type_error.316 if passed string is not UTF-8 encoded\n\n    @since version 3.0.0\n    */\n    static void throw_if_invalid_utf8(const std::string& str)\n    {\n        // start with state 0 (= accept)\n        uint8_t state = 0;\n\n        for (size_t i = 0; i < str.size(); ++i)\n        {\n            const auto byte = static_cast<uint8_t>(str[i]);\n            decode(state, byte);\n            if (state == 1)\n            {\n                // state 1 means reject\n                std::stringstream ss;\n                ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(byte);\n                JSON_THROW(type_error::create(316, \"invalid UTF-8 byte at index \" + std::to_string(i) + \": 0x\" + ss.str()));\n            }\n        }\n\n        if (state != 0)\n        {\n            // we finish reading, but do not accept: string was incomplete\n            std::stringstream ss;\n            ss << std::setw(2) << std::uppercase << std::setfill('0') << std::hex << static_cast<int>(static_cast<uint8_t>(str.back()));\n            JSON_THROW(type_error::create(316, \"incomplete UTF-8 string; last byte: 0x\" + ss.str()));\n        }\n    }\n\n  private:\n    /// the output of the serializer\n    output_adapter_t<char> o = nullptr;\n\n    /// a (hopefully) large enough character buffer\n    std::array<char, 64> number_buffer{{}};\n\n    /// the locale\n    const std::lconv* loc = nullptr;\n    /// the locale's thousand separator character\n    const char thousands_sep = '\\0';\n    /// the locale's decimal point character\n    const char decimal_point = '\\0';\n\n    /// the indentation character\n    const char indent_char;\n\n    /// the indentation string\n    string_t indent_string;\n};\n\ntemplate<typename BasicJsonType>\nclass json_ref\n{\n  public:\n    using value_type = BasicJsonType;\n\n    json_ref(value_type&& value)\n        : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true)\n    {}\n\n    json_ref(const value_type& value)\n        : value_ref(const_cast<value_type*>(&value)), is_rvalue(false)\n    {}\n\n    json_ref(std::initializer_list<json_ref> init)\n        : owned_value(init), value_ref(&owned_value), is_rvalue(true)\n    {}\n\n    template<class... Args>\n    json_ref(Args&& ... args)\n        : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true)\n    {}\n\n    // class should be movable only\n    json_ref(json_ref&&) = default;\n    json_ref(const json_ref&) = delete;\n    json_ref& operator=(const json_ref&) = delete;\n\n    value_type moved_or_copied() const\n    {\n        if (is_rvalue)\n        {\n            return std::move(*value_ref);\n        }\n        return *value_ref;\n    }\n\n    value_type const& operator*() const\n    {\n        return *static_cast<value_type const*>(value_ref);\n    }\n\n    value_type const* operator->() const\n    {\n        return static_cast<value_type const*>(value_ref);\n    }\n\n  private:\n    mutable value_type owned_value = nullptr;\n    value_type* value_ref = nullptr;\n    const bool is_rvalue;\n};\n\n} // namespace detail\n\n/// namespace to hold default `to_json` / `from_json` functions\nnamespace\n{\nconstexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;\nconstexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;\n}\n\n\n/*!\n@brief default JSONSerializer template argument\n\nThis serializer ignores the template arguments and uses ADL\n([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))\nfor serialization.\n*/\ntemplate<typename, typename>\nstruct adl_serializer\n{\n    /*!\n    @brief convert a JSON value to any value type\n\n    This function is usually called by the `get()` function of the\n    @ref basic_json class (either explicit or via conversion operators).\n\n    @param[in] j         JSON value to read from\n    @param[in,out] val  value to write to\n    */\n    template<typename BasicJsonType, typename ValueType>\n    static void from_json(BasicJsonType&& j, ValueType& val) noexcept(\n        noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))\n    {\n        ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);\n    }\n\n    /*!\n    @brief convert any value type to a JSON value\n\n    This function is usually called by the constructors of the @ref basic_json\n    class.\n\n    @param[in,out] j  JSON value to write to\n    @param[in] val     value to read from\n    */\n    template<typename BasicJsonType, typename ValueType>\n    static void to_json(BasicJsonType& j, ValueType&& val) noexcept(\n        noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))\n    {\n        ::nlohmann::to_json(j, std::forward<ValueType>(val));\n    }\n};\n\n/*!\n@brief JSON Pointer\n\nA JSON pointer defines a string syntax for identifying a specific value\nwithin a JSON document. It can be used with functions `at` and\n`operator[]`. Furthermore, JSON pointers are the base for JSON patches.\n\n@sa [RFC 6901](https://tools.ietf.org/html/rfc6901)\n\n@since version 2.0.0\n*/\nclass json_pointer\n{\n    /// allow basic_json to access private members\n    NLOHMANN_BASIC_JSON_TPL_DECLARATION\n    friend class basic_json;\n\n  public:\n    /*!\n    @brief create JSON pointer\n\n    Create a JSON pointer according to the syntax described in\n    [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).\n\n    @param[in] s  string representing the JSON pointer; if omitted, the empty\n                  string is assumed which references the whole JSON value\n\n    @throw parse_error.107 if the given JSON pointer @a s is nonempty and\n    does not begin with a slash (`/`); see example below\n\n    @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s\n    is not followed by `0` (representing `~`) or `1` (representing `/`);\n    see example below\n\n    @liveexample{The example shows the construction several valid JSON\n    pointers as well as the exceptional behavior.,json_pointer}\n\n    @since version 2.0.0\n    */\n    explicit json_pointer(const std::string& s = \"\") : reference_tokens(split(s)) {}\n\n    /*!\n    @brief return a string representation of the JSON pointer\n\n    @invariant For each JSON pointer `ptr`, it holds:\n    @code {.cpp}\n    ptr == json_pointer(ptr.to_string());\n    @endcode\n\n    @return a string representation of the JSON pointer\n\n    @liveexample{The example shows the result of `to_string`.,\n    json_pointer__to_string}\n\n    @since version 2.0.0\n    */\n    std::string to_string() const noexcept\n    {\n        return std::accumulate(reference_tokens.begin(), reference_tokens.end(),\n                               std::string{},\n                               [](const std::string & a, const std::string & b)\n        {\n            return a + \"/\" + escape(b);\n        });\n    }\n\n    /// @copydoc to_string()\n    operator std::string() const\n    {\n        return to_string();\n    }\n\n    /*!\n    @param[in] s  reference token to be converted into an array index\n\n    @return integer representation of @a s\n\n    @throw out_of_range.404 if string @a s could not be converted to an integer\n    */\n    static int array_index(const std::string& s)\n    {\n        size_t processed_chars = 0;\n        const int res = std::stoi(s, &processed_chars);\n\n        // check if the string was completely read\n        if (JSON_UNLIKELY(processed_chars != s.size()))\n        {\n            JSON_THROW(detail::out_of_range::create(404, \"unresolved reference token '\" + s + \"'\"));\n        }\n\n        return res;\n    }\n\n  private:\n    /*!\n    @brief remove and return last reference pointer\n    @throw out_of_range.405 if JSON pointer has no parent\n    */\n    std::string pop_back()\n    {\n        if (JSON_UNLIKELY(is_root()))\n        {\n            JSON_THROW(detail::out_of_range::create(405, \"JSON pointer has no parent\"));\n        }\n\n        auto last = reference_tokens.back();\n        reference_tokens.pop_back();\n        return last;\n    }\n\n    /// return whether pointer points to the root document\n    bool is_root() const\n    {\n        return reference_tokens.empty();\n    }\n\n    json_pointer top() const\n    {\n        if (JSON_UNLIKELY(is_root()))\n        {\n            JSON_THROW(detail::out_of_range::create(405, \"JSON pointer has no parent\"));\n        }\n\n        json_pointer result = *this;\n        result.reference_tokens = {reference_tokens[0]};\n        return result;\n    }\n\n    /*!\n    @brief create and return a reference to the pointed to value\n\n    @complexity Linear in the number of reference tokens.\n\n    @throw parse_error.109 if array index is not a number\n    @throw type_error.313 if value cannot be unflattened\n    */\n    NLOHMANN_BASIC_JSON_TPL_DECLARATION\n    NLOHMANN_BASIC_JSON_TPL& get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const;\n\n    /*!\n    @brief return a reference to the pointed to value\n\n    @note This version does not throw if a value is not present, but tries to\n          create nested values instead. For instance, calling this function\n          with pointer `\"/this/that\"` on a null value is equivalent to calling\n          `operator[](\"this\").operator[](\"that\")` on that value, effectively\n          changing the null value to an object.\n\n    @param[in] ptr  a JSON value\n\n    @return reference to the JSON value pointed to by the JSON pointer\n\n    @complexity Linear in the length of the JSON pointer.\n\n    @throw parse_error.106   if an array index begins with '0'\n    @throw parse_error.109   if an array index was not a number\n    @throw out_of_range.404  if the JSON pointer can not be resolved\n    */\n    NLOHMANN_BASIC_JSON_TPL_DECLARATION\n    NLOHMANN_BASIC_JSON_TPL& get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const;\n\n    /*!\n    @throw parse_error.106   if an array index begins with '0'\n    @throw parse_error.109   if an array index was not a number\n    @throw out_of_range.402  if the array index '-' is used\n    @throw out_of_range.404  if the JSON pointer can not be resolved\n    */\n    NLOHMANN_BASIC_JSON_TPL_DECLARATION\n    NLOHMANN_BASIC_JSON_TPL& get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const;\n\n    /*!\n    @brief return a const reference to the pointed to value\n\n    @param[in] ptr  a JSON value\n\n    @return const reference to the JSON value pointed to by the JSON\n    pointer\n\n    @throw parse_error.106   if an array index begins with '0'\n    @throw parse_error.109   if an array index was not a number\n    @throw out_of_range.402  if the array index '-' is used\n    @throw out_of_range.404  if the JSON pointer can not be resolved\n    */\n    NLOHMANN_BASIC_JSON_TPL_DECLARATION\n    const NLOHMANN_BASIC_JSON_TPL& get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;\n\n    /*!\n    @throw parse_error.106   if an array index begins with '0'\n    @throw parse_error.109   if an array index was not a number\n    @throw out_of_range.402  if the array index '-' is used\n    @throw out_of_range.404  if the JSON pointer can not be resolved\n    */\n    NLOHMANN_BASIC_JSON_TPL_DECLARATION\n    const NLOHMANN_BASIC_JSON_TPL& get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const;\n\n    /*!\n    @brief split the string input to reference tokens\n\n    @note This function is only called by the json_pointer constructor.\n          All exceptions below are documented there.\n\n    @throw parse_error.107  if the pointer is not empty or begins with '/'\n    @throw parse_error.108  if character '~' is not followed by '0' or '1'\n    */\n    static std::vector<std::string> split(const std::string& reference_string)\n    {\n        std::vector<std::string> result;\n\n        // special case: empty reference string -> no reference tokens\n        if (reference_string.empty())\n        {\n            return result;\n        }\n\n        // check if nonempty reference string begins with slash\n        if (JSON_UNLIKELY(reference_string[0] != '/'))\n        {\n            JSON_THROW(detail::parse_error::create(107, 1,\n                                                   \"JSON pointer must be empty or begin with '/' - was: '\" +\n                                                   reference_string + \"'\"));\n        }\n\n        // extract the reference tokens:\n        // - slash: position of the last read slash (or end of string)\n        // - start: position after the previous slash\n        for (\n            // search for the first slash after the first character\n            std::size_t slash = reference_string.find_first_of('/', 1),\n            // set the beginning of the first reference token\n            start = 1;\n            // we can stop if start == string::npos+1 = 0\n            start != 0;\n            // set the beginning of the next reference token\n            // (will eventually be 0 if slash == std::string::npos)\n            start = slash + 1,\n            // find next slash\n            slash = reference_string.find_first_of('/', start))\n        {\n            // use the text between the beginning of the reference token\n            // (start) and the last slash (slash).\n            auto reference_token = reference_string.substr(start, slash - start);\n\n            // check reference tokens are properly escaped\n            for (std::size_t pos = reference_token.find_first_of('~');\n                    pos != std::string::npos;\n                    pos = reference_token.find_first_of('~', pos + 1))\n            {\n                assert(reference_token[pos] == '~');\n\n                // ~ must be followed by 0 or 1\n                if (JSON_UNLIKELY(pos == reference_token.size() - 1 or\n                                  (reference_token[pos + 1] != '0' and\n                                   reference_token[pos + 1] != '1')))\n                {\n                    JSON_THROW(detail::parse_error::create(108, 0, \"escape character '~' must be followed with '0' or '1'\"));\n                }\n            }\n\n            // finally, store the reference token\n            unescape(reference_token);\n            result.push_back(reference_token);\n        }\n\n        return result;\n    }\n\n    /*!\n    @brief replace all occurrences of a substring by another string\n\n    @param[in,out] s  the string to manipulate; changed so that all\n                   occurrences of @a f are replaced with @a t\n    @param[in]     f  the substring to replace with @a t\n    @param[in]     t  the string to replace @a f\n\n    @pre The search string @a f must not be empty. **This precondition is\n    enforced with an assertion.**\n\n    @since version 2.0.0\n    */\n    static void replace_substring(std::string& s, const std::string& f,\n                                  const std::string& t)\n    {\n        assert(not f.empty());\n        for (auto pos = s.find(f);                // find first occurrence of f\n                pos != std::string::npos;         // make sure f was found\n                s.replace(pos, f.size(), t),      // replace with t, and\n                pos = s.find(f, pos + t.size()))  // find next occurrence of f\n        {}\n    }\n\n    /// escape \"~\"\" to \"~0\" and \"/\" to \"~1\"\n    static std::string escape(std::string s)\n    {\n        replace_substring(s, \"~\", \"~0\");\n        replace_substring(s, \"/\", \"~1\");\n        return s;\n    }\n\n    /// unescape \"~1\" to tilde and \"~0\" to slash (order is important!)\n    static void unescape(std::string& s)\n    {\n        replace_substring(s, \"~1\", \"/\");\n        replace_substring(s, \"~0\", \"~\");\n    }\n\n    /*!\n    @param[in] reference_string  the reference string to the current value\n    @param[in] value             the value to consider\n    @param[in,out] result        the result object to insert values to\n\n    @note Empty objects or arrays are flattened to `null`.\n    */\n    NLOHMANN_BASIC_JSON_TPL_DECLARATION\n    static void flatten(const std::string& reference_string,\n                        const NLOHMANN_BASIC_JSON_TPL& value,\n                        NLOHMANN_BASIC_JSON_TPL& result);\n\n    /*!\n    @param[in] value  flattened JSON\n\n    @return unflattened JSON\n\n    @throw parse_error.109 if array index is not a number\n    @throw type_error.314  if value is not an object\n    @throw type_error.315  if object values are not primitive\n    @throw type_error.313  if value cannot be unflattened\n    */\n    NLOHMANN_BASIC_JSON_TPL_DECLARATION\n    static NLOHMANN_BASIC_JSON_TPL\n    unflatten(const NLOHMANN_BASIC_JSON_TPL& value);\n\n    friend bool operator==(json_pointer const& lhs,\n                           json_pointer const& rhs) noexcept;\n\n    friend bool operator!=(json_pointer const& lhs,\n                           json_pointer const& rhs) noexcept;\n\n    /// the reference tokens\n    std::vector<std::string> reference_tokens;\n};\n\n/*!\n@brief a class to store JSON values\n\n@tparam ObjectType type for JSON objects (`std::map` by default; will be used\nin @ref object_t)\n@tparam ArrayType type for JSON arrays (`std::vector` by default; will be used\nin @ref array_t)\n@tparam StringType type for JSON strings and object keys (`std::string` by\ndefault; will be used in @ref string_t)\n@tparam BooleanType type for JSON booleans (`bool` by default; will be used\nin @ref boolean_t)\n@tparam NumberIntegerType type for JSON integer numbers (`int64_t` by\ndefault; will be used in @ref number_integer_t)\n@tparam NumberUnsignedType type for JSON unsigned integer numbers (@c\n`uint64_t` by default; will be used in @ref number_unsigned_t)\n@tparam NumberFloatType type for JSON floating-point numbers (`double` by\ndefault; will be used in @ref number_float_t)\n@tparam AllocatorType type of the allocator to use (`std::allocator` by\ndefault)\n@tparam JSONSerializer the serializer to resolve internal calls to `to_json()`\nand `from_json()` (@ref adl_serializer by default)\n\n@requirement The class satisfies the following concept requirements:\n- Basic\n - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):\n   JSON values can be default constructed. The result will be a JSON null\n   value.\n - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):\n   A JSON value can be constructed from an rvalue argument.\n - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):\n   A JSON value can be copy-constructed from an lvalue expression.\n - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):\n   A JSON value van be assigned from an rvalue argument.\n - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):\n   A JSON value can be copy-assigned from an lvalue expression.\n - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):\n   JSON values can be destructed.\n- Layout\n - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):\n   JSON values have\n   [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):\n   All non-static data members are private and standard layout types, the\n   class has no virtual functions or (virtual) base classes.\n- Library-wide\n - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):\n   JSON values can be compared with `==`, see @ref\n   operator==(const_reference,const_reference).\n - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):\n   JSON values can be compared with `<`, see @ref\n   operator<(const_reference,const_reference).\n - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):\n   Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of\n   other compatible types, using unqualified function call @ref swap().\n - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):\n   JSON values can be compared against `std::nullptr_t` objects which are used\n   to model the `null` value.\n- Container\n - [Container](http://en.cppreference.com/w/cpp/concept/Container):\n   JSON values can be used like STL containers and provide iterator access.\n - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);\n   JSON values can be used like STL containers and provide reverse iterator\n   access.\n\n@invariant The member variables @a m_value and @a m_type have the following\nrelationship:\n- If `m_type == value_t::object`, then `m_value.object != nullptr`.\n- If `m_type == value_t::array`, then `m_value.array != nullptr`.\n- If `m_type == value_t::string`, then `m_value.string != nullptr`.\nThe invariants are checked by member function assert_invariant().\n\n@internal\n@note ObjectType trick from http://stackoverflow.com/a/9860911\n@endinternal\n\n@see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange\nFormat](http://rfc7159.net/rfc7159)\n\n@since version 1.0.0\n\n@nosubgrouping\n*/\nNLOHMANN_BASIC_JSON_TPL_DECLARATION\nclass basic_json\n{\n  private:\n    template<detail::value_t> friend struct detail::external_constructor;\n    friend ::nlohmann::json_pointer;\n    friend ::nlohmann::detail::parser<basic_json>;\n    friend ::nlohmann::detail::serializer<basic_json>;\n    template<typename BasicJsonType>\n    friend class ::nlohmann::detail::iter_impl;\n    template<typename BasicJsonType, typename CharType>\n    friend class ::nlohmann::detail::binary_writer;\n    template<typename BasicJsonType>\n    friend class ::nlohmann::detail::binary_reader;\n\n    /// workaround type for MSVC\n    using basic_json_t = NLOHMANN_BASIC_JSON_TPL;\n\n    // convenience aliases for types residing in namespace detail;\n    using lexer = ::nlohmann::detail::lexer<basic_json>;\n    using parser = ::nlohmann::detail::parser<basic_json>;\n\n    using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;\n    template<typename BasicJsonType>\n    using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;\n    template<typename BasicJsonType>\n    using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;\n    template<typename Iterator>\n    using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;\n    template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;\n\n    template<typename CharType>\n    using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;\n\n    using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;\n    template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;\n\n    using serializer = ::nlohmann::detail::serializer<basic_json>;\n\n  public:\n    using value_t = detail::value_t;\n    /// @copydoc nlohmann::json_pointer\n    using json_pointer = ::nlohmann::json_pointer;\n    template<typename T, typename SFINAE>\n    using json_serializer = JSONSerializer<T, SFINAE>;\n    /// helper type for initializer lists of basic_json values\n    using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;\n\n    ////////////////\n    // exceptions //\n    ////////////////\n\n    /// @name exceptions\n    /// Classes to implement user-defined exceptions.\n    /// @{\n\n    /// @copydoc detail::exception\n    using exception = detail::exception;\n    /// @copydoc detail::parse_error\n    using parse_error = detail::parse_error;\n    /// @copydoc detail::invalid_iterator\n    using invalid_iterator = detail::invalid_iterator;\n    /// @copydoc detail::type_error\n    using type_error = detail::type_error;\n    /// @copydoc detail::out_of_range\n    using out_of_range = detail::out_of_range;\n    /// @copydoc detail::other_error\n    using other_error = detail::other_error;\n\n    /// @}\n\n\n    /////////////////////\n    // container types //\n    /////////////////////\n\n    /// @name container types\n    /// The canonic container types to use @ref basic_json like any other STL\n    /// container.\n    /// @{\n\n    /// the type of elements in a basic_json container\n    using value_type = basic_json;\n\n    /// the type of an element reference\n    using reference = value_type&;\n    /// the type of an element const reference\n    using const_reference = const value_type&;\n\n    /// a type to represent differences between iterators\n    using difference_type = std::ptrdiff_t;\n    /// a type to represent container sizes\n    using size_type = std::size_t;\n\n    /// the allocator type\n    using allocator_type = AllocatorType<basic_json>;\n\n    /// the type of an element pointer\n    using pointer = typename std::allocator_traits<allocator_type>::pointer;\n    /// the type of an element const pointer\n    using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;\n\n    /// an iterator for a basic_json container\n    using iterator = iter_impl<basic_json>;\n    /// a const iterator for a basic_json container\n    using const_iterator = iter_impl<const basic_json>;\n    /// a reverse iterator for a basic_json container\n    using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;\n    /// a const reverse iterator for a basic_json container\n    using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;\n\n    /// @}\n\n\n    /*!\n    @brief returns the allocator associated with the container\n    */\n    static allocator_type get_allocator()\n    {\n        return allocator_type();\n    }\n\n    /*!\n    @brief returns version information on the library\n\n    This function returns a JSON object with information about the library,\n    including the version number and information on the platform and compiler.\n\n    @return JSON object holding version information\n    key         | description\n    ----------- | ---------------\n    `compiler`  | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).\n    `copyright` | The copyright line for the library as string.\n    `name`      | The name of the library as string.\n    `platform`  | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.\n    `url`       | The URL of the project as string.\n    `version`   | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).\n\n    @liveexample{The following code shows an example output of the `meta()`\n    function.,meta}\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes to any JSON value.\n\n    @complexity Constant.\n\n    @since 2.1.0\n    */\n    static basic_json meta()\n    {\n        basic_json result;\n\n        result[\"copyright\"] = \"(C) 2013-2017 Niels Lohmann\";\n        result[\"name\"] = \"JSON for Modern C++\";\n        result[\"url\"] = \"https://github.com/nlohmann/json\";\n        result[\"version\"] =\n        {\n            {\"string\", \"3.0.1\"}, {\"major\", 3}, {\"minor\", 0}, {\"patch\", 1}\n        };\n\n#ifdef _WIN32\n        result[\"platform\"] = \"win32\";\n#elif defined __linux__\n        result[\"platform\"] = \"linux\";\n#elif defined __APPLE__\n        result[\"platform\"] = \"apple\";\n#elif defined __unix__\n        result[\"platform\"] = \"unix\";\n#else\n        result[\"platform\"] = \"unknown\";\n#endif\n\n#if defined(__ICC) || defined(__INTEL_COMPILER)\n        result[\"compiler\"] = {{\"family\", \"icc\"}, {\"version\", __INTEL_COMPILER}};\n#elif defined(__clang__)\n        result[\"compiler\"] = {{\"family\", \"clang\"}, {\"version\", __clang_version__}};\n#elif defined(__GNUC__) || defined(__GNUG__)\n        result[\"compiler\"] = {{\"family\", \"gcc\"}, {\"version\", std::to_string(__GNUC__) + \".\" + std::to_string(__GNUC_MINOR__) + \".\" + std::to_string(__GNUC_PATCHLEVEL__)}};\n#elif defined(__HP_cc) || defined(__HP_aCC)\n        result[\"compiler\"] = \"hp\"\n#elif defined(__IBMCPP__)\n        result[\"compiler\"] = {{\"family\", \"ilecpp\"}, {\"version\", __IBMCPP__}};\n#elif defined(_MSC_VER)\n        result[\"compiler\"] = {{\"family\", \"msvc\"}, {\"version\", _MSC_VER}};\n#elif defined(__PGI)\n        result[\"compiler\"] = {{\"family\", \"pgcpp\"}, {\"version\", __PGI}};\n#elif defined(__SUNPRO_CC)\n        result[\"compiler\"] = {{\"family\", \"sunpro\"}, {\"version\", __SUNPRO_CC}};\n#else\n        result[\"compiler\"] = {{\"family\", \"unknown\"}, {\"version\", \"unknown\"}};\n#endif\n\n#ifdef __cplusplus\n        result[\"compiler\"][\"c++\"] = std::to_string(__cplusplus);\n#else\n        result[\"compiler\"][\"c++\"] = \"unknown\";\n#endif\n        return result;\n    }\n\n\n    ///////////////////////////\n    // JSON value data types //\n    ///////////////////////////\n\n    /// @name JSON value data types\n    /// The data types to store a JSON value. These types are derived from\n    /// the template arguments passed to class @ref basic_json.\n    /// @{\n\n#if defined(JSON_HAS_CPP_14)\n    // Use transparent comparator if possible, combined with perfect forwarding\n    // on find() and count() calls prevents unnecessary string construction.\n    using object_comparator_t = std::less<>;\n#else\n    using object_comparator_t = std::less<StringType>;\n#endif\n\n    /*!\n    @brief a type for an object\n\n    [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:\n    > An object is an unordered collection of zero or more name/value pairs,\n    > where a name is a string and a value is a string, number, boolean, null,\n    > object, or array.\n\n    To store objects in C++, a type is defined by the template parameters\n    described below.\n\n    @tparam ObjectType  the container to store objects (e.g., `std::map` or\n    `std::unordered_map`)\n    @tparam StringType the type of the keys or names (e.g., `std::string`).\n    The comparison function `std::less<StringType>` is used to order elements\n    inside the container.\n    @tparam AllocatorType the allocator to use for objects (e.g.,\n    `std::allocator`)\n\n    #### Default type\n\n    With the default values for @a ObjectType (`std::map`), @a StringType\n    (`std::string`), and @a AllocatorType (`std::allocator`), the default\n    value for @a object_t is:\n\n    @code {.cpp}\n    std::map<\n      std::string, // key_type\n      basic_json, // value_type\n      std::less<std::string>, // key_compare\n      std::allocator<std::pair<const std::string, basic_json>> // allocator_type\n    >\n    @endcode\n\n    #### Behavior\n\n    The choice of @a object_t influences the behavior of the JSON class. With\n    the default type, objects have the following behavior:\n\n    - When all names are unique, objects will be interoperable in the sense\n      that all software implementations receiving that object will agree on\n      the name-value mappings.\n    - When the names within an object are not unique, later stored name/value\n      pairs overwrite previously stored name/value pairs, leaving the used\n      names unique. For instance, `{\"key\": 1}` and `{\"key\": 2, \"key\": 1}` will\n      be treated as equal and both stored as `{\"key\": 1}`.\n    - Internally, name/value pairs are stored in lexicographical order of the\n      names. Objects will also be serialized (see @ref dump) in this order.\n      For instance, `{\"b\": 1, \"a\": 2}` and `{\"a\": 2, \"b\": 1}` will be stored\n      and serialized as `{\"a\": 2, \"b\": 1}`.\n    - When comparing objects, the order of the name/value pairs is irrelevant.\n      This makes objects interoperable in the sense that they will not be\n      affected by these differences. For instance, `{\"b\": 1, \"a\": 2}` and\n      `{\"a\": 2, \"b\": 1}` will be treated as equal.\n\n    #### Limits\n\n    [RFC 7159](http://rfc7159.net/rfc7159) specifies:\n    > An implementation may set limits on the maximum depth of nesting.\n\n    In this class, the object's limit of nesting is not explicitly constrained.\n    However, a maximum depth of nesting may be introduced by the compiler or\n    runtime environment. A theoretical limit can be queried by calling the\n    @ref max_size function of a JSON object.\n\n    #### Storage\n\n    Objects are stored as pointers in a @ref basic_json type. That is, for any\n    access to object values, a pointer of type `object_t*` must be\n    dereferenced.\n\n    @sa @ref array_t -- type for an array value\n\n    @since version 1.0.0\n\n    @note The order name/value pairs are added to the object is *not*\n    preserved by the library. Therefore, iterating an object may return\n    name/value pairs in a different order than they were originally stored. In\n    fact, keys will be traversed in alphabetical order as `std::map` with\n    `std::less` is used by default. Please note this behavior conforms to [RFC\n    7159](http://rfc7159.net/rfc7159), because any order implements the\n    specified \"unordered\" nature of JSON objects.\n    */\n    using object_t = ObjectType<StringType,\n          basic_json,\n          object_comparator_t,\n          AllocatorType<std::pair<const StringType,\n          basic_json>>>;\n\n    /*!\n    @brief a type for an array\n\n    [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:\n    > An array is an ordered sequence of zero or more values.\n\n    To store objects in C++, a type is defined by the template parameters\n    explained below.\n\n    @tparam ArrayType  container type to store arrays (e.g., `std::vector` or\n    `std::list`)\n    @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)\n\n    #### Default type\n\n    With the default values for @a ArrayType (`std::vector`) and @a\n    AllocatorType (`std::allocator`), the default value for @a array_t is:\n\n    @code {.cpp}\n    std::vector<\n      basic_json, // value_type\n      std::allocator<basic_json> // allocator_type\n    >\n    @endcode\n\n    #### Limits\n\n    [RFC 7159](http://rfc7159.net/rfc7159) specifies:\n    > An implementation may set limits on the maximum depth of nesting.\n\n    In this class, the array's limit of nesting is not explicitly constrained.\n    However, a maximum depth of nesting may be introduced by the compiler or\n    runtime environment. A theoretical limit can be queried by calling the\n    @ref max_size function of a JSON array.\n\n    #### Storage\n\n    Arrays are stored as pointers in a @ref basic_json type. That is, for any\n    access to array values, a pointer of type `array_t*` must be dereferenced.\n\n    @sa @ref object_t -- type for an object value\n\n    @since version 1.0.0\n    */\n    using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;\n\n    /*!\n    @brief a type for a string\n\n    [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:\n    > A string is a sequence of zero or more Unicode characters.\n\n    To store objects in C++, a type is defined by the template parameter\n    described below. Unicode values are split by the JSON class into\n    byte-sized characters during deserialization.\n\n    @tparam StringType  the container to store strings (e.g., `std::string`).\n    Note this container is used for keys/names in objects, see @ref object_t.\n\n    #### Default type\n\n    With the default values for @a StringType (`std::string`), the default\n    value for @a string_t is:\n\n    @code {.cpp}\n    std::string\n    @endcode\n\n    #### Encoding\n\n    Strings are stored in UTF-8 encoding. Therefore, functions like\n    `std::string::size()` or `std::string::length()` return the number of\n    bytes in the string rather than the number of characters or glyphs.\n\n    #### String comparison\n\n    [RFC 7159](http://rfc7159.net/rfc7159) states:\n    > Software implementations are typically required to test names of object\n    > members for equality. Implementations that transform the textual\n    > representation into sequences of Unicode code units and then perform the\n    > comparison numerically, code unit by code unit, are interoperable in the\n    > sense that implementations will agree in all cases on equality or\n    > inequality of two strings. For example, implementations that compare\n    > strings with escaped characters unconverted may incorrectly find that\n    > `\"a\\\\b\"` and `\"a\\u005Cb\"` are not equal.\n\n    This implementation is interoperable as it does compare strings code unit\n    by code unit.\n\n    #### Storage\n\n    String values are stored as pointers in a @ref basic_json type. That is,\n    for any access to string values, a pointer of type `string_t*` must be\n    dereferenced.\n\n    @since version 1.0.0\n    */\n    using string_t = StringType;\n\n    /*!\n    @brief a type for a boolean\n\n    [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a\n    type which differentiates the two literals `true` and `false`.\n\n    To store objects in C++, a type is defined by the template parameter @a\n    BooleanType which chooses the type to use.\n\n    #### Default type\n\n    With the default values for @a BooleanType (`bool`), the default value for\n    @a boolean_t is:\n\n    @code {.cpp}\n    bool\n    @endcode\n\n    #### Storage\n\n    Boolean values are stored directly inside a @ref basic_json type.\n\n    @since version 1.0.0\n    */\n    using boolean_t = BooleanType;\n\n    /*!\n    @brief a type for a number (integer)\n\n    [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:\n    > The representation of numbers is similar to that used in most\n    > programming languages. A number is represented in base 10 using decimal\n    > digits. It contains an integer component that may be prefixed with an\n    > optional minus sign, which may be followed by a fraction part and/or an\n    > exponent part. Leading zeros are not allowed. (...) Numeric values that\n    > cannot be represented in the grammar below (such as Infinity and NaN)\n    > are not permitted.\n\n    This description includes both integer and floating-point numbers.\n    However, C++ allows more precise storage if it is known whether the number\n    is a signed integer, an unsigned integer or a floating-point number.\n    Therefore, three different types, @ref number_integer_t, @ref\n    number_unsigned_t and @ref number_float_t are used.\n\n    To store integer numbers in C++, a type is defined by the template\n    parameter @a NumberIntegerType which chooses the type to use.\n\n    #### Default type\n\n    With the default values for @a NumberIntegerType (`int64_t`), the default\n    value for @a number_integer_t is:\n\n    @code {.cpp}\n    int64_t\n    @endcode\n\n    #### Default behavior\n\n    - The restrictions about leading zeros is not enforced in C++. Instead,\n      leading zeros in integer literals lead to an interpretation as octal\n      number. Internally, the value will be stored as decimal number. For\n      instance, the C++ integer literal `010` will be serialized to `8`.\n      During deserialization, leading zeros yield an error.\n    - Not-a-number (NaN) values will be serialized to `null`.\n\n    #### Limits\n\n    [RFC 7159](http://rfc7159.net/rfc7159) specifies:\n    > An implementation may set limits on the range and precision of numbers.\n\n    When the default type is used, the maximal integer number that can be\n    stored is `9223372036854775807` (INT64_MAX) and the minimal integer number\n    that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers\n    that are out of range will yield over/underflow when used in a\n    constructor. During deserialization, too large or small integer numbers\n    will be automatically be stored as @ref number_unsigned_t or @ref\n    number_float_t.\n\n    [RFC 7159](http://rfc7159.net/rfc7159) further states:\n    > Note that when such software is used, numbers that are integers and are\n    > in the range \\f$[-2^{53}+1, 2^{53}-1]\\f$ are interoperable in the sense\n    > that implementations will agree exactly on their numeric values.\n\n    As this range is a subrange of the exactly supported range [INT64_MIN,\n    INT64_MAX], this class's integer type is interoperable.\n\n    #### Storage\n\n    Integer number values are stored directly inside a @ref basic_json type.\n\n    @sa @ref number_float_t -- type for number values (floating-point)\n\n    @sa @ref number_unsigned_t -- type for number values (unsigned integer)\n\n    @since version 1.0.0\n    */\n    using number_integer_t = NumberIntegerType;\n\n    /*!\n    @brief a type for a number (unsigned)\n\n    [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:\n    > The representation of numbers is similar to that used in most\n    > programming languages. A number is represented in base 10 using decimal\n    > digits. It contains an integer component that may be prefixed with an\n    > optional minus sign, which may be followed by a fraction part and/or an\n    > exponent part. Leading zeros are not allowed. (...) Numeric values that\n    > cannot be represented in the grammar below (such as Infinity and NaN)\n    > are not permitted.\n\n    This description includes both integer and floating-point numbers.\n    However, C++ allows more precise storage if it is known whether the number\n    is a signed integer, an unsigned integer or a floating-point number.\n    Therefore, three different types, @ref number_integer_t, @ref\n    number_unsigned_t and @ref number_float_t are used.\n\n    To store unsigned integer numbers in C++, a type is defined by the\n    template parameter @a NumberUnsignedType which chooses the type to use.\n\n    #### Default type\n\n    With the default values for @a NumberUnsignedType (`uint64_t`), the\n    default value for @a number_unsigned_t is:\n\n    @code {.cpp}\n    uint64_t\n    @endcode\n\n    #### Default behavior\n\n    - The restrictions about leading zeros is not enforced in C++. Instead,\n      leading zeros in integer literals lead to an interpretation as octal\n      number. Internally, the value will be stored as decimal number. For\n      instance, the C++ integer literal `010` will be serialized to `8`.\n      During deserialization, leading zeros yield an error.\n    - Not-a-number (NaN) values will be serialized to `null`.\n\n    #### Limits\n\n    [RFC 7159](http://rfc7159.net/rfc7159) specifies:\n    > An implementation may set limits on the range and precision of numbers.\n\n    When the default type is used, the maximal integer number that can be\n    stored is `18446744073709551615` (UINT64_MAX) and the minimal integer\n    number that can be stored is `0`. Integer numbers that are out of range\n    will yield over/underflow when used in a constructor. During\n    deserialization, too large or small integer numbers will be automatically\n    be stored as @ref number_integer_t or @ref number_float_t.\n\n    [RFC 7159](http://rfc7159.net/rfc7159) further states:\n    > Note that when such software is used, numbers that are integers and are\n    > in the range \\f$[-2^{53}+1, 2^{53}-1]\\f$ are interoperable in the sense\n    > that implementations will agree exactly on their numeric values.\n\n    As this range is a subrange (when considered in conjunction with the\n    number_integer_t type) of the exactly supported range [0, UINT64_MAX],\n    this class's integer type is interoperable.\n\n    #### Storage\n\n    Integer number values are stored directly inside a @ref basic_json type.\n\n    @sa @ref number_float_t -- type for number values (floating-point)\n    @sa @ref number_integer_t -- type for number values (integer)\n\n    @since version 2.0.0\n    */\n    using number_unsigned_t = NumberUnsignedType;\n\n    /*!\n    @brief a type for a number (floating-point)\n\n    [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:\n    > The representation of numbers is similar to that used in most\n    > programming languages. A number is represented in base 10 using decimal\n    > digits. It contains an integer component that may be prefixed with an\n    > optional minus sign, which may be followed by a fraction part and/or an\n    > exponent part. Leading zeros are not allowed. (...) Numeric values that\n    > cannot be represented in the grammar below (such as Infinity and NaN)\n    > are not permitted.\n\n    This description includes both integer and floating-point numbers.\n    However, C++ allows more precise storage if it is known whether the number\n    is a signed integer, an unsigned integer or a floating-point number.\n    Therefore, three different types, @ref number_integer_t, @ref\n    number_unsigned_t and @ref number_float_t are used.\n\n    To store floating-point numbers in C++, a type is defined by the template\n    parameter @a NumberFloatType which chooses the type to use.\n\n    #### Default type\n\n    With the default values for @a NumberFloatType (`double`), the default\n    value for @a number_float_t is:\n\n    @code {.cpp}\n    double\n    @endcode\n\n    #### Default behavior\n\n    - The restrictions about leading zeros is not enforced in C++. Instead,\n      leading zeros in floating-point literals will be ignored. Internally,\n      the value will be stored as decimal number. For instance, the C++\n      floating-point literal `01.2` will be serialized to `1.2`. During\n      deserialization, leading zeros yield an error.\n    - Not-a-number (NaN) values will be serialized to `null`.\n\n    #### Limits\n\n    [RFC 7159](http://rfc7159.net/rfc7159) states:\n    > This specification allows implementations to set limits on the range and\n    > precision of numbers accepted. Since software that implements IEEE\n    > 754-2008 binary64 (double precision) numbers is generally available and\n    > widely used, good interoperability can be achieved by implementations\n    > that expect no more precision or range than these provide, in the sense\n    > that implementations will approximate JSON numbers within the expected\n    > precision.\n\n    This implementation does exactly follow this approach, as it uses double\n    precision floating-point numbers. Note values smaller than\n    `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`\n    will be stored as NaN internally and be serialized to `null`.\n\n    #### Storage\n\n    Floating-point number values are stored directly inside a @ref basic_json\n    type.\n\n    @sa @ref number_integer_t -- type for number values (integer)\n\n    @sa @ref number_unsigned_t -- type for number values (unsigned integer)\n\n    @since version 1.0.0\n    */\n    using number_float_t = NumberFloatType;\n\n    /// @}\n\n  private:\n\n    /// helper for exception-safe object creation\n    template<typename T, typename... Args>\n    static T* create(Args&& ... args)\n    {\n        AllocatorType<T> alloc;\n        using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;\n\n        auto deleter = [&](T * object)\n        {\n            AllocatorTraits::deallocate(alloc, object, 1);\n        };\n        std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);\n        AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);\n        assert(object != nullptr);\n        return object.release();\n    }\n\n    ////////////////////////\n    // JSON value storage //\n    ////////////////////////\n\n    /*!\n    @brief a JSON value\n\n    The actual storage for a JSON value of the @ref basic_json class. This\n    union combines the different storage types for the JSON value types\n    defined in @ref value_t.\n\n    JSON type | value_t type    | used type\n    --------- | --------------- | ------------------------\n    object    | object          | pointer to @ref object_t\n    array     | array           | pointer to @ref array_t\n    string    | string          | pointer to @ref string_t\n    boolean   | boolean         | @ref boolean_t\n    number    | number_integer  | @ref number_integer_t\n    number    | number_unsigned | @ref number_unsigned_t\n    number    | number_float    | @ref number_float_t\n    null      | null            | *no value is stored*\n\n    @note Variable-length types (objects, arrays, and strings) are stored as\n    pointers. The size of the union should not exceed 64 bits if the default\n    value types are used.\n\n    @since version 1.0.0\n    */\n    union json_value\n    {\n        /// object (stored with pointer to save storage)\n        object_t* object;\n        /// array (stored with pointer to save storage)\n        array_t* array;\n        /// string (stored with pointer to save storage)\n        string_t* string;\n        /// boolean\n        boolean_t boolean;\n        /// number (integer)\n        number_integer_t number_integer;\n        /// number (unsigned integer)\n        number_unsigned_t number_unsigned;\n        /// number (floating-point)\n        number_float_t number_float;\n\n        /// default constructor (for null values)\n        json_value() = default;\n        /// constructor for booleans\n        json_value(boolean_t v) noexcept : boolean(v) {}\n        /// constructor for numbers (integer)\n        json_value(number_integer_t v) noexcept : number_integer(v) {}\n        /// constructor for numbers (unsigned)\n        json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}\n        /// constructor for numbers (floating-point)\n        json_value(number_float_t v) noexcept : number_float(v) {}\n        /// constructor for empty values of a given type\n        json_value(value_t t)\n        {\n            switch (t)\n            {\n                case value_t::object:\n                {\n                    object = create<object_t>();\n                    break;\n                }\n\n                case value_t::array:\n                {\n                    array = create<array_t>();\n                    break;\n                }\n\n                case value_t::string:\n                {\n                    string = create<string_t>(\"\");\n                    break;\n                }\n\n                case value_t::boolean:\n                {\n                    boolean = boolean_t(false);\n                    break;\n                }\n\n                case value_t::number_integer:\n                {\n                    number_integer = number_integer_t(0);\n                    break;\n                }\n\n                case value_t::number_unsigned:\n                {\n                    number_unsigned = number_unsigned_t(0);\n                    break;\n                }\n\n                case value_t::number_float:\n                {\n                    number_float = number_float_t(0.0);\n                    break;\n                }\n\n                case value_t::null:\n                {\n                    object = nullptr;  // silence warning, see #821\n                    break;\n                }\n\n                default:\n                {\n                    object = nullptr;  // silence warning, see #821\n                    if (JSON_UNLIKELY(t == value_t::null))\n                    {\n                        JSON_THROW(other_error::create(500, \"961c151d2e87f2686a955a9be24d316f1362bf21 3.0.1\")); // LCOV_EXCL_LINE\n                    }\n                    break;\n                }\n            }\n        }\n\n        /// constructor for strings\n        json_value(const string_t& value)\n        {\n            string = create<string_t>(value);\n        }\n\n        /// constructor for rvalue strings\n        json_value(string_t&& value)\n        {\n            string = create<string_t>(std::move(value));\n        }\n\n        /// constructor for objects\n        json_value(const object_t& value)\n        {\n            object = create<object_t>(value);\n        }\n\n        /// constructor for rvalue objects\n        json_value(object_t&& value)\n        {\n            object = create<object_t>(std::move(value));\n        }\n\n        /// constructor for arrays\n        json_value(const array_t& value)\n        {\n            array = create<array_t>(value);\n        }\n\n        /// constructor for rvalue arrays\n        json_value(array_t&& value)\n        {\n            array = create<array_t>(std::move(value));\n        }\n\n        void destroy(value_t t)\n        {\n            switch (t)\n            {\n                case value_t::object:\n                {\n                    AllocatorType<object_t> alloc;\n                    std::allocator_traits<decltype(alloc)>::destroy(alloc, object);\n                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);\n                    break;\n                }\n\n                case value_t::array:\n                {\n                    AllocatorType<array_t> alloc;\n                    std::allocator_traits<decltype(alloc)>::destroy(alloc, array);\n                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);\n                    break;\n                }\n\n                case value_t::string:\n                {\n                    AllocatorType<string_t> alloc;\n                    std::allocator_traits<decltype(alloc)>::destroy(alloc, string);\n                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);\n                    break;\n                }\n\n                default:\n                {\n                    break;\n                }\n            }\n        }\n    };\n\n    /*!\n    @brief checks the class invariants\n\n    This function asserts the class invariants. It needs to be called at the\n    end of every constructor to make sure that created objects respect the\n    invariant. Furthermore, it has to be called each time the type of a JSON\n    value is changed, because the invariant expresses a relationship between\n    @a m_type and @a m_value.\n    */\n    void assert_invariant() const\n    {\n        assert(m_type != value_t::object or m_value.object != nullptr);\n        assert(m_type != value_t::array or m_value.array != nullptr);\n        assert(m_type != value_t::string or m_value.string != nullptr);\n    }\n\n  public:\n    //////////////////////////\n    // JSON parser callback //\n    //////////////////////////\n\n    /*!\n    @brief parser event types\n\n    The parser callback distinguishes the following events:\n    - `object_start`: the parser read `{` and started to process a JSON object\n    - `key`: the parser read a key of a value in an object\n    - `object_end`: the parser read `}` and finished processing a JSON object\n    - `array_start`: the parser read `[` and started to process a JSON array\n    - `array_end`: the parser read `]` and finished processing a JSON array\n    - `value`: the parser finished reading a JSON value\n\n    @image html callback_events.png \"Example when certain parse events are triggered\"\n\n    @sa @ref parser_callback_t for more information and examples\n    */\n    using parse_event_t = typename parser::parse_event_t;\n\n    /*!\n    @brief per-element parser callback type\n\n    With a parser callback function, the result of parsing a JSON text can be\n    influenced. When passed to @ref parse, it is called on certain events\n    (passed as @ref parse_event_t via parameter @a event) with a set recursion\n    depth @a depth and context JSON value @a parsed. The return value of the\n    callback function is a boolean indicating whether the element that emitted\n    the callback shall be kept or not.\n\n    We distinguish six scenarios (determined by the event type) in which the\n    callback function can be called. The following table describes the values\n    of the parameters @a depth, @a event, and @a parsed.\n\n    parameter @a event | description | parameter @a depth | parameter @a parsed\n    ------------------ | ----------- | ------------------ | -------------------\n    parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded\n    parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key\n    parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object\n    parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded\n    parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array\n    parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value\n\n    @image html callback_events.png \"Example when certain parse events are triggered\"\n\n    Discarding a value (i.e., returning `false`) has different effects\n    depending on the context in which function was called:\n\n    - Discarded values in structured types are skipped. That is, the parser\n      will behave as if the discarded value was never read.\n    - In case a value outside a structured type is skipped, it is replaced\n      with `null`. This case happens if the top-level element is skipped.\n\n    @param[in] depth  the depth of the recursion during parsing\n\n    @param[in] event  an event of type parse_event_t indicating the context in\n    the callback function has been called\n\n    @param[in,out] parsed  the current intermediate parse result; note that\n    writing to this value has no effect for parse_event_t::key events\n\n    @return Whether the JSON value which called the function during parsing\n    should be kept (`true`) or not (`false`). In the latter case, it is either\n    skipped completely or replaced by an empty discarded object.\n\n    @sa @ref parse for examples\n\n    @since version 1.0.0\n    */\n    using parser_callback_t = typename parser::parser_callback_t;\n\n\n    //////////////////\n    // constructors //\n    //////////////////\n\n    /// @name constructors and destructors\n    /// Constructors of class @ref basic_json, copy/move constructor, copy\n    /// assignment, static functions creating objects, and the destructor.\n    /// @{\n\n    /*!\n    @brief create an empty value with a given type\n\n    Create an empty JSON value with a given type. The value will be default\n    initialized with an empty value which depends on the type:\n\n    Value type  | initial value\n    ----------- | -------------\n    null        | `null`\n    boolean     | `false`\n    string      | `\"\"`\n    number      | `0`\n    object      | `{}`\n    array       | `[]`\n\n    @param[in] v  the type of the value to create\n\n    @complexity Constant.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes to any JSON value.\n\n    @liveexample{The following code shows the constructor for different @ref\n    value_t values,basic_json__value_t}\n\n    @sa @ref clear() -- restores the postcondition of this constructor\n\n    @since version 1.0.0\n    */\n    basic_json(const value_t v)\n        : m_type(v), m_value(v)\n    {\n        assert_invariant();\n    }\n\n    /*!\n    @brief create a null object\n\n    Create a `null` JSON value. It either takes a null pointer as parameter\n    (explicitly creating `null`) or no parameter (implicitly creating `null`).\n    The passed null pointer itself is not read -- it is only used to choose\n    the right constructor.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this constructor never throws\n    exceptions.\n\n    @liveexample{The following code shows the constructor with and without a\n    null pointer parameter.,basic_json__nullptr_t}\n\n    @since version 1.0.0\n    */\n    basic_json(std::nullptr_t = nullptr) noexcept\n        : basic_json(value_t::null)\n    {\n        assert_invariant();\n    }\n\n    /*!\n    @brief create a JSON value\n\n    This is a \"catch all\" constructor for all compatible JSON types; that is,\n    types for which a `to_json()` method exists. The constructor forwards the\n    parameter @a val to that method (to `json_serializer<U>::to_json` method\n    with `U = uncvref_t<CompatibleType>`, to be exact).\n\n    Template type @a CompatibleType includes, but is not limited to, the\n    following types:\n    - **arrays**: @ref array_t and all kinds of compatible containers such as\n      `std::vector`, `std::deque`, `std::list`, `std::forward_list`,\n      `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,\n      `std::multiset`, and `std::unordered_multiset` with a `value_type` from\n      which a @ref basic_json value can be constructed.\n    - **objects**: @ref object_t and all kinds of compatible associative\n      containers such as `std::map`, `std::unordered_map`, `std::multimap`,\n      and `std::unordered_multimap` with a `key_type` compatible to\n      @ref string_t and a `value_type` from which a @ref basic_json value can\n      be constructed.\n    - **strings**: @ref string_t, string literals, and all compatible string\n      containers can be used.\n    - **numbers**: @ref number_integer_t, @ref number_unsigned_t,\n      @ref number_float_t, and all convertible number types such as `int`,\n      `size_t`, `int64_t`, `float` or `double` can be used.\n    - **boolean**: @ref boolean_t / `bool` can be used.\n\n    See the examples below.\n\n    @tparam CompatibleType a type such that:\n    - @a CompatibleType is not derived from `std::istream`,\n    - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move\n         constructors),\n    - @a CompatibleType is not a @ref basic_json nested type (e.g.,\n         @ref json_pointer, @ref iterator, etc ...)\n    - @ref @ref json_serializer<U> has a\n         `to_json(basic_json_t&, CompatibleType&&)` method\n\n    @tparam U = `uncvref_t<CompatibleType>`\n\n    @param[in] val the value to be forwarded to the respective constructor\n\n    @complexity Usually linear in the size of the passed @a val, also\n                depending on the implementation of the called `to_json()`\n                method.\n\n    @exceptionsafety Depends on the called constructor. For types directly\n    supported by the library (i.e., all types for which no `to_json()` function\n    was provided), strong guarantee holds: if an exception is thrown, there are\n    no changes to any JSON value.\n\n    @liveexample{The following code shows the constructor with several\n    compatible types.,basic_json__CompatibleType}\n\n    @since version 2.1.0\n    */\n    template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>,\n             detail::enable_if_t<not std::is_base_of<std::istream, U>::value and\n                                 not std::is_same<U, basic_json_t>::value and\n                                 not detail::is_basic_json_nested_type<\n                                     basic_json_t, U>::value and\n                                 detail::has_to_json<basic_json, U>::value,\n                                 int> = 0>\n    basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json(\n                std::declval<basic_json_t&>(), std::forward<CompatibleType>(val))))\n    {\n        JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));\n        assert_invariant();\n    }\n\n    /*!\n    @brief create a container (array or object) from an initializer list\n\n    Creates a JSON value of type array or object from the passed initializer\n    list @a init. In case @a type_deduction is `true` (default), the type of\n    the JSON value to be created is deducted from the initializer list @a init\n    according to the following rules:\n\n    1. If the list is empty, an empty JSON object value `{}` is created.\n    2. If the list consists of pairs whose first element is a string, a JSON\n       object value is created where the first elements of the pairs are\n       treated as keys and the second elements are as values.\n    3. In all other cases, an array is created.\n\n    The rules aim to create the best fit between a C++ initializer list and\n    JSON values. The rationale is as follows:\n\n    1. The empty initializer list is written as `{}` which is exactly an empty\n       JSON object.\n    2. C++ has no way of describing mapped types other than to list a list of\n       pairs. As JSON requires that keys must be of type string, rule 2 is the\n       weakest constraint one can pose on initializer lists to interpret them\n       as an object.\n    3. In all other cases, the initializer list could not be interpreted as\n       JSON object type, so interpreting it as JSON array type is safe.\n\n    With the rules described above, the following JSON values cannot be\n    expressed by an initializer list:\n\n    - the empty array (`[]`): use @ref array(initializer_list_t)\n      with an empty initializer list in this case\n    - arrays whose elements satisfy rule 2: use @ref\n      array(initializer_list_t) with the same initializer list\n      in this case\n\n    @note When used without parentheses around an empty initializer list, @ref\n    basic_json() is called instead of this function, yielding the JSON null\n    value.\n\n    @param[in] init  initializer list with JSON values\n\n    @param[in] type_deduction internal parameter; when set to `true`, the type\n    of the JSON value is deducted from the initializer list @a init; when set\n    to `false`, the type provided via @a manual_type is forced. This mode is\n    used by the functions @ref array(initializer_list_t) and\n    @ref object(initializer_list_t).\n\n    @param[in] manual_type internal parameter; when @a type_deduction is set\n    to `false`, the created JSON value will use the provided type (only @ref\n    value_t::array and @ref value_t::object are valid); when @a type_deduction\n    is set to `true`, this parameter has no effect\n\n    @throw type_error.301 if @a type_deduction is `false`, @a manual_type is\n    `value_t::object`, but @a init contains an element which is not a pair\n    whose first element is a string. In this case, the constructor could not\n    create an object. If @a type_deduction would have be `true`, an array\n    would have been created. See @ref object(initializer_list_t)\n    for an example.\n\n    @complexity Linear in the size of the initializer list @a init.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes to any JSON value.\n\n    @liveexample{The example below shows how JSON values are created from\n    initializer lists.,basic_json__list_init_t}\n\n    @sa @ref array(initializer_list_t) -- create a JSON array\n    value from an initializer list\n    @sa @ref object(initializer_list_t) -- create a JSON object\n    value from an initializer list\n\n    @since version 1.0.0\n    */\n    basic_json(initializer_list_t init,\n               bool type_deduction = true,\n               value_t manual_type = value_t::array)\n    {\n        // check if each element is an array with two elements whose first\n        // element is a string\n        bool is_an_object = std::all_of(init.begin(), init.end(),\n                                        [](const detail::json_ref<basic_json>& element_ref)\n        {\n            return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string());\n        });\n\n        // adjust type if type deduction is not wanted\n        if (not type_deduction)\n        {\n            // if array is wanted, do not create an object though possible\n            if (manual_type == value_t::array)\n            {\n                is_an_object = false;\n            }\n\n            // if object is wanted but impossible, throw an exception\n            if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object))\n            {\n                JSON_THROW(type_error::create(301, \"cannot create object from initializer list\"));\n            }\n        }\n\n        if (is_an_object)\n        {\n            // the initializer list is a list of pairs -> create object\n            m_type = value_t::object;\n            m_value = value_t::object;\n\n            std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)\n            {\n                auto element = element_ref.moved_or_copied();\n                m_value.object->emplace(\n                    std::move(*((*element.m_value.array)[0].m_value.string)),\n                    std::move((*element.m_value.array)[1]));\n            });\n        }\n        else\n        {\n            // the initializer list describes an array -> create array\n            m_type = value_t::array;\n            m_value.array = create<array_t>(init.begin(), init.end());\n        }\n\n        assert_invariant();\n    }\n\n    /*!\n    @brief explicitly create an array from an initializer list\n\n    Creates a JSON array value from a given initializer list. That is, given a\n    list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the\n    initializer list is empty, the empty array `[]` is created.\n\n    @note This function is only needed to express two edge cases that cannot\n    be realized with the initializer list constructor (@ref\n    basic_json(initializer_list_t, bool, value_t)). These cases\n    are:\n    1. creating an array whose elements are all pairs whose first element is a\n    string -- in this case, the initializer list constructor would create an\n    object, taking the first elements as keys\n    2. creating an empty array -- passing the empty initializer list to the\n    initializer list constructor yields an empty object\n\n    @param[in] init  initializer list with JSON values to create an array from\n    (optional)\n\n    @return JSON array value\n\n    @complexity Linear in the size of @a init.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes to any JSON value.\n\n    @liveexample{The following code shows an example for the `array`\n    function.,array}\n\n    @sa @ref basic_json(initializer_list_t, bool, value_t) --\n    create a JSON value from an initializer list\n    @sa @ref object(initializer_list_t) -- create a JSON object\n    value from an initializer list\n\n    @since version 1.0.0\n    */\n    static basic_json array(initializer_list_t init = {})\n    {\n        return basic_json(init, false, value_t::array);\n    }\n\n    /*!\n    @brief explicitly create an object from an initializer list\n\n    Creates a JSON object value from a given initializer list. The initializer\n    lists elements must be pairs, and their first elements must be strings. If\n    the initializer list is empty, the empty object `{}` is created.\n\n    @note This function is only added for symmetry reasons. In contrast to the\n    related function @ref array(initializer_list_t), there are\n    no cases which can only be expressed by this function. That is, any\n    initializer list @a init can also be passed to the initializer list\n    constructor @ref basic_json(initializer_list_t, bool, value_t).\n\n    @param[in] init  initializer list to create an object from (optional)\n\n    @return JSON object value\n\n    @throw type_error.301 if @a init is not a list of pairs whose first\n    elements are strings. In this case, no object can be created. When such a\n    value is passed to @ref basic_json(initializer_list_t, bool, value_t),\n    an array would have been created from the passed initializer list @a init.\n    See example below.\n\n    @complexity Linear in the size of @a init.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes to any JSON value.\n\n    @liveexample{The following code shows an example for the `object`\n    function.,object}\n\n    @sa @ref basic_json(initializer_list_t, bool, value_t) --\n    create a JSON value from an initializer list\n    @sa @ref array(initializer_list_t) -- create a JSON array\n    value from an initializer list\n\n    @since version 1.0.0\n    */\n    static basic_json object(initializer_list_t init = {})\n    {\n        return basic_json(init, false, value_t::object);\n    }\n\n    /*!\n    @brief construct an array with count copies of given value\n\n    Constructs a JSON array value by creating @a cnt copies of a passed value.\n    In case @a cnt is `0`, an empty array is created.\n\n    @param[in] cnt  the number of JSON copies of @a val to create\n    @param[in] val  the JSON value to copy\n\n    @post `std::distance(begin(),end()) == cnt` holds.\n\n    @complexity Linear in @a cnt.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes to any JSON value.\n\n    @liveexample{The following code shows examples for the @ref\n    basic_json(size_type\\, const basic_json&)\n    constructor.,basic_json__size_type_basic_json}\n\n    @since version 1.0.0\n    */\n    basic_json(size_type cnt, const basic_json& val)\n        : m_type(value_t::array)\n    {\n        m_value.array = create<array_t>(cnt, val);\n        assert_invariant();\n    }\n\n    /*!\n    @brief construct a JSON container given an iterator range\n\n    Constructs the JSON value with the contents of the range `[first, last)`.\n    The semantics depends on the different types a JSON value can have:\n    - In case of a null type, invalid_iterator.206 is thrown.\n    - In case of other primitive types (number, boolean, or string), @a first\n      must be `begin()` and @a last must be `end()`. In this case, the value is\n      copied. Otherwise, invalid_iterator.204 is thrown.\n    - In case of structured types (array, object), the constructor behaves as\n      similar versions for `std::vector` or `std::map`; that is, a JSON array\n      or object is constructed from the values in the range.\n\n    @tparam InputIT an input iterator type (@ref iterator or @ref\n    const_iterator)\n\n    @param[in] first begin of the range to copy from (included)\n    @param[in] last end of the range to copy from (excluded)\n\n    @pre Iterators @a first and @a last must be initialized. **This\n         precondition is enforced with an assertion (see warning).** If\n         assertions are switched off, a violation of this precondition yields\n         undefined behavior.\n\n    @pre Range `[first, last)` is valid. Usually, this precondition cannot be\n         checked efficiently. Only certain edge cases are detected; see the\n         description of the exceptions below. A violation of this precondition\n         yields undefined behavior.\n\n    @warning A precondition is enforced with a runtime assertion that will\n             result in calling `std::abort` if this precondition is not met.\n             Assertions can be disabled by defining `NDEBUG` at compile time.\n             See http://en.cppreference.com/w/cpp/error/assert for more\n             information.\n\n    @throw invalid_iterator.201 if iterators @a first and @a last are not\n    compatible (i.e., do not belong to the same JSON value). In this case,\n    the range `[first, last)` is undefined.\n    @throw invalid_iterator.204 if iterators @a first and @a last belong to a\n    primitive type (number, boolean, or string), but @a first does not point\n    to the first element any more. In this case, the range `[first, last)` is\n    undefined. See example code below.\n    @throw invalid_iterator.206 if iterators @a first and @a last belong to a\n    null value. In this case, the range `[first, last)` is undefined.\n\n    @complexity Linear in distance between @a first and @a last.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes to any JSON value.\n\n    @liveexample{The example below shows several ways to create JSON values by\n    specifying a subrange with iterators.,basic_json__InputIt_InputIt}\n\n    @since version 1.0.0\n    */\n    template<class InputIT, typename std::enable_if<\n                 std::is_same<InputIT, typename basic_json_t::iterator>::value or\n                 std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>\n    basic_json(InputIT first, InputIT last)\n    {\n        assert(first.m_object != nullptr);\n        assert(last.m_object != nullptr);\n\n        // make sure iterator fits the current value\n        if (JSON_UNLIKELY(first.m_object != last.m_object))\n        {\n            JSON_THROW(invalid_iterator::create(201, \"iterators are not compatible\"));\n        }\n\n        // copy type from first iterator\n        m_type = first.m_object->m_type;\n\n        // check if iterator range is complete for primitive values\n        switch (m_type)\n        {\n            case value_t::boolean:\n            case value_t::number_float:\n            case value_t::number_integer:\n            case value_t::number_unsigned:\n            case value_t::string:\n            {\n                if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin()\n                                  or not last.m_it.primitive_iterator.is_end()))\n                {\n                    JSON_THROW(invalid_iterator::create(204, \"iterators out of range\"));\n                }\n                break;\n            }\n\n            default:\n                break;\n        }\n\n        switch (m_type)\n        {\n            case value_t::number_integer:\n            {\n                m_value.number_integer = first.m_object->m_value.number_integer;\n                break;\n            }\n\n            case value_t::number_unsigned:\n            {\n                m_value.number_unsigned = first.m_object->m_value.number_unsigned;\n                break;\n            }\n\n            case value_t::number_float:\n            {\n                m_value.number_float = first.m_object->m_value.number_float;\n                break;\n            }\n\n            case value_t::boolean:\n            {\n                m_value.boolean = first.m_object->m_value.boolean;\n                break;\n            }\n\n            case value_t::string:\n            {\n                m_value = *first.m_object->m_value.string;\n                break;\n            }\n\n            case value_t::object:\n            {\n                m_value.object = create<object_t>(first.m_it.object_iterator,\n                                                  last.m_it.object_iterator);\n                break;\n            }\n\n            case value_t::array:\n            {\n                m_value.array = create<array_t>(first.m_it.array_iterator,\n                                                last.m_it.array_iterator);\n                break;\n            }\n\n            default:\n                JSON_THROW(invalid_iterator::create(206, \"cannot construct with iterators from \" +\n                                                    std::string(first.m_object->type_name())));\n        }\n\n        assert_invariant();\n    }\n\n\n    ///////////////////////////////////////\n    // other constructors and destructor //\n    ///////////////////////////////////////\n\n    /// @private\n    basic_json(const detail::json_ref<basic_json>& ref)\n        : basic_json(ref.moved_or_copied())\n    {}\n\n    /*!\n    @brief copy constructor\n\n    Creates a copy of a given JSON value.\n\n    @param[in] other  the JSON value to copy\n\n    @post `*this == other`\n\n    @complexity Linear in the size of @a other.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes to any JSON value.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is linear.\n    - As postcondition, it holds: `other == basic_json(other)`.\n\n    @liveexample{The following code shows an example for the copy\n    constructor.,basic_json__basic_json}\n\n    @since version 1.0.0\n    */\n    basic_json(const basic_json& other)\n        : m_type(other.m_type)\n    {\n        // check of passed value is valid\n        other.assert_invariant();\n\n        switch (m_type)\n        {\n            case value_t::object:\n            {\n                m_value = *other.m_value.object;\n                break;\n            }\n\n            case value_t::array:\n            {\n                m_value = *other.m_value.array;\n                break;\n            }\n\n            case value_t::string:\n            {\n                m_value = *other.m_value.string;\n                break;\n            }\n\n            case value_t::boolean:\n            {\n                m_value = other.m_value.boolean;\n                break;\n            }\n\n            case value_t::number_integer:\n            {\n                m_value = other.m_value.number_integer;\n                break;\n            }\n\n            case value_t::number_unsigned:\n            {\n                m_value = other.m_value.number_unsigned;\n                break;\n            }\n\n            case value_t::number_float:\n            {\n                m_value = other.m_value.number_float;\n                break;\n            }\n\n            default:\n                break;\n        }\n\n        assert_invariant();\n    }\n\n    /*!\n    @brief move constructor\n\n    Move constructor. Constructs a JSON value with the contents of the given\n    value @a other using move semantics. It \"steals\" the resources from @a\n    other and leaves it as JSON null value.\n\n    @param[in,out] other  value to move to this object\n\n    @post `*this` has the same value as @a other before the call.\n    @post @a other is a JSON null value.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this constructor never throws\n    exceptions.\n\n    @requirement This function helps `basic_json` satisfying the\n    [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible)\n    requirements.\n\n    @liveexample{The code below shows the move constructor explicitly called\n    via std::move.,basic_json__moveconstructor}\n\n    @since version 1.0.0\n    */\n    basic_json(basic_json&& other) noexcept\n        : m_type(std::move(other.m_type)),\n          m_value(std::move(other.m_value))\n    {\n        // check that passed value is valid\n        other.assert_invariant();\n\n        // invalidate payload\n        other.m_type = value_t::null;\n        other.m_value = {};\n\n        assert_invariant();\n    }\n\n    /*!\n    @brief copy assignment\n\n    Copy assignment operator. Copies a JSON value via the \"copy and swap\"\n    strategy: It is expressed in terms of the copy constructor, destructor,\n    and the `swap()` member function.\n\n    @param[in] other  value to copy from\n\n    @complexity Linear.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is linear.\n\n    @liveexample{The code below shows and example for the copy assignment. It\n    creates a copy of value `a` which is then swapped with `b`. Finally\\, the\n    copy of `a` (which is the null value after the swap) is\n    destroyed.,basic_json__copyassignment}\n\n    @since version 1.0.0\n    */\n    reference& operator=(basic_json other) noexcept (\n        std::is_nothrow_move_constructible<value_t>::value and\n        std::is_nothrow_move_assignable<value_t>::value and\n        std::is_nothrow_move_constructible<json_value>::value and\n        std::is_nothrow_move_assignable<json_value>::value\n    )\n    {\n        // check that passed value is valid\n        other.assert_invariant();\n\n        using std::swap;\n        swap(m_type, other.m_type);\n        swap(m_value, other.m_value);\n\n        assert_invariant();\n        return *this;\n    }\n\n    /*!\n    @brief destructor\n\n    Destroys the JSON value and frees all allocated memory.\n\n    @complexity Linear.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is linear.\n    - All stored elements are destroyed and all memory is freed.\n\n    @since version 1.0.0\n    */\n    ~basic_json()\n    {\n        assert_invariant();\n        m_value.destroy(m_type);\n    }\n\n    /// @}\n\n  public:\n    ///////////////////////\n    // object inspection //\n    ///////////////////////\n\n    /// @name object inspection\n    /// Functions to inspect the type of a JSON value.\n    /// @{\n\n    /*!\n    @brief serialization\n\n    Serialization function for JSON values. The function tries to mimic\n    Python's `json.dumps()` function, and currently supports its @a indent\n    and @a ensure_ascii parameters.\n\n    @param[in] indent If indent is nonnegative, then array elements and object\n    members will be pretty-printed with that indent level. An indent level of\n    `0` will only insert newlines. `-1` (the default) selects the most compact\n    representation.\n    @param[in] indent_char The character to use for indentation if @a indent is\n    greater than `0`. The default is ` ` (space).\n    @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters\n    in the output are escaped with `\\uXXXX` sequences, and the result consists\n    of ASCII characters only.\n\n    @return string containing the serialization of the JSON value\n\n    @throw type_error.316 if a string stored inside the JSON value is not\n                          UTF-8 encoded\n\n    @complexity Linear.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes in the JSON value.\n\n    @liveexample{The following example shows the effect of different @a indent\\,\n    @a indent_char\\, and @a ensure_ascii parameters to the result of the\n    serialization.,dump}\n\n    @see https://docs.python.org/2/library/json.html#json.dump\n\n    @since version 1.0.0; indentation character @a indent_char, option\n           @a ensure_ascii and exceptions added in version 3.0.0\n    */\n    string_t dump(const int indent = -1, const char indent_char = ' ',\n                  const bool ensure_ascii = false) const\n    {\n        string_t result;\n        serializer s(detail::output_adapter<char>(result), indent_char);\n\n        if (indent >= 0)\n        {\n            s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));\n        }\n        else\n        {\n            s.dump(*this, false, ensure_ascii, 0);\n        }\n\n        return result;\n    }\n\n    /*!\n    @brief return the type of the JSON value (explicit)\n\n    Return the type of the JSON value as a value from the @ref value_t\n    enumeration.\n\n    @return the type of the JSON value\n            Value type                | return value\n            ------------------------- | -------------------------\n            null                      | value_t::null\n            boolean                   | value_t::boolean\n            string                    | value_t::string\n            number (integer)          | value_t::number_integer\n            number (unsigned integer) | value_t::number_unsigned\n            number (floating-point)   | value_t::number_float\n            object                    | value_t::object\n            array                     | value_t::array\n            discarded                 | value_t::discarded\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `type()` for all JSON\n    types.,type}\n\n    @sa @ref operator value_t() -- return the type of the JSON value (implicit)\n    @sa @ref type_name() -- return the type as string\n\n    @since version 1.0.0\n    */\n    constexpr value_t type() const noexcept\n    {\n        return m_type;\n    }\n\n    /*!\n    @brief return whether type is primitive\n\n    This function returns true if and only if the JSON type is primitive\n    (string, number, boolean, or null).\n\n    @return `true` if type is primitive (string, number, boolean, or null),\n    `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_primitive()` for all JSON\n    types.,is_primitive}\n\n    @sa @ref is_structured() -- returns whether JSON value is structured\n    @sa @ref is_null() -- returns whether JSON value is `null`\n    @sa @ref is_string() -- returns whether JSON value is a string\n    @sa @ref is_boolean() -- returns whether JSON value is a boolean\n    @sa @ref is_number() -- returns whether JSON value is a number\n\n    @since version 1.0.0\n    */\n    constexpr bool is_primitive() const noexcept\n    {\n        return is_null() or is_string() or is_boolean() or is_number();\n    }\n\n    /*!\n    @brief return whether type is structured\n\n    This function returns true if and only if the JSON type is structured\n    (array or object).\n\n    @return `true` if type is structured (array or object), `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_structured()` for all JSON\n    types.,is_structured}\n\n    @sa @ref is_primitive() -- returns whether value is primitive\n    @sa @ref is_array() -- returns whether value is an array\n    @sa @ref is_object() -- returns whether value is an object\n\n    @since version 1.0.0\n    */\n    constexpr bool is_structured() const noexcept\n    {\n        return is_array() or is_object();\n    }\n\n    /*!\n    @brief return whether value is null\n\n    This function returns true if and only if the JSON value is null.\n\n    @return `true` if type is null, `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_null()` for all JSON\n    types.,is_null}\n\n    @since version 1.0.0\n    */\n    constexpr bool is_null() const noexcept\n    {\n        return (m_type == value_t::null);\n    }\n\n    /*!\n    @brief return whether value is a boolean\n\n    This function returns true if and only if the JSON value is a boolean.\n\n    @return `true` if type is boolean, `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_boolean()` for all JSON\n    types.,is_boolean}\n\n    @since version 1.0.0\n    */\n    constexpr bool is_boolean() const noexcept\n    {\n        return (m_type == value_t::boolean);\n    }\n\n    /*!\n    @brief return whether value is a number\n\n    This function returns true if and only if the JSON value is a number. This\n    includes both integer (signed and unsigned) and floating-point values.\n\n    @return `true` if type is number (regardless whether integer, unsigned\n    integer or floating-type), `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_number()` for all JSON\n    types.,is_number}\n\n    @sa @ref is_number_integer() -- check if value is an integer or unsigned\n    integer number\n    @sa @ref is_number_unsigned() -- check if value is an unsigned integer\n    number\n    @sa @ref is_number_float() -- check if value is a floating-point number\n\n    @since version 1.0.0\n    */\n    constexpr bool is_number() const noexcept\n    {\n        return is_number_integer() or is_number_float();\n    }\n\n    /*!\n    @brief return whether value is an integer number\n\n    This function returns true if and only if the JSON value is a signed or\n    unsigned integer number. This excludes floating-point values.\n\n    @return `true` if type is an integer or unsigned integer number, `false`\n    otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_number_integer()` for all\n    JSON types.,is_number_integer}\n\n    @sa @ref is_number() -- check if value is a number\n    @sa @ref is_number_unsigned() -- check if value is an unsigned integer\n    number\n    @sa @ref is_number_float() -- check if value is a floating-point number\n\n    @since version 1.0.0\n    */\n    constexpr bool is_number_integer() const noexcept\n    {\n        return (m_type == value_t::number_integer or m_type == value_t::number_unsigned);\n    }\n\n    /*!\n    @brief return whether value is an unsigned integer number\n\n    This function returns true if and only if the JSON value is an unsigned\n    integer number. This excludes floating-point and signed integer values.\n\n    @return `true` if type is an unsigned integer number, `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_number_unsigned()` for all\n    JSON types.,is_number_unsigned}\n\n    @sa @ref is_number() -- check if value is a number\n    @sa @ref is_number_integer() -- check if value is an integer or unsigned\n    integer number\n    @sa @ref is_number_float() -- check if value is a floating-point number\n\n    @since version 2.0.0\n    */\n    constexpr bool is_number_unsigned() const noexcept\n    {\n        return (m_type == value_t::number_unsigned);\n    }\n\n    /*!\n    @brief return whether value is a floating-point number\n\n    This function returns true if and only if the JSON value is a\n    floating-point number. This excludes signed and unsigned integer values.\n\n    @return `true` if type is a floating-point number, `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_number_float()` for all\n    JSON types.,is_number_float}\n\n    @sa @ref is_number() -- check if value is number\n    @sa @ref is_number_integer() -- check if value is an integer number\n    @sa @ref is_number_unsigned() -- check if value is an unsigned integer\n    number\n\n    @since version 1.0.0\n    */\n    constexpr bool is_number_float() const noexcept\n    {\n        return (m_type == value_t::number_float);\n    }\n\n    /*!\n    @brief return whether value is an object\n\n    This function returns true if and only if the JSON value is an object.\n\n    @return `true` if type is object, `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_object()` for all JSON\n    types.,is_object}\n\n    @since version 1.0.0\n    */\n    constexpr bool is_object() const noexcept\n    {\n        return (m_type == value_t::object);\n    }\n\n    /*!\n    @brief return whether value is an array\n\n    This function returns true if and only if the JSON value is an array.\n\n    @return `true` if type is array, `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_array()` for all JSON\n    types.,is_array}\n\n    @since version 1.0.0\n    */\n    constexpr bool is_array() const noexcept\n    {\n        return (m_type == value_t::array);\n    }\n\n    /*!\n    @brief return whether value is a string\n\n    This function returns true if and only if the JSON value is a string.\n\n    @return `true` if type is string, `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_string()` for all JSON\n    types.,is_string}\n\n    @since version 1.0.0\n    */\n    constexpr bool is_string() const noexcept\n    {\n        return (m_type == value_t::string);\n    }\n\n    /*!\n    @brief return whether value is discarded\n\n    This function returns true if and only if the JSON value was discarded\n    during parsing with a callback function (see @ref parser_callback_t).\n\n    @note This function will always be `false` for JSON values after parsing.\n    That is, discarded values can only occur during parsing, but will be\n    removed when inside a structured value or replaced by null in other cases.\n\n    @return `true` if type is discarded, `false` otherwise.\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies `is_discarded()` for all JSON\n    types.,is_discarded}\n\n    @since version 1.0.0\n    */\n    constexpr bool is_discarded() const noexcept\n    {\n        return (m_type == value_t::discarded);\n    }\n\n    /*!\n    @brief return the type of the JSON value (implicit)\n\n    Implicitly return the type of the JSON value as a value from the @ref\n    value_t enumeration.\n\n    @return the type of the JSON value\n\n    @complexity Constant.\n\n    @exceptionsafety No-throw guarantee: this member function never throws\n    exceptions.\n\n    @liveexample{The following code exemplifies the @ref value_t operator for\n    all JSON types.,operator__value_t}\n\n    @sa @ref type() -- return the type of the JSON value (explicit)\n    @sa @ref type_name() -- return the type as string\n\n    @since version 1.0.0\n    */\n    constexpr operator value_t() const noexcept\n    {\n        return m_type;\n    }\n\n    /// @}\n\n  private:\n    //////////////////\n    // value access //\n    //////////////////\n\n    /// get a boolean (explicit)\n    boolean_t get_impl(boolean_t* /*unused*/) const\n    {\n        if (JSON_LIKELY(is_boolean()))\n        {\n            return m_value.boolean;\n        }\n\n        JSON_THROW(type_error::create(302, \"type must be boolean, but is \" + std::string(type_name())));\n    }\n\n    /// get a pointer to the value (object)\n    object_t* get_impl_ptr(object_t* /*unused*/) noexcept\n    {\n        return is_object() ? m_value.object : nullptr;\n    }\n\n    /// get a pointer to the value (object)\n    constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept\n    {\n        return is_object() ? m_value.object : nullptr;\n    }\n\n    /// get a pointer to the value (array)\n    array_t* get_impl_ptr(array_t* /*unused*/) noexcept\n    {\n        return is_array() ? m_value.array : nullptr;\n    }\n\n    /// get a pointer to the value (array)\n    constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept\n    {\n        return is_array() ? m_value.array : nullptr;\n    }\n\n    /// get a pointer to the value (string)\n    string_t* get_impl_ptr(string_t* /*unused*/) noexcept\n    {\n        return is_string() ? m_value.string : nullptr;\n    }\n\n    /// get a pointer to the value (string)\n    constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept\n    {\n        return is_string() ? m_value.string : nullptr;\n    }\n\n    /// get a pointer to the value (boolean)\n    boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept\n    {\n        return is_boolean() ? &m_value.boolean : nullptr;\n    }\n\n    /// get a pointer to the value (boolean)\n    constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept\n    {\n        return is_boolean() ? &m_value.boolean : nullptr;\n    }\n\n    /// get a pointer to the value (integer number)\n    number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept\n    {\n        return is_number_integer() ? &m_value.number_integer : nullptr;\n    }\n\n    /// get a pointer to the value (integer number)\n    constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept\n    {\n        return is_number_integer() ? &m_value.number_integer : nullptr;\n    }\n\n    /// get a pointer to the value (unsigned number)\n    number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept\n    {\n        return is_number_unsigned() ? &m_value.number_unsigned : nullptr;\n    }\n\n    /// get a pointer to the value (unsigned number)\n    constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept\n    {\n        return is_number_unsigned() ? &m_value.number_unsigned : nullptr;\n    }\n\n    /// get a pointer to the value (floating-point number)\n    number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept\n    {\n        return is_number_float() ? &m_value.number_float : nullptr;\n    }\n\n    /// get a pointer to the value (floating-point number)\n    constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept\n    {\n        return is_number_float() ? &m_value.number_float : nullptr;\n    }\n\n    /*!\n    @brief helper function to implement get_ref()\n\n    This function helps to implement get_ref() without code duplication for\n    const and non-const overloads\n\n    @tparam ThisType will be deduced as `basic_json` or `const basic_json`\n\n    @throw type_error.303 if ReferenceType does not match underlying value\n    type of the current JSON\n    */\n    template<typename ReferenceType, typename ThisType>\n    static ReferenceType get_ref_impl(ThisType& obj)\n    {\n        // delegate the call to get_ptr<>()\n        auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();\n\n        if (JSON_LIKELY(ptr != nullptr))\n        {\n            return *ptr;\n        }\n\n        JSON_THROW(type_error::create(303, \"incompatible ReferenceType for get_ref, actual type is \" + std::string(obj.type_name())));\n    }\n\n  public:\n    /// @name value access\n    /// Direct access to the stored value of a JSON value.\n    /// @{\n\n    /*!\n    @brief get special-case overload\n\n    This overloads avoids a lot of template boilerplate, it can be seen as the\n    identity method\n\n    @tparam BasicJsonType == @ref basic_json\n\n    @return a copy of *this\n\n    @complexity Constant.\n\n    @since version 2.1.0\n    */\n    template<typename BasicJsonType, detail::enable_if_t<\n                 std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,\n                 int> = 0>\n    basic_json get() const\n    {\n        return *this;\n    }\n\n    /*!\n    @brief get a value (explicit)\n\n    Explicit type conversion between the JSON value and a compatible value\n    which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)\n    and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).\n    The value is converted by calling the @ref json_serializer<ValueType>\n    `from_json()` method.\n\n    The function is equivalent to executing\n    @code {.cpp}\n    ValueType ret;\n    JSONSerializer<ValueType>::from_json(*this, ret);\n    return ret;\n    @endcode\n\n    This overloads is chosen if:\n    - @a ValueType is not @ref basic_json,\n    - @ref json_serializer<ValueType> has a `from_json()` method of the form\n      `void from_json(const basic_json&, ValueType&)`, and\n    - @ref json_serializer<ValueType> does not have a `from_json()` method of\n      the form `ValueType from_json(const basic_json&)`\n\n    @tparam ValueTypeCV the provided value type\n    @tparam ValueType the returned value type\n\n    @return copy of the JSON value, converted to @a ValueType\n\n    @throw what @ref json_serializer<ValueType> `from_json()` method throws\n\n    @liveexample{The example below shows several conversions from JSON values\n    to other types. There a few things to note: (1) Floating-point numbers can\n    be converted to integers\\, (2) A JSON array can be converted to a standard\n    `std::vector<short>`\\, (3) A JSON object can be converted to C++\n    associative containers such as `std::unordered_map<std::string\\,\n    json>`.,get__ValueType_const}\n\n    @since version 2.1.0\n    */\n    template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,\n             detail::enable_if_t <\n                 not std::is_same<basic_json_t, ValueType>::value and\n                 detail::has_from_json<basic_json_t, ValueType>::value and\n                 not detail::has_non_default_from_json<basic_json_t, ValueType>::value,\n                 int> = 0>\n    ValueType get() const noexcept(noexcept(\n                                       JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))\n    {\n        // we cannot static_assert on ValueTypeCV being non-const, because\n        // there is support for get<const basic_json_t>(), which is why we\n        // still need the uncvref\n        static_assert(not std::is_reference<ValueTypeCV>::value,\n                      \"get() cannot be used with reference types, you might want to use get_ref()\");\n        static_assert(std::is_default_constructible<ValueType>::value,\n                      \"types must be DefaultConstructible when used with get()\");\n\n        ValueType ret;\n        JSONSerializer<ValueType>::from_json(*this, ret);\n        return ret;\n    }\n\n    /*!\n    @brief get a value (explicit); special case\n\n    Explicit type conversion between the JSON value and a compatible value\n    which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)\n    and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).\n    The value is converted by calling the @ref json_serializer<ValueType>\n    `from_json()` method.\n\n    The function is equivalent to executing\n    @code {.cpp}\n    return JSONSerializer<ValueTypeCV>::from_json(*this);\n    @endcode\n\n    This overloads is chosen if:\n    - @a ValueType is not @ref basic_json and\n    - @ref json_serializer<ValueType> has a `from_json()` method of the form\n      `ValueType from_json(const basic_json&)`\n\n    @note If @ref json_serializer<ValueType> has both overloads of\n    `from_json()`, this one is chosen.\n\n    @tparam ValueTypeCV the provided value type\n    @tparam ValueType the returned value type\n\n    @return copy of the JSON value, converted to @a ValueType\n\n    @throw what @ref json_serializer<ValueType> `from_json()` method throws\n\n    @since version 2.1.0\n    */\n    template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,\n             detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and\n                                 detail::has_non_default_from_json<basic_json_t, ValueType>::value,\n                                 int> = 0>\n    ValueType get() const noexcept(noexcept(\n                                       JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))\n    {\n        static_assert(not std::is_reference<ValueTypeCV>::value,\n                      \"get() cannot be used with reference types, you might want to use get_ref()\");\n        return JSONSerializer<ValueTypeCV>::from_json(*this);\n    }\n\n    /*!\n    @brief get a pointer value (explicit)\n\n    Explicit pointer access to the internally stored JSON value. No copies are\n    made.\n\n    @warning The pointer becomes invalid if the underlying JSON object\n    changes.\n\n    @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref\n    object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,\n    @ref number_unsigned_t, or @ref number_float_t.\n\n    @return pointer to the internally stored JSON value if the requested\n    pointer type @a PointerType fits to the JSON value; `nullptr` otherwise\n\n    @complexity Constant.\n\n    @liveexample{The example below shows how pointers to internal values of a\n    JSON value can be requested. Note that no type conversions are made and a\n    `nullptr` is returned if the value and the requested pointer type does not\n    match.,get__PointerType}\n\n    @sa @ref get_ptr() for explicit pointer-member access\n\n    @since version 1.0.0\n    */\n    template<typename PointerType, typename std::enable_if<\n                 std::is_pointer<PointerType>::value, int>::type = 0>\n    PointerType get() noexcept\n    {\n        // delegate the call to get_ptr\n        return get_ptr<PointerType>();\n    }\n\n    /*!\n    @brief get a pointer value (explicit)\n    @copydoc get()\n    */\n    template<typename PointerType, typename std::enable_if<\n                 std::is_pointer<PointerType>::value, int>::type = 0>\n    constexpr const PointerType get() const noexcept\n    {\n        // delegate the call to get_ptr\n        return get_ptr<PointerType>();\n    }\n\n    /*!\n    @brief get a pointer value (implicit)\n\n    Implicit pointer access to the internally stored JSON value. No copies are\n    made.\n\n    @warning Writing data to the pointee of the result yields an undefined\n    state.\n\n    @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref\n    object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,\n    @ref number_unsigned_t, or @ref number_float_t. Enforced by a static\n    assertion.\n\n    @return pointer to the internally stored JSON value if the requested\n    pointer type @a PointerType fits to the JSON value; `nullptr` otherwise\n\n    @complexity Constant.\n\n    @liveexample{The example below shows how pointers to internal values of a\n    JSON value can be requested. Note that no type conversions are made and a\n    `nullptr` is returned if the value and the requested pointer type does not\n    match.,get_ptr}\n\n    @since version 1.0.0\n    */\n    template<typename PointerType, typename std::enable_if<\n                 std::is_pointer<PointerType>::value, int>::type = 0>\n    PointerType get_ptr() noexcept\n    {\n        // get the type of the PointerType (remove pointer and const)\n        using pointee_t = typename std::remove_const<typename\n                          std::remove_pointer<typename\n                          std::remove_const<PointerType>::type>::type>::type;\n        // make sure the type matches the allowed types\n        static_assert(\n            std::is_same<object_t, pointee_t>::value\n            or std::is_same<array_t, pointee_t>::value\n            or std::is_same<string_t, pointee_t>::value\n            or std::is_same<boolean_t, pointee_t>::value\n            or std::is_same<number_integer_t, pointee_t>::value\n            or std::is_same<number_unsigned_t, pointee_t>::value\n            or std::is_same<number_float_t, pointee_t>::value\n            , \"incompatible pointer type\");\n\n        // delegate the call to get_impl_ptr<>()\n        return get_impl_ptr(static_cast<PointerType>(nullptr));\n    }\n\n    /*!\n    @brief get a pointer value (implicit)\n    @copydoc get_ptr()\n    */\n    template<typename PointerType, typename std::enable_if<\n                 std::is_pointer<PointerType>::value and\n                 std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>\n    constexpr const PointerType get_ptr() const noexcept\n    {\n        // get the type of the PointerType (remove pointer and const)\n        using pointee_t = typename std::remove_const<typename\n                          std::remove_pointer<typename\n                          std::remove_const<PointerType>::type>::type>::type;\n        // make sure the type matches the allowed types\n        static_assert(\n            std::is_same<object_t, pointee_t>::value\n            or std::is_same<array_t, pointee_t>::value\n            or std::is_same<string_t, pointee_t>::value\n            or std::is_same<boolean_t, pointee_t>::value\n            or std::is_same<number_integer_t, pointee_t>::value\n            or std::is_same<number_unsigned_t, pointee_t>::value\n            or std::is_same<number_float_t, pointee_t>::value\n            , \"incompatible pointer type\");\n\n        // delegate the call to get_impl_ptr<>() const\n        return get_impl_ptr(static_cast<PointerType>(nullptr));\n    }\n\n    /*!\n    @brief get a reference value (implicit)\n\n    Implicit reference access to the internally stored JSON value. No copies\n    are made.\n\n    @warning Writing data to the referee of the result yields an undefined\n    state.\n\n    @tparam ReferenceType reference type; must be a reference to @ref array_t,\n    @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or\n    @ref number_float_t. Enforced by static assertion.\n\n    @return reference to the internally stored JSON value if the requested\n    reference type @a ReferenceType fits to the JSON value; throws\n    type_error.303 otherwise\n\n    @throw type_error.303 in case passed type @a ReferenceType is incompatible\n    with the stored JSON value; see example below\n\n    @complexity Constant.\n\n    @liveexample{The example shows several calls to `get_ref()`.,get_ref}\n\n    @since version 1.1.0\n    */\n    template<typename ReferenceType, typename std::enable_if<\n                 std::is_reference<ReferenceType>::value, int>::type = 0>\n    ReferenceType get_ref()\n    {\n        // delegate call to get_ref_impl\n        return get_ref_impl<ReferenceType>(*this);\n    }\n\n    /*!\n    @brief get a reference value (implicit)\n    @copydoc get_ref()\n    */\n    template<typename ReferenceType, typename std::enable_if<\n                 std::is_reference<ReferenceType>::value and\n                 std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>\n    ReferenceType get_ref() const\n    {\n        // delegate call to get_ref_impl\n        return get_ref_impl<ReferenceType>(*this);\n    }\n\n    /*!\n    @brief get a value (implicit)\n\n    Implicit type conversion between the JSON value and a compatible value.\n    The call is realized by calling @ref get() const.\n\n    @tparam ValueType non-pointer type compatible to the JSON value, for\n    instance `int` for JSON integer numbers, `bool` for JSON booleans, or\n    `std::vector` types for JSON arrays. The character type of @ref string_t\n    as well as an initializer list of this type is excluded to avoid\n    ambiguities as these types implicitly convert to `std::string`.\n\n    @return copy of the JSON value, converted to type @a ValueType\n\n    @throw type_error.302 in case passed type @a ValueType is incompatible\n    to the JSON value type (e.g., the JSON value is of type boolean, but a\n    string is requested); see example below\n\n    @complexity Linear in the size of the JSON value.\n\n    @liveexample{The example below shows several conversions from JSON values\n    to other types. There a few things to note: (1) Floating-point numbers can\n    be converted to integers\\, (2) A JSON array can be converted to a standard\n    `std::vector<short>`\\, (3) A JSON object can be converted to C++\n    associative containers such as `std::unordered_map<std::string\\,\n    json>`.,operator__ValueType}\n\n    @since version 1.0.0\n    */\n    template < typename ValueType, typename std::enable_if <\n                   not std::is_pointer<ValueType>::value and\n                   not std::is_same<ValueType, detail::json_ref<basic_json>>::value and\n                   not std::is_same<ValueType, typename string_t::value_type>::value\n#ifndef _MSC_VER  // fix for issue #167 operator<< ambiguity under VS2015\n                   and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value\n#endif\n#if defined(JSON_HAS_CPP_17)\n                   and not std::is_same<ValueType, typename std::string_view>::value\n#endif\n                   , int >::type = 0 >\n    operator ValueType() const\n    {\n        // delegate the call to get<>() const\n        return get<ValueType>();\n    }\n\n    /// @}\n\n\n    ////////////////////\n    // element access //\n    ////////////////////\n\n    /// @name element access\n    /// Access to the JSON value.\n    /// @{\n\n    /*!\n    @brief access specified array element with bounds checking\n\n    Returns a reference to the element at specified location @a idx, with\n    bounds checking.\n\n    @param[in] idx  index of the element to access\n\n    @return reference to the element at index @a idx\n\n    @throw type_error.304 if the JSON value is not an array; in this case,\n    calling `at` with an index makes no sense. See example below.\n    @throw out_of_range.401 if the index @a idx is out of range of the array;\n    that is, `idx >= size()`. See example below.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes in the JSON value.\n\n    @complexity Constant.\n\n    @since version 1.0.0\n\n    @liveexample{The example below shows how array elements can be read and\n    written using `at()`. It also demonstrates the different exceptions that\n    can be thrown.,at__size_type}\n    */\n    reference at(size_type idx)\n    {\n        // at only works for arrays\n        if (JSON_LIKELY(is_array()))\n        {\n            JSON_TRY\n            {\n                return m_value.array->at(idx);\n            }\n            JSON_CATCH (std::out_of_range&)\n            {\n                // create better exception explanation\n                JSON_THROW(out_of_range::create(401, \"array index \" + std::to_string(idx) + \" is out of range\"));\n            }\n        }\n        else\n        {\n            JSON_THROW(type_error::create(304, \"cannot use at() with \" + std::string(type_name())));\n        }\n    }\n\n    /*!\n    @brief access specified array element with bounds checking\n\n    Returns a const reference to the element at specified location @a idx,\n    with bounds checking.\n\n    @param[in] idx  index of the element to access\n\n    @return const reference to the element at index @a idx\n\n    @throw type_error.304 if the JSON value is not an array; in this case,\n    calling `at` with an index makes no sense. See example below.\n    @throw out_of_range.401 if the index @a idx is out of range of the array;\n    that is, `idx >= size()`. See example below.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes in the JSON value.\n\n    @complexity Constant.\n\n    @since version 1.0.0\n\n    @liveexample{The example below shows how array elements can be read using\n    `at()`. It also demonstrates the different exceptions that can be thrown.,\n    at__size_type_const}\n    */\n    const_reference at(size_type idx) const\n    {\n        // at only works for arrays\n        if (JSON_LIKELY(is_array()))\n        {\n            JSON_TRY\n            {\n                return m_value.array->at(idx);\n            }\n            JSON_CATCH (std::out_of_range&)\n            {\n                // create better exception explanation\n                JSON_THROW(out_of_range::create(401, \"array index \" + std::to_string(idx) + \" is out of range\"));\n            }\n        }\n        else\n        {\n            JSON_THROW(type_error::create(304, \"cannot use at() with \" + std::string(type_name())));\n        }\n    }\n\n    /*!\n    @brief access specified object element with bounds checking\n\n    Returns a reference to the element at with specified key @a key, with\n    bounds checking.\n\n    @param[in] key  key of the element to access\n\n    @return reference to the element at key @a key\n\n    @throw type_error.304 if the JSON value is not an object; in this case,\n    calling `at` with a key makes no sense. See example below.\n    @throw out_of_range.403 if the key @a key is is not stored in the object;\n    that is, `find(key) == end()`. See example below.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes in the JSON value.\n\n    @complexity Logarithmic in the size of the container.\n\n    @sa @ref operator[](const typename object_t::key_type&) for unchecked\n    access by reference\n    @sa @ref value() for access by value with a default value\n\n    @since version 1.0.0\n\n    @liveexample{The example below shows how object elements can be read and\n    written using `at()`. It also demonstrates the different exceptions that\n    can be thrown.,at__object_t_key_type}\n    */\n    reference at(const typename object_t::key_type& key)\n    {\n        // at only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            JSON_TRY\n            {\n                return m_value.object->at(key);\n            }\n            JSON_CATCH (std::out_of_range&)\n            {\n                // create better exception explanation\n                JSON_THROW(out_of_range::create(403, \"key '\" + key + \"' not found\"));\n            }\n        }\n        else\n        {\n            JSON_THROW(type_error::create(304, \"cannot use at() with \" + std::string(type_name())));\n        }\n    }\n\n    /*!\n    @brief access specified object element with bounds checking\n\n    Returns a const reference to the element at with specified key @a key,\n    with bounds checking.\n\n    @param[in] key  key of the element to access\n\n    @return const reference to the element at key @a key\n\n    @throw type_error.304 if the JSON value is not an object; in this case,\n    calling `at` with a key makes no sense. See example below.\n    @throw out_of_range.403 if the key @a key is is not stored in the object;\n    that is, `find(key) == end()`. See example below.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes in the JSON value.\n\n    @complexity Logarithmic in the size of the container.\n\n    @sa @ref operator[](const typename object_t::key_type&) for unchecked\n    access by reference\n    @sa @ref value() for access by value with a default value\n\n    @since version 1.0.0\n\n    @liveexample{The example below shows how object elements can be read using\n    `at()`. It also demonstrates the different exceptions that can be thrown.,\n    at__object_t_key_type_const}\n    */\n    const_reference at(const typename object_t::key_type& key) const\n    {\n        // at only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            JSON_TRY\n            {\n                return m_value.object->at(key);\n            }\n            JSON_CATCH (std::out_of_range&)\n            {\n                // create better exception explanation\n                JSON_THROW(out_of_range::create(403, \"key '\" + key + \"' not found\"));\n            }\n        }\n        else\n        {\n            JSON_THROW(type_error::create(304, \"cannot use at() with \" + std::string(type_name())));\n        }\n    }\n\n    /*!\n    @brief access specified array element\n\n    Returns a reference to the element at specified location @a idx.\n\n    @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),\n    then the array is silently filled up with `null` values to make `idx` a\n    valid reference to the last stored element.\n\n    @param[in] idx  index of the element to access\n\n    @return reference to the element at index @a idx\n\n    @throw type_error.305 if the JSON value is not an array or null; in that\n    cases, using the [] operator with an index makes no sense.\n\n    @complexity Constant if @a idx is in the range of the array. Otherwise\n    linear in `idx - size()`.\n\n    @liveexample{The example below shows how array elements can be read and\n    written using `[]` operator. Note the addition of `null`\n    values.,operatorarray__size_type}\n\n    @since version 1.0.0\n    */\n    reference operator[](size_type idx)\n    {\n        // implicitly convert null value to an empty array\n        if (is_null())\n        {\n            m_type = value_t::array;\n            m_value.array = create<array_t>();\n            assert_invariant();\n        }\n\n        // operator[] only works for arrays\n        if (JSON_LIKELY(is_array()))\n        {\n            // fill up array with null values if given idx is outside range\n            if (idx >= m_value.array->size())\n            {\n                m_value.array->insert(m_value.array->end(),\n                                      idx - m_value.array->size() + 1,\n                                      basic_json());\n            }\n\n            return m_value.array->operator[](idx);\n        }\n\n        JSON_THROW(type_error::create(305, \"cannot use operator[] with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief access specified array element\n\n    Returns a const reference to the element at specified location @a idx.\n\n    @param[in] idx  index of the element to access\n\n    @return const reference to the element at index @a idx\n\n    @throw type_error.305 if the JSON value is not an array; in that case,\n    using the [] operator with an index makes no sense.\n\n    @complexity Constant.\n\n    @liveexample{The example below shows how array elements can be read using\n    the `[]` operator.,operatorarray__size_type_const}\n\n    @since version 1.0.0\n    */\n    const_reference operator[](size_type idx) const\n    {\n        // const operator[] only works for arrays\n        if (JSON_LIKELY(is_array()))\n        {\n            return m_value.array->operator[](idx);\n        }\n\n        JSON_THROW(type_error::create(305, \"cannot use operator[] with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief access specified object element\n\n    Returns a reference to the element at with specified key @a key.\n\n    @note If @a key is not found in the object, then it is silently added to\n    the object and filled with a `null` value to make `key` a valid reference.\n    In case the value was `null` before, it is converted to an object.\n\n    @param[in] key  key of the element to access\n\n    @return reference to the element at key @a key\n\n    @throw type_error.305 if the JSON value is not an object or null; in that\n    cases, using the [] operator with a key makes no sense.\n\n    @complexity Logarithmic in the size of the container.\n\n    @liveexample{The example below shows how object elements can be read and\n    written using the `[]` operator.,operatorarray__key_type}\n\n    @sa @ref at(const typename object_t::key_type&) for access by reference\n    with range checking\n    @sa @ref value() for access by value with a default value\n\n    @since version 1.0.0\n    */\n    reference operator[](const typename object_t::key_type& key)\n    {\n        // implicitly convert null value to an empty object\n        if (is_null())\n        {\n            m_type = value_t::object;\n            m_value.object = create<object_t>();\n            assert_invariant();\n        }\n\n        // operator[] only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            return m_value.object->operator[](key);\n        }\n\n        JSON_THROW(type_error::create(305, \"cannot use operator[] with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief read-only access specified object element\n\n    Returns a const reference to the element at with specified key @a key. No\n    bounds checking is performed.\n\n    @warning If the element with key @a key does not exist, the behavior is\n    undefined.\n\n    @param[in] key  key of the element to access\n\n    @return const reference to the element at key @a key\n\n    @pre The element with key @a key must exist. **This precondition is\n         enforced with an assertion.**\n\n    @throw type_error.305 if the JSON value is not an object; in that case,\n    using the [] operator with a key makes no sense.\n\n    @complexity Logarithmic in the size of the container.\n\n    @liveexample{The example below shows how object elements can be read using\n    the `[]` operator.,operatorarray__key_type_const}\n\n    @sa @ref at(const typename object_t::key_type&) for access by reference\n    with range checking\n    @sa @ref value() for access by value with a default value\n\n    @since version 1.0.0\n    */\n    const_reference operator[](const typename object_t::key_type& key) const\n    {\n        // const operator[] only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            assert(m_value.object->find(key) != m_value.object->end());\n            return m_value.object->find(key)->second;\n        }\n\n        JSON_THROW(type_error::create(305, \"cannot use operator[] with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief access specified object element\n\n    Returns a reference to the element at with specified key @a key.\n\n    @note If @a key is not found in the object, then it is silently added to\n    the object and filled with a `null` value to make `key` a valid reference.\n    In case the value was `null` before, it is converted to an object.\n\n    @param[in] key  key of the element to access\n\n    @return reference to the element at key @a key\n\n    @throw type_error.305 if the JSON value is not an object or null; in that\n    cases, using the [] operator with a key makes no sense.\n\n    @complexity Logarithmic in the size of the container.\n\n    @liveexample{The example below shows how object elements can be read and\n    written using the `[]` operator.,operatorarray__key_type}\n\n    @sa @ref at(const typename object_t::key_type&) for access by reference\n    with range checking\n    @sa @ref value() for access by value with a default value\n\n    @since version 1.1.0\n    */\n    template<typename T>\n    reference operator[](T* key)\n    {\n        // implicitly convert null to object\n        if (is_null())\n        {\n            m_type = value_t::object;\n            m_value = value_t::object;\n            assert_invariant();\n        }\n\n        // at only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            return m_value.object->operator[](key);\n        }\n\n        JSON_THROW(type_error::create(305, \"cannot use operator[] with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief read-only access specified object element\n\n    Returns a const reference to the element at with specified key @a key. No\n    bounds checking is performed.\n\n    @warning If the element with key @a key does not exist, the behavior is\n    undefined.\n\n    @param[in] key  key of the element to access\n\n    @return const reference to the element at key @a key\n\n    @pre The element with key @a key must exist. **This precondition is\n         enforced with an assertion.**\n\n    @throw type_error.305 if the JSON value is not an object; in that case,\n    using the [] operator with a key makes no sense.\n\n    @complexity Logarithmic in the size of the container.\n\n    @liveexample{The example below shows how object elements can be read using\n    the `[]` operator.,operatorarray__key_type_const}\n\n    @sa @ref at(const typename object_t::key_type&) for access by reference\n    with range checking\n    @sa @ref value() for access by value with a default value\n\n    @since version 1.1.0\n    */\n    template<typename T>\n    const_reference operator[](T* key) const\n    {\n        // at only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            assert(m_value.object->find(key) != m_value.object->end());\n            return m_value.object->find(key)->second;\n        }\n\n        JSON_THROW(type_error::create(305, \"cannot use operator[] with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief access specified object element with default value\n\n    Returns either a copy of an object's element at the specified key @a key\n    or a given default value if no element with key @a key exists.\n\n    The function is basically equivalent to executing\n    @code {.cpp}\n    try {\n        return at(key);\n    } catch(out_of_range) {\n        return default_value;\n    }\n    @endcode\n\n    @note Unlike @ref at(const typename object_t::key_type&), this function\n    does not throw if the given key @a key was not found.\n\n    @note Unlike @ref operator[](const typename object_t::key_type& key), this\n    function does not implicitly add an element to the position defined by @a\n    key. This function is furthermore also applicable to const objects.\n\n    @param[in] key  key of the element to access\n    @param[in] default_value  the value to return if @a key is not found\n\n    @tparam ValueType type compatible to JSON values, for instance `int` for\n    JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for\n    JSON arrays. Note the type of the expected value at @a key and the default\n    value @a default_value must be compatible.\n\n    @return copy of the element at key @a key or @a default_value if @a key\n    is not found\n\n    @throw type_error.306 if the JSON value is not an object; in that case,\n    using `value()` with a key makes no sense.\n\n    @complexity Logarithmic in the size of the container.\n\n    @liveexample{The example below shows how object elements can be queried\n    with a default value.,basic_json__value}\n\n    @sa @ref at(const typename object_t::key_type&) for access by reference\n    with range checking\n    @sa @ref operator[](const typename object_t::key_type&) for unchecked\n    access by reference\n\n    @since version 1.0.0\n    */\n    template<class ValueType, typename std::enable_if<\n                 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>\n    ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const\n    {\n        // at only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            // if key is found, return value and given default value otherwise\n            const auto it = find(key);\n            if (it != end())\n            {\n                return *it;\n            }\n\n            return default_value;\n        }\n\n        JSON_THROW(type_error::create(306, \"cannot use value() with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief overload for a default value of type const char*\n    @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const\n    */\n    string_t value(const typename object_t::key_type& key, const char* default_value) const\n    {\n        return value(key, string_t(default_value));\n    }\n\n    /*!\n    @brief access specified object element via JSON Pointer with default value\n\n    Returns either a copy of an object's element at the specified key @a key\n    or a given default value if no element with key @a key exists.\n\n    The function is basically equivalent to executing\n    @code {.cpp}\n    try {\n        return at(ptr);\n    } catch(out_of_range) {\n        return default_value;\n    }\n    @endcode\n\n    @note Unlike @ref at(const json_pointer&), this function does not throw\n    if the given key @a key was not found.\n\n    @param[in] ptr  a JSON pointer to the element to access\n    @param[in] default_value  the value to return if @a ptr found no value\n\n    @tparam ValueType type compatible to JSON values, for instance `int` for\n    JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for\n    JSON arrays. Note the type of the expected value at @a key and the default\n    value @a default_value must be compatible.\n\n    @return copy of the element at key @a key or @a default_value if @a key\n    is not found\n\n    @throw type_error.306 if the JSON value is not an objec; in that case,\n    using `value()` with a key makes no sense.\n\n    @complexity Logarithmic in the size of the container.\n\n    @liveexample{The example below shows how object elements can be queried\n    with a default value.,basic_json__value_ptr}\n\n    @sa @ref operator[](const json_pointer&) for unchecked access by reference\n\n    @since version 2.0.2\n    */\n    template<class ValueType, typename std::enable_if<\n                 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>\n    ValueType value(const json_pointer& ptr, const ValueType& default_value) const\n    {\n        // at only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            // if pointer resolves a value, return it or use default value\n            JSON_TRY\n            {\n                return ptr.get_checked(this);\n            }\n            JSON_CATCH (out_of_range&)\n            {\n                return default_value;\n            }\n        }\n\n        JSON_THROW(type_error::create(306, \"cannot use value() with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief overload for a default value of type const char*\n    @copydoc basic_json::value(const json_pointer&, ValueType) const\n    */\n    string_t value(const json_pointer& ptr, const char* default_value) const\n    {\n        return value(ptr, string_t(default_value));\n    }\n\n    /*!\n    @brief access the first element\n\n    Returns a reference to the first element in the container. For a JSON\n    container `c`, the expression `c.front()` is equivalent to `*c.begin()`.\n\n    @return In case of a structured type (array or object), a reference to the\n    first element is returned. In case of number, string, or boolean values, a\n    reference to the value is returned.\n\n    @complexity Constant.\n\n    @pre The JSON value must not be `null` (would throw `std::out_of_range`)\n    or an empty array or object (undefined behavior, **guarded by\n    assertions**).\n    @post The JSON value remains unchanged.\n\n    @throw invalid_iterator.214 when called on `null` value\n\n    @liveexample{The following code shows an example for `front()`.,front}\n\n    @sa @ref back() -- access the last element\n\n    @since version 1.0.0\n    */\n    reference front()\n    {\n        return *begin();\n    }\n\n    /*!\n    @copydoc basic_json::front()\n    */\n    const_reference front() const\n    {\n        return *cbegin();\n    }\n\n    /*!\n    @brief access the last element\n\n    Returns a reference to the last element in the container. For a JSON\n    container `c`, the expression `c.back()` is equivalent to\n    @code {.cpp}\n    auto tmp = c.end();\n    --tmp;\n    return *tmp;\n    @endcode\n\n    @return In case of a structured type (array or object), a reference to the\n    last element is returned. In case of number, string, or boolean values, a\n    reference to the value is returned.\n\n    @complexity Constant.\n\n    @pre The JSON value must not be `null` (would throw `std::out_of_range`)\n    or an empty array or object (undefined behavior, **guarded by\n    assertions**).\n    @post The JSON value remains unchanged.\n\n    @throw invalid_iterator.214 when called on a `null` value. See example\n    below.\n\n    @liveexample{The following code shows an example for `back()`.,back}\n\n    @sa @ref front() -- access the first element\n\n    @since version 1.0.0\n    */\n    reference back()\n    {\n        auto tmp = end();\n        --tmp;\n        return *tmp;\n    }\n\n    /*!\n    @copydoc basic_json::back()\n    */\n    const_reference back() const\n    {\n        auto tmp = cend();\n        --tmp;\n        return *tmp;\n    }\n\n    /*!\n    @brief remove element given an iterator\n\n    Removes the element specified by iterator @a pos. The iterator @a pos must\n    be valid and dereferenceable. Thus the `end()` iterator (which is valid,\n    but is not dereferenceable) cannot be used as a value for @a pos.\n\n    If called on a primitive type other than `null`, the resulting JSON value\n    will be `null`.\n\n    @param[in] pos iterator to the element to remove\n    @return Iterator following the last removed element. If the iterator @a\n    pos refers to the last element, the `end()` iterator is returned.\n\n    @tparam IteratorType an @ref iterator or @ref const_iterator\n\n    @post Invalidates iterators and references at or after the point of the\n    erase, including the `end()` iterator.\n\n    @throw type_error.307 if called on a `null` value; example: `\"cannot use\n    erase() with null\"`\n    @throw invalid_iterator.202 if called on an iterator which does not belong\n    to the current JSON value; example: `\"iterator does not fit current\n    value\"`\n    @throw invalid_iterator.205 if called on a primitive type with invalid\n    iterator (i.e., any iterator which is not `begin()`); example: `\"iterator\n    out of range\"`\n\n    @complexity The complexity depends on the type:\n    - objects: amortized constant\n    - arrays: linear in distance between @a pos and the end of the container\n    - strings: linear in the length of the string\n    - other types: constant\n\n    @liveexample{The example shows the result of `erase()` for different JSON\n    types.,erase__IteratorType}\n\n    @sa @ref erase(IteratorType, IteratorType) -- removes the elements in\n    the given range\n    @sa @ref erase(const typename object_t::key_type&) -- removes the element\n    from an object at the given key\n    @sa @ref erase(const size_type) -- removes the element from an array at\n    the given index\n\n    @since version 1.0.0\n    */\n    template<class IteratorType, typename std::enable_if<\n                 std::is_same<IteratorType, typename basic_json_t::iterator>::value or\n                 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type\n             = 0>\n    IteratorType erase(IteratorType pos)\n    {\n        // make sure iterator fits the current value\n        if (JSON_UNLIKELY(this != pos.m_object))\n        {\n            JSON_THROW(invalid_iterator::create(202, \"iterator does not fit current value\"));\n        }\n\n        IteratorType result = end();\n\n        switch (m_type)\n        {\n            case value_t::boolean:\n            case value_t::number_float:\n            case value_t::number_integer:\n            case value_t::number_unsigned:\n            case value_t::string:\n            {\n                if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))\n                {\n                    JSON_THROW(invalid_iterator::create(205, \"iterator out of range\"));\n                }\n\n                if (is_string())\n                {\n                    AllocatorType<string_t> alloc;\n                    std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);\n                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);\n                    m_value.string = nullptr;\n                }\n\n                m_type = value_t::null;\n                assert_invariant();\n                break;\n            }\n\n            case value_t::object:\n            {\n                result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);\n                break;\n            }\n\n            case value_t::array:\n            {\n                result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);\n                break;\n            }\n\n            default:\n                JSON_THROW(type_error::create(307, \"cannot use erase() with \" + std::string(type_name())));\n        }\n\n        return result;\n    }\n\n    /*!\n    @brief remove elements given an iterator range\n\n    Removes the element specified by the range `[first; last)`. The iterator\n    @a first does not need to be dereferenceable if `first == last`: erasing\n    an empty range is a no-op.\n\n    If called on a primitive type other than `null`, the resulting JSON value\n    will be `null`.\n\n    @param[in] first iterator to the beginning of the range to remove\n    @param[in] last iterator past the end of the range to remove\n    @return Iterator following the last removed element. If the iterator @a\n    second refers to the last element, the `end()` iterator is returned.\n\n    @tparam IteratorType an @ref iterator or @ref const_iterator\n\n    @post Invalidates iterators and references at or after the point of the\n    erase, including the `end()` iterator.\n\n    @throw type_error.307 if called on a `null` value; example: `\"cannot use\n    erase() with null\"`\n    @throw invalid_iterator.203 if called on iterators which does not belong\n    to the current JSON value; example: `\"iterators do not fit current value\"`\n    @throw invalid_iterator.204 if called on a primitive type with invalid\n    iterators (i.e., if `first != begin()` and `last != end()`); example:\n    `\"iterators out of range\"`\n\n    @complexity The complexity depends on the type:\n    - objects: `log(size()) + std::distance(first, last)`\n    - arrays: linear in the distance between @a first and @a last, plus linear\n      in the distance between @a last and end of the container\n    - strings: linear in the length of the string\n    - other types: constant\n\n    @liveexample{The example shows the result of `erase()` for different JSON\n    types.,erase__IteratorType_IteratorType}\n\n    @sa @ref erase(IteratorType) -- removes the element at a given position\n    @sa @ref erase(const typename object_t::key_type&) -- removes the element\n    from an object at the given key\n    @sa @ref erase(const size_type) -- removes the element from an array at\n    the given index\n\n    @since version 1.0.0\n    */\n    template<class IteratorType, typename std::enable_if<\n                 std::is_same<IteratorType, typename basic_json_t::iterator>::value or\n                 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type\n             = 0>\n    IteratorType erase(IteratorType first, IteratorType last)\n    {\n        // make sure iterator fits the current value\n        if (JSON_UNLIKELY(this != first.m_object or this != last.m_object))\n        {\n            JSON_THROW(invalid_iterator::create(203, \"iterators do not fit current value\"));\n        }\n\n        IteratorType result = end();\n\n        switch (m_type)\n        {\n            case value_t::boolean:\n            case value_t::number_float:\n            case value_t::number_integer:\n            case value_t::number_unsigned:\n            case value_t::string:\n            {\n                if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin()\n                                or not last.m_it.primitive_iterator.is_end()))\n                {\n                    JSON_THROW(invalid_iterator::create(204, \"iterators out of range\"));\n                }\n\n                if (is_string())\n                {\n                    AllocatorType<string_t> alloc;\n                    std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);\n                    std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);\n                    m_value.string = nullptr;\n                }\n\n                m_type = value_t::null;\n                assert_invariant();\n                break;\n            }\n\n            case value_t::object:\n            {\n                result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,\n                                              last.m_it.object_iterator);\n                break;\n            }\n\n            case value_t::array:\n            {\n                result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,\n                                             last.m_it.array_iterator);\n                break;\n            }\n\n            default:\n                JSON_THROW(type_error::create(307, \"cannot use erase() with \" + std::string(type_name())));\n        }\n\n        return result;\n    }\n\n    /*!\n    @brief remove element from a JSON object given a key\n\n    Removes elements from a JSON object with the key value @a key.\n\n    @param[in] key value of the elements to remove\n\n    @return Number of elements removed. If @a ObjectType is the default\n    `std::map` type, the return value will always be `0` (@a key was not\n    found) or `1` (@a key was found).\n\n    @post References and iterators to the erased elements are invalidated.\n    Other references and iterators are not affected.\n\n    @throw type_error.307 when called on a type other than JSON object;\n    example: `\"cannot use erase() with null\"`\n\n    @complexity `log(size()) + count(key)`\n\n    @liveexample{The example shows the effect of `erase()`.,erase__key_type}\n\n    @sa @ref erase(IteratorType) -- removes the element at a given position\n    @sa @ref erase(IteratorType, IteratorType) -- removes the elements in\n    the given range\n    @sa @ref erase(const size_type) -- removes the element from an array at\n    the given index\n\n    @since version 1.0.0\n    */\n    size_type erase(const typename object_t::key_type& key)\n    {\n        // this erase only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            return m_value.object->erase(key);\n        }\n\n        JSON_THROW(type_error::create(307, \"cannot use erase() with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief remove element from a JSON array given an index\n\n    Removes element from a JSON array at the index @a idx.\n\n    @param[in] idx index of the element to remove\n\n    @throw type_error.307 when called on a type other than JSON object;\n    example: `\"cannot use erase() with null\"`\n    @throw out_of_range.401 when `idx >= size()`; example: `\"array index 17\n    is out of range\"`\n\n    @complexity Linear in distance between @a idx and the end of the container.\n\n    @liveexample{The example shows the effect of `erase()`.,erase__size_type}\n\n    @sa @ref erase(IteratorType) -- removes the element at a given position\n    @sa @ref erase(IteratorType, IteratorType) -- removes the elements in\n    the given range\n    @sa @ref erase(const typename object_t::key_type&) -- removes the element\n    from an object at the given key\n\n    @since version 1.0.0\n    */\n    void erase(const size_type idx)\n    {\n        // this erase only works for arrays\n        if (JSON_LIKELY(is_array()))\n        {\n            if (JSON_UNLIKELY(idx >= size()))\n            {\n                JSON_THROW(out_of_range::create(401, \"array index \" + std::to_string(idx) + \" is out of range\"));\n            }\n\n            m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));\n        }\n        else\n        {\n            JSON_THROW(type_error::create(307, \"cannot use erase() with \" + std::string(type_name())));\n        }\n    }\n\n    /// @}\n\n\n    ////////////\n    // lookup //\n    ////////////\n\n    /// @name lookup\n    /// @{\n\n    /*!\n    @brief find an element in a JSON object\n\n    Finds an element in a JSON object with key equivalent to @a key. If the\n    element is not found or the JSON value is not an object, end() is\n    returned.\n\n    @note This method always returns @ref end() when executed on a JSON type\n          that is not an object.\n\n    @param[in] key key value of the element to search for.\n\n    @return Iterator to an element with key equivalent to @a key. If no such\n    element is found or the JSON value is not an object, past-the-end (see\n    @ref end()) iterator is returned.\n\n    @complexity Logarithmic in the size of the JSON object.\n\n    @liveexample{The example shows how `find()` is used.,find__key_type}\n\n    @since version 1.0.0\n    */\n    template<typename KeyT>\n    iterator find(KeyT&& key)\n    {\n        auto result = end();\n\n        if (is_object())\n        {\n            result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));\n        }\n\n        return result;\n    }\n\n    /*!\n    @brief find an element in a JSON object\n    @copydoc find(KeyT&&)\n    */\n    template<typename KeyT>\n    const_iterator find(KeyT&& key) const\n    {\n        auto result = cend();\n\n        if (is_object())\n        {\n            result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));\n        }\n\n        return result;\n    }\n\n    /*!\n    @brief returns the number of occurrences of a key in a JSON object\n\n    Returns the number of elements with key @a key. If ObjectType is the\n    default `std::map` type, the return value will always be `0` (@a key was\n    not found) or `1` (@a key was found).\n\n    @note This method always returns `0` when executed on a JSON type that is\n          not an object.\n\n    @param[in] key key value of the element to count\n\n    @return Number of elements with key @a key. If the JSON value is not an\n    object, the return value will be `0`.\n\n    @complexity Logarithmic in the size of the JSON object.\n\n    @liveexample{The example shows how `count()` is used.,count}\n\n    @since version 1.0.0\n    */\n    template<typename KeyT>\n    size_type count(KeyT&& key) const\n    {\n        // return 0 for all nonobject types\n        return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;\n    }\n\n    /// @}\n\n\n    ///////////////\n    // iterators //\n    ///////////////\n\n    /// @name iterators\n    /// @{\n\n    /*!\n    @brief returns an iterator to the first element\n\n    Returns an iterator to the first element.\n\n    @image html range-begin-end.svg \"Illustration from cppreference.com\"\n\n    @return iterator to the first element\n\n    @complexity Constant.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is constant.\n\n    @liveexample{The following code shows an example for `begin()`.,begin}\n\n    @sa @ref cbegin() -- returns a const iterator to the beginning\n    @sa @ref end() -- returns an iterator to the end\n    @sa @ref cend() -- returns a const iterator to the end\n\n    @since version 1.0.0\n    */\n    iterator begin() noexcept\n    {\n        iterator result(this);\n        result.set_begin();\n        return result;\n    }\n\n    /*!\n    @copydoc basic_json::cbegin()\n    */\n    const_iterator begin() const noexcept\n    {\n        return cbegin();\n    }\n\n    /*!\n    @brief returns a const iterator to the first element\n\n    Returns a const iterator to the first element.\n\n    @image html range-begin-end.svg \"Illustration from cppreference.com\"\n\n    @return const iterator to the first element\n\n    @complexity Constant.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is constant.\n    - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.\n\n    @liveexample{The following code shows an example for `cbegin()`.,cbegin}\n\n    @sa @ref begin() -- returns an iterator to the beginning\n    @sa @ref end() -- returns an iterator to the end\n    @sa @ref cend() -- returns a const iterator to the end\n\n    @since version 1.0.0\n    */\n    const_iterator cbegin() const noexcept\n    {\n        const_iterator result(this);\n        result.set_begin();\n        return result;\n    }\n\n    /*!\n    @brief returns an iterator to one past the last element\n\n    Returns an iterator to one past the last element.\n\n    @image html range-begin-end.svg \"Illustration from cppreference.com\"\n\n    @return iterator one past the last element\n\n    @complexity Constant.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is constant.\n\n    @liveexample{The following code shows an example for `end()`.,end}\n\n    @sa @ref cend() -- returns a const iterator to the end\n    @sa @ref begin() -- returns an iterator to the beginning\n    @sa @ref cbegin() -- returns a const iterator to the beginning\n\n    @since version 1.0.0\n    */\n    iterator end() noexcept\n    {\n        iterator result(this);\n        result.set_end();\n        return result;\n    }\n\n    /*!\n    @copydoc basic_json::cend()\n    */\n    const_iterator end() const noexcept\n    {\n        return cend();\n    }\n\n    /*!\n    @brief returns a const iterator to one past the last element\n\n    Returns a const iterator to one past the last element.\n\n    @image html range-begin-end.svg \"Illustration from cppreference.com\"\n\n    @return const iterator one past the last element\n\n    @complexity Constant.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is constant.\n    - Has the semantics of `const_cast<const basic_json&>(*this).end()`.\n\n    @liveexample{The following code shows an example for `cend()`.,cend}\n\n    @sa @ref end() -- returns an iterator to the end\n    @sa @ref begin() -- returns an iterator to the beginning\n    @sa @ref cbegin() -- returns a const iterator to the beginning\n\n    @since version 1.0.0\n    */\n    const_iterator cend() const noexcept\n    {\n        const_iterator result(this);\n        result.set_end();\n        return result;\n    }\n\n    /*!\n    @brief returns an iterator to the reverse-beginning\n\n    Returns an iterator to the reverse-beginning; that is, the last element.\n\n    @image html range-rbegin-rend.svg \"Illustration from cppreference.com\"\n\n    @complexity Constant.\n\n    @requirement This function helps `basic_json` satisfying the\n    [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)\n    requirements:\n    - The complexity is constant.\n    - Has the semantics of `reverse_iterator(end())`.\n\n    @liveexample{The following code shows an example for `rbegin()`.,rbegin}\n\n    @sa @ref crbegin() -- returns a const reverse iterator to the beginning\n    @sa @ref rend() -- returns a reverse iterator to the end\n    @sa @ref crend() -- returns a const reverse iterator to the end\n\n    @since version 1.0.0\n    */\n    reverse_iterator rbegin() noexcept\n    {\n        return reverse_iterator(end());\n    }\n\n    /*!\n    @copydoc basic_json::crbegin()\n    */\n    const_reverse_iterator rbegin() const noexcept\n    {\n        return crbegin();\n    }\n\n    /*!\n    @brief returns an iterator to the reverse-end\n\n    Returns an iterator to the reverse-end; that is, one before the first\n    element.\n\n    @image html range-rbegin-rend.svg \"Illustration from cppreference.com\"\n\n    @complexity Constant.\n\n    @requirement This function helps `basic_json` satisfying the\n    [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)\n    requirements:\n    - The complexity is constant.\n    - Has the semantics of `reverse_iterator(begin())`.\n\n    @liveexample{The following code shows an example for `rend()`.,rend}\n\n    @sa @ref crend() -- returns a const reverse iterator to the end\n    @sa @ref rbegin() -- returns a reverse iterator to the beginning\n    @sa @ref crbegin() -- returns a const reverse iterator to the beginning\n\n    @since version 1.0.0\n    */\n    reverse_iterator rend() noexcept\n    {\n        return reverse_iterator(begin());\n    }\n\n    /*!\n    @copydoc basic_json::crend()\n    */\n    const_reverse_iterator rend() const noexcept\n    {\n        return crend();\n    }\n\n    /*!\n    @brief returns a const reverse iterator to the last element\n\n    Returns a const iterator to the reverse-beginning; that is, the last\n    element.\n\n    @image html range-rbegin-rend.svg \"Illustration from cppreference.com\"\n\n    @complexity Constant.\n\n    @requirement This function helps `basic_json` satisfying the\n    [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)\n    requirements:\n    - The complexity is constant.\n    - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.\n\n    @liveexample{The following code shows an example for `crbegin()`.,crbegin}\n\n    @sa @ref rbegin() -- returns a reverse iterator to the beginning\n    @sa @ref rend() -- returns a reverse iterator to the end\n    @sa @ref crend() -- returns a const reverse iterator to the end\n\n    @since version 1.0.0\n    */\n    const_reverse_iterator crbegin() const noexcept\n    {\n        return const_reverse_iterator(cend());\n    }\n\n    /*!\n    @brief returns a const reverse iterator to one before the first\n\n    Returns a const reverse iterator to the reverse-end; that is, one before\n    the first element.\n\n    @image html range-rbegin-rend.svg \"Illustration from cppreference.com\"\n\n    @complexity Constant.\n\n    @requirement This function helps `basic_json` satisfying the\n    [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)\n    requirements:\n    - The complexity is constant.\n    - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.\n\n    @liveexample{The following code shows an example for `crend()`.,crend}\n\n    @sa @ref rend() -- returns a reverse iterator to the end\n    @sa @ref rbegin() -- returns a reverse iterator to the beginning\n    @sa @ref crbegin() -- returns a const reverse iterator to the beginning\n\n    @since version 1.0.0\n    */\n    const_reverse_iterator crend() const noexcept\n    {\n        return const_reverse_iterator(cbegin());\n    }\n\n  public:\n    /*!\n    @brief wrapper to access iterator member functions in range-based for\n\n    This function allows to access @ref iterator::key() and @ref\n    iterator::value() during range-based for loops. In these loops, a\n    reference to the JSON values is returned, so there is no access to the\n    underlying iterator.\n\n    For loop without iterator_wrapper:\n\n    @code{cpp}\n    for (auto it = j_object.begin(); it != j_object.end(); ++it)\n    {\n        std::cout << \"key: \" << it.key() << \", value:\" << it.value() << '\\n';\n    }\n    @endcode\n\n    Range-based for loop without iterator proxy:\n\n    @code{cpp}\n    for (auto it : j_object)\n    {\n        // \"it\" is of type json::reference and has no key() member\n        std::cout << \"value: \" << it << '\\n';\n    }\n    @endcode\n\n    Range-based for loop with iterator proxy:\n\n    @code{cpp}\n    for (auto it : json::iterator_wrapper(j_object))\n    {\n        std::cout << \"key: \" << it.key() << \", value:\" << it.value() << '\\n';\n    }\n    @endcode\n\n    @note When iterating over an array, `key()` will return the index of the\n          element as string (see example).\n\n    @param[in] ref  reference to a JSON value\n    @return iteration proxy object wrapping @a ref with an interface to use in\n            range-based for loops\n\n    @liveexample{The following code shows how the wrapper is used,iterator_wrapper}\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes in the JSON value.\n\n    @complexity Constant.\n\n    @note The name of this function is not yet final and may change in the\n    future.\n    */\n    static iteration_proxy<iterator> iterator_wrapper(reference ref)\n    {\n        return iteration_proxy<iterator>(ref);\n    }\n\n    /*!\n    @copydoc iterator_wrapper(reference)\n    */\n    static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref)\n    {\n        return iteration_proxy<const_iterator>(ref);\n    }\n\n    /// @}\n\n\n    //////////////\n    // capacity //\n    //////////////\n\n    /// @name capacity\n    /// @{\n\n    /*!\n    @brief checks whether the container is empty.\n\n    Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).\n\n    @return The return value depends on the different types and is\n            defined as follows:\n            Value type  | return value\n            ----------- | -------------\n            null        | `true`\n            boolean     | `false`\n            string      | `false`\n            number      | `false`\n            object      | result of function `object_t::empty()`\n            array       | result of function `array_t::empty()`\n\n    @liveexample{The following code uses `empty()` to check if a JSON\n    object contains any elements.,empty}\n\n    @complexity Constant, as long as @ref array_t and @ref object_t satisfy\n    the Container concept; that is, their `empty()` functions have constant\n    complexity.\n\n    @iterators No changes.\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @note This function does not return whether a string stored as JSON value\n    is empty - it returns whether the JSON container itself is empty which is\n    false in the case of a string.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is constant.\n    - Has the semantics of `begin() == end()`.\n\n    @sa @ref size() -- returns the number of elements\n\n    @since version 1.0.0\n    */\n    bool empty() const noexcept\n    {\n        switch (m_type)\n        {\n            case value_t::null:\n            {\n                // null values are empty\n                return true;\n            }\n\n            case value_t::array:\n            {\n                // delegate call to array_t::empty()\n                return m_value.array->empty();\n            }\n\n            case value_t::object:\n            {\n                // delegate call to object_t::empty()\n                return m_value.object->empty();\n            }\n\n            default:\n            {\n                // all other types are nonempty\n                return false;\n            }\n        }\n    }\n\n    /*!\n    @brief returns the number of elements\n\n    Returns the number of elements in a JSON value.\n\n    @return The return value depends on the different types and is\n            defined as follows:\n            Value type  | return value\n            ----------- | -------------\n            null        | `0`\n            boolean     | `1`\n            string      | `1`\n            number      | `1`\n            object      | result of function object_t::size()\n            array       | result of function array_t::size()\n\n    @liveexample{The following code calls `size()` on the different value\n    types.,size}\n\n    @complexity Constant, as long as @ref array_t and @ref object_t satisfy\n    the Container concept; that is, their size() functions have constant\n    complexity.\n\n    @iterators No changes.\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @note This function does not return the length of a string stored as JSON\n    value - it returns the number of elements in the JSON value which is 1 in\n    the case of a string.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is constant.\n    - Has the semantics of `std::distance(begin(), end())`.\n\n    @sa @ref empty() -- checks whether the container is empty\n    @sa @ref max_size() -- returns the maximal number of elements\n\n    @since version 1.0.0\n    */\n    size_type size() const noexcept\n    {\n        switch (m_type)\n        {\n            case value_t::null:\n            {\n                // null values are empty\n                return 0;\n            }\n\n            case value_t::array:\n            {\n                // delegate call to array_t::size()\n                return m_value.array->size();\n            }\n\n            case value_t::object:\n            {\n                // delegate call to object_t::size()\n                return m_value.object->size();\n            }\n\n            default:\n            {\n                // all other types have size 1\n                return 1;\n            }\n        }\n    }\n\n    /*!\n    @brief returns the maximum possible number of elements\n\n    Returns the maximum number of elements a JSON value is able to hold due to\n    system or library implementation limitations, i.e. `std::distance(begin(),\n    end())` for the JSON value.\n\n    @return The return value depends on the different types and is\n            defined as follows:\n            Value type  | return value\n            ----------- | -------------\n            null        | `0` (same as `size()`)\n            boolean     | `1` (same as `size()`)\n            string      | `1` (same as `size()`)\n            number      | `1` (same as `size()`)\n            object      | result of function `object_t::max_size()`\n            array       | result of function `array_t::max_size()`\n\n    @liveexample{The following code calls `max_size()` on the different value\n    types. Note the output is implementation specific.,max_size}\n\n    @complexity Constant, as long as @ref array_t and @ref object_t satisfy\n    the Container concept; that is, their `max_size()` functions have constant\n    complexity.\n\n    @iterators No changes.\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @requirement This function helps `basic_json` satisfying the\n    [Container](http://en.cppreference.com/w/cpp/concept/Container)\n    requirements:\n    - The complexity is constant.\n    - Has the semantics of returning `b.size()` where `b` is the largest\n      possible JSON value.\n\n    @sa @ref size() -- returns the number of elements\n\n    @since version 1.0.0\n    */\n    size_type max_size() const noexcept\n    {\n        switch (m_type)\n        {\n            case value_t::array:\n            {\n                // delegate call to array_t::max_size()\n                return m_value.array->max_size();\n            }\n\n            case value_t::object:\n            {\n                // delegate call to object_t::max_size()\n                return m_value.object->max_size();\n            }\n\n            default:\n            {\n                // all other types have max_size() == size()\n                return size();\n            }\n        }\n    }\n\n    /// @}\n\n\n    ///////////////\n    // modifiers //\n    ///////////////\n\n    /// @name modifiers\n    /// @{\n\n    /*!\n    @brief clears the contents\n\n    Clears the content of a JSON value and resets it to the default value as\n    if @ref basic_json(value_t) would have been called with the current value\n    type from @ref type():\n\n    Value type  | initial value\n    ----------- | -------------\n    null        | `null`\n    boolean     | `false`\n    string      | `\"\"`\n    number      | `0`\n    object      | `{}`\n    array       | `[]`\n\n    @post Has the same effect as calling\n    @code {.cpp}\n    *this = basic_json(type());\n    @endcode\n\n    @liveexample{The example below shows the effect of `clear()` to different\n    JSON types.,clear}\n\n    @complexity Linear in the size of the JSON value.\n\n    @iterators All iterators, pointers and references related to this container\n               are invalidated.\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @sa @ref basic_json(value_t) -- constructor that creates an object with the\n        same value than calling `clear()`\n\n    @since version 1.0.0\n    */\n    void clear() noexcept\n    {\n        switch (m_type)\n        {\n            case value_t::number_integer:\n            {\n                m_value.number_integer = 0;\n                break;\n            }\n\n            case value_t::number_unsigned:\n            {\n                m_value.number_unsigned = 0;\n                break;\n            }\n\n            case value_t::number_float:\n            {\n                m_value.number_float = 0.0;\n                break;\n            }\n\n            case value_t::boolean:\n            {\n                m_value.boolean = false;\n                break;\n            }\n\n            case value_t::string:\n            {\n                m_value.string->clear();\n                break;\n            }\n\n            case value_t::array:\n            {\n                m_value.array->clear();\n                break;\n            }\n\n            case value_t::object:\n            {\n                m_value.object->clear();\n                break;\n            }\n\n            default:\n                break;\n        }\n    }\n\n    /*!\n    @brief add an object to an array\n\n    Appends the given element @a val to the end of the JSON value. If the\n    function is called on a JSON null value, an empty array is created before\n    appending @a val.\n\n    @param[in] val the value to add to the JSON array\n\n    @throw type_error.308 when called on a type other than JSON array or\n    null; example: `\"cannot use push_back() with number\"`\n\n    @complexity Amortized constant.\n\n    @liveexample{The example shows how `push_back()` and `+=` can be used to\n    add elements to a JSON array. Note how the `null` value was silently\n    converted to a JSON array.,push_back}\n\n    @since version 1.0.0\n    */\n    void push_back(basic_json&& val)\n    {\n        // push_back only works for null objects or arrays\n        if (JSON_UNLIKELY(not(is_null() or is_array())))\n        {\n            JSON_THROW(type_error::create(308, \"cannot use push_back() with \" + std::string(type_name())));\n        }\n\n        // transform null object into an array\n        if (is_null())\n        {\n            m_type = value_t::array;\n            m_value = value_t::array;\n            assert_invariant();\n        }\n\n        // add element to array (move semantics)\n        m_value.array->push_back(std::move(val));\n        // invalidate object\n        val.m_type = value_t::null;\n    }\n\n    /*!\n    @brief add an object to an array\n    @copydoc push_back(basic_json&&)\n    */\n    reference operator+=(basic_json&& val)\n    {\n        push_back(std::move(val));\n        return *this;\n    }\n\n    /*!\n    @brief add an object to an array\n    @copydoc push_back(basic_json&&)\n    */\n    void push_back(const basic_json& val)\n    {\n        // push_back only works for null objects or arrays\n        if (JSON_UNLIKELY(not(is_null() or is_array())))\n        {\n            JSON_THROW(type_error::create(308, \"cannot use push_back() with \" + std::string(type_name())));\n        }\n\n        // transform null object into an array\n        if (is_null())\n        {\n            m_type = value_t::array;\n            m_value = value_t::array;\n            assert_invariant();\n        }\n\n        // add element to array\n        m_value.array->push_back(val);\n    }\n\n    /*!\n    @brief add an object to an array\n    @copydoc push_back(basic_json&&)\n    */\n    reference operator+=(const basic_json& val)\n    {\n        push_back(val);\n        return *this;\n    }\n\n    /*!\n    @brief add an object to an object\n\n    Inserts the given element @a val to the JSON object. If the function is\n    called on a JSON null value, an empty object is created before inserting\n    @a val.\n\n    @param[in] val the value to add to the JSON object\n\n    @throw type_error.308 when called on a type other than JSON object or\n    null; example: `\"cannot use push_back() with number\"`\n\n    @complexity Logarithmic in the size of the container, O(log(`size()`)).\n\n    @liveexample{The example shows how `push_back()` and `+=` can be used to\n    add elements to a JSON object. Note how the `null` value was silently\n    converted to a JSON object.,push_back__object_t__value}\n\n    @since version 1.0.0\n    */\n    void push_back(const typename object_t::value_type& val)\n    {\n        // push_back only works for null objects or objects\n        if (JSON_UNLIKELY(not(is_null() or is_object())))\n        {\n            JSON_THROW(type_error::create(308, \"cannot use push_back() with \" + std::string(type_name())));\n        }\n\n        // transform null object into an object\n        if (is_null())\n        {\n            m_type = value_t::object;\n            m_value = value_t::object;\n            assert_invariant();\n        }\n\n        // add element to array\n        m_value.object->insert(val);\n    }\n\n    /*!\n    @brief add an object to an object\n    @copydoc push_back(const typename object_t::value_type&)\n    */\n    reference operator+=(const typename object_t::value_type& val)\n    {\n        push_back(val);\n        return *this;\n    }\n\n    /*!\n    @brief add an object to an object\n\n    This function allows to use `push_back` with an initializer list. In case\n\n    1. the current value is an object,\n    2. the initializer list @a init contains only two elements, and\n    3. the first element of @a init is a string,\n\n    @a init is converted into an object element and added using\n    @ref push_back(const typename object_t::value_type&). Otherwise, @a init\n    is converted to a JSON value and added using @ref push_back(basic_json&&).\n\n    @param[in] init  an initializer list\n\n    @complexity Linear in the size of the initializer list @a init.\n\n    @note This function is required to resolve an ambiguous overload error,\n          because pairs like `{\"key\", \"value\"}` can be both interpreted as\n          `object_t::value_type` or `std::initializer_list<basic_json>`, see\n          https://github.com/nlohmann/json/issues/235 for more information.\n\n    @liveexample{The example shows how initializer lists are treated as\n    objects when possible.,push_back__initializer_list}\n    */\n    void push_back(initializer_list_t init)\n    {\n        if (is_object() and init.size() == 2 and (*init.begin())->is_string())\n        {\n            basic_json&& key = init.begin()->moved_or_copied();\n            push_back(typename object_t::value_type(\n                          std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));\n        }\n        else\n        {\n            push_back(basic_json(init));\n        }\n    }\n\n    /*!\n    @brief add an object to an object\n    @copydoc push_back(initializer_list_t)\n    */\n    reference operator+=(initializer_list_t init)\n    {\n        push_back(init);\n        return *this;\n    }\n\n    /*!\n    @brief add an object to an array\n\n    Creates a JSON value from the passed parameters @a args to the end of the\n    JSON value. If the function is called on a JSON null value, an empty array\n    is created before appending the value created from @a args.\n\n    @param[in] args arguments to forward to a constructor of @ref basic_json\n    @tparam Args compatible types to create a @ref basic_json object\n\n    @throw type_error.311 when called on a type other than JSON array or\n    null; example: `\"cannot use emplace_back() with number\"`\n\n    @complexity Amortized constant.\n\n    @liveexample{The example shows how `push_back()` can be used to add\n    elements to a JSON array. Note how the `null` value was silently converted\n    to a JSON array.,emplace_back}\n\n    @since version 2.0.8\n    */\n    template<class... Args>\n    void emplace_back(Args&& ... args)\n    {\n        // emplace_back only works for null objects or arrays\n        if (JSON_UNLIKELY(not(is_null() or is_array())))\n        {\n            JSON_THROW(type_error::create(311, \"cannot use emplace_back() with \" + std::string(type_name())));\n        }\n\n        // transform null object into an array\n        if (is_null())\n        {\n            m_type = value_t::array;\n            m_value = value_t::array;\n            assert_invariant();\n        }\n\n        // add element to array (perfect forwarding)\n        m_value.array->emplace_back(std::forward<Args>(args)...);\n    }\n\n    /*!\n    @brief add an object to an object if key does not exist\n\n    Inserts a new element into a JSON object constructed in-place with the\n    given @a args if there is no element with the key in the container. If the\n    function is called on a JSON null value, an empty object is created before\n    appending the value created from @a args.\n\n    @param[in] args arguments to forward to a constructor of @ref basic_json\n    @tparam Args compatible types to create a @ref basic_json object\n\n    @return a pair consisting of an iterator to the inserted element, or the\n            already-existing element if no insertion happened, and a bool\n            denoting whether the insertion took place.\n\n    @throw type_error.311 when called on a type other than JSON object or\n    null; example: `\"cannot use emplace() with number\"`\n\n    @complexity Logarithmic in the size of the container, O(log(`size()`)).\n\n    @liveexample{The example shows how `emplace()` can be used to add elements\n    to a JSON object. Note how the `null` value was silently converted to a\n    JSON object. Further note how no value is added if there was already one\n    value stored with the same key.,emplace}\n\n    @since version 2.0.8\n    */\n    template<class... Args>\n    std::pair<iterator, bool> emplace(Args&& ... args)\n    {\n        // emplace only works for null objects or arrays\n        if (JSON_UNLIKELY(not(is_null() or is_object())))\n        {\n            JSON_THROW(type_error::create(311, \"cannot use emplace() with \" + std::string(type_name())));\n        }\n\n        // transform null object into an object\n        if (is_null())\n        {\n            m_type = value_t::object;\n            m_value = value_t::object;\n            assert_invariant();\n        }\n\n        // add element to array (perfect forwarding)\n        auto res = m_value.object->emplace(std::forward<Args>(args)...);\n        // create result iterator and set iterator to the result of emplace\n        auto it = begin();\n        it.m_it.object_iterator = res.first;\n\n        // return pair of iterator and boolean\n        return {it, res.second};\n    }\n\n    /*!\n    @brief inserts element\n\n    Inserts element @a val before iterator @a pos.\n\n    @param[in] pos iterator before which the content will be inserted; may be\n    the end() iterator\n    @param[in] val element to insert\n    @return iterator pointing to the inserted @a val.\n\n    @throw type_error.309 if called on JSON values other than arrays;\n    example: `\"cannot use insert() with string\"`\n    @throw invalid_iterator.202 if @a pos is not an iterator of *this;\n    example: `\"iterator does not fit current value\"`\n\n    @complexity Constant plus linear in the distance between @a pos and end of\n    the container.\n\n    @liveexample{The example shows how `insert()` is used.,insert}\n\n    @since version 1.0.0\n    */\n    iterator insert(const_iterator pos, const basic_json& val)\n    {\n        // insert only works for arrays\n        if (JSON_LIKELY(is_array()))\n        {\n            // check if iterator pos fits to this JSON value\n            if (JSON_UNLIKELY(pos.m_object != this))\n            {\n                JSON_THROW(invalid_iterator::create(202, \"iterator does not fit current value\"));\n            }\n\n            // insert to array and return iterator\n            iterator result(this);\n            result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);\n            return result;\n        }\n\n        JSON_THROW(type_error::create(309, \"cannot use insert() with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief inserts element\n    @copydoc insert(const_iterator, const basic_json&)\n    */\n    iterator insert(const_iterator pos, basic_json&& val)\n    {\n        return insert(pos, val);\n    }\n\n    /*!\n    @brief inserts elements\n\n    Inserts @a cnt copies of @a val before iterator @a pos.\n\n    @param[in] pos iterator before which the content will be inserted; may be\n    the end() iterator\n    @param[in] cnt number of copies of @a val to insert\n    @param[in] val element to insert\n    @return iterator pointing to the first element inserted, or @a pos if\n    `cnt==0`\n\n    @throw type_error.309 if called on JSON values other than arrays; example:\n    `\"cannot use insert() with string\"`\n    @throw invalid_iterator.202 if @a pos is not an iterator of *this;\n    example: `\"iterator does not fit current value\"`\n\n    @complexity Linear in @a cnt plus linear in the distance between @a pos\n    and end of the container.\n\n    @liveexample{The example shows how `insert()` is used.,insert__count}\n\n    @since version 1.0.0\n    */\n    iterator insert(const_iterator pos, size_type cnt, const basic_json& val)\n    {\n        // insert only works for arrays\n        if (JSON_LIKELY(is_array()))\n        {\n            // check if iterator pos fits to this JSON value\n            if (JSON_UNLIKELY(pos.m_object != this))\n            {\n                JSON_THROW(invalid_iterator::create(202, \"iterator does not fit current value\"));\n            }\n\n            // insert to array and return iterator\n            iterator result(this);\n            result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);\n            return result;\n        }\n\n        JSON_THROW(type_error::create(309, \"cannot use insert() with \" + std::string(type_name())));\n    }\n\n    /*!\n    @brief inserts elements\n\n    Inserts elements from range `[first, last)` before iterator @a pos.\n\n    @param[in] pos iterator before which the content will be inserted; may be\n    the end() iterator\n    @param[in] first begin of the range of elements to insert\n    @param[in] last end of the range of elements to insert\n\n    @throw type_error.309 if called on JSON values other than arrays; example:\n    `\"cannot use insert() with string\"`\n    @throw invalid_iterator.202 if @a pos is not an iterator of *this;\n    example: `\"iterator does not fit current value\"`\n    @throw invalid_iterator.210 if @a first and @a last do not belong to the\n    same JSON value; example: `\"iterators do not fit\"`\n    @throw invalid_iterator.211 if @a first or @a last are iterators into\n    container for which insert is called; example: `\"passed iterators may not\n    belong to container\"`\n\n    @return iterator pointing to the first element inserted, or @a pos if\n    `first==last`\n\n    @complexity Linear in `std::distance(first, last)` plus linear in the\n    distance between @a pos and end of the container.\n\n    @liveexample{The example shows how `insert()` is used.,insert__range}\n\n    @since version 1.0.0\n    */\n    iterator insert(const_iterator pos, const_iterator first, const_iterator last)\n    {\n        // insert only works for arrays\n        if (JSON_UNLIKELY(not is_array()))\n        {\n            JSON_THROW(type_error::create(309, \"cannot use insert() with \" + std::string(type_name())));\n        }\n\n        // check if iterator pos fits to this JSON value\n        if (JSON_UNLIKELY(pos.m_object != this))\n        {\n            JSON_THROW(invalid_iterator::create(202, \"iterator does not fit current value\"));\n        }\n\n        // check if range iterators belong to the same JSON object\n        if (JSON_UNLIKELY(first.m_object != last.m_object))\n        {\n            JSON_THROW(invalid_iterator::create(210, \"iterators do not fit\"));\n        }\n\n        if (JSON_UNLIKELY(first.m_object == this))\n        {\n            JSON_THROW(invalid_iterator::create(211, \"passed iterators may not belong to container\"));\n        }\n\n        // insert to array and return iterator\n        iterator result(this);\n        result.m_it.array_iterator = m_value.array->insert(\n                                         pos.m_it.array_iterator,\n                                         first.m_it.array_iterator,\n                                         last.m_it.array_iterator);\n        return result;\n    }\n\n    /*!\n    @brief inserts elements\n\n    Inserts elements from initializer list @a ilist before iterator @a pos.\n\n    @param[in] pos iterator before which the content will be inserted; may be\n    the end() iterator\n    @param[in] ilist initializer list to insert the values from\n\n    @throw type_error.309 if called on JSON values other than arrays; example:\n    `\"cannot use insert() with string\"`\n    @throw invalid_iterator.202 if @a pos is not an iterator of *this;\n    example: `\"iterator does not fit current value\"`\n\n    @return iterator pointing to the first element inserted, or @a pos if\n    `ilist` is empty\n\n    @complexity Linear in `ilist.size()` plus linear in the distance between\n    @a pos and end of the container.\n\n    @liveexample{The example shows how `insert()` is used.,insert__ilist}\n\n    @since version 1.0.0\n    */\n    iterator insert(const_iterator pos, initializer_list_t ilist)\n    {\n        // insert only works for arrays\n        if (JSON_UNLIKELY(not is_array()))\n        {\n            JSON_THROW(type_error::create(309, \"cannot use insert() with \" + std::string(type_name())));\n        }\n\n        // check if iterator pos fits to this JSON value\n        if (JSON_UNLIKELY(pos.m_object != this))\n        {\n            JSON_THROW(invalid_iterator::create(202, \"iterator does not fit current value\"));\n        }\n\n        // insert to array and return iterator\n        iterator result(this);\n        result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist.begin(), ilist.end());\n        return result;\n    }\n\n    /*!\n    @brief inserts elements\n\n    Inserts elements from range `[first, last)`.\n\n    @param[in] first begin of the range of elements to insert\n    @param[in] last end of the range of elements to insert\n\n    @throw type_error.309 if called on JSON values other than objects; example:\n    `\"cannot use insert() with string\"`\n    @throw invalid_iterator.202 if iterator @a first or @a last does does not\n    point to an object; example: `\"iterators first and last must point to\n    objects\"`\n    @throw invalid_iterator.210 if @a first and @a last do not belong to the\n    same JSON value; example: `\"iterators do not fit\"`\n\n    @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number\n    of elements to insert.\n\n    @liveexample{The example shows how `insert()` is used.,insert__range_object}\n\n    @since version 3.0.0\n    */\n    void insert(const_iterator first, const_iterator last)\n    {\n        // insert only works for objects\n        if (JSON_UNLIKELY(not is_object()))\n        {\n            JSON_THROW(type_error::create(309, \"cannot use insert() with \" + std::string(type_name())));\n        }\n\n        // check if range iterators belong to the same JSON object\n        if (JSON_UNLIKELY(first.m_object != last.m_object))\n        {\n            JSON_THROW(invalid_iterator::create(210, \"iterators do not fit\"));\n        }\n\n        // passed iterators must belong to objects\n        if (JSON_UNLIKELY(not first.m_object->is_object()))\n        {\n            JSON_THROW(invalid_iterator::create(202, \"iterators first and last must point to objects\"));\n        }\n\n        m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);\n    }\n\n    /*!\n    @brief updates a JSON object from another object, overwriting existing keys\n\n    Inserts all values from JSON object @a j and overwrites existing keys.\n\n    @param[in] j  JSON object to read values from\n\n    @throw type_error.312 if called on JSON values other than objects; example:\n    `\"cannot use update() with string\"`\n\n    @complexity O(N*log(size() + N)), where N is the number of elements to\n                insert.\n\n    @liveexample{The example shows how `update()` is used.,update}\n\n    @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update\n\n    @since version 3.0.0\n    */\n    void update(const_reference j)\n    {\n        // implicitly convert null value to an empty object\n        if (is_null())\n        {\n            m_type = value_t::object;\n            m_value.object = create<object_t>();\n            assert_invariant();\n        }\n\n        if (JSON_UNLIKELY(not is_object()))\n        {\n            JSON_THROW(type_error::create(312, \"cannot use update() with \" + std::string(type_name())));\n        }\n        if (JSON_UNLIKELY(not j.is_object()))\n        {\n            JSON_THROW(type_error::create(312, \"cannot use update() with \" + std::string(j.type_name())));\n        }\n\n        for (auto it = j.cbegin(); it != j.cend(); ++it)\n        {\n            m_value.object->operator[](it.key()) = it.value();\n        }\n    }\n\n    /*!\n    @brief updates a JSON object from another object, overwriting existing keys\n\n    Inserts all values from from range `[first, last)` and overwrites existing\n    keys.\n\n    @param[in] first begin of the range of elements to insert\n    @param[in] last end of the range of elements to insert\n\n    @throw type_error.312 if called on JSON values other than objects; example:\n    `\"cannot use update() with string\"`\n    @throw invalid_iterator.202 if iterator @a first or @a last does does not\n    point to an object; example: `\"iterators first and last must point to\n    objects\"`\n    @throw invalid_iterator.210 if @a first and @a last do not belong to the\n    same JSON value; example: `\"iterators do not fit\"`\n\n    @complexity O(N*log(size() + N)), where N is the number of elements to\n                insert.\n\n    @liveexample{The example shows how `update()` is used__range.,update}\n\n    @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update\n\n    @since version 3.0.0\n    */\n    void update(const_iterator first, const_iterator last)\n    {\n        // implicitly convert null value to an empty object\n        if (is_null())\n        {\n            m_type = value_t::object;\n            m_value.object = create<object_t>();\n            assert_invariant();\n        }\n\n        if (JSON_UNLIKELY(not is_object()))\n        {\n            JSON_THROW(type_error::create(312, \"cannot use update() with \" + std::string(type_name())));\n        }\n\n        // check if range iterators belong to the same JSON object\n        if (JSON_UNLIKELY(first.m_object != last.m_object))\n        {\n            JSON_THROW(invalid_iterator::create(210, \"iterators do not fit\"));\n        }\n\n        // passed iterators must belong to objects\n        if (JSON_UNLIKELY(not first.m_object->is_object()\n                          or not first.m_object->is_object()))\n        {\n            JSON_THROW(invalid_iterator::create(202, \"iterators first and last must point to objects\"));\n        }\n\n        for (auto it = first; it != last; ++it)\n        {\n            m_value.object->operator[](it.key()) = it.value();\n        }\n    }\n\n    /*!\n    @brief exchanges the values\n\n    Exchanges the contents of the JSON value with those of @a other. Does not\n    invoke any move, copy, or swap operations on individual elements. All\n    iterators and references remain valid. The past-the-end iterator is\n    invalidated.\n\n    @param[in,out] other JSON value to exchange the contents with\n\n    @complexity Constant.\n\n    @liveexample{The example below shows how JSON values can be swapped with\n    `swap()`.,swap__reference}\n\n    @since version 1.0.0\n    */\n    void swap(reference other) noexcept (\n        std::is_nothrow_move_constructible<value_t>::value and\n        std::is_nothrow_move_assignable<value_t>::value and\n        std::is_nothrow_move_constructible<json_value>::value and\n        std::is_nothrow_move_assignable<json_value>::value\n    )\n    {\n        std::swap(m_type, other.m_type);\n        std::swap(m_value, other.m_value);\n        assert_invariant();\n    }\n\n    /*!\n    @brief exchanges the values\n\n    Exchanges the contents of a JSON array with those of @a other. Does not\n    invoke any move, copy, or swap operations on individual elements. All\n    iterators and references remain valid. The past-the-end iterator is\n    invalidated.\n\n    @param[in,out] other array to exchange the contents with\n\n    @throw type_error.310 when JSON value is not an array; example: `\"cannot\n    use swap() with string\"`\n\n    @complexity Constant.\n\n    @liveexample{The example below shows how arrays can be swapped with\n    `swap()`.,swap__array_t}\n\n    @since version 1.0.0\n    */\n    void swap(array_t& other)\n    {\n        // swap only works for arrays\n        if (JSON_LIKELY(is_array()))\n        {\n            std::swap(*(m_value.array), other);\n        }\n        else\n        {\n            JSON_THROW(type_error::create(310, \"cannot use swap() with \" + std::string(type_name())));\n        }\n    }\n\n    /*!\n    @brief exchanges the values\n\n    Exchanges the contents of a JSON object with those of @a other. Does not\n    invoke any move, copy, or swap operations on individual elements. All\n    iterators and references remain valid. The past-the-end iterator is\n    invalidated.\n\n    @param[in,out] other object to exchange the contents with\n\n    @throw type_error.310 when JSON value is not an object; example:\n    `\"cannot use swap() with string\"`\n\n    @complexity Constant.\n\n    @liveexample{The example below shows how objects can be swapped with\n    `swap()`.,swap__object_t}\n\n    @since version 1.0.0\n    */\n    void swap(object_t& other)\n    {\n        // swap only works for objects\n        if (JSON_LIKELY(is_object()))\n        {\n            std::swap(*(m_value.object), other);\n        }\n        else\n        {\n            JSON_THROW(type_error::create(310, \"cannot use swap() with \" + std::string(type_name())));\n        }\n    }\n\n    /*!\n    @brief exchanges the values\n\n    Exchanges the contents of a JSON string with those of @a other. Does not\n    invoke any move, copy, or swap operations on individual elements. All\n    iterators and references remain valid. The past-the-end iterator is\n    invalidated.\n\n    @param[in,out] other string to exchange the contents with\n\n    @throw type_error.310 when JSON value is not a string; example: `\"cannot\n    use swap() with boolean\"`\n\n    @complexity Constant.\n\n    @liveexample{The example below shows how strings can be swapped with\n    `swap()`.,swap__string_t}\n\n    @since version 1.0.0\n    */\n    void swap(string_t& other)\n    {\n        // swap only works for strings\n        if (JSON_LIKELY(is_string()))\n        {\n            std::swap(*(m_value.string), other);\n        }\n        else\n        {\n            JSON_THROW(type_error::create(310, \"cannot use swap() with \" + std::string(type_name())));\n        }\n    }\n\n    /// @}\n\n  public:\n    //////////////////////////////////////////\n    // lexicographical comparison operators //\n    //////////////////////////////////////////\n\n    /// @name lexicographical comparison operators\n    /// @{\n\n    /*!\n    @brief comparison: equal\n\n    Compares two JSON values for equality according to the following rules:\n    - Two JSON values are equal if (1) they are from the same type and (2)\n      their stored values are the same according to their respective\n      `operator==`.\n    - Integer and floating-point numbers are automatically converted before\n      comparison. Note than two NaN values are always treated as unequal.\n    - Two JSON null values are equal.\n\n    @note Floating-point inside JSON values numbers are compared with\n    `json::number_float_t::operator==` which is `double::operator==` by\n    default. To compare floating-point while respecting an epsilon, an alternative\n    [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)\n    could be used, for instance\n    @code {.cpp}\n    template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>\n    inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept\n    {\n        return std::abs(a - b) <= epsilon;\n    }\n    @endcode\n\n    @note NaN values never compare equal to themselves or to other NaN values.\n\n    @param[in] lhs  first JSON value to consider\n    @param[in] rhs  second JSON value to consider\n    @return whether the values @a lhs and @a rhs are equal\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @complexity Linear.\n\n    @liveexample{The example demonstrates comparing several JSON\n    types.,operator__equal}\n\n    @since version 1.0.0\n    */\n    friend bool operator==(const_reference lhs, const_reference rhs) noexcept\n    {\n        const auto lhs_type = lhs.type();\n        const auto rhs_type = rhs.type();\n\n        if (lhs_type == rhs_type)\n        {\n            switch (lhs_type)\n            {\n                case value_t::array:\n                    return (*lhs.m_value.array == *rhs.m_value.array);\n\n                case value_t::object:\n                    return (*lhs.m_value.object == *rhs.m_value.object);\n\n                case value_t::null:\n                    return true;\n\n                case value_t::string:\n                    return (*lhs.m_value.string == *rhs.m_value.string);\n\n                case value_t::boolean:\n                    return (lhs.m_value.boolean == rhs.m_value.boolean);\n\n                case value_t::number_integer:\n                    return (lhs.m_value.number_integer == rhs.m_value.number_integer);\n\n                case value_t::number_unsigned:\n                    return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned);\n\n                case value_t::number_float:\n                    return (lhs.m_value.number_float == rhs.m_value.number_float);\n\n                default:\n                    return false;\n            }\n        }\n        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)\n        {\n            return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float);\n        }\n        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)\n        {\n            return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer));\n        }\n        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)\n        {\n            return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float);\n        }\n        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)\n        {\n            return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned));\n        }\n        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)\n        {\n            return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer);\n        }\n        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)\n        {\n            return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned));\n        }\n\n        return false;\n    }\n\n    /*!\n    @brief comparison: equal\n    @copydoc operator==(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept\n    {\n        return (lhs == basic_json(rhs));\n    }\n\n    /*!\n    @brief comparison: equal\n    @copydoc operator==(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept\n    {\n        return (basic_json(lhs) == rhs);\n    }\n\n    /*!\n    @brief comparison: not equal\n\n    Compares two JSON values for inequality by calculating `not (lhs == rhs)`.\n\n    @param[in] lhs  first JSON value to consider\n    @param[in] rhs  second JSON value to consider\n    @return whether the values @a lhs and @a rhs are not equal\n\n    @complexity Linear.\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @liveexample{The example demonstrates comparing several JSON\n    types.,operator__notequal}\n\n    @since version 1.0.0\n    */\n    friend bool operator!=(const_reference lhs, const_reference rhs) noexcept\n    {\n        return not (lhs == rhs);\n    }\n\n    /*!\n    @brief comparison: not equal\n    @copydoc operator!=(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept\n    {\n        return (lhs != basic_json(rhs));\n    }\n\n    /*!\n    @brief comparison: not equal\n    @copydoc operator!=(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept\n    {\n        return (basic_json(lhs) != rhs);\n    }\n\n    /*!\n    @brief comparison: less than\n\n    Compares whether one JSON value @a lhs is less than another JSON value @a\n    rhs according to the following rules:\n    - If @a lhs and @a rhs have the same type, the values are compared using\n      the default `<` operator.\n    - Integer and floating-point numbers are automatically converted before\n      comparison\n    - In case @a lhs and @a rhs have different types, the values are ignored\n      and the order of the types is considered, see\n      @ref operator<(const value_t, const value_t).\n\n    @param[in] lhs  first JSON value to consider\n    @param[in] rhs  second JSON value to consider\n    @return whether @a lhs is less than @a rhs\n\n    @complexity Linear.\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @liveexample{The example demonstrates comparing several JSON\n    types.,operator__less}\n\n    @since version 1.0.0\n    */\n    friend bool operator<(const_reference lhs, const_reference rhs) noexcept\n    {\n        const auto lhs_type = lhs.type();\n        const auto rhs_type = rhs.type();\n\n        if (lhs_type == rhs_type)\n        {\n            switch (lhs_type)\n            {\n                case value_t::array:\n                    return (*lhs.m_value.array) < (*rhs.m_value.array);\n\n                case value_t::object:\n                    return *lhs.m_value.object < *rhs.m_value.object;\n\n                case value_t::null:\n                    return false;\n\n                case value_t::string:\n                    return *lhs.m_value.string < *rhs.m_value.string;\n\n                case value_t::boolean:\n                    return lhs.m_value.boolean < rhs.m_value.boolean;\n\n                case value_t::number_integer:\n                    return lhs.m_value.number_integer < rhs.m_value.number_integer;\n\n                case value_t::number_unsigned:\n                    return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;\n\n                case value_t::number_float:\n                    return lhs.m_value.number_float < rhs.m_value.number_float;\n\n                default:\n                    return false;\n            }\n        }\n        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)\n        {\n            return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;\n        }\n        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)\n        {\n            return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);\n        }\n        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)\n        {\n            return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;\n        }\n        else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)\n        {\n            return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);\n        }\n        else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)\n        {\n            return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);\n        }\n        else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)\n        {\n            return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;\n        }\n\n        // We only reach this line if we cannot compare values. In that case,\n        // we compare types. Note we have to call the operator explicitly,\n        // because MSVC has problems otherwise.\n        return operator<(lhs_type, rhs_type);\n    }\n\n    /*!\n    @brief comparison: less than\n    @copydoc operator<(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept\n    {\n        return (lhs < basic_json(rhs));\n    }\n\n    /*!\n    @brief comparison: less than\n    @copydoc operator<(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept\n    {\n        return (basic_json(lhs) < rhs);\n    }\n\n    /*!\n    @brief comparison: less than or equal\n\n    Compares whether one JSON value @a lhs is less than or equal to another\n    JSON value by calculating `not (rhs < lhs)`.\n\n    @param[in] lhs  first JSON value to consider\n    @param[in] rhs  second JSON value to consider\n    @return whether @a lhs is less than or equal to @a rhs\n\n    @complexity Linear.\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @liveexample{The example demonstrates comparing several JSON\n    types.,operator__greater}\n\n    @since version 1.0.0\n    */\n    friend bool operator<=(const_reference lhs, const_reference rhs) noexcept\n    {\n        return not (rhs < lhs);\n    }\n\n    /*!\n    @brief comparison: less than or equal\n    @copydoc operator<=(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept\n    {\n        return (lhs <= basic_json(rhs));\n    }\n\n    /*!\n    @brief comparison: less than or equal\n    @copydoc operator<=(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept\n    {\n        return (basic_json(lhs) <= rhs);\n    }\n\n    /*!\n    @brief comparison: greater than\n\n    Compares whether one JSON value @a lhs is greater than another\n    JSON value by calculating `not (lhs <= rhs)`.\n\n    @param[in] lhs  first JSON value to consider\n    @param[in] rhs  second JSON value to consider\n    @return whether @a lhs is greater than to @a rhs\n\n    @complexity Linear.\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @liveexample{The example demonstrates comparing several JSON\n    types.,operator__lessequal}\n\n    @since version 1.0.0\n    */\n    friend bool operator>(const_reference lhs, const_reference rhs) noexcept\n    {\n        return not (lhs <= rhs);\n    }\n\n    /*!\n    @brief comparison: greater than\n    @copydoc operator>(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept\n    {\n        return (lhs > basic_json(rhs));\n    }\n\n    /*!\n    @brief comparison: greater than\n    @copydoc operator>(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept\n    {\n        return (basic_json(lhs) > rhs);\n    }\n\n    /*!\n    @brief comparison: greater than or equal\n\n    Compares whether one JSON value @a lhs is greater than or equal to another\n    JSON value by calculating `not (lhs < rhs)`.\n\n    @param[in] lhs  first JSON value to consider\n    @param[in] rhs  second JSON value to consider\n    @return whether @a lhs is greater than or equal to @a rhs\n\n    @complexity Linear.\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @liveexample{The example demonstrates comparing several JSON\n    types.,operator__greaterequal}\n\n    @since version 1.0.0\n    */\n    friend bool operator>=(const_reference lhs, const_reference rhs) noexcept\n    {\n        return not (lhs < rhs);\n    }\n\n    /*!\n    @brief comparison: greater than or equal\n    @copydoc operator>=(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept\n    {\n        return (lhs >= basic_json(rhs));\n    }\n\n    /*!\n    @brief comparison: greater than or equal\n    @copydoc operator>=(const_reference, const_reference)\n    */\n    template<typename ScalarType, typename std::enable_if<\n                 std::is_scalar<ScalarType>::value, int>::type = 0>\n    friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept\n    {\n        return (basic_json(lhs) >= rhs);\n    }\n\n    /// @}\n\n    ///////////////////\n    // serialization //\n    ///////////////////\n\n    /// @name serialization\n    /// @{\n\n    /*!\n    @brief serialize to stream\n\n    Serialize the given JSON value @a j to the output stream @a o. The JSON\n    value will be serialized using the @ref dump member function.\n\n    - The indentation of the output can be controlled with the member variable\n      `width` of the output stream @a o. For instance, using the manipulator\n      `std::setw(4)` on @a o sets the indentation level to `4` and the\n      serialization result is the same as calling `dump(4)`.\n\n    - The indentation character can be controlled with the member variable\n      `fill` of the output stream @a o. For instance, the manipulator\n      `std::setfill('\\\\t')` sets indentation to use a tab character rather than\n      the default space character.\n\n    @param[in,out] o  stream to serialize to\n    @param[in] j  JSON value to serialize\n\n    @return the stream @a o\n\n    @throw type_error.316 if a string stored inside the JSON value is not\n                          UTF-8 encoded\n\n    @complexity Linear.\n\n    @liveexample{The example below shows the serialization with different\n    parameters to `width` to adjust the indentation level.,operator_serialize}\n\n    @since version 1.0.0; indentation character added in version 3.0.0\n    */\n    friend std::ostream& operator<<(std::ostream& o, const basic_json& j)\n    {\n        // read width member and use it as indentation parameter if nonzero\n        const bool pretty_print = (o.width() > 0);\n        const auto indentation = (pretty_print ? o.width() : 0);\n\n        // reset width to 0 for subsequent calls to this stream\n        o.width(0);\n\n        // do the actual serialization\n        serializer s(detail::output_adapter<char>(o), o.fill());\n        s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));\n        return o;\n    }\n\n    /*!\n    @brief serialize to stream\n    @deprecated This stream operator is deprecated and will be removed in a\n                future version of the library. Please use\n                @ref operator<<(std::ostream&, const basic_json&)\n                instead; that is, replace calls like `j >> o;` with `o << j;`.\n    @since version 1.0.0; deprecated since version 3.0.0\n    */\n    JSON_DEPRECATED\n    friend std::ostream& operator>>(const basic_json& j, std::ostream& o)\n    {\n        return o << j;\n    }\n\n    /// @}\n\n\n    /////////////////////\n    // deserialization //\n    /////////////////////\n\n    /// @name deserialization\n    /// @{\n\n    /*!\n    @brief deserialize from a compatible input\n\n    This function reads from a compatible input. Examples are:\n    - an array of 1-byte values\n    - strings with character/literal type with size of 1 byte\n    - input streams\n    - container with contiguous storage of 1-byte values. Compatible container\n      types include `std::vector`, `std::string`, `std::array`,\n      `std::valarray`, and `std::initializer_list`. Furthermore, C-style\n      arrays can be used with `std::begin()`/`std::end()`. User-defined\n      containers can be used as long as they implement random-access iterators\n      and a contiguous storage.\n\n    @pre Each element of the container has a size of 1 byte. Violating this\n    precondition yields undefined behavior. **This precondition is enforced\n    with a static assertion.**\n\n    @pre The container storage is contiguous. Violating this precondition\n    yields undefined behavior. **This precondition is enforced with an\n    assertion.**\n    @pre Each element of the container has a size of 1 byte. Violating this\n    precondition yields undefined behavior. **This precondition is enforced\n    with a static assertion.**\n\n    @warning There is no way to enforce all preconditions at compile-time. If\n             the function is called with a noncompliant container and with\n             assertions switched off, the behavior is undefined and will most\n             likely yield segmentation violation.\n\n    @param[in] i  input to read from\n    @param[in] cb  a parser callback function of type @ref parser_callback_t\n    which is used to control the deserialization by filtering unwanted values\n    (optional)\n\n    @return result of the deserialization\n\n    @throw parse_error.101 if a parse error occurs; example: `\"\"unexpected end\n    of input; expected string literal\"\"`\n    @throw parse_error.102 if to_unicode fails or surrogate error\n    @throw parse_error.103 if to_unicode fails\n\n    @complexity Linear in the length of the input. The parser is a predictive\n    LL(1) parser. The complexity can be higher if the parser callback function\n    @a cb has a super-linear complexity.\n\n    @note A UTF-8 byte order mark is silently ignored.\n\n    @liveexample{The example below demonstrates the `parse()` function reading\n    from an array.,parse__array__parser_callback_t}\n\n    @liveexample{The example below demonstrates the `parse()` function with\n    and without callback function.,parse__string__parser_callback_t}\n\n    @liveexample{The example below demonstrates the `parse()` function with\n    and without callback function.,parse__istream__parser_callback_t}\n\n    @liveexample{The example below demonstrates the `parse()` function reading\n    from a contiguous container.,parse__contiguouscontainer__parser_callback_t}\n\n    @since version 2.0.3 (contiguous containers)\n    */\n    static basic_json parse(detail::input_adapter i,\n                            const parser_callback_t cb = nullptr,\n                            const bool allow_exceptions = true)\n    {\n        basic_json result;\n        parser(i, cb, allow_exceptions).parse(true, result);\n        return result;\n    }\n\n    /*!\n    @copydoc basic_json parse(detail::input_adapter, const parser_callback_t)\n    */\n    static basic_json parse(detail::input_adapter& i,\n                            const parser_callback_t cb = nullptr,\n                            const bool allow_exceptions = true)\n    {\n        basic_json result;\n        parser(i, cb, allow_exceptions).parse(true, result);\n        return result;\n    }\n\n    static bool accept(detail::input_adapter i)\n    {\n        return parser(i).accept(true);\n    }\n\n    static bool accept(detail::input_adapter& i)\n    {\n        return parser(i).accept(true);\n    }\n\n    /*!\n    @brief deserialize from an iterator range with contiguous storage\n\n    This function reads from an iterator range of a container with contiguous\n    storage of 1-byte values. Compatible container types include\n    `std::vector`, `std::string`, `std::array`, `std::valarray`, and\n    `std::initializer_list`. Furthermore, C-style arrays can be used with\n    `std::begin()`/`std::end()`. User-defined containers can be used as long\n    as they implement random-access iterators and a contiguous storage.\n\n    @pre The iterator range is contiguous. Violating this precondition yields\n    undefined behavior. **This precondition is enforced with an assertion.**\n    @pre Each element in the range has a size of 1 byte. Violating this\n    precondition yields undefined behavior. **This precondition is enforced\n    with a static assertion.**\n\n    @warning There is no way to enforce all preconditions at compile-time. If\n             the function is called with noncompliant iterators and with\n             assertions switched off, the behavior is undefined and will most\n             likely yield segmentation violation.\n\n    @tparam IteratorType iterator of container with contiguous storage\n    @param[in] first  begin of the range to parse (included)\n    @param[in] last  end of the range to parse (excluded)\n    @param[in] cb  a parser callback function of type @ref parser_callback_t\n    which is used to control the deserialization by filtering unwanted values\n    (optional)\n    @param[in] allow_exceptions  whether to throw exceptions in case of a\n    parse error (optional, true by default)\n\n    @return result of the deserialization\n\n    @throw parse_error.101 in case of an unexpected token\n    @throw parse_error.102 if to_unicode fails or surrogate error\n    @throw parse_error.103 if to_unicode fails\n\n    @complexity Linear in the length of the input. The parser is a predictive\n    LL(1) parser. The complexity can be higher if the parser callback function\n    @a cb has a super-linear complexity.\n\n    @note A UTF-8 byte order mark is silently ignored.\n\n    @liveexample{The example below demonstrates the `parse()` function reading\n    from an iterator range.,parse__iteratortype__parser_callback_t}\n\n    @since version 2.0.3\n    */\n    template<class IteratorType, typename std::enable_if<\n                 std::is_base_of<\n                     std::random_access_iterator_tag,\n                     typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>\n    static basic_json parse(IteratorType first, IteratorType last,\n                            const parser_callback_t cb = nullptr,\n                            const bool allow_exceptions = true)\n    {\n        basic_json result;\n        parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);\n        return result;\n    }\n\n    template<class IteratorType, typename std::enable_if<\n                 std::is_base_of<\n                     std::random_access_iterator_tag,\n                     typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>\n    static bool accept(IteratorType first, IteratorType last)\n    {\n        return parser(detail::input_adapter(first, last)).accept(true);\n    }\n\n    /*!\n    @brief deserialize from stream\n    @deprecated This stream operator is deprecated and will be removed in a\n                future version of the library. Please use\n                @ref operator>>(std::istream&, basic_json&)\n                instead; that is, replace calls like `j << i;` with `i >> j;`.\n    @since version 1.0.0; deprecated since version 3.0.0\n    */\n    JSON_DEPRECATED\n    friend std::istream& operator<<(basic_json& j, std::istream& i)\n    {\n        return operator>>(i, j);\n    }\n\n    /*!\n    @brief deserialize from stream\n\n    Deserializes an input stream to a JSON value.\n\n    @param[in,out] i  input stream to read a serialized JSON value from\n    @param[in,out] j  JSON value to write the deserialized input to\n\n    @throw parse_error.101 in case of an unexpected token\n    @throw parse_error.102 if to_unicode fails or surrogate error\n    @throw parse_error.103 if to_unicode fails\n\n    @complexity Linear in the length of the input. The parser is a predictive\n    LL(1) parser.\n\n    @note A UTF-8 byte order mark is silently ignored.\n\n    @liveexample{The example below shows how a JSON value is constructed by\n    reading a serialization from a stream.,operator_deserialize}\n\n    @sa parse(std::istream&, const parser_callback_t) for a variant with a\n    parser callback function to filter values while parsing\n\n    @since version 1.0.0\n    */\n    friend std::istream& operator>>(std::istream& i, basic_json& j)\n    {\n        parser(detail::input_adapter(i)).parse(false, j);\n        return i;\n    }\n\n    /// @}\n\n    ///////////////////////////\n    // convenience functions //\n    ///////////////////////////\n\n    /*!\n    @brief return the type as string\n\n    Returns the type name as string to be used in error messages - usually to\n    indicate that a function was called on a wrong JSON type.\n\n    @return a string representation of a the @a m_type member:\n            Value type  | return value\n            ----------- | -------------\n            null        | `\"null\"`\n            boolean     | `\"boolean\"`\n            string      | `\"string\"`\n            number      | `\"number\"` (for all number types)\n            object      | `\"object\"`\n            array       | `\"array\"`\n            discarded   | `\"discarded\"`\n\n    @exceptionsafety No-throw guarantee: this function never throws exceptions.\n\n    @complexity Constant.\n\n    @liveexample{The following code exemplifies `type_name()` for all JSON\n    types.,type_name}\n\n    @sa @ref type() -- return the type of the JSON value\n    @sa @ref operator value_t() -- return the type of the JSON value (implicit)\n\n    @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`\n    since 3.0.0\n    */\n    const char* type_name() const noexcept\n    {\n        {\n            switch (m_type)\n            {\n                case value_t::null:\n                    return \"null\";\n                case value_t::object:\n                    return \"object\";\n                case value_t::array:\n                    return \"array\";\n                case value_t::string:\n                    return \"string\";\n                case value_t::boolean:\n                    return \"boolean\";\n                case value_t::discarded:\n                    return \"discarded\";\n                default:\n                    return \"number\";\n            }\n        }\n    }\n\n\n  private:\n    //////////////////////\n    // member variables //\n    //////////////////////\n\n    /// the type of the current element\n    value_t m_type = value_t::null;\n\n    /// the value of the current element\n    json_value m_value = {};\n\n    //////////////////////////////////////////\n    // binary serialization/deserialization //\n    //////////////////////////////////////////\n\n    /// @name binary serialization/deserialization support\n    /// @{\n\n  public:\n    /*!\n    @brief create a CBOR serialization of a given JSON value\n\n    Serializes a given JSON value @a j to a byte vector using the CBOR (Concise\n    Binary Object Representation) serialization format. CBOR is a binary\n    serialization format which aims to be more compact than JSON itself, yet\n    more efficient to parse.\n\n    The library uses the following mapping from JSON values types to\n    CBOR types according to the CBOR specification (RFC 7049):\n\n    JSON value type | value/range                                | CBOR type                          | first byte\n    --------------- | ------------------------------------------ | ---------------------------------- | ---------------\n    null            | `null`                                     | Null                               | 0xF6\n    boolean         | `true`                                     | True                               | 0xF5\n    boolean         | `false`                                    | False                              | 0xF4\n    number_integer  | -9223372036854775808..-2147483649          | Negative integer (8 bytes follow)  | 0x3B\n    number_integer  | -2147483648..-32769                        | Negative integer (4 bytes follow)  | 0x3A\n    number_integer  | -32768..-129                               | Negative integer (2 bytes follow)  | 0x39\n    number_integer  | -128..-25                                  | Negative integer (1 byte follow)   | 0x38\n    number_integer  | -24..-1                                    | Negative integer                   | 0x20..0x37\n    number_integer  | 0..23                                      | Integer                            | 0x00..0x17\n    number_integer  | 24..255                                    | Unsigned integer (1 byte follow)   | 0x18\n    number_integer  | 256..65535                                 | Unsigned integer (2 bytes follow)  | 0x19\n    number_integer  | 65536..4294967295                          | Unsigned integer (4 bytes follow)  | 0x1A\n    number_integer  | 4294967296..18446744073709551615           | Unsigned integer (8 bytes follow)  | 0x1B\n    number_unsigned | 0..23                                      | Integer                            | 0x00..0x17\n    number_unsigned | 24..255                                    | Unsigned integer (1 byte follow)   | 0x18\n    number_unsigned | 256..65535                                 | Unsigned integer (2 bytes follow)  | 0x19\n    number_unsigned | 65536..4294967295                          | Unsigned integer (4 bytes follow)  | 0x1A\n    number_unsigned | 4294967296..18446744073709551615           | Unsigned integer (8 bytes follow)  | 0x1B\n    number_float    | *any value*                                | Double-Precision Float             | 0xFB\n    string          | *length*: 0..23                            | UTF-8 string                       | 0x60..0x77\n    string          | *length*: 23..255                          | UTF-8 string (1 byte follow)       | 0x78\n    string          | *length*: 256..65535                       | UTF-8 string (2 bytes follow)      | 0x79\n    string          | *length*: 65536..4294967295                | UTF-8 string (4 bytes follow)      | 0x7A\n    string          | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow)      | 0x7B\n    array           | *size*: 0..23                              | array                              | 0x80..0x97\n    array           | *size*: 23..255                            | array (1 byte follow)              | 0x98\n    array           | *size*: 256..65535                         | array (2 bytes follow)             | 0x99\n    array           | *size*: 65536..4294967295                  | array (4 bytes follow)             | 0x9A\n    array           | *size*: 4294967296..18446744073709551615   | array (8 bytes follow)             | 0x9B\n    object          | *size*: 0..23                              | map                                | 0xA0..0xB7\n    object          | *size*: 23..255                            | map (1 byte follow)                | 0xB8\n    object          | *size*: 256..65535                         | map (2 bytes follow)               | 0xB9\n    object          | *size*: 65536..4294967295                  | map (4 bytes follow)               | 0xBA\n    object          | *size*: 4294967296..18446744073709551615   | map (8 bytes follow)               | 0xBB\n\n    @note The mapping is **complete** in the sense that any JSON value type\n          can be converted to a CBOR value.\n\n    @note If NaN or Infinity are stored inside a JSON number, they are\n          serialized properly. This behavior differs from the @ref dump()\n          function which serializes NaN or Infinity to `null`.\n\n    @note The following CBOR types are not used in the conversion:\n          - byte strings (0x40..0x5F)\n          - UTF-8 strings terminated by \"break\" (0x7F)\n          - arrays terminated by \"break\" (0x9F)\n          - maps terminated by \"break\" (0xBF)\n          - date/time (0xC0..0xC1)\n          - bignum (0xC2..0xC3)\n          - decimal fraction (0xC4)\n          - bigfloat (0xC5)\n          - tagged items (0xC6..0xD4, 0xD8..0xDB)\n          - expected conversions (0xD5..0xD7)\n          - simple values (0xE0..0xF3, 0xF8)\n          - undefined (0xF7)\n          - half and single-precision floats (0xF9-0xFA)\n          - break (0xFF)\n\n    @param[in] j  JSON value to serialize\n    @return MessagePack serialization as byte vector\n\n    @complexity Linear in the size of the JSON value @a j.\n\n    @liveexample{The example shows the serialization of a JSON value to a byte\n    vector in CBOR format.,to_cbor}\n\n    @sa http://cbor.io\n    @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the\n        analogous deserialization\n    @sa @ref to_msgpack(const basic_json&) for the related MessagePack format\n\n    @since version 2.0.9\n    */\n    static std::vector<uint8_t> to_cbor(const basic_json& j)\n    {\n        std::vector<uint8_t> result;\n        to_cbor(j, result);\n        return result;\n    }\n\n    static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)\n    {\n        binary_writer<uint8_t>(o).write_cbor(j);\n    }\n\n    static void to_cbor(const basic_json& j, detail::output_adapter<char> o)\n    {\n        binary_writer<char>(o).write_cbor(j);\n    }\n\n    /*!\n    @brief create a MessagePack serialization of a given JSON value\n\n    Serializes a given JSON value @a j to a byte vector using the MessagePack\n    serialization format. MessagePack is a binary serialization format which\n    aims to be more compact than JSON itself, yet more efficient to parse.\n\n    The library uses the following mapping from JSON values types to\n    MessagePack types according to the MessagePack specification:\n\n    JSON value type | value/range                       | MessagePack type | first byte\n    --------------- | --------------------------------- | ---------------- | ----------\n    null            | `null`                            | nil              | 0xC0\n    boolean         | `true`                            | true             | 0xC3\n    boolean         | `false`                           | false            | 0xC2\n    number_integer  | -9223372036854775808..-2147483649 | int64            | 0xD3\n    number_integer  | -2147483648..-32769               | int32            | 0xD2\n    number_integer  | -32768..-129                      | int16            | 0xD1\n    number_integer  | -128..-33                         | int8             | 0xD0\n    number_integer  | -32..-1                           | negative fixint  | 0xE0..0xFF\n    number_integer  | 0..127                            | positive fixint  | 0x00..0x7F\n    number_integer  | 128..255                          | uint 8           | 0xCC\n    number_integer  | 256..65535                        | uint 16          | 0xCD\n    number_integer  | 65536..4294967295                 | uint 32          | 0xCE\n    number_integer  | 4294967296..18446744073709551615  | uint 64          | 0xCF\n    number_unsigned | 0..127                            | positive fixint  | 0x00..0x7F\n    number_unsigned | 128..255                          | uint 8           | 0xCC\n    number_unsigned | 256..65535                        | uint 16          | 0xCD\n    number_unsigned | 65536..4294967295                 | uint 32          | 0xCE\n    number_unsigned | 4294967296..18446744073709551615  | uint 64          | 0xCF\n    number_float    | *any value*                       | float 64         | 0xCB\n    string          | *length*: 0..31                   | fixstr           | 0xA0..0xBF\n    string          | *length*: 32..255                 | str 8            | 0xD9\n    string          | *length*: 256..65535              | str 16           | 0xDA\n    string          | *length*: 65536..4294967295       | str 32           | 0xDB\n    array           | *size*: 0..15                     | fixarray         | 0x90..0x9F\n    array           | *size*: 16..65535                 | array 16         | 0xDC\n    array           | *size*: 65536..4294967295         | array 32         | 0xDD\n    object          | *size*: 0..15                     | fix map          | 0x80..0x8F\n    object          | *size*: 16..65535                 | map 16           | 0xDE\n    object          | *size*: 65536..4294967295         | map 32           | 0xDF\n\n    @note The mapping is **complete** in the sense that any JSON value type\n          can be converted to a MessagePack value.\n\n    @note The following values can **not** be converted to a MessagePack value:\n          - strings with more than 4294967295 bytes\n          - arrays with more than 4294967295 elements\n          - objects with more than 4294967295 elements\n\n    @note The following MessagePack types are not used in the conversion:\n          - bin 8 - bin 32 (0xC4..0xC6)\n          - ext 8 - ext 32 (0xC7..0xC9)\n          - float 32 (0xCA)\n          - fixext 1 - fixext 16 (0xD4..0xD8)\n\n    @note Any MessagePack output created @ref to_msgpack can be successfully\n          parsed by @ref from_msgpack.\n\n    @note If NaN or Infinity are stored inside a JSON number, they are\n          serialized properly. This behavior differs from the @ref dump()\n          function which serializes NaN or Infinity to `null`.\n\n    @param[in] j  JSON value to serialize\n    @return MessagePack serialization as byte vector\n\n    @complexity Linear in the size of the JSON value @a j.\n\n    @liveexample{The example shows the serialization of a JSON value to a byte\n    vector in MessagePack format.,to_msgpack}\n\n    @sa http://msgpack.org\n    @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the\n        analogous deserialization\n    @sa @ref to_cbor(const basic_json& for the related CBOR format\n\n    @since version 2.0.9\n    */\n    static std::vector<uint8_t> to_msgpack(const basic_json& j)\n    {\n        std::vector<uint8_t> result;\n        to_msgpack(j, result);\n        return result;\n    }\n\n    static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)\n    {\n        binary_writer<uint8_t>(o).write_msgpack(j);\n    }\n\n    static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)\n    {\n        binary_writer<char>(o).write_msgpack(j);\n    }\n\n    /*!\n    @brief create a JSON value from an input in CBOR format\n\n    Deserializes a given input @a i to a JSON value using the CBOR (Concise\n    Binary Object Representation) serialization format.\n\n    The library maps CBOR types to JSON value types as follows:\n\n    CBOR type              | JSON value type | first byte\n    ---------------------- | --------------- | ----------\n    Integer                | number_unsigned | 0x00..0x17\n    Unsigned integer       | number_unsigned | 0x18\n    Unsigned integer       | number_unsigned | 0x19\n    Unsigned integer       | number_unsigned | 0x1A\n    Unsigned integer       | number_unsigned | 0x1B\n    Negative integer       | number_integer  | 0x20..0x37\n    Negative integer       | number_integer  | 0x38\n    Negative integer       | number_integer  | 0x39\n    Negative integer       | number_integer  | 0x3A\n    Negative integer       | number_integer  | 0x3B\n    Negative integer       | number_integer  | 0x40..0x57\n    UTF-8 string           | string          | 0x60..0x77\n    UTF-8 string           | string          | 0x78\n    UTF-8 string           | string          | 0x79\n    UTF-8 string           | string          | 0x7A\n    UTF-8 string           | string          | 0x7B\n    UTF-8 string           | string          | 0x7F\n    array                  | array           | 0x80..0x97\n    array                  | array           | 0x98\n    array                  | array           | 0x99\n    array                  | array           | 0x9A\n    array                  | array           | 0x9B\n    array                  | array           | 0x9F\n    map                    | object          | 0xA0..0xB7\n    map                    | object          | 0xB8\n    map                    | object          | 0xB9\n    map                    | object          | 0xBA\n    map                    | object          | 0xBB\n    map                    | object          | 0xBF\n    False                  | `false`         | 0xF4\n    True                   | `true`          | 0xF5\n    Nill                   | `null`          | 0xF6\n    Half-Precision Float   | number_float    | 0xF9\n    Single-Precision Float | number_float    | 0xFA\n    Double-Precision Float | number_float    | 0xFB\n\n    @warning The mapping is **incomplete** in the sense that not all CBOR\n             types can be converted to a JSON value. The following CBOR types\n             are not supported and will yield parse errors (parse_error.112):\n             - byte strings (0x40..0x5F)\n             - date/time (0xC0..0xC1)\n             - bignum (0xC2..0xC3)\n             - decimal fraction (0xC4)\n             - bigfloat (0xC5)\n             - tagged items (0xC6..0xD4, 0xD8..0xDB)\n             - expected conversions (0xD5..0xD7)\n             - simple values (0xE0..0xF3, 0xF8)\n             - undefined (0xF7)\n\n    @warning CBOR allows map keys of any type, whereas JSON only allows\n             strings as keys in object values. Therefore, CBOR maps with keys\n             other than UTF-8 strings are rejected (parse_error.113).\n\n    @note Any CBOR output created @ref to_cbor can be successfully parsed by\n          @ref from_cbor.\n\n    @param[in] i  an input in CBOR format convertible to an input adapter\n    @param[in] strict  whether to expect the input to be consumed until EOF\n                       (true by default)\n    @return deserialized JSON value\n\n    @throw parse_error.110 if the given input ends prematurely or the end of\n    file was not reached when @a strict was set to true\n    @throw parse_error.112 if unsupported features from CBOR were\n    used in the given input @a v or if the input is not valid CBOR\n    @throw parse_error.113 if a string was expected as map key, but not found\n\n    @complexity Linear in the size of the input @a i.\n\n    @liveexample{The example shows the deserialization of a byte vector in CBOR\n    format to a JSON value.,from_cbor}\n\n    @sa http://cbor.io\n    @sa @ref to_cbor(const basic_json&) for the analogous serialization\n    @sa @ref from_msgpack(detail::input_adapter, const bool) for the\n        related MessagePack format\n\n    @since version 2.0.9; parameter @a start_index since 2.1.1; changed to\n           consume input adapters, removed start_index parameter, and added\n           @a strict parameter since 3.0.0\n    */\n    static basic_json from_cbor(detail::input_adapter i,\n                                const bool strict = true)\n    {\n        return binary_reader(i).parse_cbor(strict);\n    }\n\n    /*!\n    @copydoc from_cbor(detail::input_adapter, const bool)\n    */\n    template<typename A1, typename A2,\n             detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>\n    static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true)\n    {\n        return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_cbor(strict);\n    }\n\n    /*!\n    @brief create a JSON value from an input in MessagePack format\n\n    Deserializes a given input @a i to a JSON value using the MessagePack\n    serialization format.\n\n    The library maps MessagePack types to JSON value types as follows:\n\n    MessagePack type | JSON value type | first byte\n    ---------------- | --------------- | ----------\n    positive fixint  | number_unsigned | 0x00..0x7F\n    fixmap           | object          | 0x80..0x8F\n    fixarray         | array           | 0x90..0x9F\n    fixstr           | string          | 0xA0..0xBF\n    nil              | `null`          | 0xC0\n    false            | `false`         | 0xC2\n    true             | `true`          | 0xC3\n    float 32         | number_float    | 0xCA\n    float 64         | number_float    | 0xCB\n    uint 8           | number_unsigned | 0xCC\n    uint 16          | number_unsigned | 0xCD\n    uint 32          | number_unsigned | 0xCE\n    uint 64          | number_unsigned | 0xCF\n    int 8            | number_integer  | 0xD0\n    int 16           | number_integer  | 0xD1\n    int 32           | number_integer  | 0xD2\n    int 64           | number_integer  | 0xD3\n    str 8            | string          | 0xD9\n    str 16           | string          | 0xDA\n    str 32           | string          | 0xDB\n    array 16         | array           | 0xDC\n    array 32         | array           | 0xDD\n    map 16           | object          | 0xDE\n    map 32           | object          | 0xDF\n    negative fixint  | number_integer  | 0xE0-0xFF\n\n    @warning The mapping is **incomplete** in the sense that not all\n             MessagePack types can be converted to a JSON value. The following\n             MessagePack types are not supported and will yield parse errors:\n              - bin 8 - bin 32 (0xC4..0xC6)\n              - ext 8 - ext 32 (0xC7..0xC9)\n              - fixext 1 - fixext 16 (0xD4..0xD8)\n\n    @note Any MessagePack output created @ref to_msgpack can be successfully\n          parsed by @ref from_msgpack.\n\n    @param[in] i  an input in MessagePack format convertible to an input\n                  adapter\n    @param[in] strict  whether to expect the input to be consumed until EOF\n                       (true by default)\n\n    @throw parse_error.110 if the given input ends prematurely or the end of\n    file was not reached when @a strict was set to true\n    @throw parse_error.112 if unsupported features from MessagePack were\n    used in the given input @a i or if the input is not valid MessagePack\n    @throw parse_error.113 if a string was expected as map key, but not found\n\n    @complexity Linear in the size of the input @a i.\n\n    @liveexample{The example shows the deserialization of a byte vector in\n    MessagePack format to a JSON value.,from_msgpack}\n\n    @sa http://msgpack.org\n    @sa @ref to_msgpack(const basic_json&) for the analogous serialization\n    @sa @ref from_cbor(detail::input_adapter, const bool) for the related CBOR\n        format\n\n    @since version 2.0.9; parameter @a start_index since 2.1.1; changed to\n           consume input adapters, removed start_index parameter, and added\n           @a strict parameter since 3.0.0\n    */\n    static basic_json from_msgpack(detail::input_adapter i,\n                                   const bool strict = true)\n    {\n        return binary_reader(i).parse_msgpack(strict);\n    }\n\n    /*!\n    @copydoc from_msgpack(detail::input_adapter, const bool)\n    */\n    template<typename A1, typename A2,\n             detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>\n    static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true)\n    {\n        return binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).parse_msgpack(strict);\n    }\n\n    /// @}\n\n    //////////////////////////\n    // JSON Pointer support //\n    //////////////////////////\n\n    /// @name JSON Pointer functions\n    /// @{\n\n    /*!\n    @brief access specified element via JSON Pointer\n\n    Uses a JSON pointer to retrieve a reference to the respective JSON value.\n    No bound checking is performed. Similar to @ref operator[](const typename\n    object_t::key_type&), `null` values are created in arrays and objects if\n    necessary.\n\n    In particular:\n    - If the JSON pointer points to an object key that does not exist, it\n      is created an filled with a `null` value before a reference to it\n      is returned.\n    - If the JSON pointer points to an array index that does not exist, it\n      is created an filled with a `null` value before a reference to it\n      is returned. All indices between the current maximum and the given\n      index are also filled with `null`.\n    - The special value `-` is treated as a synonym for the index past the\n      end.\n\n    @param[in] ptr  a JSON pointer\n\n    @return reference to the element pointed to by @a ptr\n\n    @complexity Constant.\n\n    @throw parse_error.106   if an array index begins with '0'\n    @throw parse_error.109   if an array index was not a number\n    @throw out_of_range.404  if the JSON pointer can not be resolved\n\n    @liveexample{The behavior is shown in the example.,operatorjson_pointer}\n\n    @since version 2.0.0\n    */\n    reference operator[](const json_pointer& ptr)\n    {\n        return ptr.get_unchecked(this);\n    }\n\n    /*!\n    @brief access specified element via JSON Pointer\n\n    Uses a JSON pointer to retrieve a reference to the respective JSON value.\n    No bound checking is performed. The function does not change the JSON\n    value; no `null` values are created. In particular, the the special value\n    `-` yields an exception.\n\n    @param[in] ptr  JSON pointer to the desired element\n\n    @return const reference to the element pointed to by @a ptr\n\n    @complexity Constant.\n\n    @throw parse_error.106   if an array index begins with '0'\n    @throw parse_error.109   if an array index was not a number\n    @throw out_of_range.402  if the array index '-' is used\n    @throw out_of_range.404  if the JSON pointer can not be resolved\n\n    @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}\n\n    @since version 2.0.0\n    */\n    const_reference operator[](const json_pointer& ptr) const\n    {\n        return ptr.get_unchecked(this);\n    }\n\n    /*!\n    @brief access specified element via JSON Pointer\n\n    Returns a reference to the element at with specified JSON pointer @a ptr,\n    with bounds checking.\n\n    @param[in] ptr  JSON pointer to the desired element\n\n    @return reference to the element pointed to by @a ptr\n\n    @throw parse_error.106 if an array index in the passed JSON pointer @a ptr\n    begins with '0'. See example below.\n\n    @throw parse_error.109 if an array index in the passed JSON pointer @a ptr\n    is not a number. See example below.\n\n    @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr\n    is out of range. See example below.\n\n    @throw out_of_range.402 if the array index '-' is used in the passed JSON\n    pointer @a ptr. As `at` provides checked access (and no elements are\n    implicitly inserted), the index '-' is always invalid. See example below.\n\n    @throw out_of_range.403 if the JSON pointer describes a key of an object\n    which cannot be found. See example below.\n\n    @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.\n    See example below.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes in the JSON value.\n\n    @complexity Constant.\n\n    @since version 2.0.0\n\n    @liveexample{The behavior is shown in the example.,at_json_pointer}\n    */\n    reference at(const json_pointer& ptr)\n    {\n        return ptr.get_checked(this);\n    }\n\n    /*!\n    @brief access specified element via JSON Pointer\n\n    Returns a const reference to the element at with specified JSON pointer @a\n    ptr, with bounds checking.\n\n    @param[in] ptr  JSON pointer to the desired element\n\n    @return reference to the element pointed to by @a ptr\n\n    @throw parse_error.106 if an array index in the passed JSON pointer @a ptr\n    begins with '0'. See example below.\n\n    @throw parse_error.109 if an array index in the passed JSON pointer @a ptr\n    is not a number. See example below.\n\n    @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr\n    is out of range. See example below.\n\n    @throw out_of_range.402 if the array index '-' is used in the passed JSON\n    pointer @a ptr. As `at` provides checked access (and no elements are\n    implicitly inserted), the index '-' is always invalid. See example below.\n\n    @throw out_of_range.403 if the JSON pointer describes a key of an object\n    which cannot be found. See example below.\n\n    @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.\n    See example below.\n\n    @exceptionsafety Strong guarantee: if an exception is thrown, there are no\n    changes in the JSON value.\n\n    @complexity Constant.\n\n    @since version 2.0.0\n\n    @liveexample{The behavior is shown in the example.,at_json_pointer_const}\n    */\n    const_reference at(const json_pointer& ptr) const\n    {\n        return ptr.get_checked(this);\n    }\n\n    /*!\n    @brief return flattened JSON value\n\n    The function creates a JSON object whose keys are JSON pointers (see [RFC\n    6901](https://tools.ietf.org/html/rfc6901)) and whose values are all\n    primitive. The original JSON value can be restored using the @ref\n    unflatten() function.\n\n    @return an object that maps JSON pointers to primitive values\n\n    @note Empty objects and arrays are flattened to `null` and will not be\n          reconstructed correctly by the @ref unflatten() function.\n\n    @complexity Linear in the size the JSON value.\n\n    @liveexample{The following code shows how a JSON object is flattened to an\n    object whose keys consist of JSON pointers.,flatten}\n\n    @sa @ref unflatten() for the reverse function\n\n    @since version 2.0.0\n    */\n    basic_json flatten() const\n    {\n        basic_json result(value_t::object);\n        json_pointer::flatten(\"\", *this, result);\n        return result;\n    }\n\n    /*!\n    @brief unflatten a previously flattened JSON value\n\n    The function restores the arbitrary nesting of a JSON value that has been\n    flattened before using the @ref flatten() function. The JSON value must\n    meet certain constraints:\n    1. The value must be an object.\n    2. The keys must be JSON pointers (see\n       [RFC 6901](https://tools.ietf.org/html/rfc6901))\n    3. The mapped values must be primitive JSON types.\n\n    @return the original JSON from a flattened version\n\n    @note Empty objects and arrays are flattened by @ref flatten() to `null`\n          values and can not unflattened to their original type. Apart from\n          this example, for a JSON value `j`, the following is always true:\n          `j == j.flatten().unflatten()`.\n\n    @complexity Linear in the size the JSON value.\n\n    @throw type_error.314  if value is not an object\n    @throw type_error.315  if object values are not primitive\n\n    @liveexample{The following code shows how a flattened JSON object is\n    unflattened into the original nested JSON object.,unflatten}\n\n    @sa @ref flatten() for the reverse function\n\n    @since version 2.0.0\n    */\n    basic_json unflatten() const\n    {\n        return json_pointer::unflatten(*this);\n    }\n\n    /// @}\n\n    //////////////////////////\n    // JSON Patch functions //\n    //////////////////////////\n\n    /// @name JSON Patch functions\n    /// @{\n\n    /*!\n    @brief applies a JSON patch\n\n    [JSON Patch](http://jsonpatch.com) defines a JSON document structure for\n    expressing a sequence of operations to apply to a JSON) document. With\n    this function, a JSON Patch is applied to the current JSON value by\n    executing all operations from the patch.\n\n    @param[in] json_patch  JSON patch document\n    @return patched document\n\n    @note The application of a patch is atomic: Either all operations succeed\n          and the patched document is returned or an exception is thrown. In\n          any case, the original value is not changed: the patch is applied\n          to a copy of the value.\n\n    @throw parse_error.104 if the JSON patch does not consist of an array of\n    objects\n\n    @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory\n    attributes are missing); example: `\"operation add must have member path\"`\n\n    @throw out_of_range.401 if an array index is out of range.\n\n    @throw out_of_range.403 if a JSON pointer inside the patch could not be\n    resolved successfully in the current JSON value; example: `\"key baz not\n    found\"`\n\n    @throw out_of_range.405 if JSON pointer has no parent (\"add\", \"remove\",\n    \"move\")\n\n    @throw other_error.501 if \"test\" operation was unsuccessful\n\n    @complexity Linear in the size of the JSON value and the length of the\n    JSON patch. As usually only a fraction of the JSON value is affected by\n    the patch, the complexity can usually be neglected.\n\n    @liveexample{The following code shows how a JSON patch is applied to a\n    value.,patch}\n\n    @sa @ref diff -- create a JSON patch by comparing two JSON values\n\n    @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)\n    @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)\n\n    @since version 2.0.0\n    */\n    basic_json patch(const basic_json& json_patch) const\n    {\n        // make a working copy to apply the patch to\n        basic_json result = *this;\n\n        // the valid JSON Patch operations\n        enum class patch_operations {add, remove, replace, move, copy, test, invalid};\n\n        const auto get_op = [](const std::string & op)\n        {\n            if (op == \"add\")\n            {\n                return patch_operations::add;\n            }\n            if (op == \"remove\")\n            {\n                return patch_operations::remove;\n            }\n            if (op == \"replace\")\n            {\n                return patch_operations::replace;\n            }\n            if (op == \"move\")\n            {\n                return patch_operations::move;\n            }\n            if (op == \"copy\")\n            {\n                return patch_operations::copy;\n            }\n            if (op == \"test\")\n            {\n                return patch_operations::test;\n            }\n\n            return patch_operations::invalid;\n        };\n\n        // wrapper for \"add\" operation; add value at ptr\n        const auto operation_add = [&result](json_pointer & ptr, basic_json val)\n        {\n            // adding to the root of the target document means replacing it\n            if (ptr.is_root())\n            {\n                result = val;\n            }\n            else\n            {\n                // make sure the top element of the pointer exists\n                json_pointer top_pointer = ptr.top();\n                if (top_pointer != ptr)\n                {\n                    result.at(top_pointer);\n                }\n\n                // get reference to parent of JSON pointer ptr\n                const auto last_path = ptr.pop_back();\n                basic_json& parent = result[ptr];\n\n                switch (parent.m_type)\n                {\n                    case value_t::null:\n                    case value_t::object:\n                    {\n                        // use operator[] to add value\n                        parent[last_path] = val;\n                        break;\n                    }\n\n                    case value_t::array:\n                    {\n                        if (last_path == \"-\")\n                        {\n                            // special case: append to back\n                            parent.push_back(val);\n                        }\n                        else\n                        {\n                            const auto idx = json_pointer::array_index(last_path);\n                            if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size()))\n                            {\n                                // avoid undefined behavior\n                                JSON_THROW(out_of_range::create(401, \"array index \" + std::to_string(idx) + \" is out of range\"));\n                            }\n                            else\n                            {\n                                // default case: insert add offset\n                                parent.insert(parent.begin() + static_cast<difference_type>(idx), val);\n                            }\n                        }\n                        break;\n                    }\n\n                    default:\n                    {\n                        // if there exists a parent it cannot be primitive\n                        assert(false);  // LCOV_EXCL_LINE\n                    }\n                }\n            }\n        };\n\n        // wrapper for \"remove\" operation; remove value at ptr\n        const auto operation_remove = [&result](json_pointer & ptr)\n        {\n            // get reference to parent of JSON pointer ptr\n            const auto last_path = ptr.pop_back();\n            basic_json& parent = result.at(ptr);\n\n            // remove child\n            if (parent.is_object())\n            {\n                // perform range check\n                auto it = parent.find(last_path);\n                if (JSON_LIKELY(it != parent.end()))\n                {\n                    parent.erase(it);\n                }\n                else\n                {\n                    JSON_THROW(out_of_range::create(403, \"key '\" + last_path + \"' not found\"));\n                }\n            }\n            else if (parent.is_array())\n            {\n                // note erase performs range check\n                parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));\n            }\n        };\n\n        // type check: top level value must be an array\n        if (JSON_UNLIKELY(not json_patch.is_array()))\n        {\n            JSON_THROW(parse_error::create(104, 0, \"JSON patch must be an array of objects\"));\n        }\n\n        // iterate and apply the operations\n        for (const auto& val : json_patch)\n        {\n            // wrapper to get a value for an operation\n            const auto get_value = [&val](const std::string & op,\n                                          const std::string & member,\n                                          bool string_type) -> basic_json&\n            {\n                // find value\n                auto it = val.m_value.object->find(member);\n\n                // context-sensitive error message\n                const auto error_msg = (op == \"op\") ? \"operation\" : \"operation '\" + op + \"'\";\n\n                // check if desired value is present\n                if (JSON_UNLIKELY(it == val.m_value.object->end()))\n                {\n                    JSON_THROW(parse_error::create(105, 0, error_msg + \" must have member '\" + member + \"'\"));\n                }\n\n                // check if result is of type string\n                if (JSON_UNLIKELY(string_type and not it->second.is_string()))\n                {\n                    JSON_THROW(parse_error::create(105, 0, error_msg + \" must have string member '\" + member + \"'\"));\n                }\n\n                // no error: return value\n                return it->second;\n            };\n\n            // type check: every element of the array must be an object\n            if (JSON_UNLIKELY(not val.is_object()))\n            {\n                JSON_THROW(parse_error::create(104, 0, \"JSON patch must be an array of objects\"));\n            }\n\n            // collect mandatory members\n            const std::string op = get_value(\"op\", \"op\", true);\n            const std::string path = get_value(op, \"path\", true);\n            json_pointer ptr(path);\n\n            switch (get_op(op))\n            {\n                case patch_operations::add:\n                {\n                    operation_add(ptr, get_value(\"add\", \"value\", false));\n                    break;\n                }\n\n                case patch_operations::remove:\n                {\n                    operation_remove(ptr);\n                    break;\n                }\n\n                case patch_operations::replace:\n                {\n                    // the \"path\" location must exist - use at()\n                    result.at(ptr) = get_value(\"replace\", \"value\", false);\n                    break;\n                }\n\n                case patch_operations::move:\n                {\n                    const std::string from_path = get_value(\"move\", \"from\", true);\n                    json_pointer from_ptr(from_path);\n\n                    // the \"from\" location must exist - use at()\n                    basic_json v = result.at(from_ptr);\n\n                    // The move operation is functionally identical to a\n                    // \"remove\" operation on the \"from\" location, followed\n                    // immediately by an \"add\" operation at the target\n                    // location with the value that was just removed.\n                    operation_remove(from_ptr);\n                    operation_add(ptr, v);\n                    break;\n                }\n\n                case patch_operations::copy:\n                {\n                    const std::string from_path = get_value(\"copy\", \"from\", true);\n                    const json_pointer from_ptr(from_path);\n\n                    // the \"from\" location must exist - use at()\n                    basic_json v = result.at(from_ptr);\n\n                    // The copy is functionally identical to an \"add\"\n                    // operation at the target location using the value\n                    // specified in the \"from\" member.\n                    operation_add(ptr, v);\n                    break;\n                }\n\n                case patch_operations::test:\n                {\n                    bool success = false;\n                    JSON_TRY\n                    {\n                        // check if \"value\" matches the one at \"path\"\n                        // the \"path\" location must exist - use at()\n                        success = (result.at(ptr) == get_value(\"test\", \"value\", false));\n                    }\n                    JSON_CATCH (out_of_range&)\n                    {\n                        // ignore out of range errors: success remains false\n                    }\n\n                    // throw an exception if test fails\n                    if (JSON_UNLIKELY(not success))\n                    {\n                        JSON_THROW(other_error::create(501, \"unsuccessful: \" + val.dump()));\n                    }\n\n                    break;\n                }\n\n                case patch_operations::invalid:\n                {\n                    // op must be \"add\", \"remove\", \"replace\", \"move\", \"copy\", or\n                    // \"test\"\n                    JSON_THROW(parse_error::create(105, 0, \"operation value '\" + op + \"' is invalid\"));\n                }\n            }\n        }\n\n        return result;\n    }\n\n    /*!\n    @brief creates a diff as a JSON patch\n\n    Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can\n    be changed into the value @a target by calling @ref patch function.\n\n    @invariant For two JSON values @a source and @a target, the following code\n    yields always `true`:\n    @code {.cpp}\n    source.patch(diff(source, target)) == target;\n    @endcode\n\n    @note Currently, only `remove`, `add`, and `replace` operations are\n          generated.\n\n    @param[in] source  JSON value to compare from\n    @param[in] target  JSON value to compare against\n    @param[in] path    helper value to create JSON pointers\n\n    @return a JSON patch to convert the @a source to @a target\n\n    @complexity Linear in the lengths of @a source and @a target.\n\n    @liveexample{The following code shows how a JSON patch is created as a\n    diff for two JSON values.,diff}\n\n    @sa @ref patch -- apply a JSON patch\n\n    @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)\n\n    @since version 2.0.0\n    */\n    static basic_json diff(const basic_json& source, const basic_json& target,\n                           const std::string& path = \"\")\n    {\n        // the patch\n        basic_json result(value_t::array);\n\n        // if the values are the same, return empty patch\n        if (source == target)\n        {\n            return result;\n        }\n\n        if (source.type() != target.type())\n        {\n            // different types: replace value\n            result.push_back(\n            {\n                {\"op\", \"replace\"}, {\"path\", path}, {\"value\", target}\n            });\n        }\n        else\n        {\n            switch (source.type())\n            {\n                case value_t::array:\n                {\n                    // first pass: traverse common elements\n                    std::size_t i = 0;\n                    while (i < source.size() and i < target.size())\n                    {\n                        // recursive call to compare array values at index i\n                        auto temp_diff = diff(source[i], target[i], path + \"/\" + std::to_string(i));\n                        result.insert(result.end(), temp_diff.begin(), temp_diff.end());\n                        ++i;\n                    }\n\n                    // i now reached the end of at least one array\n                    // in a second pass, traverse the remaining elements\n\n                    // remove my remaining elements\n                    const auto end_index = static_cast<difference_type>(result.size());\n                    while (i < source.size())\n                    {\n                        // add operations in reverse order to avoid invalid\n                        // indices\n                        result.insert(result.begin() + end_index, object(\n                        {\n                            {\"op\", \"remove\"},\n                            {\"path\", path + \"/\" + std::to_string(i)}\n                        }));\n                        ++i;\n                    }\n\n                    // add other remaining elements\n                    while (i < target.size())\n                    {\n                        result.push_back(\n                        {\n                            {\"op\", \"add\"},\n                            {\"path\", path + \"/\" + std::to_string(i)},\n                            {\"value\", target[i]}\n                        });\n                        ++i;\n                    }\n\n                    break;\n                }\n\n                case value_t::object:\n                {\n                    // first pass: traverse this object's elements\n                    for (auto it = source.cbegin(); it != source.cend(); ++it)\n                    {\n                        // escape the key name to be used in a JSON patch\n                        const auto key = json_pointer::escape(it.key());\n\n                        if (target.find(it.key()) != target.end())\n                        {\n                            // recursive call to compare object values at key it\n                            auto temp_diff = diff(it.value(), target[it.key()], path + \"/\" + key);\n                            result.insert(result.end(), temp_diff.begin(), temp_diff.end());\n                        }\n                        else\n                        {\n                            // found a key that is not in o -> remove it\n                            result.push_back(object(\n                            {\n                                {\"op\", \"remove\"}, {\"path\", path + \"/\" + key}\n                            }));\n                        }\n                    }\n\n                    // second pass: traverse other object's elements\n                    for (auto it = target.cbegin(); it != target.cend(); ++it)\n                    {\n                        if (source.find(it.key()) == source.end())\n                        {\n                            // found a key that is not in this -> add it\n                            const auto key = json_pointer::escape(it.key());\n                            result.push_back(\n                            {\n                                {\"op\", \"add\"}, {\"path\", path + \"/\" + key},\n                                {\"value\", it.value()}\n                            });\n                        }\n                    }\n\n                    break;\n                }\n\n                default:\n                {\n                    // both primitive type: replace value\n                    result.push_back(\n                    {\n                        {\"op\", \"replace\"}, {\"path\", path}, {\"value\", target}\n                    });\n                    break;\n                }\n            }\n        }\n\n        return result;\n    }\n\n    /// @}\n};\n\n/////////////\n// presets //\n/////////////\n\n/*!\n@brief default JSON class\n\nThis type is the default specialization of the @ref basic_json class which\nuses the standard template types.\n\n@since version 1.0.0\n*/\nusing json = basic_json<>;\n\n//////////////////\n// json_pointer //\n//////////////////\n\nNLOHMANN_BASIC_JSON_TPL_DECLARATION\nNLOHMANN_BASIC_JSON_TPL&\njson_pointer::get_and_create(NLOHMANN_BASIC_JSON_TPL& j) const\n{\n    using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;\n    auto result = &j;\n\n    // in case no reference tokens exist, return a reference to the JSON value\n    // j which will be overwritten by a primitive value\n    for (const auto& reference_token : reference_tokens)\n    {\n        switch (result->m_type)\n        {\n            case detail::value_t::null:\n            {\n                if (reference_token == \"0\")\n                {\n                    // start a new array if reference token is 0\n                    result = &result->operator[](0);\n                }\n                else\n                {\n                    // start a new object otherwise\n                    result = &result->operator[](reference_token);\n                }\n                break;\n            }\n\n            case detail::value_t::object:\n            {\n                // create an entry in the object\n                result = &result->operator[](reference_token);\n                break;\n            }\n\n            case detail::value_t::array:\n            {\n                // create an entry in the array\n                JSON_TRY\n                {\n                    result = &result->operator[](static_cast<size_type>(array_index(reference_token)));\n                }\n                JSON_CATCH(std::invalid_argument&)\n                {\n                    JSON_THROW(detail::parse_error::create(109, 0, \"array index '\" + reference_token + \"' is not a number\"));\n                }\n                break;\n            }\n\n            /*\n            The following code is only reached if there exists a reference\n            token _and_ the current value is primitive. In this case, we have\n            an error situation, because primitive values may only occur as\n            single value; that is, with an empty list of reference tokens.\n            */\n            default:\n                JSON_THROW(detail::type_error::create(313, \"invalid value to unflatten\"));\n        }\n    }\n\n    return *result;\n}\n\nNLOHMANN_BASIC_JSON_TPL_DECLARATION\nNLOHMANN_BASIC_JSON_TPL&\njson_pointer::get_unchecked(NLOHMANN_BASIC_JSON_TPL* ptr) const\n{\n    using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;\n    for (const auto& reference_token : reference_tokens)\n    {\n        // convert null values to arrays or objects before continuing\n        if (ptr->m_type == detail::value_t::null)\n        {\n            // check if reference token is a number\n            const bool nums =\n                std::all_of(reference_token.begin(), reference_token.end(),\n                            [](const char x)\n            {\n                return (x >= '0' and x <= '9');\n            });\n\n            // change value to array for numbers or \"-\" or to object otherwise\n            *ptr = (nums or reference_token == \"-\")\n                   ? detail::value_t::array\n                   : detail::value_t::object;\n        }\n\n        switch (ptr->m_type)\n        {\n            case detail::value_t::object:\n            {\n                // use unchecked object access\n                ptr = &ptr->operator[](reference_token);\n                break;\n            }\n\n            case detail::value_t::array:\n            {\n                // error condition (cf. RFC 6901, Sect. 4)\n                if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))\n                {\n                    JSON_THROW(detail::parse_error::create(106, 0,\n                                                           \"array index '\" + reference_token +\n                                                           \"' must not begin with '0'\"));\n                }\n\n                if (reference_token == \"-\")\n                {\n                    // explicitly treat \"-\" as index beyond the end\n                    ptr = &ptr->operator[](ptr->m_value.array->size());\n                }\n                else\n                {\n                    // convert array index to number; unchecked access\n                    JSON_TRY\n                    {\n                        ptr = &ptr->operator[](\n                            static_cast<size_type>(array_index(reference_token)));\n                    }\n                    JSON_CATCH(std::invalid_argument&)\n                    {\n                        JSON_THROW(detail::parse_error::create(109, 0, \"array index '\" + reference_token + \"' is not a number\"));\n                    }\n                }\n                break;\n            }\n\n            default:\n                JSON_THROW(detail::out_of_range::create(404, \"unresolved reference token '\" + reference_token + \"'\"));\n        }\n    }\n\n    return *ptr;\n}\n\nNLOHMANN_BASIC_JSON_TPL_DECLARATION\nNLOHMANN_BASIC_JSON_TPL&\njson_pointer::get_checked(NLOHMANN_BASIC_JSON_TPL* ptr) const\n{\n    using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;\n    for (const auto& reference_token : reference_tokens)\n    {\n        switch (ptr->m_type)\n        {\n            case detail::value_t::object:\n            {\n                // note: at performs range check\n                ptr = &ptr->at(reference_token);\n                break;\n            }\n\n            case detail::value_t::array:\n            {\n                if (JSON_UNLIKELY(reference_token == \"-\"))\n                {\n                    // \"-\" always fails the range check\n                    JSON_THROW(detail::out_of_range::create(402,\n                                                            \"array index '-' (\" + std::to_string(ptr->m_value.array->size()) +\n                                                            \") is out of range\"));\n                }\n\n                // error condition (cf. RFC 6901, Sect. 4)\n                if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))\n                {\n                    JSON_THROW(detail::parse_error::create(106, 0,\n                                                           \"array index '\" + reference_token +\n                                                           \"' must not begin with '0'\"));\n                }\n\n                // note: at performs range check\n                JSON_TRY\n                {\n                    ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));\n                }\n                JSON_CATCH(std::invalid_argument&)\n                {\n                    JSON_THROW(detail::parse_error::create(109, 0, \"array index '\" + reference_token + \"' is not a number\"));\n                }\n                break;\n            }\n\n            default:\n                JSON_THROW(detail::out_of_range::create(404, \"unresolved reference token '\" + reference_token + \"'\"));\n        }\n    }\n\n    return *ptr;\n}\n\nNLOHMANN_BASIC_JSON_TPL_DECLARATION\nconst NLOHMANN_BASIC_JSON_TPL&\njson_pointer::get_unchecked(const NLOHMANN_BASIC_JSON_TPL* ptr) const\n{\n    using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;\n    for (const auto& reference_token : reference_tokens)\n    {\n        switch (ptr->m_type)\n        {\n            case detail::value_t::object:\n            {\n                // use unchecked object access\n                ptr = &ptr->operator[](reference_token);\n                break;\n            }\n\n            case detail::value_t::array:\n            {\n                if (JSON_UNLIKELY(reference_token == \"-\"))\n                {\n                    // \"-\" cannot be used for const access\n                    JSON_THROW(detail::out_of_range::create(402,\n                                                            \"array index '-' (\" + std::to_string(ptr->m_value.array->size()) +\n                                                            \") is out of range\"));\n                }\n\n                // error condition (cf. RFC 6901, Sect. 4)\n                if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))\n                {\n                    JSON_THROW(detail::parse_error::create(106, 0,\n                                                           \"array index '\" + reference_token +\n                                                           \"' must not begin with '0'\"));\n                }\n\n                // use unchecked array access\n                JSON_TRY\n                {\n                    ptr = &ptr->operator[](\n                        static_cast<size_type>(array_index(reference_token)));\n                }\n                JSON_CATCH(std::invalid_argument&)\n                {\n                    JSON_THROW(detail::parse_error::create(109, 0, \"array index '\" + reference_token + \"' is not a number\"));\n                }\n                break;\n            }\n\n            default:\n                JSON_THROW(detail::out_of_range::create(404, \"unresolved reference token '\" + reference_token + \"'\"));\n        }\n    }\n\n    return *ptr;\n}\n\nNLOHMANN_BASIC_JSON_TPL_DECLARATION\nconst NLOHMANN_BASIC_JSON_TPL&\njson_pointer::get_checked(const NLOHMANN_BASIC_JSON_TPL* ptr) const\n{\n    using size_type = typename NLOHMANN_BASIC_JSON_TPL::size_type;\n    for (const auto& reference_token : reference_tokens)\n    {\n        switch (ptr->m_type)\n        {\n            case detail::value_t::object:\n            {\n                // note: at performs range check\n                ptr = &ptr->at(reference_token);\n                break;\n            }\n\n            case detail::value_t::array:\n            {\n                if (JSON_UNLIKELY(reference_token == \"-\"))\n                {\n                    // \"-\" always fails the range check\n                    JSON_THROW(detail::out_of_range::create(402,\n                                                            \"array index '-' (\" + std::to_string(ptr->m_value.array->size()) +\n                                                            \") is out of range\"));\n                }\n\n                // error condition (cf. RFC 6901, Sect. 4)\n                if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0'))\n                {\n                    JSON_THROW(detail::parse_error::create(106, 0,\n                                                           \"array index '\" + reference_token +\n                                                           \"' must not begin with '0'\"));\n                }\n\n                // note: at performs range check\n                JSON_TRY\n                {\n                    ptr = &ptr->at(static_cast<size_type>(array_index(reference_token)));\n                }\n                JSON_CATCH(std::invalid_argument&)\n                {\n                    JSON_THROW(detail::parse_error::create(109, 0, \"array index '\" + reference_token + \"' is not a number\"));\n                }\n                break;\n            }\n\n            default:\n                JSON_THROW(detail::out_of_range::create(404, \"unresolved reference token '\" + reference_token + \"'\"));\n        }\n    }\n\n    return *ptr;\n}\n\nNLOHMANN_BASIC_JSON_TPL_DECLARATION\nvoid json_pointer::flatten(const std::string& reference_string,\n                           const NLOHMANN_BASIC_JSON_TPL& value,\n                           NLOHMANN_BASIC_JSON_TPL& result)\n{\n    switch (value.m_type)\n    {\n        case detail::value_t::array:\n        {\n            if (value.m_value.array->empty())\n            {\n                // flatten empty array as null\n                result[reference_string] = nullptr;\n            }\n            else\n            {\n                // iterate array and use index as reference string\n                for (std::size_t i = 0; i < value.m_value.array->size(); ++i)\n                {\n                    flatten(reference_string + \"/\" + std::to_string(i),\n                            value.m_value.array->operator[](i), result);\n                }\n            }\n            break;\n        }\n\n        case detail::value_t::object:\n        {\n            if (value.m_value.object->empty())\n            {\n                // flatten empty object as null\n                result[reference_string] = nullptr;\n            }\n            else\n            {\n                // iterate object and use keys as reference string\n                for (const auto& element : *value.m_value.object)\n                {\n                    flatten(reference_string + \"/\" + escape(element.first), element.second, result);\n                }\n            }\n            break;\n        }\n\n        default:\n        {\n            // add primitive value with its reference string\n            result[reference_string] = value;\n            break;\n        }\n    }\n}\n\nNLOHMANN_BASIC_JSON_TPL_DECLARATION\nNLOHMANN_BASIC_JSON_TPL\njson_pointer::unflatten(const NLOHMANN_BASIC_JSON_TPL& value)\n{\n    if (JSON_UNLIKELY(not value.is_object()))\n    {\n        JSON_THROW(detail::type_error::create(314, \"only objects can be unflattened\"));\n    }\n\n    NLOHMANN_BASIC_JSON_TPL result;\n\n    // iterate the JSON object values\n    for (const auto& element : *value.m_value.object)\n    {\n        if (JSON_UNLIKELY(not element.second.is_primitive()))\n        {\n            JSON_THROW(detail::type_error::create(315, \"values in object must be primitive\"));\n        }\n\n        // assign value to reference pointed to by JSON pointer; Note that if\n        // the JSON pointer is \"\" (i.e., points to the whole value), function\n        // get_and_create returns a reference to result itself. An assignment\n        // will then create a primitive value.\n        json_pointer(element.first).get_and_create(result) = element.second;\n    }\n\n    return result;\n}\n\ninline bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept\n{\n    return (lhs.reference_tokens == rhs.reference_tokens);\n}\n\ninline bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept\n{\n    return not (lhs == rhs);\n}\n} // namespace nlohmann\n\n\n///////////////////////\n// nonmember support //\n///////////////////////\n\n// specialization of std::swap, and std::hash\nnamespace std\n{\n/*!\n@brief exchanges the values of two JSON objects\n\n@since version 1.0.0\n*/\ntemplate<>\ninline void swap(nlohmann::json& j1,\n                 nlohmann::json& j2) noexcept(\n                     is_nothrow_move_constructible<nlohmann::json>::value and\n                     is_nothrow_move_assignable<nlohmann::json>::value\n                 )\n{\n    j1.swap(j2);\n}\n\n/// hash value for JSON objects\ntemplate<>\nstruct hash<nlohmann::json>\n{\n    /*!\n    @brief return a hash value for a JSON object\n\n    @since version 1.0.0\n    */\n    std::size_t operator()(const nlohmann::json& j) const\n    {\n        // a naive hashing via the string representation\n        const auto& h = hash<nlohmann::json::string_t>();\n        return h(j.dump());\n    }\n};\n\n/// specialization for std::less<value_t>\n/// @note: do not remove the space after '<',\n///        see https://github.com/nlohmann/json/pull/679\ntemplate<>\nstruct less< ::nlohmann::detail::value_t>\n{\n    /*!\n    @brief compare two value_t enum values\n    @since version 3.0.0\n    */\n    bool operator()(nlohmann::detail::value_t lhs,\n                    nlohmann::detail::value_t rhs) const noexcept\n    {\n        return nlohmann::detail::operator<(lhs, rhs);\n    }\n};\n\n} // namespace std\n\n/*!\n@brief user-defined string literal for JSON values\n\nThis operator implements a user-defined string literal for JSON objects. It\ncan be used by adding `\"_json\"` to a string literal and returns a JSON object\nif no parse error occurred.\n\n@param[in] s  a string representation of a JSON object\n@param[in] n  the length of string @a s\n@return a JSON object\n\n@since version 1.0.0\n*/\ninline nlohmann::json operator \"\" _json(const char* s, std::size_t n)\n{\n    return nlohmann::json::parse(s, s + n);\n}\n\n/*!\n@brief user-defined string literal for JSON pointer\n\nThis operator implements a user-defined string literal for JSON Pointers. It\ncan be used by adding `\"_json_pointer\"` to a string literal and returns a JSON pointer\nobject if no parse error occurred.\n\n@param[in] s  a string representation of a JSON Pointer\n@param[in] n  the length of string @a s\n@return a JSON pointer object\n\n@since version 2.0.0\n*/\ninline nlohmann::json::json_pointer operator \"\" _json_pointer(const char* s, std::size_t n)\n{\n    return nlohmann::json::json_pointer(std::string(s, n));\n}\n\n// restore GCC/clang diagnostic settings\n#if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)\n    #pragma GCC diagnostic pop\n#endif\n#if defined(__clang__)\n    #pragma GCC diagnostic pop\n#endif\n\n// clean up\n#undef JSON_CATCH\n#undef JSON_THROW\n#undef JSON_TRY\n#undef JSON_LIKELY\n#undef JSON_UNLIKELY\n#undef JSON_DEPRECATED\n#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION\n#undef NLOHMANN_BASIC_JSON_TPL\n\n#endif\n"
  }
]